commit 5bb6c0ea321cfb2f60a6381c7b6bd0721e4bf99d
parent 18fa4ceede196d0013bd8c851e5f35e48b617cda
Author: xplshn <anto@xplshn.com.ar>
Date: Tue, 16 Jun 2026 19:23:04 -0300
SH build system - added manpages - large refactor
Signed-off-by: xplshn <anto@xplshn.com.ar>
Diffstat:
201 files changed, 12098 insertions(+), 2402 deletions(-)
diff --git a/Makefile b/Makefile
@@ -25,7 +25,8 @@ HDR =\
shared/passwd.h\
shared/reboot.h\
shared/rtc.h\
- shared/proc.h
+ shared/proc.h\
+ shared/tls.h
LIBUTFOBJ =\
shared/libutf/fgetrune.o\
@@ -98,9 +99,15 @@ LIBUTILOBJ =\
shared/libutil/tty.o\
shared/libutil/fconcat.o\
shared/libutil/recurse_dir.o\
- shared/libutil/sig.o
+ shared/libutil/sig.o\
+ shared/libutil/net.o\
+ shared/libutil/sysinfo.o\
+ shared/libutil/tls.o
-LIB = shared/libutf/libutf.a shared/libutil/libutil.a
+LIBREDLINEOBJ =\
+ shared/libredline/redline.o
+
+LIB = shared/libredline/libredline.a shared/libutil/libutil.a shared/libutf/libutf.a
POSIX_BIN_ALL =\
cmd/posix/basename\
@@ -179,48 +186,46 @@ POSIX_BIN_ALL =\
cmd/posix/xargs\
cmd/posix/awk/awk\
cmd/posix/sh/sh\
- cmd/posix/pax
+ cmd/posix/pax\
+ cmd/posix/make/make
LINUX_BIN_ALL =\
cmd/linux/blkdiscard\
cmd/linux/chvt\
cmd/linux/ctrlaltdel\
- cmd/linux/dmesg\
cmd/linux/eject\
- cmd/linux/fallocate\
- cmd/linux/free\
cmd/linux/freeramdisk\
cmd/linux/fsfreeze\
cmd/linux/hwclock\
cmd/linux/insmod\
cmd/linux/lsmod\
+ cmd/linux/modprobe\
+ cmd/linux/depmod\
cmd/linux/mkswap\
cmd/linux/mount\
cmd/linux/mountpoint\
- cmd/linux/pidof\
cmd/linux/pivot_root\
- cmd/linux/pwdx\
cmd/linux/readahead\
cmd/linux/rmmod\
cmd/linux/swaplabel\
cmd/linux/swapoff\
cmd/linux/swapon\
cmd/linux/switch_root\
+ cmd/linux/tunctl\
cmd/linux/umount\
cmd/linux/unshare\
- cmd/linux/uptime\
cmd/linux/vtallow
NET_BIN_ALL =\
cmd/net/netcat\
cmd/net/tftp\
- cmd/net/tunctl\
cmd/net/wget\
cmd/net/ping\
cmd/net/sdhcp\
cmd/net/ifconfig\
cmd/net/host\
- cmd/net/httpd
+ cmd/net/httpd\
+ cmd/net/ip
XSI_BIN_ALL =\
cmd/xsi/mknod\
@@ -266,7 +271,17 @@ PSEUDO_BIN_ALL =\
cmd/pseudo/xinstall\
cmd/pseudo/yes\
cmd/pseudo/base64\
- cmd/extra/b3sum
+ cmd/extra/b3sum\
+ cmd/dev/ar/ar\
+ cmd/dev/as/as\
+ cmd/dev/ld/ld\
+ cmd/dev/cc/cc\
+ cmd/pseudo/dmesg\
+ cmd/pseudo/fallocate\
+ cmd/pseudo/free\
+ cmd/pseudo/pidof\
+ cmd/pseudo/pwdx\
+ cmd/pseudo/uptime
MAKEOBJ =\
cmd/posix/make/defaults.o\
@@ -352,45 +367,43 @@ BIN_xargs_1 = cmd/posix/xargs
BIN_awk_1 = cmd/posix/awk/awk
BIN_sh_1 = cmd/posix/sh/sh
BIN_pax_1 = cmd/posix/pax
+BIN_make_1 = cmd/posix/make/make
BIN_blkdiscard_1 = cmd/linux/blkdiscard
BIN_chvt_1 = cmd/linux/chvt
BIN_ctrlaltdel_1 = cmd/linux/ctrlaltdel
-BIN_dmesg_1 = cmd/linux/dmesg
BIN_eject_1 = cmd/linux/eject
-BIN_fallocate_1 = cmd/linux/fallocate
-BIN_free_1 = cmd/linux/free
BIN_freeramdisk_1 = cmd/linux/freeramdisk
BIN_fsfreeze_1 = cmd/linux/fsfreeze
BIN_hwclock_1 = cmd/linux/hwclock
BIN_insmod_1 = cmd/linux/insmod
BIN_lsmod_1 = cmd/linux/lsmod
+BIN_modprobe_1 = cmd/linux/modprobe
+BIN_depmod_1 = cmd/linux/depmod
BIN_mkswap_1 = cmd/linux/mkswap
BIN_mount_1 = cmd/linux/mount
BIN_mountpoint_1 = cmd/linux/mountpoint
-BIN_pidof_1 = cmd/linux/pidof
BIN_pivot_root_1 = cmd/linux/pivot_root
-BIN_pwdx_1 = cmd/linux/pwdx
BIN_readahead_1 = cmd/linux/readahead
BIN_rmmod_1 = cmd/linux/rmmod
BIN_swaplabel_1 = cmd/linux/swaplabel
BIN_swapoff_1 = cmd/linux/swapoff
BIN_swapon_1 = cmd/linux/swapon
BIN_switch_root_1 = cmd/linux/switch_root
+BIN_tunctl_1 = cmd/linux/tunctl
BIN_umount_1 = cmd/linux/umount
BIN_unshare_1 = cmd/linux/unshare
-BIN_uptime_1 = cmd/linux/uptime
BIN_vtallow_1 = cmd/linux/vtallow
BIN_netcat_1 = cmd/net/netcat
BIN_tftp_1 = cmd/net/tftp
-BIN_tunctl_1 = cmd/net/tunctl
BIN_wget_1 = cmd/net/wget
BIN_ping_1 = cmd/net/ping
BIN_sdhcp_1 = cmd/net/sdhcp
BIN_ifconfig_1 = cmd/net/ifconfig
BIN_host_1 = cmd/net/host
BIN_httpd_1 = cmd/net/httpd
+BIN_ip_1 = cmd/net/ip
BIN_mknod_1 = cmd/xsi/mknod
BIN_passwd_1 = cmd/xsi/passwd
@@ -435,8 +448,16 @@ BIN_xinstall_1 = cmd/pseudo/xinstall
BIN_yes_1 = cmd/pseudo/yes
BIN_base64_1 = cmd/pseudo/base64
BIN_b3sum_1 = cmd/extra/b3sum
-
-BIN_make_tool_1 = cmd/posix/make/make
+BIN_ar_1 = cmd/dev/ar/ar
+BIN_as_1 = cmd/dev/as/as
+BIN_ld_1 = cmd/dev/ld/ld
+BIN_cc_1 = cmd/dev/cc/cc
+BIN_dmesg_1 = cmd/pseudo/dmesg
+BIN_fallocate_1 = cmd/pseudo/fallocate
+BIN_free_1 = cmd/pseudo/free
+BIN_pidof_1 = cmd/pseudo/pidof
+BIN_pwdx_1 = cmd/pseudo/pwdx
+BIN_uptime_1 = cmd/pseudo/uptime
POSIX_BIN = \
$(BIN_basename_$(BUILD_POSIX_BASENAME)) \
@@ -515,48 +536,46 @@ POSIX_BIN = \
$(BIN_xargs_$(BUILD_POSIX_XARGS)) \
$(BIN_awk_$(BUILD_POSIX_AWK)) \
$(BIN_sh_$(BUILD_POSIX_SH)) \
- $(BIN_pax_$(BUILD_POSIX_PAX))
+ $(BIN_pax_$(BUILD_POSIX_PAX)) \
+ $(BIN_make_$(BUILD_POSIX_MAKE))
LINUX_BIN = \
$(BIN_blkdiscard_$(BUILD_LINUX_BLKDISCARD)) \
$(BIN_chvt_$(BUILD_LINUX_CHVT)) \
$(BIN_ctrlaltdel_$(BUILD_LINUX_CTRLALTDEL)) \
- $(BIN_dmesg_$(BUILD_LINUX_DMESG)) \
$(BIN_eject_$(BUILD_LINUX_EJECT)) \
- $(BIN_fallocate_$(BUILD_LINUX_FALLOCATE)) \
- $(BIN_free_$(BUILD_LINUX_FREE)) \
$(BIN_freeramdisk_$(BUILD_LINUX_FREERAMDISK)) \
$(BIN_fsfreeze_$(BUILD_LINUX_FSFREEZE)) \
$(BIN_hwclock_$(BUILD_LINUX_HWCLOCK)) \
$(BIN_insmod_$(BUILD_LINUX_INSMOD)) \
$(BIN_lsmod_$(BUILD_LINUX_LSMOD)) \
+ $(BIN_modprobe_$(BUILD_LINUX_MODPROBE)) \
+ $(BIN_depmod_$(BUILD_LINUX_DEPMOD)) \
$(BIN_mkswap_$(BUILD_LINUX_MKSWAP)) \
$(BIN_mount_$(BUILD_LINUX_MOUNT)) \
$(BIN_mountpoint_$(BUILD_LINUX_MOUNTPOINT)) \
- $(BIN_pidof_$(BUILD_LINUX_PIDOF)) \
$(BIN_pivot_root_$(BUILD_LINUX_PIVOT_ROOT)) \
- $(BIN_pwdx_$(BUILD_LINUX_PWDX)) \
$(BIN_readahead_$(BUILD_LINUX_READAHEAD)) \
$(BIN_rmmod_$(BUILD_LINUX_RMMOD)) \
$(BIN_swaplabel_$(BUILD_LINUX_SWAPLABEL)) \
$(BIN_swapoff_$(BUILD_LINUX_SWAPOFF)) \
$(BIN_swapon_$(BUILD_LINUX_SWAPON)) \
$(BIN_switch_root_$(BUILD_LINUX_SWITCH_ROOT)) \
+ $(BIN_tunctl_$(BUILD_LINUX_TUNCTL)) \
$(BIN_umount_$(BUILD_LINUX_UMOUNT)) \
$(BIN_unshare_$(BUILD_LINUX_UNSHARE)) \
- $(BIN_uptime_$(BUILD_LINUX_UPTIME)) \
$(BIN_vtallow_$(BUILD_LINUX_VTALLOW))
NET_BIN = \
$(BIN_netcat_$(BUILD_NET_NETCAT)) \
$(BIN_tftp_$(BUILD_NET_TFTP)) \
- $(BIN_tunctl_$(BUILD_NET_TUNCTL)) \
$(BIN_wget_$(BUILD_NET_WGET)) \
$(BIN_ping_$(BUILD_NET_PING)) \
$(BIN_sdhcp_$(BUILD_NET_SDHCP)) \
$(BIN_ifconfig_$(BUILD_NET_IFCONFIG)) \
$(BIN_host_$(BUILD_NET_HOST)) \
- $(BIN_httpd_$(BUILD_NET_HTTPD))
+ $(BIN_httpd_$(BUILD_NET_HTTPD)) \
+ $(BIN_ip_$(BUILD_NET_IP))
XSI_BIN = \
$(BIN_mknod_$(BUILD_XSI_MKNOD)) \
@@ -606,13 +625,17 @@ PSEUDO_BIN = \
$(BIN_ar_$(BUILD_DEV_AR)) \
$(BIN_as_$(BUILD_DEV_CC)) \
$(BIN_ld_$(BUILD_DEV_LD)) \
- $(BIN_cc_$(BUILD_DEV_CC))
-
-MAKE_BIN = $(BIN_make_tool_$(BUILD_MAKE_MAKE))
+ $(BIN_cc_$(BUILD_DEV_CC)) \
+ $(BIN_dmesg_$(BUILD_PSEUDO_DMESG)) \
+ $(BIN_fallocate_$(BUILD_PSEUDO_FALLOCATE)) \
+ $(BIN_free_$(BUILD_PSEUDO_FREE)) \
+ $(BIN_pidof_$(BUILD_PSEUDO_PIDOF)) \
+ $(BIN_pwdx_$(BUILD_PSEUDO_PWDX)) \
+ $(BIN_uptime_$(BUILD_PSEUDO_UPTIME))
OBJ = $(LIBUTFOBJ) $(LIBUTILOBJ) $(MAKEOBJ)
-all: $(LIB) $(POSIX_BIN) $(LINUX_BIN) $(NET_BIN) $(XSI_BIN) $(PSEUDO_BIN) $(MAKE_BIN)
+all: $(LIB) $(POSIX_BIN) $(LINUX_BIN) $(NET_BIN) $(XSI_BIN) $(PSEUDO_BIN)
$(POSIX_BIN_ALL) $(LINUX_BIN_ALL) $(NET_BIN_ALL) $(XSI_BIN_ALL) $(PSEUDO_BIN_ALL): $(LIB)
@@ -642,6 +665,10 @@ shared/libutf/libutf.a: $(LIBUTFOBJ)
$(AR) $(ARFLAGS) $@ $?
$(RANLIB) $@
+shared/libredline/libredline.a: $(LIBREDLINEOBJ)
+ $(AR) $(ARFLAGS) $@ $?
+ $(RANLIB) $@
+
shared/libutil/libutil.a: $(LIBUTILOBJ)
$(AR) $(ARFLAGS) $@ $?
$(RANLIB) $@
@@ -656,14 +683,39 @@ box: $(LIB)
LDFLAGS='$(LDFLAGS)' LDLIBS='$(LDLIBS)' OBJCOPY='$(OBJCOPY)' \
scripts/mkbox
+.PHONY: man clean
+
+scripts/mkman/mkman: scripts/mkman/main.go scripts/mkman/troff.go
+ cd scripts/mkman && go build -o mkman .
+
+man: scripts/mkman/mkman
+ @for src in $(POSIX_BIN_ALL:=.c) $(PSEUDO_BIN_ALL:=.c); do \
+ if [ -f "$$src" ] && grep -qE '!man|\?man' "$$src"; then \
+ base=$$(basename $$src .c); \
+ mkdir -p man/man1; \
+ scripts/mkman/mkman -config config.mk -section 1 "$$src" > "man/man1/$$base.1"; \
+ fi; \
+ done
+ @for src in $(LINUX_BIN_ALL:=.c) $(NET_BIN_ALL:=.c) $(XSI_BIN_ALL:=.c); do \
+ if [ -f "$$src" ] && grep -qE '!man|\?man' "$$src"; then \
+ base=$$(basename $$src .c); \
+ mkdir -p man/man8; \
+ scripts/mkman/mkman -config config.mk -section 8 "$$src" > "man/man8/$$base.8"; \
+ fi; \
+ done
+
clean:
- rm -f shared/libutf/*.o shared/libutil/*.o cmd/posix/make/*.o cmd/posix/awk/*.o cmd/posix/sh/*.o cmd/extra/*.o
+ rm -f shared/libutf/*.o shared/libutil/*.o shared/libredline/*.o
+ rm -f cmd/posix/*.o cmd/posix/make/*.o cmd/posix/awk/*.o cmd/posix/sh/*.o
+ rm -f cmd/linux/*.o cmd/net/*.o cmd/xsi/*.o cmd/pseudo/*.o
+ rm -f cmd/extra/*.o cmd/dev/ar/*.o cmd/dev/ld/*.o cmd/dev/cc/*.o cmd/dev/as/*.o
rm -f $(POSIX_BIN_ALL) $(LINUX_BIN_ALL) $(NET_BIN_ALL) $(XSI_BIN_ALL) $(PSEUDO_BIN_ALL) $(LIB)
rm -f cmd/posix/make/make cmd/posix/getconf.h cmd/posix/bc.c
rm -f cmd/posix/awk/awk cmd/posix/awk/maketab cmd/posix/awk/awkgram.tab.c cmd/posix/awk/awkgram.tab.h cmd/posix/awk/proctab.c
rm -f cmd/posix/sh/sh cmd/posix/sh/mknodes cmd/posix/sh/mksyntax
rm -f cmd/posix/sh/syntax.c cmd/posix/sh/syntax.h cmd/posix/sh/nodes.c cmd/posix/sh/nodes.h cmd/posix/sh/builtins.c cmd/posix/sh/builtins.h cmd/posix/sh/token.h
- rm -rf aruu-box .box
+ rm -f cmd/dev/cc/cc1 cmd/dev/cc/cpp cmd/dev/as/as shared/libaruuelf.so
+ rm -rf aruu-box .box man/man1 man/man8 scripts/mkman/mkman
AWKOBJ =\
cmd/posix/awk/b.o\
@@ -693,7 +745,7 @@ SHOBJ =\
cmd/posix/sh/eval.o\
cmd/posix/sh/exec.o\
cmd/posix/sh/expand.o\
- cmd/posix/sh/histedit.o\
+ cmd/posix/sh/lineedit.o\
cmd/posix/sh/input.o\
cmd/posix/sh/jobs.o\
cmd/posix/sh/kill.o\
@@ -757,3 +809,93 @@ cmd/posix/sh/%.o: cmd/posix/sh/%.c
cmd/posix/sh/sh: $(SHOBJ) $(LIB)
$(CC) $(LDFLAGS) -o $@ $(SHOBJ) $(LIB) $(LDLIBS)
+
+cmd/dev/ar/ar: cmd/dev/ar/ar.o $(LIB)
+ $(CC) $(LDFLAGS) -o $@ cmd/dev/ar/ar.o $(LIB) $(LDLIBS)
+
+cmd/dev/ar/%.o: cmd/dev/ar/%.c
+ $(CC) $(CPPFLAGS) -Icmd/dev/ar $(CFLAGS) -o $@ -c $<
+
+LD_OBJ =\
+ cmd/dev/ld/ld.o
+
+cmd/dev/ld/%.o: cmd/dev/ld/%.c
+ $(CC) $(CPPFLAGS) -DLD_TARGET_X86_64 -Icmd/dev/ld $(CFLAGS) -fPIC -o $@ -c $<
+
+shared/libaruuelf.so: cmd/dev/ld/elf.o cmd/dev/ld/x86_64.o cmd/dev/ld/ld_support.o
+ $(CC) $(LDFLAGS) -shared -o $@ cmd/dev/ld/elf.o cmd/dev/ld/x86_64.o cmd/dev/ld/ld_support.o
+
+cmd/dev/ld/ld: $(LD_OBJ) shared/libaruuelf.so $(LIB)
+ $(CC) $(LDFLAGS) -o $@ $(LD_OBJ) -Lshared -laruuelf $(LIB) $(LDLIBS) -Wl,-rpath,'$$ORIGIN/../../../shared'
+
+AS_OBJ =\
+ cmd/dev/as/as.o\
+ cmd/dev/as/asm_lex.o\
+ cmd/dev/as/asm_parse.o\
+ cmd/dev/as/asm_x86_64.o\
+ cmd/dev/as/asm_elf.o
+
+cmd/dev/as/%.o: cmd/dev/as/%.c
+ $(CC) $(CPPFLAGS) -Icmd/dev/as -Ishared $(CFLAGS) -o $@ -c $<
+
+cmd/dev/as/as: $(AS_OBJ) $(LIB)
+ $(CC) $(LDFLAGS) -o $@ $(AS_OBJ) $(LIB) $(LDLIBS)
+
+cmd/dev/cc/driver.o: cmd/dev/cc/driver.c
+ $(CC) -Icmd/dev/cc $(CPPFLAGS) $(CFLAGS) -o $@ -c $<
+
+cmd/dev/cc/cc: cmd/dev/cc/driver.o cmd/dev/cc/util.o $(LIB) cmd/dev/cc/cc1 cmd/dev/cc/cpp cmd/dev/as/as
+ $(CC) $(LDFLAGS) -o $@ cmd/dev/cc/driver.o cmd/dev/cc/util.o $(LIB) $(LDLIBS)
+
+CC1_OBJ =\
+ cmd/dev/cc/attr.o\
+ cmd/dev/cc/decl.o\
+ cmd/dev/cc/eval.o\
+ cmd/dev/cc/expr.o\
+ cmd/dev/cc/init.o\
+ cmd/dev/cc/cc1.o\
+ cmd/dev/cc/map.o\
+ cmd/dev/cc/pp.o\
+ cmd/dev/cc/qbe.o\
+ cmd/dev/cc/scan.o\
+ cmd/dev/cc/scope.o\
+ cmd/dev/cc/stmt.o\
+ cmd/dev/cc/targ.o\
+ cmd/dev/cc/token.o\
+ cmd/dev/cc/tree.o\
+ cmd/dev/cc/type.o\
+ cmd/dev/cc/utf.o\
+ cmd/dev/cc/util.o
+
+CPP_OBJ =\
+ cmd/dev/cc/attr.o\
+ cmd/dev/cc/decl.o\
+ cmd/dev/cc/eval.o\
+ cmd/dev/cc/expr.o\
+ cmd/dev/cc/init.o\
+ cmd/dev/cc/map.o\
+ cmd/dev/cc/pp.o\
+ cmd/dev/cc/qbe.o\
+ cmd/dev/cc/scan.o\
+ cmd/dev/cc/scope.o\
+ cmd/dev/cc/stmt.o\
+ cmd/dev/cc/targ.o\
+ cmd/dev/cc/token.o\
+ cmd/dev/cc/tree.o\
+ cmd/dev/cc/type.o\
+ cmd/dev/cc/utf.o\
+ cmd/dev/cc/util.o
+
+cmd/dev/cc/%.o: cmd/dev/cc/%.c
+ $(CC) -Icmd/dev/cc $(CPPFLAGS) $(CFLAGS) -o $@ -c $<
+
+cmd/dev/cc/cc1: $(CC1_OBJ) $(LIB)
+ $(CC) $(LDFLAGS) -o $@ $(CC1_OBJ) $(LIB) $(LDLIBS)
+
+cmd/dev/cc/cpp: cmd/dev/cc/cpp.o $(CPP_OBJ) $(LIB)
+ $(CC) $(LDFLAGS) -o $@ cmd/dev/cc/cpp.o $(CPP_OBJ) $(LIB) $(LDLIBS)
+
+
+
+
+
diff --git a/Makefile.sh b/Makefile.sh
@@ -0,0 +1,522 @@
+#!/bin/sh
+# drives the build without needing a working make to bootstrap
+#
+set -e
+
+# per-run work directory, cleaned up on exit
+#
+WORKDIR="${TMPDIR:-/tmp}/aruu.$$"
+mkdir -p "$WORKDIR"
+trap 'rm -rf "$WORKDIR"' EXIT INT TERM HUP
+
+JOBS=1
+LOAD=0
+TARGET=all
+
+while [ $# -gt 0 ]; do
+ case "$1" in
+ -j) shift; JOBS="${1:?-j requires a number}" ;;
+ -j*) JOBS="${1#-j}" ;;
+ -l) shift; LOAD="${1:?-l requires a number}" ;;
+ -l*) LOAD="${1#-l}" ;;
+ -*) printf 'unknown flag: %s\n' "$1" >&2; exit 1 ;;
+ *) TARGET="$1" ;;
+ esac
+ shift
+done
+
+[ -f build.cfg ] || { printf 'build.cfg not found; see the repository README\n' >&2; exit 1; }
+# shellcheck disable=SC1091
+. ./build.cfg
+
+# cppflags derived from build.cfg; any feature_* added there is picked up automatically
+_feature_flags=""
+while IFS= read -r _line; do
+ _trimmed=$(printf '%s' "$_line" | tr -d ' \t')
+ case "$_trimmed" in
+ FEATURE_*=*)
+ _key=${_trimmed%%=*}
+ eval "_val=\$$_key"
+ _feature_flags="$_feature_flags -D${_key}=${_val}"
+ ;;
+ esac
+done <<EOF
+$(tr ';' '\n' < build.cfg)
+EOF
+unset _line _key _val _trimmed
+CPPFLAGS="-Ishared -DPREFIX=\"$PREFIX\" -D_DEFAULT_SOURCE -D_GNU_SOURCE -D_NETBSD_SOURCE -D_BSD_SOURCE -D_XOPEN_SOURCE=700 -D_FILE_OFFSET_BITS=64 -DSTD_NON_POSIX$_feature_flags"
+if [ "$FEATURE_USE_BEARSSL" = "1" ]; then
+ CPPFLAGS="$CPPFLAGS -IexternalRepos/BearSSL/inc"
+ LDFLAGS="$LDFLAGS -LexternalRepos/BearSSL/build"
+ LDLIBS="$LDLIBS externalRepos/BearSSL/build/libbearssl.a"
+fi
+if [ "$FEATURE_USE_LIBRESSL" = "1" ]; then
+ LDLIBS="$LDLIBS -ltls"
+fi
+unset _feature_flags
+
+CC=${CC:-cc}
+AR=${AR:-ar}
+ARFLAGS=${ARFLAGS:-rc}
+RANLIB=${RANLIB:-ranlib}
+PREFIX=${PREFIX:-/usr/local}
+MANPREFIX=${MANPREFIX:-$PREFIX/share/man}
+
+# shared headers; every object depends on these
+HDR=$(echo shared/*.h)
+LIB="shared/libredline/libredline.a shared/libutil/libutil.a shared/libutf/libutf.a"
+
+# set by multi-file builders for generated headers, cleared after use
+EXTRA_HDR=
+
+# timestamp comparison
+#
+mtime() {
+ stat -c '%Y' "$1" 2>/dev/null || stat -f '%m' "$1" 2>/dev/null || echo 0
+}
+
+newer_than() {
+ local s t
+ [ -e "$2" ] || return 0
+ s=$(mtime "$1"); t=$(mtime "$2")
+ [ "$s" -gt "$t" ]
+}
+
+any_newer_than() {
+ local target="$1"; shift
+ for src do
+ newer_than "$src" "$target" && return 0
+ done
+ return 1
+}
+
+# parallel job queue
+#
+# objs_for must not run in a subshell; enqueue writes _qn/_queue in the current shell
+
+_qn=0
+_queue=""
+_objs=""
+
+# wraps arg in single quotes, escaping embedded ones, for safe eval
+shquote() {
+ printf "'"
+ printf '%s' "$1" | sed "s/'/'\\\\''/g"
+ printf "'"
+}
+
+enqueue() {
+ local desc="$1" cmd="$2"
+ _qn=$((_qn + 1))
+ local s="$WORKDIR/j${_qn}.sh"
+ {
+ printf '#!/bin/sh\n'
+ printf 'printf "%%s\\n" %s\n' "$(shquote "$desc")"
+ printf 'eval %s\n' "$(shquote "$cmd")"
+ } > "$s"
+ _queue="$_queue $_qn"
+}
+
+# silently skipped on systems without /proc/loadavg
+_wait_for_load() {
+ [ "$LOAD" -eq 0 ] && return 0
+ local avg
+ while true; do
+ avg=$(awk '{printf "%d", int($1 + 0.5)}' /proc/loadavg 2>/dev/null) || return 0
+ [ "$avg" -le "$LOAD" ] && return 0
+ sleep 1
+ done
+}
+
+drain() {
+ [ -z "$_queue" ] && return 0
+ local n
+ _wait_for_load
+ if [ "$JOBS" -le 1 ]; then
+ for n in $_queue; do
+ sh "$WORKDIR/j${n}.sh" || { printf 'error: build step failed\n' >&2; exit 1; }
+ done
+ else
+ # xargs -P (POSIX 2024), -n 1 so each path becomes its own sh invocation
+ for n in $_queue; do
+ printf '%s\n' "$WORKDIR/j${n}.sh"
+ done | xargs -P "$JOBS" -n 1 sh || { printf 'error: build step failed\n' >&2; exit 1; }
+ fi
+ _queue=""
+}
+
+# compile and link primitives
+#
+compile_c() {
+ local src="$1" obj="$2"; shift 2
+ # shellcheck disable=SC2086
+ any_newer_than "$obj" "$src" $HDR $EXTRA_HDR || return 0
+ enqueue " CC $obj" "$CC $CPPFLAGS $* $CFLAGS -o $obj -c $src"
+}
+
+link_bin() {
+ local bin="$1" objs="" libs="" sep=0; shift
+ for a do
+ if [ "$a" = "--" ]; then sep=1
+ elif [ "$sep" = 0 ]; then objs="$objs $a"
+ else libs="$libs $a"
+ fi
+ done
+ drain
+ # shellcheck disable=SC2086
+ any_newer_than "$bin" $objs || return 0
+ printf ' LD %s\n' "$bin"
+ # shellcheck disable=SC2086
+ eval "$CC $LDFLAGS -o $bin $objs $libs $LDLIBS"
+}
+
+# writes to _objs rather than stdout so the caller avoids a subshell that
+# would discard enqueued jobs
+objs_for() {
+ local dir="$1" skip=" $2 " flags="$3" src base
+ _objs=""
+ for src in "$dir"/*.c; do
+ [ -f "$src" ] || continue
+ base=${src##*/}
+ case "$skip" in *" $base "*) continue ;; esac
+ compile_c "$src" "${src%.c}.o" $flags
+ _objs="$_objs ${src%.c}.o"
+ done
+}
+
+# static libraries
+#
+# both directories enqueued before the single drain so they compile in parallel
+build_lib() {
+ local utf_objs util_objs redline_objs
+ objs_for shared/libutf "" ""
+ utf_objs="$_objs"
+ objs_for shared/libutil "" ""
+ util_objs="$_objs"
+ objs_for shared/libredline "" ""
+ redline_objs="$_objs"
+ drain
+ # shellcheck disable=SC2086
+ any_newer_than shared/libutf/libutf.a $utf_objs && {
+ printf ' AR shared/libutf/libutf.a\n'
+ $AR $ARFLAGS shared/libutf/libutf.a $utf_objs
+ $RANLIB shared/libutf/libutf.a
+ }
+ # shellcheck disable=SC2086
+ any_newer_than shared/libutil/libutil.a $util_objs && {
+ printf ' AR shared/libutil/libutil.a\n'
+ $AR $ARFLAGS shared/libutil/libutil.a $util_objs
+ $RANLIB shared/libutil/libutil.a
+ }
+ # shellcheck disable=SC2086
+ any_newer_than shared/libredline/libredline.a $redline_objs && {
+ printf ' AR shared/libredline/libredline.a\n'
+ $AR $ARFLAGS shared/libredline/libredline.a $redline_objs
+ $RANLIB shared/libredline/libredline.a
+ }
+ return 0
+}
+
+# per-tool category builder
+#
+cfgvar() {
+ local cat="$1" base="$2"
+ [ "$cat" = extra ] && cat=pseudo
+ printf 'BUILD_%s_%s' "$cat" "$base" | tr 'a-z-' 'A-Z_'
+}
+
+# individual flag overrides group flag
+cfg_enabled() {
+ local _var="$1" _v
+ while [ -n "$_var" ]; do
+ eval "_v=\${${_var}-UNSET}"
+ if [ "$_v" = "1" ]; then
+ return 0
+ elif [ "$_v" = "0" ]; then
+ return 1
+ fi
+ case "$_var" in
+ *_[^_]*) _var=$(printf '%s' "$_var" | sed 's/_[^_]*$//') ;;
+ *) break ;;
+ esac
+ done
+ return 1
+}
+
+build_simple_tools() {
+ local cat="$1" src base var staged=""
+ for src in cmd/"$cat"/*.c; do
+ [ -f "$src" ] || continue
+ base=${src##*/}; base=${base%.c}
+ var=$(cfgvar "$cat" "$base")
+ cfg_enabled "$var" || continue
+ compile_c "$src" "${src%.c}.o"
+ staged="$staged ${src%.c}"
+ done
+ drain
+ local bin
+ for bin in $staged; do
+ link_bin "$bin" "${bin}.o" -- $LIB
+ done
+}
+
+# generated multi-file tools under cmd/posix
+#
+build_awk() {
+ cfg_enabled BUILD_POSIX_AWK || return 0
+ local dir=cmd/posix/awk
+
+ any_newer_than "$dir/awkgram.tab.c" "$dir/awkgram.y" && {
+ if command -v yacc >/dev/null 2>&1; then
+ printf ' YACC %s/awkgram.tab.c\n' "$dir"
+ yacc -d -o "$dir/awkgram.tab.c" "$dir/awkgram.y"
+ elif command -v bison >/dev/null 2>&1; then
+ printf ' BISON %s/awkgram.tab.c\n' "$dir"
+ bison -d -o "$dir/awkgram.tab.c" "$dir/awkgram.y"
+ else
+ printf 'awk: no yacc/bison; using pre-generated awkgram.tab.c\n' >&2
+ fi
+ }
+
+ any_newer_than "$dir/maketab" "$dir/maketab.c" "$dir/awkgram.tab.h" && {
+ printf ' CC %s/maketab\n' "$dir"
+ eval "$CC $CFLAGS -o $dir/maketab $dir/maketab.c"
+ }
+
+ any_newer_than "$dir/proctab.c" "$dir/maketab" && {
+ printf ' GEN %s/proctab.c\n' "$dir"
+ "$dir/maketab" "$dir/awkgram.tab.h" > "$dir/proctab.c"
+ }
+
+ EXTRA_HDR="$dir/awk.h $dir/awkgram.tab.h $dir/proto.h"
+ objs_for "$dir" maketab.c "-I$dir"
+ EXTRA_HDR=
+ link_bin "$dir/awk" $_objs -- $LIB -lm
+}
+
+build_sh() {
+ cfg_enabled BUILD_POSIX_SH || return 0
+ local dir=cmd/posix/sh
+
+ any_newer_than "$dir/mknodes" "$dir/mknodes.c" && {
+ printf ' CC %s/mknodes\n' "$dir"
+ eval "$CC $CFLAGS -o $dir/mknodes $dir/mknodes.c"
+ }
+
+ any_newer_than "$dir/mksyntax" "$dir/mksyntax.c" && {
+ printf ' CC %s/mksyntax\n' "$dir"
+ eval "$CC $CPPFLAGS -I$dir $CFLAGS -o $dir/mksyntax $dir/mksyntax.c"
+ }
+
+ any_newer_than "$dir/token.h" "$dir/mktokens" && {
+ printf ' GEN %s/token.h\n' "$dir"
+ (cd "$dir" && sh mktokens)
+ }
+
+ any_newer_than "$dir/syntax.c" "$dir/mksyntax" && {
+ printf ' GEN %s/syntax.c\n' "$dir"
+ (cd "$dir" && ./mksyntax)
+ }
+
+ any_newer_than "$dir/nodes.c" "$dir/mknodes" "$dir/nodetypes" "$dir/nodes.c.pat" && {
+ printf ' GEN %s/nodes.c\n' "$dir"
+ (cd "$dir" && ./mknodes nodetypes nodes.c.pat)
+ }
+
+ any_newer_than "$dir/builtins.c" "$dir/mkbuiltins" "$dir/builtins.def" "$dir/shell.h" && {
+ printf ' GEN %s/builtins.c\n' "$dir"
+ (cd "$dir" && sh mkbuiltins .)
+ }
+
+ EXTRA_HDR="$dir/syntax.h $dir/nodes.h $dir/builtins.h $dir/token.h"
+ objs_for "$dir" "mknodes.c mksyntax.c" "-DSHELL -I$dir"
+ EXTRA_HDR=
+ link_bin "$dir/sh" $_objs -- $LIB
+}
+
+build_make() {
+ cfg_enabled BUILD_POSIX_MAKE || return 0
+ local dir=cmd/posix/make
+ EXTRA_HDR="$dir/make.h"
+ objs_for "$dir" "" ""
+ EXTRA_HDR=
+ link_bin "$dir/make" $_objs -- $LIB
+}
+
+build_posix() {
+ cfg_enabled BUILD_POSIX_GETCONF && [ ! -f cmd/posix/getconf.h ] && {
+ printf ' GEN cmd/posix/getconf.h\n'
+ scripts/getconf.sh > cmd/posix/getconf.h || { rm -f cmd/posix/getconf.h; exit 1; }
+ }
+ build_simple_tools posix
+ build_awk
+ build_sh
+ build_make
+}
+
+# multi-file dev toolchain
+#
+build_ar() {
+ cfg_enabled BUILD_DEV_AR || return 0
+ local dir=cmd/dev/ar
+ objs_for "$dir" tinyar.c "-I$dir"
+ link_bin "$dir/ar" $_objs -- $LIB
+}
+
+build_as() {
+ cfg_enabled BUILD_DEV_AS || return 0
+ local dir=cmd/dev/as
+ objs_for "$dir" "" "-I$dir -Ishared"
+ link_bin "$dir/as" $_objs -- $LIB
+}
+
+# rpath embeds $ORIGIN so the installed ld finds libaruuelf.so next to itself
+build_ld() {
+ cfg_enabled BUILD_DEV_LD || return 0
+ local dir="cmd/dev/ld"
+ local cflags="-DLD_TARGET_X86_64 -I$dir -fPIC"
+ local src
+
+ for src in "$dir"/*.c; do
+ compile_c "$src" "${src%.c}.o" $cflags
+ done
+ drain
+
+ any_newer_than shared/libaruuelf.so "$dir/elf.o" "$dir/x86_64.o" "$dir/ld_support.o" && {
+ printf ' LD shared/libaruuelf.so\n'
+ eval "$CC $LDFLAGS -shared -o shared/libaruuelf.so $dir/elf.o $dir/x86_64.o $dir/ld_support.o"
+ }
+
+ any_newer_than "$dir/ld" "$dir/ld.o" shared/libaruuelf.so && {
+ printf ' LD %s/ld\n' "$dir"
+ # $ORIGIN is a dynamic-linker token, not a shell variable
+ eval "$CC $LDFLAGS -o $dir/ld $dir/ld.o -Lshared -laruuelf $LIB $LDLIBS -Wl,-rpath,'\$ORIGIN/../../../shared'"
+ }
+ return 0
+}
+
+build_cc() {
+ cfg_enabled BUILD_DEV_CC || return 0
+ local dir="cmd/dev/cc"
+ local cflags="-I$dir"
+ local common
+
+ # compiled once, linked into both cc1 and cpp
+ objs_for "$dir" "driver.c cc1.c cpp.c" "$cflags"
+ common="$_objs"
+ drain
+
+ compile_c "$dir/cc1.c" "$dir/cc1.o" $cflags
+ compile_c "$dir/cpp.c" "$dir/cpp.o" $cflags
+ compile_c "$dir/driver.c" "$dir/driver.o" $cflags
+ drain
+
+ link_bin "$dir/cc1" "$dir/cc1.o" $common -- $LIB
+ link_bin "$dir/cpp" "$dir/cpp.o" $common -- $LIB
+ link_bin "$dir/cc" "$dir/driver.o" "$dir/util.o" -- $LIB
+}
+
+build_dev() {
+ build_ar
+ build_as
+ build_ld
+ build_cc
+}
+
+# manual page generation
+#
+man_section() {
+ case "$1" in
+ */linux/*|*/net/*|*/xsi/*) printf '8\n' ;;
+ *) printf '1\n' ;;
+ esac
+}
+
+build_man_for() {
+ local var="$1" src="$2" base sec out
+ cfg_enabled "$var" || return 0
+ [ -x scripts/mkman/mkman ] || { printf 'error: mkman not built\n' >&2; exit 1; }
+ base=${src##*/}; base=${base%.c}
+ sec=$(man_section "$src")
+ out="man/man${sec}/${base}.${sec}"
+ mkdir -p "man/man${sec}"
+ any_newer_than "$out" "$src" build.cfg scripts/mkman/mkman || return 0
+ printf ' MAN %s\n' "$out"
+ scripts/mkman/mkman -config build.cfg -section "$sec" "$src" > "$out"
+}
+
+build_man() {
+ local dir cat src base
+ if [ ! -x scripts/mkman/mkman ] || any_newer_than scripts/mkman/mkman scripts/mkman/main.go scripts/mkman/troff.go; then
+ printf ' GO scripts/mkman/mkman\n'
+ (cd scripts/mkman && go build -o mkman .)
+ fi
+ for dir in cmd/*; do
+ [ -d "$dir" ] || continue
+ cat=${dir##*/}
+ for src in "$dir"/*.c; do
+ [ -f "$src" ] || continue
+ base=${src##*/}; base=${base%.c}
+ build_man_for "$(cfgvar "$cat" "$base")" "$src"
+ done
+ done
+}
+
+# install and clean
+#
+do_install() {
+ local bin f sec
+ mkdir -p "$PREFIX/bin" "$MANPREFIX/man1" "$MANPREFIX/man8"
+ find cmd -type f ! -name '*.*' -perm -100 | while read -r bin; do
+ printf ' INSTALL %s/bin/%s\n' "$PREFIX" "${bin##*/}"
+ cp "$bin" "$PREFIX/bin/${bin##*/}"
+ chmod 755 "$PREFIX/bin/${bin##*/}"
+ done
+ find man/man1 man/man8 -type f -name '*.[18]' 2>/dev/null | while read -r f; do
+ sec=${f%/*}; sec=${sec##*/}
+ cp "$f" "$MANPREFIX/${sec}/${f##*/}"
+ done
+}
+
+do_clean() {
+ find shared cmd -name '*.o' -exec rm -f {} +
+ find shared -name '*.a' -exec rm -f {} +
+ find cmd -type f ! -name '*.*' -perm -100 -exec rm -f {} +
+ rm -f shared/libaruuelf.so
+ rm -f cmd/posix/bc.c cmd/posix/getconf.h
+ rm -f cmd/posix/awk/maketab cmd/posix/awk/proctab.c
+ rm -f cmd/posix/awk/awkgram.tab.c cmd/posix/awk/awkgram.tab.h
+ rm -f cmd/posix/sh/mknodes cmd/posix/sh/mksyntax
+ rm -f cmd/posix/sh/token.h cmd/posix/sh/syntax.c cmd/posix/sh/syntax.h
+ rm -f cmd/posix/sh/nodes.c cmd/posix/sh/nodes.h
+ rm -f cmd/posix/sh/builtins.c cmd/posix/sh/builtins.h
+ rm -rf man/man1 man/man8
+ rm -rf aruu-box .box
+ rm -f scripts/mkman/mkman
+}
+
+case "$TARGET" in
+ all)
+ build_lib
+ build_posix
+ build_dev
+ build_simple_tools linux
+ build_simple_tools net
+ build_simple_tools xsi
+ build_simple_tools pseudo
+ build_simple_tools extra
+ ;;
+ lib) build_lib ;;
+ posix) build_lib; build_posix ;;
+ dev) build_lib; build_dev ;;
+ make) build_lib; build_make ;;
+ linux|net|xsi|pseudo|extra)
+ build_lib; build_simple_tools "$TARGET" ;;
+ man) build_man ;;
+ install) do_install ;;
+ clean) do_clean ;;
+ *)
+ printf 'usage: sh Makefile.sh [-jN] [-lN] [all|clean|install|man|lib|posix|linux|net|xsi|pseudo|extra|dev|make]\n' >&2
+ exit 1
+ ;;
+esac
diff --git a/README b/README
@@ -177,8 +177,8 @@ Copyright (c) 2016 Eivind Uggedal [eivind@uggedal.com](mailto:eivind@uggedal.com
Copyright (c) 2016 Mattias Andrée [m@maandree.se](mailto:m@maandree.se)
Copyright (c) 2026 xplshn [anto@xplshn.com.ar](mailto:anto@xplshn.com.ar) (https://github.com/xplshn)
-Portions of this software (specifically utils under net/) are partially
-based on code written by Rob Landley
+Portions of this software (specifically utils under net/) are partially based on code written by Rob Landley
+Our line editing library is partially based on work by Salvatore Sanfilippo (linenoise) and JC Wang (crossline)
The rest are based on SBASE/UBASE source code
=~= Argentino Roca Unix Utilities =~= https://github.com/xplshn/aruu =~=
diff --git a/build.cfg b/build.cfg
@@ -0,0 +1,124 @@
+# posix: POSIX 2024 only common: uncontroversial extras all: everything except external libs
+PRESET_FEATURES=all
+
+# subset of: posix linux net xsi pseudo dev
+PRESET_UTILS="posix linux net xsi pseudo"
+
+# installation paths
+VERSION=2026-06-08T05-53-UTC-03
+PREFIX=/usr/local
+MANPREFIX=/usr/local/share/man
+
+# toolchain
+CC=cc
+CFLAGS="-std=c99 -Wall -Wextra -pedantic"
+LDFLAGS=""
+LDLIBS="-lcrypt -lresolv"
+AR=ar
+ARFLAGS="rc"
+RANLIB=ranlib
+
+# --- preset expansion: do not edit below ---
+
+case "$PRESET_FEATURES" in
+posix)
+ FEATURE_FIND_DELETE=0; FEATURE_FIND_QUIT=0
+ FEATURE_FIND_EMPTY=0; FEATURE_FIND_INUM=0
+ FEATURE_FIND_SAMEFILE=0; FEATURE_FIND_MAXDEPTH=0
+ FEATURE_FIND_MINDEPTH=0; FEATURE_FIND_MMIN=0
+ FEATURE_FIND_AMIN=0; FEATURE_FIND_CMIN=0
+ FEATURE_FIND_INAME=0; FEATURE_FIND_IPATH=0
+ FEATURE_FIND_REGEX=0; FEATURE_FIND_PRINT0=0
+ FEATURE_SED_INPLACE=0; FEATURE_SED_PRESERVE_NEWLINE=0
+ FEATURE_GREP_CONTEXT=0; FEATURE_GREP_MAX_COUNT=0
+ FEATURE_TAR_CREATE=0; FEATURE_TAR_EXCLUDE=0
+ FEATURE_STAT_FILESYSTEM=0; FEATURE_STAT_FORMAT=0
+ FEATURE_SORT_BIG=0; FEATURE_SORT_STABLE=0
+ FEATURE_OD_ENDIAN=0;
+ FEATURE_SH_HISTEDIT=0; FEATURE_SH_LOCAL=0
+ FEATURE_SH_LET=0; FEATURE_SH_ULIMIT=0
+ FEATURE_SH_SETVAR=0; FEATURE_SH_WORDEXP=0
+ FEATURE_CAL_EXT=0
+ FEATURE_LS_COLOR=0
+ FEATURE_MODPROBE_SHOW_DEPENDS=0; FEATURE_MODPROBE_BLACKLIST=0
+ FEATURE_MODPROBE_SYSLOG=0; FEATURE_MODPROBE_DIR_OVERRIDE=0
+ FEATURE_DEPMOD_ALIAS=0; FEATURE_DEPMOD_SYMBOLS=0
+ ;;
+common)
+ FEATURE_FIND_DELETE=1; FEATURE_FIND_QUIT=1
+ FEATURE_FIND_EMPTY=1; FEATURE_FIND_INUM=1
+ FEATURE_FIND_SAMEFILE=1; FEATURE_FIND_MAXDEPTH=1
+ FEATURE_FIND_MINDEPTH=1; FEATURE_FIND_MMIN=1
+ FEATURE_FIND_AMIN=1; FEATURE_FIND_CMIN=1
+ FEATURE_FIND_INAME=1; FEATURE_FIND_IPATH=1
+ FEATURE_FIND_REGEX=1; FEATURE_FIND_PRINT0=1
+ FEATURE_SED_INPLACE=1; FEATURE_SED_PRESERVE_NEWLINE=1
+ FEATURE_GREP_CONTEXT=1; FEATURE_GREP_MAX_COUNT=1
+ FEATURE_TAR_CREATE=1; FEATURE_TAR_EXCLUDE=1
+ FEATURE_STAT_FILESYSTEM=1; FEATURE_STAT_FORMAT=1
+ FEATURE_SORT_BIG=0; FEATURE_SORT_STABLE=1
+ FEATURE_OD_ENDIAN=0;
+ FEATURE_SH_HISTEDIT=0; FEATURE_SH_LOCAL=1
+ FEATURE_SH_LET=1; FEATURE_SH_ULIMIT=1
+ FEATURE_SH_SETVAR=0; FEATURE_SH_WORDEXP=0
+ FEATURE_CAL_EXT=1
+ FEATURE_LS_COLOR=1
+ FEATURE_MODPROBE_SHOW_DEPENDS=1; FEATURE_MODPROBE_BLACKLIST=1
+ FEATURE_MODPROBE_SYSLOG=1; FEATURE_MODPROBE_DIR_OVERRIDE=1
+ FEATURE_DEPMOD_ALIAS=1; FEATURE_DEPMOD_SYMBOLS=1
+ ;;
+all)
+ # histedit now included via redline
+ FEATURE_FIND_DELETE=1; FEATURE_FIND_QUIT=1
+ FEATURE_FIND_EMPTY=1; FEATURE_FIND_INUM=1
+ FEATURE_FIND_SAMEFILE=1; FEATURE_FIND_MAXDEPTH=1
+ FEATURE_FIND_MINDEPTH=1; FEATURE_FIND_MMIN=1
+ FEATURE_FIND_AMIN=1; FEATURE_FIND_CMIN=1
+ FEATURE_FIND_INAME=1; FEATURE_FIND_IPATH=1
+ FEATURE_FIND_REGEX=1; FEATURE_FIND_PRINT0=1
+ FEATURE_SED_INPLACE=1; FEATURE_SED_PRESERVE_NEWLINE=1
+ FEATURE_GREP_CONTEXT=1; FEATURE_GREP_MAX_COUNT=1
+ FEATURE_TAR_CREATE=1; FEATURE_TAR_EXCLUDE=1
+ FEATURE_STAT_FILESYSTEM=1; FEATURE_STAT_FORMAT=1
+ FEATURE_SORT_BIG=1; FEATURE_SORT_STABLE=1
+ FEATURE_OD_ENDIAN=1;
+ FEATURE_SH_HISTEDIT=1; FEATURE_SH_LOCAL=1
+ FEATURE_SH_LET=1; FEATURE_SH_ULIMIT=1
+ FEATURE_SH_SETVAR=1; FEATURE_SH_WORDEXP=1
+ FEATURE_CAL_EXT=1
+ FEATURE_LS_COLOR=1
+ FEATURE_MODPROBE_SHOW_DEPENDS=1; FEATURE_MODPROBE_BLACKLIST=1
+ FEATURE_MODPROBE_SYSLOG=1; FEATURE_MODPROBE_DIR_OVERRIDE=1
+ FEATURE_DEPMOD_ALIAS=1; FEATURE_DEPMOD_SYMBOLS=1
+ ;;
+*)
+ printf 'build.cfg: unknown PRESET_FEATURES value: %s\n' "$PRESET_FEATURES" >&2
+ return 1 2>/dev/null || exit 1
+ ;;
+esac
+
+BUILD_POSIX=0; BUILD_LINUX=0; BUILD_NET=0; BUILD_XSI=0
+BUILD_PSEUDO=0; BUILD_DEV=0
+for _p in $PRESET_UTILS; do
+ case "$_p" in
+ posix) BUILD_POSIX=1 ;;
+ linux) BUILD_LINUX=1 ;;
+ net) BUILD_NET=1 ;;
+ xsi) BUILD_XSI=1 ;;
+ pseudo) BUILD_PSEUDO=1 ;;
+ dev) BUILD_DEV=1 ;;
+ *)
+ printf 'build.cfg: unknown util preset: %s\n' "$_p" >&2
+ return 1 2>/dev/null || exit 1
+ ;;
+ esac
+done
+unset _p
+
+# --- per-item overrides (after preset expansion) ---
+# BUILD_POSIX_SH=0 # disable a tool when its group is active
+# BUILD_DEV_AS=1 # enable a tool whose group isnt in PRESET_UTILS
+FEATURE_SH_HISTEDIT=1
+FEATURE_USE_LIBRESSL=0
+FEATURE_USE_BEARSSL=1
+# FEATURE_MY_NEW_THING=1 # new FEATURE_* are picked up by Makefile.sh automatically
diff --git a/cmd/extra/b3sum.c b/cmd/extra/b3sum.c
@@ -1,4 +1,10 @@
/* See LICENSE file for copyright and license details. */
+/* ?man
+b3sum: compute blake3 checksums
+usage: b3sum [-bct] [-l length] [file ...]
+
+compute and check blake3 message digests
+*/
#include "util.h"
#include "arg.h"
@@ -3972,17 +3978,21 @@ main(int argc, char *argv[])
int ret = 0;
ARGBEGIN {
+ // ?man -b: read in binary mode
case 'b':
mode = "rb";
break;
+ // ?man -c: check blake3 sums from file
case 'c':
func = check;
break;
+ // ?man -l length: output digest length in bytes
case 'l':
outlen = strtoul(EARGF(usage()), &end, 10);
if (*end)
usage();
break;
+ // ?man -t: read in text mode
case 't':
mode = "r";
break;
diff --git a/cmd/linux/blkdiscard.c b/cmd/linux/blkdiscard.c
@@ -1,4 +1,11 @@
/* See LICENSE file for copyright and license details. */
+/* ?man
+blkdiscard: discard sectors on a device
+usage: blkdiscard device
+
+discard sectors on a block device
+*/
+
#include <sys/ioctl.h>
#include <sys/mount.h>
#include <sys/stat.h>
diff --git a/cmd/linux/chvt.c b/cmd/linux/chvt.c
@@ -1,4 +1,11 @@
/* See LICENSE file for copyright and license details. */
+/* ?man
+chvt: change foreground virtual terminal
+usage: chvt num
+
+change the active virtual terminal
+*/
+
#include <sys/ioctl.h>
#include <sys/types.h>
diff --git a/cmd/linux/ctrlaltdel.c b/cmd/linux/ctrlaltdel.c
@@ -1,4 +1,11 @@
/* See LICENSE file for copyright and license details. */
+/* ?man
+ctrlaltdel: set ctrl-alt-del function
+usage: ctrlaltdel -h | -s
+
+set the behavior of the ctrl-alt-del key combination
+*/
+
#include <sys/syscall.h>
#include <stdio.h>
@@ -19,9 +26,11 @@ main(int argc, char *argv[])
int hflag = 0, sflag = 0, cmd;
ARGBEGIN {
+ // ?man -h: suppress headers or print help
case 'h':
hflag = 1;
break;
+ // ?man -s: silent mode or print summary
case 's':
sflag = 1;
break;
diff --git a/cmd/linux/dmesg.c b/cmd/linux/dmesg.c
@@ -1,81 +0,0 @@
-/* See LICENSE file for copyright and license details. */
-#include <sys/klog.h>
-
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <unistd.h>
-
-#include "util.h"
-
-enum {
- SYSLOG_ACTION_READ_ALL = 3,
- SYSLOG_ACTION_CLEAR = 5,
- SYSLOG_ACTION_CONSOLE_LEVEL = 8,
- SYSLOG_ACTION_SIZE_BUFFER = 10
-};
-
-static void
-dmesg_show(const void *buf, size_t n)
-{
- const char *p = buf;
- ssize_t r;
-
- r = write(1, p, n);
- if (r < 0)
- eprintf("write:");
- if (r > 0 && p[r - 1] != '\n')
- putchar('\n');
-}
-
-static void
-usage(void)
-{
- eprintf("usage: %s [-Ccr] [-n level]\n", argv0);
-}
-
-int
-main(int argc, char *argv[])
-{
- int n;
- char *buf;
- int cflag = 0;
- long level;
-
- ARGBEGIN {
- case 'C':
- if (klogctl(SYSLOG_ACTION_CLEAR, NULL, 0) < 0)
- eprintf("klogctl:");
- return 0;
- case 'c':
- cflag = 1;
- break;
- case 'r':
- break;
- case 'n':
- level = estrtol(EARGF(usage()), 10);
- if (klogctl(SYSLOG_ACTION_CONSOLE_LEVEL, NULL, level) < 0)
- eprintf("klogctl:");
- return 0;
- default:
- usage();
- } ARGEND;
-
- n = klogctl(SYSLOG_ACTION_SIZE_BUFFER, NULL, 0);
- if (n < 0)
- eprintf("klogctl:");
-
- buf = emalloc(n);
-
- n = klogctl(SYSLOG_ACTION_READ_ALL, buf, n);
- if (n < 0)
- eprintf("klogctl:");
-
- dmesg_show(buf, n);
-
- if (cflag && klogctl(SYSLOG_ACTION_CLEAR, NULL, 0) < 0)
- eprintf("klogctl:");
-
- free(buf);
- return 0;
-}
-\ No newline at end of file
diff --git a/cmd/linux/eject.c b/cmd/linux/eject.c
@@ -1,4 +1,11 @@
/* See LICENSE file for copyright and license details. */
+/* ?man
+eject: eject removable media
+usage: eject [-t] [device ...]
+
+eject optical discs or other removable storage media
+*/
+
#include <sys/ioctl.h>
#include <sys/stat.h>
#include <sys/types.h>
@@ -50,6 +57,7 @@ int
main(int argc, char *argv[])
{
ARGBEGIN {
+ // ?man -t: sort or specify timestamp
case 't':
tflag = 1;
break;
diff --git a/cmd/linux/fallocate.c b/cmd/linux/fallocate.c
@@ -1,55 +0,0 @@
-/* See LICENSE file for copyright and license details. */
-#include <sys/stat.h>
-
-#include <fcntl.h>
-#include <limits.h>
-#include <stdint.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <unistd.h>
-
-#include "util.h"
-
-static void
-usage(void)
-{
- eprintf("usage: %s [-o num] -l num file ...\n", argv0);
-}
-
-int
-main(int argc, char *argv[])
-{
- int fd, ret = 0;
- off_t size = 0, offset = 0;
-
- ARGBEGIN {
- case 'l':
- size = estrtonum(EARGF(usage()), 1, MIN((unsigned long long)LLONG_MAX, (unsigned long long)SIZE_MAX));
- break;
- case 'o':
- offset = estrtonum(EARGF(usage()), 0, MIN((unsigned long long)LLONG_MAX, (unsigned long long)SIZE_MAX));
- break;
- default:
- usage();
- } ARGEND;
-
- if (!argc || !size)
- usage();
-
- for (; *argv; argc--, argv++) {
- if ((fd = open(*argv, O_RDWR | O_CREAT, 0644)) < 0) {
- weprintf("open %s:", *argv);
- ret = 1;
- } else if (posix_fallocate(fd, offset, size) < 0) {
- weprintf("posix_fallocate %s:", *argv);
- ret = 1;
- }
-
- if (fd >= 0 && close(fd) < 0) {
- weprintf("close %s:", *argv);
- ret = 1;
- }
- }
-
- return ret;
-}
diff --git a/cmd/linux/free.c b/cmd/linux/free.c
@@ -1,72 +0,0 @@
-/* See LICENSE file for copyright and license details. */
-#include <sys/sysinfo.h>
-
-#include <stdio.h>
-#include <stdlib.h>
-
-#include "util.h"
-
-static unsigned int mem_unit = 1;
-static unsigned int unit_shift;
-
-static unsigned long long
-scale(unsigned long long v)
-{
- return (v * mem_unit) >> unit_shift;
-}
-
-static void
-usage(void)
-{
- eprintf("usage: %s [-bkmg]\n", argv0);
-}
-
-int
-main(int argc, char *argv[])
-{
- struct sysinfo info;
-
- if (sysinfo(&info) < 0)
- eprintf("sysinfo:");
- mem_unit = info.mem_unit ? info.mem_unit : 1;
-
- ARGBEGIN {
- case 'b':
- unit_shift = 0;
- break;
- case 'k':
- unit_shift = 10;
- break;
- case 'm':
- unit_shift = 20;
- break;
- case 'g':
- unit_shift = 30;
- break;
- default:
- usage();
- } ARGEND;
-
- printf(" %13s%13s%13s%13s%13s\n",
- "total",
- "used",
- "free",
- "shared", "buffers");
- printf("Mem: ");
- printf("%13llu%13llu%13llu%13llu%13llu\n",
- scale(info.totalram),
- scale(info.totalram - info.freeram),
- scale(info.freeram),
- scale(info.sharedram),
- scale(info.bufferram));
- printf("-/+ buffers/cache:");
- printf("%13llu%13llu\n",
- scale(info.totalram - info.freeram - info.bufferram),
- scale(info.freeram + info.bufferram));
- printf("Swap:");
- printf("%13llu%13llu%13llu\n",
- scale(info.totalswap),
- scale(info.totalswap - info.freeswap),
- scale(info.freeswap));
- return 0;
-}
diff --git a/cmd/linux/freeramdisk.c b/cmd/linux/freeramdisk.c
@@ -1,4 +1,11 @@
/* See LICENSE file for copyright and license details. */
+/* ?man
+freeramdisk: free ramdisk memory
+usage: freeramdisk
+
+free memory associated with a ramdisk device
+*/
+
#include <sys/ioctl.h>
#include <sys/mount.h>
#include <sys/types.h>
diff --git a/cmd/linux/fsfreeze.c b/cmd/linux/fsfreeze.c
@@ -1,4 +1,11 @@
/* See LICENSE file for copyright and license details. */
+/* ?man
+fsfreeze: suspend access to a filesystem
+usage: fsfreeze (-f | -u) mountpoint
+
+freeze or unfreeze a filesystem to allow safe backups
+*/
+
#include <sys/ioctl.h>
#include <sys/stat.h>
#include <sys/types.h>
@@ -28,9 +35,11 @@ main(int argc, char *argv[])
int fd;
ARGBEGIN {
+ // ?man -f: force the operation
case 'f':
fflag = 1;
break;
+ // ?man -u: unbuffered output
case 'u':
uflag = 1;
break;
diff --git a/cmd/linux/hwclock.c b/cmd/linux/hwclock.c
@@ -1,4 +1,11 @@
/* See LICENSE file for copyright and license details. */
+/* ?man
+hwclock: query or set the hardware clock
+usage: hwclock [-rsw] [-u] [dev]
+
+view or adjust the hardware real time clock
+*/
+
#include <sys/ioctl.h>
#include <sys/stat.h>
#include <sys/time.h>
@@ -121,15 +128,19 @@ main(int argc, char *argv[])
int wflag = 0;
ARGBEGIN {
+ // ?man -r: operate recursively
case 'r':
rflag = 1;
break;
+ // ?man -s: silent mode or print summary
case 's':
sflag = 1;
break;
+ // ?man -w: wait for completion
case 'w':
wflag = 1;
break;
+ // ?man -u: unbuffered output
case 'u':
break;
default:
diff --git a/cmd/linux/insmod.c b/cmd/linux/insmod.c
@@ -1,4 +1,9 @@
-/* See LICENSE file for copyright and license details. */
+/* ?man
+insmod: insert a module into the Linux kernel
+usage: insmod filename [args...]
+
+insmod inserts a kernel module from filename into the running kernel
+*/
#include <sys/stat.h>
#include <sys/syscall.h>
diff --git a/cmd/linux/lsmod.c b/cmd/linux/lsmod.c
@@ -1,4 +1,9 @@
-/* See LICENSE file for copyright and license details. */
+/* ?man
+lsmod: show the status of modules in the Linux kernel
+usage: lsmod
+
+lsmod formats and displays /proc/modules, showing currently loaded modules
+*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
diff --git a/cmd/linux/lsusb.c b/cmd/linux/lsusb.c
@@ -1,4 +1,11 @@
/* See LICENSE file for copyright and license details. */
+/* ?man
+lsusb: list usb devices
+usage: lsusb
+
+display information about usb buses and connected devices
+*/
+
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
diff --git a/cmd/linux/mkswap.c b/cmd/linux/mkswap.c
@@ -1,4 +1,11 @@
/* See LICENSE file for copyright and license details. */
+/* ?man
+mkswap: set up a swap area
+usage: mkswap device
+
+initialize a linux swap area on a device or file
+*/
+
#include <sys/stat.h>
#include <fcntl.h>
diff --git a/cmd/linux/mount.c b/cmd/linux/mount.c
@@ -1,4 +1,11 @@
/* See LICENSE file for copyright and license details. */
+/* ?man
+mount: mount a filesystem
+usage: mount [-BMRan] [-t fstype] [-o options] [source] [target]
+
+mount a filesystem to the directory tree
+*/
+
#include <sys/mount.h>
#include <sys/stat.h>
#include <sys/types.h>
@@ -200,25 +207,32 @@ main(int argc, char *argv[])
FILE *fp;
ARGBEGIN {
+ // ?man -B: specify option flag
case 'B':
argflags |= MS_BIND;
break;
+ // ?man -M: specify option flag
case 'M':
argflags |= MS_MOVE;
break;
+ // ?man -R: operate recursively on directories
case 'R':
argflags |= MS_REC;
break;
+ // ?man -a: print or show all entries
case 'a':
aflag = 1;
break;
+ // ?man -o: specify output file
case 'o':
estrlcat(fsopts, EARGF(usage()), sizeof(fsopts));
parseopts(fsopts, &flags, data, sizeof(data));
break;
+ // ?man -t: sort or specify timestamp
case 't':
types = EARGF(usage());
break;
+ // ?man -n: print line numbers or counts
case 'n':
break;
default:
diff --git a/cmd/linux/mountpoint.c b/cmd/linux/mountpoint.c
@@ -1,4 +1,11 @@
/* See LICENSE file for copyright and license details. */
+/* ?man
+mountpoint: check if a directory is a mountpoint
+usage: mountpoint [-dqx] target
+
+determine if a directory is a mountpoint
+*/
+
#include <sys/stat.h>
#include <sys/sysmacros.h>
#include <sys/types.h>
@@ -27,12 +34,15 @@ main(int argc, char *argv[])
struct stat st1, st2;
ARGBEGIN {
+ // ?man -d: specify directory
case 'd':
dflag = 1;
break;
+ // ?man -q: quiet mode; suppress output
case 'q':
qflag = 1;
break;
+ // ?man -x: hex format or match whole lines
case 'x':
xflag = 1;
break;
diff --git a/cmd/linux/pidof.c b/cmd/linux/pidof.c
@@ -1,116 +0,0 @@
-/* See LICENSE file for copyright and license details. */
-#include <sys/types.h>
-
-#include <dirent.h>
-#include <libgen.h>
-#include <limits.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <unistd.h>
-
-#include "proc.h"
-#include "queue.h"
-#include "util.h"
-
-struct pidentry {
- pid_t pid;
- SLIST_ENTRY(pidentry) entry;
-};
-
-static SLIST_HEAD(, pidentry) omitpid_head;
-
-static void
-usage(void)
-{
- eprintf("usage: %s [-o pid1,pid2,...pidN] [-s] [program...]\n", argv0);
-}
-
-int
-main(int argc, char *argv[])
-{
- DIR *dp;
- struct dirent *entry;
- pid_t pid;
- struct procstat ps;
- char cmdline[BUFSIZ], *cmd, *cmdbase = NULL, *p, *arg = NULL;
- int i, found = 0;
- int sflag = 0, oflag = 0;
- struct pidentry *pe;
-
- ARGBEGIN {
- case 's':
- sflag = 1;
- break;
- case 'o':
- oflag = 1;
- arg = EARGF(usage());
- break;
- default:
- usage();
- } ARGEND;
-
- if (!argc)
- return 1;
-
- SLIST_INIT(&omitpid_head);
-
- if (oflag) {
- for (p = strtok(arg, ","); p; p = strtok(NULL, ",")) {
- pe = emalloc(sizeof(*pe));
- if (strcmp(p, "%PPID") == 0)
- pe->pid = getppid();
- else
- pe->pid = estrtol(p, 10);
- SLIST_INSERT_HEAD(&omitpid_head, pe, entry);
- }
- }
-
- if (!(dp = opendir("/proc")))
- eprintf("opendir /proc:");
-
- while ((entry = readdir(dp))) {
- if (!pidfile(entry->d_name))
- continue;
- pid = estrtol(entry->d_name, 10);
- if (oflag) {
- SLIST_FOREACH(pe, &omitpid_head, entry)
- if (pe->pid == pid)
- break;
- if (pe)
- continue;
- }
- if (parsestat(pid, &ps) < 0)
- continue;
- if (parsecmdline(ps.pid, cmdline,
- sizeof(cmdline)) < 0) {
- cmd = ps.comm;
- cmdbase = cmd;
- } else {
- if ((p = strchr(cmdline, ' ')))
- *p = '\0';
- cmd = cmdline;
- cmdbase = basename(cmdline);
- }
- /* Workaround for login shells */
- if (cmd[0] == '-')
- cmd++;
- for (i = 0; i < argc; i++) {
- if (strcmp(cmd, argv[i]) == 0 ||
- strcmp(cmdbase, argv[i]) == 0) {
- putword(stdout, entry->d_name);
- found++;
- if (sflag)
- goto out;
- }
- }
- }
-
-out:
- if (found)
- putchar('\n');
-
- closedir(dp);
-
- return found ? 0 : 1;
-}
diff --git a/cmd/linux/pivot_root.c b/cmd/linux/pivot_root.c
@@ -1,4 +1,11 @@
/* See LICENSE file for copyright and license details. */
+/* ?man
+pivot_root: change the root filesystem
+usage: pivot_root new-root put-old
+
+change the root filesystem of the current process
+*/
+
#include <sys/syscall.h>
#include <stdio.h>
diff --git a/cmd/linux/pwdx.c b/cmd/linux/pwdx.c
@@ -1,51 +0,0 @@
-/* See LICENSE file for copyright and license details. */
-#include <errno.h>
-#include <limits.h>
-#include <stdio.h>
-#include <string.h>
-#include <unistd.h>
-
-#include "util.h"
-
-static void
-usage(void)
-{
- eprintf("usage: %s pid...\n", argv0);
-}
-
-int
-main(int argc, char *argv[])
-{
- int ret = 0;
- char path[PATH_MAX];
- char target[PATH_MAX + sizeof(" (deleted)")];
- ssize_t n;
-
- ARGBEGIN {
- default:
- usage();
- } ARGEND;
-
- if (argc == 0)
- usage();
-
- for (; argc > 0; argc--, argv++) {
- n = snprintf(path, sizeof(path), "/proc/%s/cwd", *argv);
- if (n < 0 || (size_t)n >= sizeof(path)) {
- errno = ESRCH;
- } else {
- n = readlink(path, target, sizeof(target) - 1);
- if (n >= 0) {
- target[n] = '\0';
- printf("%s: %s\n", *argv, target);
- continue;
- }
- }
- if (errno == ENOENT)
- errno = ESRCH;
- weprintf("%s:", *argv);
- ret = 1;
- }
-
- return ret;
-}
diff --git a/cmd/linux/readahead.c b/cmd/linux/readahead.c
@@ -1,4 +1,11 @@
/* See LICENSE file for copyright and license details. */
+/* ?man
+readahead: read files into page cache
+usage: readahead file...
+
+preload file contents into the page cache
+*/
+
#include <fcntl.h>
#include <limits.h>
#include <stdio.h>
diff --git a/cmd/linux/rmmod.c b/cmd/linux/rmmod.c
@@ -1,4 +1,12 @@
-/* See LICENSE file for copyright and license details. */
+/* ?man
+rmmod: remove a module from the Linux kernel
+usage: rmmod [-fw] module...
+
+rmmod removes a kernel module from the running kernel
+
+// ?man -f: force removal of a module even if it is busy or in use
+// ?man -w: wait for the module to become unused before removing
+*/
#include <sys/syscall.h>
#include <fcntl.h>
diff --git a/cmd/linux/swaplabel.c b/cmd/linux/swaplabel.c
@@ -1,4 +1,11 @@
/* See LICENSE file for copyright and license details. */
+/* ?man
+swaplabel: print or change swap label
+usage: swaplabel [-L label] device
+
+display or modify the label and uuid of a swap device
+*/
+
#include <sys/types.h>
#include <fcntl.h>
@@ -33,6 +40,7 @@ main(int argc, char *argv[])
int i;
ARGBEGIN {
+ // ?man -L: specify option flag
case 'L':
setlabel = 1;
label = EARGF(usage());
diff --git a/cmd/linux/swapoff.c b/cmd/linux/swapoff.c
@@ -1,4 +1,11 @@
/* See LICENSE file for copyright and license details. */
+/* ?man
+swapoff: disable swap devices
+usage: swapoff -a | device
+
+disable paging and swapping on specified devices
+*/
+
#include <sys/swap.h>
#include <mntent.h>
@@ -24,6 +31,7 @@ main(int argc, char *argv[])
FILE *fp;
ARGBEGIN {
+ // ?man -a: print or show all entries
case 'a':
all = 1;
break;
diff --git a/cmd/linux/swapon.c b/cmd/linux/swapon.c
@@ -1,4 +1,11 @@
/* See LICENSE file for copyright and license details. */
+/* ?man
+swapon: enable swap devices
+usage: swapon [-dp] -a | device
+
+enable paging and swapping on specified devices
+*/
+
#include <sys/swap.h>
#include <mntent.h>
@@ -25,12 +32,15 @@ main(int argc, char *argv[])
FILE *fp;
ARGBEGIN {
+ // ?man -a: print or show all entries
case 'a':
all = 1;
break;
+ // ?man -d: specify directory
case 'd':
flags |= SWAP_FLAG_DISCARD;
break;
+ // ?man -p: preserve file attributes
case 'p':
flags |= SWAP_FLAG_PREFER;
break;
diff --git a/cmd/linux/switch_root.c b/cmd/linux/switch_root.c
@@ -1,4 +1,11 @@
/* See LICENSE file for copyright and license details. */
+/* ?man
+switch_root: switch to another root filesystem
+usage: switch_root [-c console] [newroot] [init] (PID 1)
+
+switch to another filesystem as the root of the mount tree
+*/
+
#include <sys/mount.h>
#include <sys/stat.h>
#include <sys/vfs.h>
@@ -73,6 +80,7 @@ main(int argc, char *argv[])
struct statfs stfs;
ARGBEGIN {
+ // ?man -c: print count or perform stdout action
case 'c':
console = EARGF(usage());
break;
diff --git a/cmd/linux/sysctl.c b/cmd/linux/sysctl.c
@@ -1,4 +1,11 @@
/* See LICENSE file for copyright and license details. */
+/* ?man
+sysctl: configure kernel parameters
+usage: sysctl [-p file] variable[=value]...
+
+view and modify kernel parameters at runtime
+*/
+
#include <fcntl.h>
#include <limits.h>
#include <stdio.h>
@@ -169,6 +176,7 @@ main(int argc, char *argv[])
int r = 0;
ARGBEGIN {
+ // ?man -p: preserve file attributes
case 'p':
file = EARGF(usage());
break;
diff --git a/cmd/linux/tunctl.c b/cmd/linux/tunctl.c
@@ -0,0 +1,109 @@
+/* See LICENSE file for copyright and license details. */
+/* ?man
+tunctl: configure tun/tap interfaces
+usage: tunctl [-dtT] [-u owner] [device]
+
+create or destroy tun/tap network interfaces
+*/
+
+#include <sys/ioctl.h>
+#include <sys/socket.h>
+#include <sys/stat.h>
+#include <sys/types.h>
+
+#include <fcntl.h>
+#include <limits.h>
+#include <pwd.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+
+#include <linux/if.h>
+#include <linux/if_tun.h>
+
+#include "util.h"
+
+static int dflag;
+static int tflag = 1;
+static int Tflag;
+static char *owner;
+
+static void
+usage(void)
+{
+ eprintf("usage: %s [-dtT] [-u owner] [device]\n", argv0);
+}
+
+int
+main(int argc, char *argv[])
+{
+ struct ifreq ifr;
+ struct passwd *pw;
+ uid_t owner_uid = 0;
+ int fd;
+
+ ARGBEGIN
+ {
+ // ?man -d: specify directory
+ case 'd':
+ dflag = 1;
+ tflag = 0;
+ break;
+ // ?man -t: sort or specify timestamp
+ case 't':
+ tflag = 1;
+ dflag = 0;
+ break;
+ // ?man -T: specify option flag
+ case 'T':
+ Tflag = 1;
+ break;
+ // ?man -u: unbuffered output
+ case 'u':
+ owner = EARGF(usage());
+ break;
+ default:
+ usage();
+ }
+ ARGEND
+
+ if (owner) {
+ pw = getpwnam(owner);
+ if (!pw)
+ owner_uid = estrtonum(owner, 0, UINT_MAX);
+ else
+ owner_uid = pw->pw_uid;
+ }
+
+ fd = open("/dev/net/tun", O_RDWR);
+ if (fd < 0)
+ eprintf("open /dev/net/tun:");
+
+ memset(&ifr, 0, sizeof(ifr));
+ ifr.ifr_flags = (Tflag ? IFF_TAP : IFF_TUN) | IFF_NO_PI;
+
+ if (argc > 0)
+ estrlcpy(ifr.ifr_name, argv[0], sizeof(ifr.ifr_name));
+
+ if (ioctl(fd, TUNSETIFF, (void *)&ifr) < 0)
+ eprintf("ioctl TUNSETIFF:");
+
+ if (tflag) {
+ if (ioctl(fd, TUNSETPERSIST, (void *)1) < 0)
+ eprintf("ioctl TUNSETPERSIST:");
+ if (owner) {
+ if (ioctl(fd, TUNSETOWNER, (void *)(long)owner_uid) < 0)
+ eprintf("ioctl TUNSETOWNER:");
+ }
+ printf("Set '%s' persistent and owned by %u\n", ifr.ifr_name,
+ owner_uid);
+ } else if (dflag) {
+ if (ioctl(fd, TUNSETPERSIST, (void *)0) < 0)
+ eprintf("ioctl TUNSETPERSIST:");
+ printf("Set '%s' non-persistent\n", ifr.ifr_name);
+ }
+
+ close(fd);
+ return 0;
+}
diff --git a/cmd/linux/umount.c b/cmd/linux/umount.c
@@ -1,4 +1,11 @@
/* See LICENSE file for copyright and license details. */
+/* ?man
+umount: unmount filesystems
+usage: umount [-lfn] [-O options] target...
+
+unmount a filesystem from the directory tree
+*/
+
#include <sys/mount.h>
#include <mntent.h>
@@ -135,18 +142,23 @@ main(int argc, char *argv[])
#endif
ARGBEGIN {
+ // ?man -a: print or show all entries
case 'a':
aflag = 1;
break;
+ // ?man -f: force the operation
case 'f':
flags |= MNT_FORCE;
break;
+ // ?man -l: list in long format
case 'l':
flags |= MNT_DETACH;
break;
+ // ?man -n: print line numbers or counts
case 'n':
break;
#ifdef STD_NON_POSIX
+ // ?man -O: specify option flag
case 'O':
oflag = EARGF(usage());
break;
diff --git a/cmd/linux/unshare.c b/cmd/linux/unshare.c
@@ -1,4 +1,11 @@
/* See LICENSE file for copyright and license details. */
+/* ?man
+unshare: run program in new namespaces
+usage: unshare [-muinpU] cmd [args...]
+
+run a program with some namespaces unshared from the parent
+*/
+
#include <sched.h>
#include <stdio.h>
#include <stdlib.h>
@@ -19,21 +26,27 @@ main(int argc, char *argv[])
int flags = 0;
ARGBEGIN {
+ // ?man -m: specify mode or limit
case 'm':
flags |= CLONE_NEWNS;
break;
+ // ?man -u: unbuffered output
case 'u':
flags |= CLONE_NEWUTS;
break;
+ // ?man -i: interactive mode or prompt for confirmation
case 'i':
flags |= CLONE_NEWIPC;
break;
+ // ?man -n: print line numbers or counts
case 'n':
flags |= CLONE_NEWNET;
break;
+ // ?man -p: preserve file attributes
case 'p':
flags |= CLONE_NEWPID;
break;
+ // ?man -U: specify option flag
case 'U':
flags |= CLONE_NEWUSER;
break;
diff --git a/cmd/linux/uptime.c b/cmd/linux/uptime.c
@@ -1,73 +0,0 @@
-/* See LICENSE file for copyright and license details. */
-#include <sys/sysinfo.h>
-
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <time.h>
-#include <utmpx.h>
-
-#include "config.h"
-#include "util.h"
-
-static void
-usage(void)
-{
- eprintf("usage: %s\n", argv0);
-}
-
-int
-main(int argc, char *argv[])
-{
- struct utmpx utx;
- FILE *ufp;
- struct sysinfo info;
- time_t tmptime;
- struct tm *now;
- unsigned int days, hours, minutes;
- int nusers = 0;
- size_t n;
-
- ARGBEGIN {
- default:
- usage();
- } ARGEND;
-
- if (sysinfo(&info) < 0)
- eprintf("sysinfo:");
- time(&tmptime);
- now = localtime(&tmptime);
- printf(" %02d:%02d:%02d up ", now->tm_hour, now->tm_min, now->tm_sec);
- info.uptime /= 60;
- minutes = info.uptime % 60;
- info.uptime /= 60;
- hours = info.uptime % 24;
- days = info.uptime / 24;
- if (days)
- printf("%d day%s, ", days, days != 1 ? "s" : "");
- if (hours)
- printf("%2d:%02d, ", hours, minutes);
- else
- printf("%d min, ", minutes);
-
- if ((ufp = fopen(UTMP_PATH, "r"))) {
- while ((n = fread(&utx, sizeof(utx), 1, ufp)) > 0) {
- if (!utx.ut_user[0])
- continue;
- if (utx.ut_type != USER_PROCESS)
- continue;
- nusers++;
- }
- if (ferror(ufp))
- eprintf("%s: read error:", UTMP_PATH);
- fclose(ufp);
- printf(" %d user%s, ", nusers, nusers != 1 ? "s" : "");
- }
-
- printf(" load average: %.02f, %.02f, %.02f\n",
- info.loads[0] / 65536.0f,
- info.loads[1] / 65536.0f,
- info.loads[2] / 65536.0f);
-
- return 0;
-}
diff --git a/cmd/linux/vtallow.c b/cmd/linux/vtallow.c
@@ -1,4 +1,11 @@
/* See LICENSE file for copyright and license details. */
+/* ?man
+vtallow: allow non-root vt access
+usage: vtallow n | y
+
+allow non-root users to access virtual terminal devices
+*/
+
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/ioctl.h>
diff --git a/cmd/net/host.c b/cmd/net/host.c
@@ -1,4 +1,11 @@
/* See LICENSE file for copyright and license details. */
+/* ?man
+host: dns lookup utility
+usage: host [-t type] name [server]
+
+look up hostnames and IP addresses using dns
+*/
+
#include "util.h"
#include "arg.h"
@@ -269,6 +276,7 @@ main(int argc, char *argv[])
int i, r;
ARGBEGIN {
+ // ?man -t: sort or specify timestamp
case 't':
tflag = EARGF(usage());
break;
diff --git a/cmd/net/httpd.c b/cmd/net/httpd.c
@@ -1,4 +1,11 @@
/* See LICENSE file for copyright and license details. */
+/* ?man
+httpd: simple http daemon
+usage: httpd [-e string] [-d string] [-v] [dir]
+
+serve static files over http
+*/
+
#include "util.h"
#include "arg.h"
@@ -257,12 +264,15 @@ main(int argc, char *argv[])
char *enc;
ARGBEGIN {
+ // ?man -e: specify expression or pattern
case 'e':
eflag = EARGF(usage());
break;
+ // ?man -d: specify directory
case 'd':
dflag = EARGF(usage());
break;
+ // ?man -v: verbose mode; show progress
case 'v':
break;
default:
diff --git a/cmd/net/ifconfig.c b/cmd/net/ifconfig.c
@@ -1,13 +1,15 @@
/* See LICENSE file for copyright and license details. */
-#include "util.h"
-#include "arg.h"
+/* ?man
+ifconfig: configure network interfaces
+usage: ifconfig [-a] [interface [action ...]]
+
+configure network interface parameters and view stats
+*/
#include <arpa/inet.h>
#include <ctype.h>
#include <errno.h>
#include <net/if.h>
-#include <net/if_arp.h>
-#include <netinet/in.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
@@ -16,6 +18,12 @@
#include <sys/types.h>
#include <unistd.h>
+#include "util.h"
+
+int net_get_interfaces(struct NetInterface **, int *);
+int net_get_stats(const char *, struct NetStats *);
+int net_set_txqueuelen(const char *, int);
+
static void
usage(void)
{
@@ -23,200 +31,82 @@ usage(void)
}
static void
-print_ipv6(const char *name)
+display_interface(const struct NetInterface *iface)
{
- FILE *fp = fopen("/proc/net/if_inet6", "r");
- char line[256];
- char addr_hex[40];
- char ifname[IFNAMSIZ];
- unsigned int ifindex, plen, scope, flags;
- int i, j;
- char ipv6_str[40];
- const char *scope_str;
-
- if (!fp)
- return;
-
- while (fgets(line, sizeof(line), fp)) {
- if (sscanf(line, "%32s %x %x %x %x %15s", addr_hex, &ifindex, &plen, &scope, &flags, ifname) == 6) {
- if (strcmp(name, ifname) == 0) {
- j = 0;
- for (i = 0; i < 32; i++) {
- ipv6_str[j++] = addr_hex[i];
- if (i > 0 && i < 31 && (i % 4 == 3))
- ipv6_str[j++] = ':';
- }
- ipv6_str[j] = '\0';
-
- scope_str = "Unknown";
- switch (scope) {
- case 0x00: scope_str = "Global"; break;
- case 0x10: scope_str = "Host"; break;
- case 0x20: scope_str = "Link"; break;
- case 0x40: scope_str = "Site"; break;
- case 0x80: scope_str = "Compat"; break;
- }
- printf(" inet6 addr: %s/%d Scope:%s\n", ipv6_str, plen, scope_str);
- }
- }
- }
- fclose(fp);
-}
-
-static void
-display_interface(int sock, const char *name)
-{
- struct ifreq ifr;
- struct sockaddr_in *sin;
- unsigned char *hwaddr;
- FILE *fp;
- char line[256];
- char *p, *ifname;
- short flags;
- int mtu = 0;
- int metric = 0;
- unsigned long long rx_bytes, rx_packets, rx_errs, rx_drop;
- unsigned long long tx_bytes, tx_packets, tx_errs, tx_drop;
-
- memset(&ifr, 0, sizeof(ifr));
- strncpy(ifr.ifr_name, name, IFNAMSIZ - 1);
-
- if (ioctl(sock, SIOCGIFFLAGS, &ifr) < 0) {
- weprintf("ioctl SIOCGIFFLAGS %s:\n", name);
- return;
- }
- flags = ifr.ifr_flags;
-
- printf("%-9s ", name);
-
- if (ioctl(sock, SIOCGIFHWADDR, &ifr) >= 0) {
- hwaddr = (unsigned char *)ifr.ifr_hwaddr.sa_data;
- printf("Link encap:");
- switch (ifr.ifr_hwaddr.sa_family) {
- case ARPHRD_ETHER:
- printf("Ethernet HWaddr %02x:%02x:%02x:%02x:%02x:%02x\n",
- hwaddr[0], hwaddr[1], hwaddr[2], hwaddr[3], hwaddr[4], hwaddr[5]);
- break;
- case ARPHRD_LOOPBACK:
- printf("Local Loopback\n");
- break;
- default:
- printf("UNSPEC\n");
- break;
- }
+ struct NetStats stats;
+ char ipv6_str[INET6_ADDRSTRLEN];
+
+ printf("%-9s Link encap:", iface->name);
+ if (iface->has_mac) {
+ printf("Ethernet HWaddr %02x:%02x:%02x:%02x:%02x:%02x\n",
+ iface->mac[0], iface->mac[1], iface->mac[2],
+ iface->mac[3], iface->mac[4], iface->mac[5]);
+ } else if (iface->flags & IFF_LOOPBACK) {
+ printf("Local Loopback\n");
} else {
- printf("Link encap:UNSPEC\n");
+ printf("UNSPEC\n");
}
- memset(&ifr, 0, sizeof(ifr));
- strncpy(ifr.ifr_name, name, IFNAMSIZ - 1);
- if (ioctl(sock, SIOCGIFADDR, &ifr) >= 0) {
- sin = (struct sockaddr_in *)&ifr.ifr_addr;
- printf(" inet addr:%s", inet_ntoa(sin->sin_addr));
-
- memset(&ifr, 0, sizeof(ifr));
- strncpy(ifr.ifr_name, name, IFNAMSIZ - 1);
- if (ioctl(sock, SIOCGIFBRDADDR, &ifr) >= 0) {
- sin = (struct sockaddr_in *)&ifr.ifr_broadaddr;
- printf(" Bcast:%s", inet_ntoa(sin->sin_addr));
- }
+ if (iface->has_ipv4) {
+ printf(" inet addr:%s", inet_ntoa(iface->ipv4_addr.sin_addr));
+ printf(" Bcast:%s", inet_ntoa(iface->ipv4_brd.sin_addr));
+ printf(" Mask:%s\n", inet_ntoa(iface->ipv4_mask.sin_addr));
+ }
- memset(&ifr, 0, sizeof(ifr));
- strncpy(ifr.ifr_name, name, IFNAMSIZ - 1);
- if (ioctl(sock, SIOCGIFNETMASK, &ifr) >= 0) {
- sin = (struct sockaddr_in *)&ifr.ifr_netmask;
- printf(" Mask:%s", inet_ntoa(sin->sin_addr));
+ if (iface->has_ipv6) {
+ if (inet_ntop(AF_INET6, &iface->ipv6_addr.sin6_addr, ipv6_str, sizeof(ipv6_str))) {
+ printf(" inet6 addr: %s\n", ipv6_str);
}
- printf("\n");
}
- print_ipv6(name);
-
printf(" ");
- if (flags & IFF_UP) printf("UP ");
- if (flags & IFF_BROADCAST) printf("BROADCAST ");
- if (flags & IFF_DEBUG) printf("DEBUG ");
- if (flags & IFF_LOOPBACK) printf("LOOPBACK ");
- if (flags & IFF_POINTOPOINT) printf("POINTOPOINT ");
- if (flags & IFF_RUNNING) printf("RUNNING ");
- if (flags & IFF_NOARP) printf("NOARP ");
- if (flags & IFF_PROMISC) printf("PROMISC ");
- if (flags & IFF_ALLMULTI) printf("ALLMULTI ");
- if (flags & IFF_MULTICAST) printf("MULTICAST ");
-
- memset(&ifr, 0, sizeof(ifr));
- strncpy(ifr.ifr_name, name, IFNAMSIZ - 1);
- if (ioctl(sock, SIOCGIFMTU, &ifr) >= 0)
- mtu = ifr.ifr_mtu;
- if (ioctl(sock, SIOCGIFMETRIC, &ifr) >= 0)
- metric = ifr.ifr_metric;
- printf(" MTU:%d Metric:%d\n", mtu, metric);
-
- fp = fopen("/proc/net/dev", "r");
- if (fp) {
- while (fgets(line, sizeof(line), fp)) {
- p = strchr(line, ':');
- if (p) {
- *p = '\0';
- ifname = line;
- while (isspace(*ifname))
- ifname++;
- if (strcmp(ifname, name) == 0) {
- if (sscanf(p + 1, "%llu %llu %llu %llu %*u %*u %*u %*u %llu %llu %llu %llu",
- &rx_bytes, &rx_packets, &rx_errs, &rx_drop,
- &tx_bytes, &tx_packets, &tx_errs, &tx_drop) == 8) {
- printf(" RX packets:%llu errors:%llu dropped:%llu overruns:0 frame:0\n",
- rx_packets, rx_errs, rx_drop);
- printf(" TX packets:%llu errors:%llu dropped:%llu overruns:0 carrier:0\n",
- tx_packets, tx_errs, tx_drop);
- printf(" RX bytes:%llu TX bytes:%llu\n", rx_bytes, tx_bytes);
- }
- break;
- }
- }
- }
- fclose(fp);
+ if (iface->flags & IFF_UP) printf("UP ");
+ if (iface->flags & IFF_BROADCAST) printf("BROADCAST ");
+ if (iface->flags & IFF_DEBUG) printf("DEBUG ");
+ if (iface->flags & IFF_LOOPBACK) printf("LOOPBACK ");
+ if (iface->flags & IFF_POINTOPOINT) printf("POINTOPOINT ");
+ if (iface->flags & IFF_RUNNING) printf("RUNNING ");
+ if (iface->flags & IFF_NOARP) printf("NOARP ");
+ if (iface->flags & IFF_PROMISC) printf("PROMISC ");
+ if (iface->flags & IFF_ALLMULTI) printf("ALLMULTI ");
+ if (iface->flags & IFF_MULTICAST) printf("MULTICAST ");
+
+ printf(" MTU:%d Metric:%d\n", iface->mtu, iface->metric);
+
+ if (net_get_stats(iface->name, &stats) >= 0) {
+ printf(" RX packets:%llu errors:%llu dropped:%llu overruns:0 frame:0\n",
+ stats.rx_packets, stats.rx_errs, stats.rx_drop);
+ printf(" TX packets:%llu errors:%llu dropped:%llu overruns:0 carrier:0\n",
+ stats.tx_packets, stats.tx_errs, stats.tx_drop);
+ printf(" RX bytes:%llu TX bytes:%llu\n",
+ stats.rx_bytes, stats.tx_bytes);
}
printf("\n");
}
static void
-list_interfaces(int sock, int all)
+list_interfaces(int all)
{
- FILE *fp = fopen("/proc/net/dev", "r");
- struct ifreq ifr;
- char line[256];
- char *p, *name;
- int line_num = 0;
-
- if (!fp)
- eprintf("fopen /proc/net/dev:\n");
-
- while (fgets(line, sizeof(line), fp)) {
- line_num++;
- if (line_num <= 2)
- continue;
- p = strchr(line, ':');
- if (p) {
- *p = '\0';
- name = line;
- while (isspace(*name))
- name++;
- memset(&ifr, 0, sizeof(ifr));
- strncpy(ifr.ifr_name, name, IFNAMSIZ - 1);
- if (ioctl(sock, SIOCGIFFLAGS, &ifr) >= 0) {
- if (all || (ifr.ifr_flags & IFF_UP)) {
- display_interface(sock, name);
- }
- }
+ struct NetInterface *ifaces = NULL;
+ int count = 0;
+ int i;
+
+ if (net_get_interfaces(&ifaces, &count) < 0)
+ eprintf("net_get_interfaces:");
+
+ for (i = 0; i < count; i++) {
+ if (all || (ifaces[i].flags & IFF_UP)) {
+ display_interface(&ifaces[i]);
}
}
- fclose(fp);
+ free(ifaces);
}
int
main(int argc, char *argv[])
{
+ struct NetInterface *ifaces = NULL;
+ const struct NetInterface *iface = NULL;
struct ifreq ifr;
struct sockaddr_in *sin;
char *name;
@@ -226,9 +116,11 @@ main(int argc, char *argv[])
int sock = -1;
int i = 1;
int prefix;
+ int count = 0;
unsigned int mask;
ARGBEGIN {
+ // ?man -a: print or show all entries
case 'a':
aflag = 1;
break;
@@ -236,26 +128,37 @@ main(int argc, char *argv[])
usage();
} ARGEND
- sock = socket(AF_INET, SOCK_DGRAM, 0);
- if (sock < 0)
- eprintf("socket:\n");
-
if (argc == 0) {
- list_interfaces(sock, aflag);
- close(sock);
+ list_interfaces(aflag);
return 0;
}
name = argv[0];
+ if (net_get_interfaces(&ifaces, &count) < 0)
+ eprintf("net_get_interfaces:");
+
+ for (prefix = 0; prefix < count; prefix++) {
+ if (strcmp(ifaces[prefix].name, name) == 0) {
+ iface = &ifaces[prefix];
+ break;
+ }
+ }
+
if (argc == 1) {
- display_interface(sock, name);
- close(sock);
+ if (!iface)
+ eprintf("interface %s not found\n", name);
+ display_interface(iface);
+ free(ifaces);
return 0;
}
+ sock = socket(AF_INET, SOCK_DGRAM, 0);
+ if (sock < 0)
+ eprintf("socket:");
+
memset(&ifr, 0, sizeof(ifr));
- strncpy(ifr.ifr_name, name, IFNAMSIZ - 1);
+ strlcpy(ifr.ifr_name, name, sizeof(ifr.ifr_name));
while (i < argc) {
arg = argv[i];
@@ -301,8 +204,8 @@ main(int argc, char *argv[])
i += 2;
} else if (strcmp(arg, "txqueuelen") == 0) {
if (i + 1 >= argc) eprintf("txqueuelen needs a value\n");
- ifr.ifr_qlen = atoi(argv[i + 1]);
- if (ioctl(sock, SIOCSIFTXQLEN, &ifr) < 0) eprintf("ioctl SIOCSIFTXQLEN:");
+ if (net_set_txqueuelen(name, atoi(argv[i + 1])) < 0)
+ eprintf("net_set_txqueuelen:");
i += 2;
} else if (strcmp(arg, "dstaddr") == 0 || strcmp(arg, "pointopoint") == 0) {
if (i + 1 >= argc) eprintf("%s needs an address\n", arg);
@@ -387,6 +290,11 @@ main(int argc, char *argv[])
}
}
+ free(ifaces);
close(sock);
+
+ if (fshut(stdin, "<stdin>") | fshut(stdout, "<stdout>"))
+ return 1;
+
return 0;
}
diff --git a/cmd/net/ip.c b/cmd/net/ip.c
@@ -0,0 +1,269 @@
+/* See LICENSE file for copyright and license details. */
+/* ?man
+ip: show or configure routing and devices
+usage: ip [addr | link | route] [args...]
+
+configure and view network devices, routing, and tunnels
+*/
+
+#include <arpa/inet.h>
+#include <ctype.h>
+#include <errno.h>
+#include <net/if.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/socket.h>
+#include <sys/types.h>
+#include <unistd.h>
+
+#include "util.h"
+
+int net_get_interfaces(struct NetInterface **, int *);
+int net_get_stats(const char *, struct NetStats *);
+int net_set_flags(const char *, unsigned int, int);
+int net_set_mtu(const char *, int);
+int net_set_mac(const char *, const unsigned char *);
+int net_add_addr(const char *, const char *, int);
+int net_del_addr(const char *, const char *, int);
+int net_show_routes(void);
+
+static void
+usage(void)
+{
+ eprintf("usage: %s [addr | link | route] [args...]\n", argv0);
+}
+
+static void
+parse_mac(const char *str, unsigned char mac[6])
+{
+ unsigned int val;
+ int i;
+ const char *p = str;
+
+ for (i = 0; i < 6; i++) {
+ if (i > 0) {
+ if (*p != ':')
+ eprintf("invalid mac address: %s\n", str);
+ p++;
+ }
+ if (sscanf(p, "%2x", &val) != 1)
+ eprintf("invalid mac address: %s\n", str);
+ mac[i] = val;
+ p += 2;
+ }
+}
+
+static void
+print_link_iface(const struct NetInterface *iface)
+{
+ printf("%d: %s: mtu %d ", iface->metric, iface->name, iface->mtu);
+ if (iface->flags & IFF_UP) printf("UP ");
+ if (iface->flags & IFF_LOOPBACK) printf("LOOPBACK ");
+ if (iface->flags & IFF_POINTOPOINT) printf("POINTOPOINT ");
+ if (iface->flags & IFF_RUNNING) printf("RUNNING ");
+ printf("\n");
+ if (iface->has_mac) {
+ printf(" link/ether %02x:%02x:%02x:%02x:%02x:%02x\n",
+ iface->mac[0], iface->mac[1], iface->mac[2],
+ iface->mac[3], iface->mac[4], iface->mac[5]);
+ }
+}
+
+static void
+print_addr_iface(const struct NetInterface *iface)
+{
+ char ipv6_str[INET6_ADDRSTRLEN];
+
+ print_link_iface(iface);
+ if (iface->has_ipv4) {
+ printf(" inet %s netmask %s\n",
+ inet_ntoa(iface->ipv4_addr.sin_addr),
+ inet_ntoa(iface->ipv4_mask.sin_addr));
+ }
+ if (iface->has_ipv6) {
+ if (inet_ntop(AF_INET6, &iface->ipv6_addr.sin6_addr, ipv6_str, sizeof(ipv6_str))) {
+ printf(" inet6 %s\n", ipv6_str);
+ }
+ }
+}
+
+static int
+do_addr(int argc, char *argv[])
+{
+ struct NetInterface *ifaces = NULL;
+ char *cmd, *ip, *dev, *slash;
+ int count = 0;
+ int prefix = -1;
+ int i, r;
+
+ if (argc == 0)
+ cmd = "show";
+ else
+ cmd = argv[0];
+
+ if (strcmp(cmd, "show") == 0 || strcmp(cmd, "list") == 0) {
+ dev = NULL;
+ if (argc > 1) {
+ if (strcmp(argv[1], "dev") == 0 && argc > 2)
+ dev = argv[2];
+ else
+ dev = argv[1];
+ }
+ if (net_get_interfaces(&ifaces, &count) < 0)
+ eprintf("net_get_interfaces:");
+ for (i = 0; i < count; i++) {
+ if (!dev || strcmp(ifaces[i].name, dev) == 0)
+ print_addr_iface(&ifaces[i]);
+ }
+ free(ifaces);
+ return 0;
+ }
+
+ if (strcmp(cmd, "add") == 0 || strcmp(cmd, "del") == 0) {
+ if (argc < 4)
+ eprintf("usage: ip addr %s <ip>/<prefix> dev <interface>\n", cmd);
+ ip = argv[1];
+ dev = NULL;
+ for (i = 2; i < argc; i++) {
+ if (strcmp(argv[i], "dev") == 0 && i + 1 < argc) {
+ dev = argv[i + 1];
+ break;
+ }
+ }
+ if (!dev)
+ eprintf("missing dev parameter\n");
+
+ slash = strchr(ip, '/');
+ if (slash) {
+ *slash = '\0';
+ prefix = atoi(slash + 1);
+ }
+
+ if (strcmp(cmd, "add") == 0)
+ r = net_add_addr(dev, ip, prefix);
+ else
+ r = net_del_addr(dev, ip, prefix);
+
+ if (r < 0)
+ eprintf("net_%s_addr:", cmd);
+ return 0;
+ }
+
+ usage();
+ return 1;
+}
+
+static int
+do_link(int argc, char *argv[])
+{
+ struct NetInterface *ifaces = NULL;
+ char *cmd, *dev, *mac_str;
+ int count = 0;
+ int i, mtu;
+ unsigned char mac[6];
+
+ if (argc == 0)
+ cmd = "show";
+ else
+ cmd = argv[0];
+
+ if (strcmp(cmd, "show") == 0 || strcmp(cmd, "list") == 0) {
+ dev = NULL;
+ if (argc > 1) {
+ if (strcmp(argv[1], "dev") == 0 && argc > 2)
+ dev = argv[2];
+ else
+ dev = argv[1];
+ }
+ if (net_get_interfaces(&ifaces, &count) < 0)
+ eprintf("net_get_interfaces:");
+ for (i = 0; i < count; i++) {
+ if (!dev || strcmp(ifaces[i].name, dev) == 0)
+ print_link_iface(&ifaces[i]);
+ }
+ free(ifaces);
+ return 0;
+ }
+
+ if (strcmp(cmd, "set") == 0) {
+ if (argc < 3)
+ eprintf("usage: ip link set <interface> [up | down | mtu <mtu> | address <mac>]\n");
+ dev = argv[1];
+ for (i = 2; i < argc; i++) {
+ if (strcmp(argv[i], "up") == 0) {
+ if (net_set_flags(dev, IFF_UP, 1) < 0)
+ eprintf("net_set_flags up:");
+ } else if (strcmp(argv[i], "down") == 0) {
+ if (net_set_flags(dev, IFF_UP, 0) < 0)
+ eprintf("net_set_flags down:");
+ } else if (strcmp(argv[i], "mtu") == 0 && i + 1 < argc) {
+ mtu = atoi(argv[i + 1]);
+ if (net_set_mtu(dev, mtu) < 0)
+ eprintf("net_set_mtu:");
+ i++;
+ } else if (strcmp(argv[i], "address") == 0 && i + 1 < argc) {
+ mac_str = argv[i + 1];
+ parse_mac(mac_str, mac);
+ if (net_set_mac(dev, mac) < 0)
+ eprintf("net_set_mac:");
+ i++;
+ }
+ }
+ return 0;
+ }
+
+ usage();
+ return 1;
+}
+
+static int
+do_route(int argc, char *argv[])
+{
+ char *cmd;
+
+ if (argc == 0)
+ cmd = "show";
+ else
+ cmd = argv[0];
+
+ if (strcmp(cmd, "show") == 0 || strcmp(cmd, "list") == 0) {
+ if (net_show_routes() < 0)
+ eprintf("net_show_routes:");
+ return 0;
+ }
+
+ usage();
+ return 1;
+}
+
+int
+main(int argc, char *argv[])
+{
+ char *obj;
+
+ ARGBEGIN {
+ default:
+ usage();
+ } ARGEND
+
+ if (argc == 0)
+ usage();
+
+ obj = argv[0];
+
+ if (strcmp(obj, "addr") == 0 || strcmp(obj, "address") == 0) {
+ return do_addr(argc - 1, argv + 1);
+ } else if (strcmp(obj, "link") == 0) {
+ return do_link(argc - 1, argv + 1);
+ } else if (strcmp(obj, "route") == 0) {
+ return do_route(argc - 1, argv + 1);
+ }
+
+ usage();
+
+ if (fshut(stdin, "<stdin>") | fshut(stdout, "<stdout>"))
+ return 1;
+
+ return 0;
+}
diff --git a/cmd/net/netcat.c b/cmd/net/netcat.c
@@ -1,4 +1,11 @@
/* See LICENSE file for copyright and license details. */
+/* ?man
+netcat: read and write data across network connections
+usage: netcat [-lu] [-p localport] [host] [port]
+
+arbitrary data transmission over tcp or udp
+*/
+
#include <sys/socket.h>
#include <sys/types.h>
@@ -65,12 +72,15 @@ main(int argc, char *argv[])
ARGBEGIN
{
+ // ?man -l: list in long format
case 'l':
lflag = 1;
break;
+ // ?man -p: preserve file attributes
case 'p':
local_port = EARGF(usage());
break;
+ // ?man -u: unbuffered output
case 'u':
uflag = 1;
break;
diff --git a/cmd/net/ping.c b/cmd/net/ping.c
@@ -1,4 +1,11 @@
/* See LICENSE file for copyright and license details. */
+/* ?man
+ping: send icmp echo requests
+usage: ping [-c count] [-i interval] [-s size] [-t ttl] [-w deadline] [-q] host
+
+send icmp echo requests to verify network connectivity
+*/
+
#include "util.h"
#include "arg.h"
@@ -136,21 +143,27 @@ main(int argc, char *argv[])
socklen_t fromlen;
ARGBEGIN {
+ // ?man -c: print count or perform stdout action
case 'c':
cflag = EARGF(usage());
break;
+ // ?man -i: interactive mode or prompt for confirmation
case 'i':
iflag = EARGF(usage());
break;
+ // ?man -s: silent mode or print summary
case 's':
sflag = EARGF(usage());
break;
+ // ?man -t: sort or specify timestamp
case 't':
tflag = EARGF(usage());
break;
+ // ?man -w: wait for completion
case 'w':
wflag = EARGF(usage());
break;
+ // ?man -q: quiet mode; suppress output
case 'q':
qflag = 1;
break;
diff --git a/cmd/net/tftp.c b/cmd/net/tftp.c
@@ -1,4 +1,11 @@
/* See LICENSE file for copyright and license details. */
+/* ?man
+tftp: tftp client
+usage: tftp -h host [-p port] [-x | -c] file
+
+transfer files to and from a remote tftp server
+*/
+
#include <sys/time.h>
#include <sys/types.h>
#include <sys/socket.h>
@@ -256,15 +263,19 @@ main(int argc, char *argv[])
int ret;
ARGBEGIN {
+ // ?man -h: suppress headers or print help
case 'h':
host = EARGF(usage());
break;
+ // ?man -p: preserve file attributes
case 'p':
port = EARGF(usage());
break;
+ // ?man -x: hex format or match whole lines
case 'x':
fn = getfile;
break;
+ // ?man -c: print count or perform stdout action
case 'c':
fn = putfile;
break;
diff --git a/cmd/net/tunctl.c b/cmd/net/tunctl.c
@@ -1,98 +0,0 @@
-/* See LICENSE file for copyright and license details. */
-#include <sys/ioctl.h>
-#include <sys/socket.h>
-#include <sys/stat.h>
-#include <sys/types.h>
-
-#include <fcntl.h>
-#include <limits.h>
-#include <pwd.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <unistd.h>
-
-#include <linux/if.h>
-#include <linux/if_tun.h>
-
-#include "util.h"
-
-static int dflag;
-static int tflag = 1;
-static int Tflag;
-static char *owner;
-
-static void
-usage(void)
-{
- eprintf("usage: %s [-dtT] [-u owner] [device]\n", argv0);
-}
-
-int
-main(int argc, char *argv[])
-{
- struct ifreq ifr;
- struct passwd *pw;
- uid_t owner_uid = 0;
- int fd;
-
- ARGBEGIN
- {
- case 'd':
- dflag = 1;
- tflag = 0;
- break;
- case 't':
- tflag = 1;
- dflag = 0;
- break;
- case 'T':
- Tflag = 1;
- break;
- case 'u':
- owner = EARGF(usage());
- break;
- default:
- usage();
- }
- ARGEND
-
- if (owner) {
- pw = getpwnam(owner);
- if (!pw)
- owner_uid = estrtonum(owner, 0, UINT_MAX);
- else
- owner_uid = pw->pw_uid;
- }
-
- fd = open("/dev/net/tun", O_RDWR);
- if (fd < 0)
- eprintf("open /dev/net/tun:");
-
- memset(&ifr, 0, sizeof(ifr));
- ifr.ifr_flags = (Tflag ? IFF_TAP : IFF_TUN) | IFF_NO_PI;
-
- if (argc > 0)
- estrlcpy(ifr.ifr_name, argv[0], sizeof(ifr.ifr_name));
-
- if (ioctl(fd, TUNSETIFF, (void *)&ifr) < 0)
- eprintf("ioctl TUNSETIFF:");
-
- if (tflag) {
- if (ioctl(fd, TUNSETPERSIST, (void *)1) < 0)
- eprintf("ioctl TUNSETPERSIST:");
- if (owner) {
- if (ioctl(fd, TUNSETOWNER, (void *)(long)owner_uid) < 0)
- eprintf("ioctl TUNSETOWNER:");
- }
- printf("Set '%s' persistent and owned by %u\n", ifr.ifr_name,
- owner_uid);
- } else if (dflag) {
- if (ioctl(fd, TUNSETPERSIST, (void *)0) < 0)
- eprintf("ioctl TUNSETPERSIST:");
- printf("Set '%s' non-persistent\n", ifr.ifr_name);
- }
-
- close(fd);
- return 0;
-}
diff --git a/cmd/net/wget.c b/cmd/net/wget.c
@@ -1,6 +1,14 @@
-/* See LICENSE file for copyright and license details. */
+/* see license file for copyright and license details */
+/* ?man
+wget: retrieve files from the web
+usage: wget [-cqS] [-O file] [-P dir] [-T timeout] [-U user_agent] [-post-data data] [-post-file file] [-header header] [-no-check-certificate] [-spider] url
+
+download files over http or https
+*/
+
#include "util.h"
#include "arg.h"
+#include "tls.h"
#include <arpa/inet.h>
#include <ctype.h>
@@ -12,20 +20,44 @@
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
+#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
struct Stream {
- int fd;
+ struct TlsSocket *ts;
char buf[8192];
size_t len;
size_t idx;
};
+static int qflag = 0;
+static int Sflag = 0;
+static int cflag = 0;
+static int spider = 0;
+static int no_check_certificate = 0;
+static int timeout_sec = 900;
+static char *Pflag = NULL;
+static char *Oflag = NULL;
+static char *user_agent = "wget/aruu";
+static char *post_data = NULL;
+static char *post_file = NULL;
+static char **custom_headers = NULL;
+static size_t custom_headers_num = 0;
+
static void
usage(void)
{
- eprintf("usage: %s [-O file] [-p post_data] [-r limit] url\n", argv0);
+ eprintf("usage: %s [-cqS] [-O file] [-P dir] [-T timeout] [-U user_agent] "
+ "[-post-data data] [-post-file file] [-header header] "
+ "[-no-check-certificate] [-spider] url\n", argv0);
+}
+
+static void
+add_header(const char *hdr)
+{
+ custom_headers = ereallocarray(custom_headers, custom_headers_num + 1, sizeof(*custom_headers));
+ custom_headers[custom_headers_num++] = estrdup(hdr);
}
static int
@@ -40,7 +72,8 @@ dial(const char *host, const char *port)
r = getaddrinfo(host, port, &hints, &res);
if (r != 0) {
- weprintf("getaddrinfo %s:%s: %s\n", host, port, gai_strerror(r));
+ if (!qflag)
+ weprintf("getaddrinfo %s:%s: %s\n", host, port, gai_strerror(r));
return -1;
}
@@ -48,6 +81,13 @@ dial(const char *host, const char *port)
fd = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
if (fd < 0)
continue;
+ if (timeout_sec > 0) {
+ struct timeval tv;
+ tv.tv_sec = timeout_sec;
+ tv.tv_usec = 0;
+ setsockopt(fd, SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(tv));
+ setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv));
+ }
if (connect(fd, rp->ai_addr, rp->ai_addrlen) == 0)
break;
close(fd);
@@ -59,14 +99,16 @@ dial(const char *host, const char *port)
}
static void
-parse_url(char *url, char **host, char **port, char **path)
+parse_url(char *url, char **host, char **port, char **path, int *is_tls)
{
char *p, *ss;
+ *is_tls = 0;
if (strncasecmp(url, "http://", 7) == 0) {
url += 7;
} else if (strncasecmp(url, "https://", 8) == 0) {
url += 8;
+ *is_tls = 1;
} else {
eprintf("unsupported protocol or invalid url: %s\n", url);
}
@@ -90,7 +132,7 @@ parse_url(char *url, char **host, char **port, char **path)
if (*ss == ':')
*port = ss + 1;
else
- *port = "80";
+ *port = *is_tls ? "443" : "80";
} else {
eprintf("invalid ipv6 literal: %s\n", *host);
}
@@ -100,7 +142,7 @@ parse_url(char *url, char **host, char **port, char **path)
*p = '\0';
*port = p + 1;
} else {
- *port = "80";
+ *port = *is_tls ? "443" : "80";
}
}
}
@@ -136,7 +178,7 @@ stream_getc(struct Stream *s)
return (unsigned char)s->buf[s->idx++];
}
s->idx = 0;
- r = read(s->fd, s->buf, sizeof(s->buf));
+ r = tls_read(s->ts, s->buf, sizeof(s->buf));
if (r <= 0) {
s->len = 0;
return EOF;
@@ -161,7 +203,7 @@ stream_read(struct Stream *s, void *ptr, size_t size)
total += n;
} else {
s->idx = 0;
- r = read(s->fd, s->buf, sizeof(s->buf));
+ r = tls_read(s->ts, s->buf, sizeof(s->buf));
if (r <= 0) {
s->len = 0;
break;
@@ -242,13 +284,24 @@ read_non_chunked(struct Stream *s, int out_fd, long long content_len)
}
}
+static void
+req_printf(struct TlsSocket *ts, const char *fmt, ...)
+{
+ va_list ap;
+ char buf[1024];
+ int len;
+
+ va_start(ap, fmt);
+ len = vsnprintf(buf, sizeof(buf), fmt, ap);
+ va_end(ap);
+ if (len > 0)
+ tls_write(ts, buf, len);
+}
+
int
main(int argc, char *argv[])
{
struct Stream s;
- char *Oflag = NULL;
- char *pflag = NULL;
- char *rflag = NULL;
char *url, *host, *port, *path, *loc;
char *curr_host, *curr_port, *curr_path;
char *new_url;
@@ -258,7 +311,7 @@ main(int argc, char *argv[])
char *out_name;
int redirects = 0;
int max_redirects = 20;
- int sock = -1;
+ int sock_fd = -1;
int out_fd = 1;
int chunked;
int status;
@@ -267,16 +320,83 @@ main(int argc, char *argv[])
ssize_t n;
size_t dir_len;
char *last_slash;
+ int is_tls = 0;
+ struct TlsSocket *tls_sock = NULL;
+ off_t resume_offset = 0;
+ int out_mode = O_WRONLY | O_CREAT | O_TRUNC;
+ long long post_len = 0;
+ int post_fd = -1;
+ size_t i;
ARGBEGIN {
+ // ?man -O: specify output file path
case 'O':
Oflag = EARGF(usage());
break;
- case 'p':
- pflag = EARGF(usage());
+ // ?man -P: specify output directory prefix
+ case 'P':
+ Pflag = EARGF(usage());
+ break;
+ // ?man -T: set network read and connect timeout
+ case 'T':
+ timeout_sec = estrtonum(EARGF(usage()), 0, 100000);
+ break;
+ // ?man -U: set User-Agent header
+ case 'U':
+ user_agent = EARGF(usage());
break;
- case 'r':
- rflag = EARGF(usage());
+ // ?man -c: continue retrieval of aborted transfer
+ case 'c':
+ cflag = 1;
+ break;
+ // ?man -q: quiet mode to suppress stderr output
+ case 'q':
+ qflag = 1;
+ break;
+ // ?man -S: print server response headers to stderr
+ case 'S':
+ Sflag = 1;
+ break;
+ case '-':
+ if (strcmp(argv[0], "-no-check-certificate") == 0) {
+ no_check_certificate = 1;
+ brk_ = 1;
+ } else if (strncmp(argv[0], "-header=", 8) == 0) {
+ add_header(argv[0] + 8);
+ brk_ = 1;
+ } else if (strcmp(argv[0], "-header") == 0) {
+ brk_ = 1;
+ if (!argv[1])
+ usage();
+ add_header(argv[1]);
+ argv++;
+ argc--;
+ } else if (strncmp(argv[0], "-post-data=", 11) == 0) {
+ post_data = argv[0] + 11;
+ brk_ = 1;
+ } else if (strcmp(argv[0], "-post-data") == 0) {
+ brk_ = 1;
+ if (!argv[1])
+ usage();
+ post_data = argv[1];
+ argv++;
+ argc--;
+ } else if (strncmp(argv[0], "-post-file=", 11) == 0) {
+ post_file = argv[0] + 11;
+ brk_ = 1;
+ } else if (strcmp(argv[0], "-post-file") == 0) {
+ brk_ = 1;
+ if (!argv[1])
+ usage();
+ post_file = argv[1];
+ argv++;
+ argc--;
+ } else if (strcmp(argv[0], "-spider") == 0) {
+ spider = 1;
+ brk_ = 1;
+ } else {
+ usage();
+ }
break;
default:
usage();
@@ -285,47 +405,109 @@ main(int argc, char *argv[])
if (argc < 1)
usage();
- if (rflag)
- max_redirects = estrtonum(rflag, 0, 1000);
-
url = estrdup(argv[0]);
- while (sock < 0) {
+ /* determine output filename early to check for resume */
+ out_name = NULL;
+ if (Oflag) {
+ out_name = Oflag;
+ } else {
+ last_slash = strrchr(url, '/');
+ if (last_slash && *(last_slash + 1))
+ out_name = last_slash + 1;
+ else
+ out_name = "index.html";
+
+ if (Pflag) {
+ char *tmp = emalloc(strlen(Pflag) + 1 + strlen(out_name) + 1);
+ sprintf(tmp, "%s/%s", Pflag, out_name);
+ out_name = tmp;
+ }
+ }
+
+ if (cflag && out_name && strcmp(out_name, "-") != 0) {
+ struct stat st;
+ if (stat(out_name, &st) == 0 && S_ISREG(st.st_mode)) {
+ resume_offset = st.st_size;
+ }
+ }
+
+ if (post_data) {
+ post_len = strlen(post_data);
+ } else if (post_file) {
+ struct stat st;
+ post_fd = open(post_file, O_RDONLY);
+ if (post_fd < 0)
+ eprintf("open %s:\n", post_file);
+ if (fstat(post_fd, &st) < 0)
+ eprintf("stat %s:\n", post_file);
+ post_len = st.st_size;
+ }
+
+ while (!tls_sock) {
if (redirects > max_redirects)
eprintf("too many redirects\n");
- /* parse url and backup original parts for relative redirect resolves */
curr_host = curr_port = curr_path = NULL;
- parse_url(url, &curr_host, &curr_port, &curr_path);
+ parse_url(url, &curr_host, &curr_port, &curr_path, &is_tls);
host = estrdup(curr_host);
port = estrdup(curr_port);
path = estrdup(curr_path);
- sock = dial(host, port);
- if (sock < 0)
+ sock_fd = dial(host, port);
+ if (sock_fd < 0)
eprintf("failed to connect to %s:%s\n", host, port);
- if (pflag) {
- dprintf(sock, "POST /%s HTTP/1.1\r\n"
- "Host: %s\r\n"
- "User-Agent: wget/aruu\r\n"
-#ifdef STD_NON_POSIX
- "Accept: */*\r\n"
-#endif
- "Content-Length: %zu\r\n"
- "Connection: close\r\n\r\n",
- path, host, strlen(pflag));
- writeall(sock, pflag, strlen(pflag));
- } else {
- dprintf(sock, "GET /%s HTTP/1.1\r\n"
- "Host: %s\r\n"
- "User-Agent: wget/aruu\r\n"
-#ifdef STD_NON_POSIX
- "Accept: */*\r\n"
-#endif
- "Connection: close\r\n\r\n",
- path, host);
+ tls_sock = tls_connect(sock_fd, host, !no_check_certificate, is_tls);
+ if (!tls_sock) {
+ close(sock_fd);
+ eprintf("failed to establish TLS connection with %s\n", host);
+ }
+
+ /* send http request */
+ const char *method = spider ? "HEAD" : ((post_data || post_file) ? "POST" : "GET");
+ req_printf(tls_sock, "%s /%s HTTP/1.1\r\n", method, path);
+ req_printf(tls_sock, "Host: %s\r\n", host);
+ req_printf(tls_sock, "User-Agent: %s\r\n", user_agent);
+ req_printf(tls_sock, "Connection: close\r\n");
+
+ if (resume_offset > 0) {
+ req_printf(tls_sock, "Range: bytes=%lld-\r\n", (long long)resume_offset);
+ }
+
+ if (post_data || post_file) {
+ int has_ct = 0;
+ for (i = 0; i < custom_headers_num; i++) {
+ if (strncasecmp(custom_headers[i], "Content-Type:", 13) == 0) {
+ has_ct = 1;
+ break;
+ }
+ }
+ if (!has_ct) {
+ req_printf(tls_sock, "Content-Type: application/x-www-form-urlencoded\r\n");
+ }
+ req_printf(tls_sock, "Content-Length: %lld\r\n", post_len);
+ }
+
+ for (i = 0; i < custom_headers_num; i++) {
+ req_printf(tls_sock, "%s\r\n", custom_headers[i]);
+ }
+
+ req_printf(tls_sock, "\r\n");
+
+ if (post_data) {
+ tls_write(tls_sock, post_data, strlen(post_data));
+ } else if (post_file) {
+ char io_buf[8192];
+ ssize_t r;
+ while ((r = read(post_fd, io_buf, sizeof(io_buf))) > 0) {
+ if (tls_write(tls_sock, io_buf, r) < 0) {
+ eprintf("failed to write post data:\n");
+ }
+ }
+ close(post_fd);
+ post_fd = -1;
}
/* read headers */
@@ -333,7 +515,7 @@ main(int argc, char *argv[])
header_end = NULL;
memset(s.buf, 0, sizeof(s.buf));
while (total_read < sizeof(s.buf) - 1) {
- n = read(sock, s.buf + total_read, sizeof(s.buf) - 1 - total_read);
+ n = tls_read(tls_sock, s.buf + total_read, sizeof(s.buf) - 1 - total_read);
if (n <= 0) {
if (n < 0)
eprintf("read socket:\n");
@@ -351,11 +533,14 @@ main(int argc, char *argv[])
eprintf("http header too large or not found\n");
*header_end = '\0';
- s.fd = sock;
+ s.ts = tls_sock;
s.len = total_read;
s.idx = (header_end + 4) - s.buf;
- /* parse HTTP status code */
+ if (Sflag) {
+ fprintf(stderr, "%s\n\n", s.buf);
+ }
+
if (strncasecmp(s.buf, "HTTP/1.1 ", 9) != 0 &&
strncasecmp(s.buf, "HTTP/1.0 ", 9) != 0) {
eprintf("invalid http response: %s\n", s.buf);
@@ -372,14 +557,14 @@ main(int argc, char *argv[])
new_url = estrdup(loc);
} else if (loc[0] == '/') {
new_url = emalloc(8 + strlen(host) + strlen(port) + strlen(loc) + 2);
- sprintf(new_url, "http://%s:%s%s", host, port, loc);
+ sprintf(new_url, "%s://%s:%s%s", is_tls ? "https" : "http", host, port, loc);
} else {
last_slash = strrchr(path, '/');
dir_len = 0;
if (last_slash)
dir_len = last_slash - path + 1;
new_url = emalloc(8 + strlen(host) + strlen(port) + 1 + dir_len + strlen(loc) + 2);
- sprintf(new_url, "http://%s:%s/", host, port);
+ sprintf(new_url, "%s://%s:%s/", is_tls ? "https" : "http", host, port);
if (dir_len > 0)
strncat(new_url, path, dir_len);
strcat(new_url, loc);
@@ -388,10 +573,23 @@ main(int argc, char *argv[])
free(loc);
free(url);
url = new_url;
- close(sock);
- sock = -1;
+ tls_close(tls_sock, 1);
+ tls_sock = NULL;
redirects++;
- } else if (status != 200) {
+ } else if (status == 206) {
+ out_mode = O_WRONLY | O_CREAT | O_APPEND;
+ } else if (status == 200) {
+ out_mode = O_WRONLY | O_CREAT | O_TRUNC;
+ } else if (status == 416) {
+ if (!qflag)
+ weprintf("file already fully retrieved or range invalid\n");
+ tls_close(tls_sock, 1);
+ free(url);
+ free(host);
+ free(port);
+ free(path);
+ return 0;
+ } else {
eprintf("server returned status: %d\n", status);
}
@@ -400,7 +598,12 @@ main(int argc, char *argv[])
free(path);
}
- /* parse headers for content length and chunked encoding */
+ if (spider) {
+ tls_close(tls_sock, 1);
+ free(url);
+ return 0;
+ }
+
cl_str = find_header(s.buf, "Content-Length:");
content_len = -1;
if (cl_str) {
@@ -416,34 +619,28 @@ main(int argc, char *argv[])
free(te_str);
}
- /* open output file */
- out_name = NULL;
- if (Oflag) {
- out_name = Oflag;
- } else {
- last_slash = strrchr(url, '/');
- if (last_slash && *(last_slash + 1))
- out_name = last_slash + 1;
- else
- out_name = "index.html";
- }
-
if (strcmp(out_name, "-") != 0) {
- out_fd = open(out_name, O_WRONLY | O_CREAT | O_TRUNC, 0644);
+ out_fd = open(out_name, out_mode, 0644);
if (out_fd < 0)
eprintf("open %s:\n", out_name);
}
- /* read and write body */
if (chunked)
read_chunked(&s, out_fd);
else
read_non_chunked(&s, out_fd, content_len);
- close(sock);
+ tls_close(tls_sock, 1);
if (out_fd != 1)
close(out_fd);
+ if (Oflag != out_name && Pflag)
+ free(out_name);
free(url);
+ for (i = 0; i < custom_headers_num; i++) {
+ free(custom_headers[i]);
+ }
+ free(custom_headers);
+
return 0;
}
diff --git a/cmd/posix/basename.c b/cmd/posix/basename.c
@@ -1,4 +1,11 @@
/* See LICENSE file for copyright and license details. */
+/* ?man
+basename: strip directory and suffix from filenames
+usage: basename path [suffix]
+
+print filename with leading directories and optional suffix removed
+*/
+
#include <libgen.h>
#include <stdio.h>
#include <string.h>
diff --git a/cmd/posix/cal.c b/cmd/posix/cal.c
@@ -1,4 +1,11 @@
/* See LICENSE file for copyright and license details. */
+/* ?man
+cal: display a calendar
+usage: cal [-1 | -3 | -y | -n num]
+
+print a formatted calendar of the specified month or year
+*/
+
#include <limits.h>
#include <stdint.h>
#include <stdio.h>
@@ -175,9 +182,11 @@ main(int argc, char *argv[])
ARGBEGIN {
#ifdef FEATURE_CAL_EXT
+ // ?man -1: specify option flag
case '1':
nmons = 1;
break;
+ // ?man -3: specify option flag
case '3':
nmons = 3;
if (--month == 0) {
@@ -185,22 +194,28 @@ main(int argc, char *argv[])
year--;
}
break;
+ // ?man -c: print count or perform stdout action
case 'c':
ncols = estrtonum(EARGF(usage()), 0, MIN((unsigned long long)SIZE_MAX, (unsigned long long)LLONG_MAX));
break;
+ // ?man -f: force the operation
case 'f':
fday = estrtonum(EARGF(usage()), 0, 6);
break;
+ // ?man -m: specify mode or limit
case 'm': /* Monday */
fday = 1;
break;
+ // ?man -n: print line numbers or counts
case 'n':
nmons = estrtonum(EARGF(usage()), 1, MIN((unsigned long long)SIZE_MAX, (unsigned long long)LLONG_MAX));
break;
+ // ?man -s: silent mode or print summary
case 's': /* Sunday */
fday = 0;
break;
#endif
+ // ?man -y: specify option flag
case 'y':
month = 1;
nmons = 12;
diff --git a/cmd/posix/cat.c b/cmd/posix/cat.c
@@ -1,4 +1,13 @@
/* See LICENSE file for copyright and license details. */
+
+/* ?man
+cat: concatenate files and print to standard output
+usage: cat [-u] [file ...]
+
+cat reads each file in sequence and writes it to standard output
+if no file is given, or a file is -, standard input is read
+*/
+
#include <fcntl.h>
#include <string.h>
#include <unistd.h>
@@ -18,6 +27,7 @@ main(int argc, char *argv[])
ARGBEGIN {
case 'u':
+ // ?man -u: ignored; accepted for posix compatibility; output is always unbuffered
break;
default:
usage();
@@ -48,5 +58,16 @@ main(int argc, char *argv[])
}
}
+ /* ?man
+ ## Exit status
+
+ cat exits 0 on success, and >0 if an error occurs reading any file
+ or writing to standard output
+
+ ## See also
+
+ cp(1), dd(1)
+ */
+
return ret;
}
diff --git a/cmd/posix/chgrp.c b/cmd/posix/chgrp.c
@@ -1,4 +1,11 @@
/* See LICENSE file for copyright and license details. */
+/* ?man
+chgrp: change group ownership
+usage: chgrp [-h] [-R [-H | -L | -P]] group file ...
+
+change the group ownership of files and directories
+*/
+
#include <sys/stat.h>
#include <errno.h>
@@ -43,14 +50,19 @@ main(int argc, char *argv[])
struct recursor r = { .fn = chgrp, .maxdepth = 1, .follow = 'P' };
ARGBEGIN {
+ // ?man -h: affect symbolic links instead of referenced files
case 'h':
hflag = 1;
break;
+ // ?man -R: change group ownership recursively
case 'R':
r.maxdepth = 0;
break;
+ // ?man -H: specify option flag
case 'H':
+ // ?man -L: specify option flag
case 'L':
+ // ?man -P: specify option flag
case 'P':
r.follow = ARGC();
break;
diff --git a/cmd/posix/chmod.c b/cmd/posix/chmod.c
@@ -1,4 +1,11 @@
/* See LICENSE file for copyright and license details. */
+/* ?man
+chmod: change file modes
+usage: chmod [-R] mode file ...
+
+change the file mode bits of files and directories
+*/
+
#include <fcntl.h>
#include <sys/stat.h>
diff --git a/cmd/posix/chown.c b/cmd/posix/chown.c
@@ -1,4 +1,11 @@
/* See LICENSE file for copyright and license details. */
+/* ?man
+chown: change ownership
+usage: chown [-h] [-R [-H | -L | -P]] owner[:[group]] file ...
+
+change the user and group ownership of files and directories
+*/
+
#include <errno.h>
#include <fcntl.h>
#include <grp.h>
@@ -51,15 +58,21 @@ main(int argc, char *argv[])
char *owner, *group;
ARGBEGIN {
+ // ?man -h: affect symbolic links instead of referenced files
case 'h':
hflag = 1;
break;
+ // ?man -r: operate recursively
case 'r':
+ // ?man -R: change files and directories recursively
case 'R':
r.maxdepth = 0;
break;
+ // ?man -H: specify option flag
case 'H':
+ // ?man -L: specify option flag
case 'L':
+ // ?man -P: specify option flag
case 'P':
r.follow = ARGC();
break;
diff --git a/cmd/posix/cksum.c b/cmd/posix/cksum.c
@@ -1,4 +1,11 @@
/* See LICENSE file for copyright and license details. */
+/* ?man
+cksum: checksum and count bytes
+usage: cksum [file ...]
+
+print crc checksum and byte counts for files
+*/
+
#include <fcntl.h>
#include <inttypes.h>
#include <stdio.h>
diff --git a/cmd/posix/cmp.c b/cmd/posix/cmp.c
@@ -1,4 +1,11 @@
/* See LICENSE file for copyright and license details. */
+/* ?man
+cmp: compare two files
+usage: cmp [-l | -s] file1 file2
+
+compare two files byte by byte
+*/
+
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
@@ -19,9 +26,11 @@ main(int argc, char *argv[])
int ret = 0, lflag = 0, sflag = 0, same = 1, b[2];
ARGBEGIN {
+ // ?man -l: list in long format
case 'l':
lflag = 1;
break;
+ // ?man -s: silent mode or print summary
case 's':
sflag = 1;
break;
diff --git a/cmd/posix/comm.c b/cmd/posix/comm.c
@@ -1,4 +1,11 @@
/* See LICENSE file for copyright and license details. */
+/* ?man
+comm: compare two sorted files
+usage: comm [-123] file1 file2
+
+compare two sorted files line by line
+*/
+
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
@@ -39,8 +46,11 @@ main(int argc, char *argv[])
int ret = 0, i, diff = 0, seenline = 0;
ARGBEGIN {
+ // ?man -1: specify option flag
case '1':
+ // ?man -2: specify option flag
case '2':
+ // ?man -3: specify option flag
case '3':
show &= 0x07 ^ (1 << (ARGC() - '1'));
break;
diff --git a/cmd/posix/cp.c b/cmd/posix/cp.c
@@ -1,4 +1,11 @@
/* See LICENSE file for copyright and license details. */
+/* ?man
+cp: copy files and directories
+usage: cp [-afipv] [-R [-H | -L | -P]] source ... dest
+
+copy files and directories to a destination
+*/
+
#include <sys/stat.h>
#include "fs.h"
@@ -16,28 +23,38 @@ main(int argc, char *argv[])
struct stat st;
ARGBEGIN {
+ // ?man -i: prompt before overwriting existing files
case 'i':
cp_iflag = 1;
break;
+ // ?man -a: archive mode; equivalent to -dpR
case 'a':
cp_follow = 'P';
cp_aflag = cp_pflag = cp_rflag = 1;
break;
+ // ?man -f: force copy by removing existing destination files
case 'f':
cp_fflag = 1;
break;
+ // ?man -p: preserve file attributes
case 'p':
cp_pflag = 1;
break;
+ // ?man -r: copy directories recursively
case 'r':
+ // ?man -R: copy directories recursively
case 'R':
cp_rflag = 1;
break;
+ // ?man -v: verbose mode; show progress
case 'v':
cp_vflag = 1;
break;
+ // ?man -H: specify option flag
case 'H':
+ // ?man -L: specify option flag
case 'L':
+ // ?man -P: specify option flag
case 'P':
cp_follow = ARGC();
break;
diff --git a/cmd/posix/cut.c b/cmd/posix/cut.c
@@ -1,4 +1,11 @@
/* See LICENSE file for copyright and license details. */
+/* ?man
+cut: cut out fields from lines
+usage: cut -b list [-n] [file ...]
+
+print selected parts of lines from files
+*/
+
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
@@ -166,21 +173,27 @@ main(int argc, char *argv[])
int ret = 0;
ARGBEGIN {
+ // ?man -b: specify block size or base directory
case 'b':
+ // ?man -c: print count or perform stdout action
case 'c':
+ // ?man -f: force the operation
case 'f':
mode = ARGC();
parselist(EARGF(usage()));
break;
+ // ?man -d: specify directory
case 'd':
delim = EARGF(usage());
if (!*delim)
eprintf("empty delimiter\n");
delimlen = unescape(delim);
break;
+ // ?man -n: print line numbers or counts
case 'n':
nflag = 1;
break;
+ // ?man -s: silent mode or print summary
case 's':
sflag = 1;
break;
diff --git a/cmd/posix/date.c b/cmd/posix/date.c
@@ -1,4 +1,11 @@
/* See LICENSE file for copyright and license details. */
+/* ?man
+date: print or set system date and time
+usage: date [-u] [-d time] [+format | mmddHHMM[[CC]yy]]
+
+display or configure the system date and time
+*/
+
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
@@ -73,9 +80,11 @@ main(int argc, char *argv[])
eprintf("time:");
ARGBEGIN {
+ // ?man -d: specify directory
case 'd':
t = estrtonum(EARGF(usage()), 0, LLONG_MAX);
break;
+ // ?man -u: unbuffered output
case 'u':
if (setenv("TZ", "UTC0", 1) < 0)
eprintf("setenv:");
diff --git a/cmd/posix/dd.c b/cmd/posix/dd.c
@@ -1,4 +1,11 @@
/* See LICENSE file for copyright and license details. */
+/* ?man
+dd: convert and copy a file
+usage: dd [operand...]
+
+copy a file while performing conversions
+*/
+
#include <ctype.h>
#include <fcntl.h>
#include <inttypes.h>
diff --git a/cmd/posix/df.c b/cmd/posix/df.c
@@ -1,4 +1,11 @@
/* See LICENSE file for copyright and license details. */
+/* ?man
+df: report disk space usage
+usage: df [-a]
+
+display free and used disk space on filesystems
+*/
+
#include <sys/statvfs.h>
#include <mntent.h>
@@ -97,19 +104,24 @@ main(int argc, char *argv[])
int ret = 0;
ARGBEGIN {
+ // ?man -a: print or show all entries
case 'a':
aflag = 1;
break;
+ // ?man -h: suppress headers or print help
case 'h':
hflag = 1;
kflag = 0;
break;
+ // ?man -k: specify option flag
case 'k':
kflag = 1;
hflag = 0;
blksize = 1024;
break;
+ // ?man -s: silent mode or print summary
case 's':
+ // ?man -i: interactive mode or prompt for confirmation
case 'i':
eprintf("not implemented\n");
break;
diff --git a/cmd/posix/dirname.c b/cmd/posix/dirname.c
@@ -1,4 +1,11 @@
/* See LICENSE file for copyright and license details. */
+/* ?man
+dirname: strip non-directory suffix from filename
+usage: dirname path
+
+print the directory portion of a pathname
+*/
+
#include <libgen.h>
#include <stdio.h>
diff --git a/cmd/posix/du.c b/cmd/posix/du.c
@@ -1,4 +1,11 @@
/* See LICENSE file for copyright and license details. */
+/* ?man
+du: estimate file space usage
+usage: du [-a | -s] [-d depth] [-h] [-k] [-H | -L | -P] [-x] [file ...]
+
+display disk space used by files and directories
+*/
+
#include <sys/stat.h>
#include <sys/types.h>
@@ -117,27 +124,36 @@ main(int argc, char *argv[])
char *bsize;
ARGBEGIN {
+ // ?man -a: print or show all entries
case 'a':
aflag = 1;
break;
+ // ?man -d: specify directory
case 'd':
dflag = 1;
maxdepth = estrtonum(EARGF(usage()), 0, MIN((unsigned long long)LLONG_MAX, (unsigned long long)SIZE_MAX));
break;
+ // ?man -h: suppress headers or print help
case 'h':
hflag = 1;
break;
+ // ?man -k: specify option flag
case 'k':
kflag = 1;
break;
+ // ?man -s: silent mode or print summary
case 's':
sflag = 1;
break;
+ // ?man -x: hex format or match whole lines
case 'x':
r.flags |= SAMEDEV;
break;
+ // ?man -H: specify option flag
case 'H':
+ // ?man -L: specify option flag
case 'L':
+ // ?man -P: specify option flag
case 'P':
r.follow = ARGC();
break;
diff --git a/cmd/posix/echo.c b/cmd/posix/echo.c
@@ -1,4 +1,11 @@
/* See LICENSE file for copyright and license details. */
+/* ?man
+echo: write arguments to stdout
+usage: echo
+
+print the specified arguments to standard output
+*/
+
#include <stdio.h>
#include <string.h>
#include "util.h"
diff --git a/cmd/posix/ed.c b/cmd/posix/ed.c
@@ -1,4 +1,11 @@
/* See LICENSE file for copyright and license details. */
+/* ?man
+ed: line editor
+usage: ed [-s] [-p] [file]
+
+simple text line editor
+*/
+
#include <sys/stat.h>
#include <fcntl.h>
#include <regex.h>
@@ -1332,6 +1339,7 @@ repeat:
goto print;
case 'l':
case 'n':
+ // ?man -p: preserve file attributes
case 'p':
back(cmd);
chkprint(1);
@@ -1390,6 +1398,7 @@ repeat:
error("nothing to undo");
undo();
break;
+ // ?man -s: silent mode or print summary
case 's':
deflines(curln, curln);
c = input();
@@ -1700,10 +1709,12 @@ int
main(int argc, char *argv[])
{
ARGBEGIN {
+ // ?man -p: preserve file attributes
case 'p':
prompt = EARGF(usage());
optprompt = 1;
break;
+ // ?man -s: silent mode or print summary
case 's':
optdiag = 0;
break;
diff --git a/cmd/posix/env.c b/cmd/posix/env.c
@@ -1,4 +1,11 @@
/* See LICENSE file for copyright and license details. */
+/* ?man
+env: run command in modified environment
+usage: env [-i] [-u var] ... [var=value] ... [cmd [arg ...]]
+
+set environment variables and run a command
+*/
+
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
@@ -21,9 +28,11 @@ main(int argc, char *argv[])
int savederrno;
ARGBEGIN {
+ // ?man -i: interactive mode or prompt for confirmation
case 'i':
*environ = NULL;
break;
+ // ?man -u: unbuffered output
case 'u':
if (unsetenv(EARGF(usage())) < 0)
eprintf("unsetenv:");
diff --git a/cmd/posix/expand.c b/cmd/posix/expand.c
@@ -1,4 +1,11 @@
/* See LICENSE file for copyright and license details. */
+/* ?man
+expand: convert tabs to spaces
+usage: expand [-i] [-t tablist] [file ...]
+
+convert tab characters to space characters
+*/
+
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
@@ -93,9 +100,11 @@ main(int argc, char *argv[])
char *tl = "8";
ARGBEGIN {
+ // ?man -i: interactive mode or prompt for confirmation
case 'i':
iflag = 1;
break;
+ // ?man -t: sort or specify timestamp
case 't':
tl = EARGF(usage());
if (!*tl)
diff --git a/cmd/posix/expr.c b/cmd/posix/expr.c
@@ -1,4 +1,11 @@
/* See LICENSE file for copyright and license details. */
+/* ?man
+expr: evaluate expression
+usage: expr
+
+evaluate a command line expression and print the result
+*/
+
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
diff --git a/cmd/posix/false.c b/cmd/posix/false.c
@@ -1,4 +1,11 @@
/* See LICENSE file for copyright and license details. */
+/* ?man
+false: return unsuccessful exit status
+usage: false
+
+exit with status 1 representing failure
+*/
+
int
main(void)
{
diff --git a/cmd/posix/find.c b/cmd/posix/find.c
@@ -1,4 +1,11 @@
/* See LICENSE file for copyright and license details. */
+/* ?man
+find: search for files
+usage: find [-H | -L] path ... [expression ...]
+
+search for files in a directory hierarchy
+*/
+
#include "config.h"
#include "util.h"
@@ -1429,10 +1436,12 @@ main(int argc, char **argv)
gflags.mindepth = -1;
ARGBEGIN {
+ // ?man -H: specify option flag
case 'H':
gflags.h = 1;
gflags.l = 0;
break;
+ // ?man -L: specify option flag
case 'L':
gflags.l = 1;
gflags.h = 0;
diff --git a/cmd/posix/fold.c b/cmd/posix/fold.c
@@ -1,4 +1,11 @@
/* See LICENSE file for copyright and license details. */
+/* ?man
+fold: wrap lines to fit width
+usage: fold [-bs] [-w num | -num] [FILE ...]
+
+wrap input lines to fit a specified width
+*/
+
#include <ctype.h>
#include <stdint.h>
#include <stdio.h>
@@ -89,12 +96,15 @@ main(int argc, char *argv[])
int ret = 0;
ARGBEGIN {
+ // ?man -b: specify block size or base directory
case 'b':
bflag = 1;
break;
+ // ?man -s: silent mode or print summary
case 's':
sflag = 1;
break;
+ // ?man -w: wait for completion
case 'w':
width = estrtonum(EARGF(usage()), 1, MIN((unsigned long long)LLONG_MAX, (unsigned long long)SIZE_MAX));
break;
diff --git a/cmd/posix/getconf.c b/cmd/posix/getconf.c
@@ -1,4 +1,11 @@
/* See LICENSE file for copyright and license details. */
+/* ?man
+getconf: query configuration variables
+usage: getconf [-v spec] var [path]
+
+query system configuration variables
+*/
+
#include <errno.h>
#include <unistd.h>
#include <limits.h>
@@ -29,6 +36,7 @@ main(int argc, char *argv[])
char *str;
ARGBEGIN {
+ // ?man -v: verbose mode; show progress
case 'v':
/* ignore */
EARGF(usage());
diff --git a/cmd/posix/getconf.h b/cmd/posix/getconf.h
@@ -1,605 +0,0 @@
-static const struct var confstr_l[] = {
-#ifdef _CS_PATH
- {"PATH", _CS_PATH},
-#endif
-#ifdef _CS_POSIX_V7_ILP32_OFF32_CFLAGS
- {"POSIX_V7_ILP32_OFF32_CFLAGS", _CS_POSIX_V7_ILP32_OFF32_CFLAGS},
-#endif
-#ifdef _CS_POSIX_V7_ILP32_OFF32_LDFLAGS
- {"POSIX_V7_ILP32_OFF32_LDFLAGS", _CS_POSIX_V7_ILP32_OFF32_LDFLAGS},
-#endif
-#ifdef _CS_POSIX_V7_ILP32_OFF32_LIBS
- {"POSIX_V7_ILP32_OFF32_LIBS", _CS_POSIX_V7_ILP32_OFF32_LIBS},
-#endif
-#ifdef _CS_POSIX_V7_ILP32_OFFBIG_CFLAGS
- {"POSIX_V7_ILP32_OFFBIG_CFLAGS", _CS_POSIX_V7_ILP32_OFFBIG_CFLAGS},
-#endif
-#ifdef _CS_POSIX_V7_ILP32_OFFBIG_LDFLAGS
- {"POSIX_V7_ILP32_OFFBIG_LDFLAGS", _CS_POSIX_V7_ILP32_OFFBIG_LDFLAGS},
-#endif
-#ifdef _CS_POSIX_V7_ILP32_OFFBIG_LIBS
- {"POSIX_V7_ILP32_OFFBIG_LIBS", _CS_POSIX_V7_ILP32_OFFBIG_LIBS},
-#endif
-#ifdef _CS_POSIX_V7_LP64_OFF64_CFLAGS
- {"POSIX_V7_LP64_OFF64_CFLAGS", _CS_POSIX_V7_LP64_OFF64_CFLAGS},
-#endif
-#ifdef _CS_POSIX_V7_LP64_OFF64_LDFLAGS
- {"POSIX_V7_LP64_OFF64_LDFLAGS", _CS_POSIX_V7_LP64_OFF64_LDFLAGS},
-#endif
-#ifdef _CS_POSIX_V7_LP64_OFF64_LIBS
- {"POSIX_V7_LP64_OFF64_LIBS", _CS_POSIX_V7_LP64_OFF64_LIBS},
-#endif
-#ifdef _CS_POSIX_V7_LPBIG_OFFBIG_CFLAGS
- {"POSIX_V7_LPBIG_OFFBIG_CFLAGS", _CS_POSIX_V7_LPBIG_OFFBIG_CFLAGS},
-#endif
-#ifdef _CS_POSIX_V7_LPBIG_OFFBIG_LDFLAGS
- {"POSIX_V7_LPBIG_OFFBIG_LDFLAGS", _CS_POSIX_V7_LPBIG_OFFBIG_LDFLAGS},
-#endif
-#ifdef _CS_POSIX_V7_LPBIG_OFFBIG_LIBS
- {"POSIX_V7_LPBIG_OFFBIG_LIBS", _CS_POSIX_V7_LPBIG_OFFBIG_LIBS},
-#endif
-#ifdef _CS_POSIX_V7_THREADS_CFLAGS
- {"POSIX_V7_THREADS_CFLAGS", _CS_POSIX_V7_THREADS_CFLAGS},
-#endif
-#ifdef _CS_POSIX_V7_THREADS_LDFLAGS
- {"POSIX_V7_THREADS_LDFLAGS", _CS_POSIX_V7_THREADS_LDFLAGS},
-#endif
-#ifdef _CS_POSIX_V7_WIDTH_RESTRICTED_ENVS
- {"POSIX_V7_WIDTH_RESTRICTED_ENVS", _CS_POSIX_V7_WIDTH_RESTRICTED_ENVS},
-#endif
-#ifdef _CS_V7_ENV
- {"V7_ENV", _CS_V7_ENV},
-#endif
-};
-static const struct var limits_l[] = {
-#ifdef _POSIX_CLOCKRES_MIN
- {"_POSIX_CLOCKRES_MIN", _POSIX_CLOCKRES_MIN},
-#endif
-#ifdef _POSIX_AIO_LISTIO_MAX
- {"_POSIX_AIO_LISTIO_MAX", _POSIX_AIO_LISTIO_MAX},
-#endif
-#ifdef _POSIX_AIO_MAX
- {"_POSIX_AIO_MAX", _POSIX_AIO_MAX},
-#endif
-#ifdef _POSIX_ARG_MAX
- {"_POSIX_ARG_MAX", _POSIX_ARG_MAX},
-#endif
-#ifdef _POSIX_CHILD_MAX
- {"_POSIX_CHILD_MAX", _POSIX_CHILD_MAX},
-#endif
-#ifdef _POSIX_DELAYTIMER_MAX
- {"_POSIX_DELAYTIMER_MAX", _POSIX_DELAYTIMER_MAX},
-#endif
-#ifdef _POSIX_HOST_NAME_MAX
- {"_POSIX_HOST_NAME_MAX", _POSIX_HOST_NAME_MAX},
-#endif
-#ifdef _POSIX_LINK_MAX
- {"_POSIX_LINK_MAX", _POSIX_LINK_MAX},
-#endif
-#ifdef _POSIX_LOGIN_NAME_MAX
- {"_POSIX_LOGIN_NAME_MAX", _POSIX_LOGIN_NAME_MAX},
-#endif
-#ifdef _POSIX_MAX_CANON
- {"_POSIX_MAX_CANON", _POSIX_MAX_CANON},
-#endif
-#ifdef _POSIX_MAX_INPUT
- {"_POSIX_MAX_INPUT", _POSIX_MAX_INPUT},
-#endif
-#ifdef _POSIX_MQ_OPEN_MAX
- {"_POSIX_MQ_OPEN_MAX", _POSIX_MQ_OPEN_MAX},
-#endif
-#ifdef _POSIX_MQ_PRIO_MAX
- {"_POSIX_MQ_PRIO_MAX", _POSIX_MQ_PRIO_MAX},
-#endif
-#ifdef _POSIX_NAME_MAX
- {"_POSIX_NAME_MAX", _POSIX_NAME_MAX},
-#endif
-#ifdef _POSIX_NGROUPS_MAX
- {"_POSIX_NGROUPS_MAX", _POSIX_NGROUPS_MAX},
-#endif
-#ifdef _POSIX_OPEN_MAX
- {"_POSIX_OPEN_MAX", _POSIX_OPEN_MAX},
-#endif
-#ifdef _POSIX_PATH_MAX
- {"_POSIX_PATH_MAX", _POSIX_PATH_MAX},
-#endif
-#ifdef _POSIX_PIPE_BUF
- {"_POSIX_PIPE_BUF", _POSIX_PIPE_BUF},
-#endif
-#ifdef _POSIX_RE_DUP_MAX
- {"_POSIX_RE_DUP_MAX", _POSIX_RE_DUP_MAX},
-#endif
-#ifdef _POSIX_RTSIG_MAX
- {"_POSIX_RTSIG_MAX", _POSIX_RTSIG_MAX},
-#endif
-#ifdef _POSIX_SEM_NSEMS_MAX
- {"_POSIX_SEM_NSEMS_MAX", _POSIX_SEM_NSEMS_MAX},
-#endif
-#ifdef _POSIX_SEM_VALUE_MAX
- {"_POSIX_SEM_VALUE_MAX", _POSIX_SEM_VALUE_MAX},
-#endif
-#ifdef _POSIX_SIGQUEUE_MAX
- {"_POSIX_SIGQUEUE_MAX", _POSIX_SIGQUEUE_MAX},
-#endif
-#ifdef _POSIX_SSIZE_MAX
- {"_POSIX_SSIZE_MAX", _POSIX_SSIZE_MAX},
-#endif
-#ifdef _POSIX_SS_REPL_MAX
- {"_POSIX_SS_REPL_MAX", _POSIX_SS_REPL_MAX},
-#endif
-#ifdef _POSIX_STREAM_MAX
- {"_POSIX_STREAM_MAX", _POSIX_STREAM_MAX},
-#endif
-#ifdef _POSIX_SYMLINK_MAX
- {"_POSIX_SYMLINK_MAX", _POSIX_SYMLINK_MAX},
-#endif
-#ifdef _POSIX_SYMLOOP_MAX
- {"_POSIX_SYMLOOP_MAX", _POSIX_SYMLOOP_MAX},
-#endif
-#ifdef _POSIX_THREAD_DESTRUCTOR_ITERATIONS
- {"_POSIX_THREAD_DESTRUCTOR_ITERATIONS", _POSIX_THREAD_DESTRUCTOR_ITERATIONS},
-#endif
-#ifdef _POSIX_THREAD_KEYS_MAX
- {"_POSIX_THREAD_KEYS_MAX", _POSIX_THREAD_KEYS_MAX},
-#endif
-#ifdef _POSIX_THREAD_THREADS_MAX
- {"_POSIX_THREAD_THREADS_MAX", _POSIX_THREAD_THREADS_MAX},
-#endif
-#ifdef _POSIX_TIMER_MAX
- {"_POSIX_TIMER_MAX", _POSIX_TIMER_MAX},
-#endif
-#ifdef _POSIX_TTY_NAME_MAX
- {"_POSIX_TTY_NAME_MAX", _POSIX_TTY_NAME_MAX},
-#endif
-#ifdef _POSIX_TZNAME_MAX
- {"_POSIX_TZNAME_MAX", _POSIX_TZNAME_MAX},
-#endif
-#ifdef _POSIX2_BC_BASE_MAX
- {"_POSIX2_BC_BASE_MAX", _POSIX2_BC_BASE_MAX},
-#endif
-#ifdef _POSIX2_BC_DIM_MAX
- {"_POSIX2_BC_DIM_MAX", _POSIX2_BC_DIM_MAX},
-#endif
-#ifdef _POSIX2_BC_SCALE_MAX
- {"_POSIX2_BC_SCALE_MAX", _POSIX2_BC_SCALE_MAX},
-#endif
-#ifdef _POSIX2_BC_STRING_MAX
- {"_POSIX2_BC_STRING_MAX", _POSIX2_BC_STRING_MAX},
-#endif
-#ifdef _POSIX2_CHARCLASS_NAME_MAX
- {"_POSIX2_CHARCLASS_NAME_MAX", _POSIX2_CHARCLASS_NAME_MAX},
-#endif
-#ifdef _POSIX2_COLL_WEIGHTS_MAX
- {"_POSIX2_COLL_WEIGHTS_MAX", _POSIX2_COLL_WEIGHTS_MAX},
-#endif
-#ifdef _POSIX2_EXPR_NEST_MAX
- {"_POSIX2_EXPR_NEST_MAX", _POSIX2_EXPR_NEST_MAX},
-#endif
-#ifdef _POSIX2_LINE_MAX
- {"_POSIX2_LINE_MAX", _POSIX2_LINE_MAX},
-#endif
-#ifdef _POSIX2_RE_DUP_MAX
- {"_POSIX2_RE_DUP_MAX", _POSIX2_RE_DUP_MAX},
-#endif
-};
-static const struct var sysconf_l[] = {
-#ifdef _SC_AIO_LISTIO_MAX
- {"AIO_LISTIO_MAX", _SC_AIO_LISTIO_MAX},
-#endif
-#ifdef _SC_AIO_MAX
- {"AIO_MAX", _SC_AIO_MAX},
-#endif
-#ifdef _SC_AIO_PRIO_DELTA_MAX
- {"AIO_PRIO_DELTA_MAX", _SC_AIO_PRIO_DELTA_MAX},
-#endif
-#ifdef _SC_ARG_MAX
- {"ARG_MAX", _SC_ARG_MAX},
-#endif
-#ifdef _SC_ATEXIT_MAX
- {"ATEXIT_MAX", _SC_ATEXIT_MAX},
-#endif
-#ifdef _SC_BC_BASE_MAX
- {"BC_BASE_MAX", _SC_BC_BASE_MAX},
-#endif
-#ifdef _SC_BC_DIM_MAX
- {"BC_DIM_MAX", _SC_BC_DIM_MAX},
-#endif
-#ifdef _SC_BC_SCALE_MAX
- {"BC_SCALE_MAX", _SC_BC_SCALE_MAX},
-#endif
-#ifdef _SC_BC_STRING_MAX
- {"BC_STRING_MAX", _SC_BC_STRING_MAX},
-#endif
-#ifdef _SC_CHILD_MAX
- {"CHILD_MAX", _SC_CHILD_MAX},
-#endif
-#ifdef _SC_COLL_WEIGHTS_MAX
- {"COLL_WEIGHTS_MAX", _SC_COLL_WEIGHTS_MAX},
-#endif
-#ifdef _SC_DELAYTIMER_MAX
- {"DELAYTIMER_MAX", _SC_DELAYTIMER_MAX},
-#endif
-#ifdef _SC_EXPR_NEST_MAX
- {"EXPR_NEST_MAX", _SC_EXPR_NEST_MAX},
-#endif
-#ifdef _SC_HOST_NAME_MAX
- {"HOST_NAME_MAX", _SC_HOST_NAME_MAX},
-#endif
-#ifdef _SC_IOV_MAX
- {"IOV_MAX", _SC_IOV_MAX},
-#endif
-#ifdef _SC_LINE_MAX
- {"LINE_MAX", _SC_LINE_MAX},
-#endif
-#ifdef _SC_LOGIN_NAME_MAX
- {"LOGIN_NAME_MAX", _SC_LOGIN_NAME_MAX},
-#endif
-#ifdef _SC_NGROUPS_MAX
- {"NGROUPS_MAX", _SC_NGROUPS_MAX},
-#endif
-#ifdef _SC_MQ_OPEN_MAX
- {"MQ_OPEN_MAX", _SC_MQ_OPEN_MAX},
-#endif
-#ifdef _SC_MQ_PRIO_MAX
- {"MQ_PRIO_MAX", _SC_MQ_PRIO_MAX},
-#endif
-#ifdef _SC_OPEN_MAX
- {"OPEN_MAX", _SC_OPEN_MAX},
-#endif
-#ifdef _SC_ADVISORY_INFO
- {"_POSIX_ADVISORY_INFO", _SC_ADVISORY_INFO},
-#endif
-#ifdef _SC_BARRIERS
- {"_POSIX_BARRIERS", _SC_BARRIERS},
-#endif
-#ifdef _SC_ASYNCHRONOUS_IO
- {"_POSIX_ASYNCHRONOUS_IO", _SC_ASYNCHRONOUS_IO},
-#endif
-#ifdef _SC_CLOCK_SELECTION
- {"_POSIX_CLOCK_SELECTION", _SC_CLOCK_SELECTION},
-#endif
-#ifdef _SC_CPUTIME
- {"_POSIX_CPUTIME", _SC_CPUTIME},
-#endif
-#ifdef _SC_FSYNC
- {"_POSIX_FSYNC", _SC_FSYNC},
-#endif
-#ifdef _SC_IPV6
- {"_POSIX_IPV6", _SC_IPV6},
-#endif
-#ifdef _SC_JOB_CONTROL
- {"_POSIX_JOB_CONTROL", _SC_JOB_CONTROL},
-#endif
-#ifdef _SC_MAPPED_FILES
- {"_POSIX_MAPPED_FILES", _SC_MAPPED_FILES},
-#endif
-#ifdef _SC_MEMLOCK
- {"_POSIX_MEMLOCK", _SC_MEMLOCK},
-#endif
-#ifdef _SC_MEMLOCK_RANGE
- {"_POSIX_MEMLOCK_RANGE", _SC_MEMLOCK_RANGE},
-#endif
-#ifdef _SC_MEMORY_PROTECTION
- {"_POSIX_MEMORY_PROTECTION", _SC_MEMORY_PROTECTION},
-#endif
-#ifdef _SC_MESSAGE_PASSING
- {"_POSIX_MESSAGE_PASSING", _SC_MESSAGE_PASSING},
-#endif
-#ifdef _SC_MONOTONIC_CLOCK
- {"_POSIX_MONOTONIC_CLOCK", _SC_MONOTONIC_CLOCK},
-#endif
-#ifdef _SC_PRIORITIZED_IO
- {"_POSIX_PRIORITIZED_IO", _SC_PRIORITIZED_IO},
-#endif
-#ifdef _SC_PRIORITY_SCHEDULING
- {"_POSIX_PRIORITY_SCHEDULING", _SC_PRIORITY_SCHEDULING},
-#endif
-#ifdef _SC_RAW_SOCKETS
- {"_POSIX_RAW_SOCKETS", _SC_RAW_SOCKETS},
-#endif
-#ifdef _SC_READER_WRITER_LOCKS
- {"_POSIX_READER_WRITER_LOCKS", _SC_READER_WRITER_LOCKS},
-#endif
-#ifdef _SC_REALTIME_SIGNALS
- {"_POSIX_REALTIME_SIGNALS", _SC_REALTIME_SIGNALS},
-#endif
-#ifdef _SC_REGEXP
- {"_POSIX_REGEXP", _SC_REGEXP},
-#endif
-#ifdef _SC_SAVED_IDS
- {"_POSIX_SAVED_IDS", _SC_SAVED_IDS},
-#endif
-#ifdef _SC_SEMAPHORES
- {"_POSIX_SEMAPHORES", _SC_SEMAPHORES},
-#endif
-#ifdef _SC_SHARED_MEMORY_OBJECTS
- {"_POSIX_SHARED_MEMORY_OBJECTS", _SC_SHARED_MEMORY_OBJECTS},
-#endif
-#ifdef _SC_SHELL
- {"_POSIX_SHELL", _SC_SHELL},
-#endif
-#ifdef _SC_SPAWN
- {"_POSIX_SPAWN", _SC_SPAWN},
-#endif
-#ifdef _SC_SPIN_LOCKS
- {"_POSIX_SPIN_LOCKS", _SC_SPIN_LOCKS},
-#endif
-#ifdef _SC_SPORADIC_SERVER
- {"_POSIX_SPORADIC_SERVER", _SC_SPORADIC_SERVER},
-#endif
-#ifdef _SC_SS_REPL_MAX
- {"_POSIX_SS_REPL_MAX", _SC_SS_REPL_MAX},
-#endif
-#ifdef _SC_SYNCHRONIZED_IO
- {"_POSIX_SYNCHRONIZED_IO", _SC_SYNCHRONIZED_IO},
-#endif
-#ifdef _SC_THREAD_ATTR_STACKADDR
- {"_POSIX_THREAD_ATTR_STACKADDR", _SC_THREAD_ATTR_STACKADDR},
-#endif
-#ifdef _SC_THREAD_ATTR_STACKSIZE
- {"_POSIX_THREAD_ATTR_STACKSIZE", _SC_THREAD_ATTR_STACKSIZE},
-#endif
-#ifdef _SC_THREAD_CPUTIME
- {"_POSIX_THREAD_CPUTIME", _SC_THREAD_CPUTIME},
-#endif
-#ifdef _SC_THREAD_PRIO_INHERIT
- {"_POSIX_THREAD_PRIO_INHERIT", _SC_THREAD_PRIO_INHERIT},
-#endif
-#ifdef _SC_THREAD_PRIO_PROTECT
- {"_POSIX_THREAD_PRIO_PROTECT", _SC_THREAD_PRIO_PROTECT},
-#endif
-#ifdef _SC_THREAD_PRIORITY_SCHEDULING
- {"_POSIX_THREAD_PRIORITY_SCHEDULING", _SC_THREAD_PRIORITY_SCHEDULING},
-#endif
-#ifdef _SC_THREAD_PROCESS_SHARED
- {"_POSIX_THREAD_PROCESS_SHARED", _SC_THREAD_PROCESS_SHARED},
-#endif
-#ifdef _SC_THREAD_ROBUST_PRIO_INHERIT
- {"_POSIX_THREAD_ROBUST_PRIO_INHERIT", _SC_THREAD_ROBUST_PRIO_INHERIT},
-#endif
-#ifdef _SC_THREAD_ROBUST_PRIO_PROTECT
- {"_POSIX_THREAD_ROBUST_PRIO_PROTECT", _SC_THREAD_ROBUST_PRIO_PROTECT},
-#endif
-#ifdef _SC_THREAD_SAFE_FUNCTIONS
- {"_POSIX_THREAD_SAFE_FUNCTIONS", _SC_THREAD_SAFE_FUNCTIONS},
-#endif
-#ifdef _SC_THREAD_SPORADIC_SERVER
- {"_POSIX_THREAD_SPORADIC_SERVER", _SC_THREAD_SPORADIC_SERVER},
-#endif
-#ifdef _SC_THREADS
- {"_POSIX_THREADS", _SC_THREADS},
-#endif
-#ifdef _SC_TIMEOUTS
- {"_POSIX_TIMEOUTS", _SC_TIMEOUTS},
-#endif
-#ifdef _SC_TIMERS
- {"_POSIX_TIMERS", _SC_TIMERS},
-#endif
-#ifdef _SC_TRACE
- {"_POSIX_TRACE", _SC_TRACE},
-#endif
-#ifdef _SC_TRACE_EVENT_FILTER
- {"_POSIX_TRACE_EVENT_FILTER", _SC_TRACE_EVENT_FILTER},
-#endif
-#ifdef _SC_TRACE_EVENT_NAME_MAX
- {"_POSIX_TRACE_EVENT_NAME_MAX", _SC_TRACE_EVENT_NAME_MAX},
-#endif
-#ifdef _SC_TRACE_INHERIT
- {"_POSIX_TRACE_INHERIT", _SC_TRACE_INHERIT},
-#endif
-#ifdef _SC_TRACE_LOG
- {"_POSIX_TRACE_LOG", _SC_TRACE_LOG},
-#endif
-#ifdef _SC_TRACE_NAME_MAX
- {"_POSIX_TRACE_NAME_MAX", _SC_TRACE_NAME_MAX},
-#endif
-#ifdef _SC_TRACE_SYS_MAX
- {"_POSIX_TRACE_SYS_MAX", _SC_TRACE_SYS_MAX},
-#endif
-#ifdef _SC_TRACE_USER_EVENT_MAX
- {"_POSIX_TRACE_USER_EVENT_MAX", _SC_TRACE_USER_EVENT_MAX},
-#endif
-#ifdef _SC_TYPED_MEMORY_OBJECTS
- {"_POSIX_TYPED_MEMORY_OBJECTS", _SC_TYPED_MEMORY_OBJECTS},
-#endif
-#ifdef _SC_VERSION
- {"_POSIX_VERSION", _SC_VERSION},
-#endif
-#ifdef _SC_V7_ILP32_OFF32
- {"_POSIX_V7_ILP32_OFF32", _SC_V7_ILP32_OFF32},
-#endif
-#ifdef _SC_V7_ILP32_OFFBIG
- {"_POSIX_V7_ILP32_OFFBIG", _SC_V7_ILP32_OFFBIG},
-#endif
-#ifdef _SC_V7_LP64_OFF64
- {"_POSIX_V7_LP64_OFF64", _SC_V7_LP64_OFF64},
-#endif
-#ifdef _SC_V7_LPBIG_OFFBIG
- {"_POSIX_V7_LPBIG_OFFBIG", _SC_V7_LPBIG_OFFBIG},
-#endif
-#ifdef _SC_2_C_BIND
- {"_POSIX2_C_BIND", _SC_2_C_BIND},
-#endif
-#ifdef _SC_2_C_DEV
- {"_POSIX2_C_DEV", _SC_2_C_DEV},
-#endif
-#ifdef _SC_2_CHAR_TERM
- {"_POSIX2_CHAR_TERM", _SC_2_CHAR_TERM},
-#endif
-#ifdef _SC_2_FORT_DEV
- {"_POSIX2_FORT_DEV", _SC_2_FORT_DEV},
-#endif
-#ifdef _SC_2_FORT_RUN
- {"_POSIX2_FORT_RUN", _SC_2_FORT_RUN},
-#endif
-#ifdef _SC_2_LOCALEDEF
- {"_POSIX2_LOCALEDEF", _SC_2_LOCALEDEF},
-#endif
-#ifdef _SC_2_PBS
- {"_POSIX2_PBS", _SC_2_PBS},
-#endif
-#ifdef _SC_2_PBS_ACCOUNTING
- {"_POSIX2_PBS_ACCOUNTING", _SC_2_PBS_ACCOUNTING},
-#endif
-#ifdef _SC_2_PBS_CHECKPOINT
- {"_POSIX2_PBS_CHECKPOINT", _SC_2_PBS_CHECKPOINT},
-#endif
-#ifdef _SC_2_PBS_LOCATE
- {"_POSIX2_PBS_LOCATE", _SC_2_PBS_LOCATE},
-#endif
-#ifdef _SC_2_PBS_MESSAGE
- {"_POSIX2_PBS_MESSAGE", _SC_2_PBS_MESSAGE},
-#endif
-#ifdef _SC_2_PBS_TRACK
- {"_POSIX2_PBS_TRACK", _SC_2_PBS_TRACK},
-#endif
-#ifdef _SC_2_SW_DEV
- {"_POSIX2_SW_DEV", _SC_2_SW_DEV},
-#endif
-#ifdef _SC_2_UPE
- {"_POSIX2_UPE", _SC_2_UPE},
-#endif
-#ifdef _SC_2_VERSION
- {"_POSIX2_VERSION", _SC_2_VERSION},
-#endif
-#ifdef _SC_PAGE_SIZE
- {"PAGE_SIZE", _SC_PAGE_SIZE},
-#endif
-#ifdef _SC_PAGESIZE
- {"PAGESIZE", _SC_PAGESIZE},
-#endif
-#ifdef _SC_THREAD_DESTRUCTOR_ITERATIONS
- {"PTHREAD_DESTRUCTOR_ITERATIONS", _SC_THREAD_DESTRUCTOR_ITERATIONS},
-#endif
-#ifdef _SC_THREAD_KEYS_MAX
- {"PTHREAD_KEYS_MAX", _SC_THREAD_KEYS_MAX},
-#endif
-#ifdef _SC_THREAD_STACK_MIN
- {"PTHREAD_STACK_MIN", _SC_THREAD_STACK_MIN},
-#endif
-#ifdef _SC_THREAD_THREADS_MAX
- {"PTHREAD_THREADS_MAX", _SC_THREAD_THREADS_MAX},
-#endif
-#ifdef _SC_RE_DUP_MAX
- {"RE_DUP_MAX", _SC_RE_DUP_MAX},
-#endif
-#ifdef _SC_RTSIG_MAX
- {"RTSIG_MAX", _SC_RTSIG_MAX},
-#endif
-#ifdef _SC_SEM_NSEMS_MAX
- {"SEM_NSEMS_MAX", _SC_SEM_NSEMS_MAX},
-#endif
-#ifdef _SC_SEM_VALUE_MAX
- {"SEM_VALUE_MAX", _SC_SEM_VALUE_MAX},
-#endif
-#ifdef _SC_SIGQUEUE_MAX
- {"SIGQUEUE_MAX", _SC_SIGQUEUE_MAX},
-#endif
-#ifdef _SC_STREAM_MAX
- {"STREAM_MAX", _SC_STREAM_MAX},
-#endif
-#ifdef _SC_SYMLOOP_MAX
- {"SYMLOOP_MAX", _SC_SYMLOOP_MAX},
-#endif
-#ifdef _SC_TIMER_MAX
- {"TIMER_MAX", _SC_TIMER_MAX},
-#endif
-#ifdef _SC_TTY_NAME_MAX
- {"TTY_NAME_MAX", _SC_TTY_NAME_MAX},
-#endif
-#ifdef _SC_TZNAME_MAX
- {"TZNAME_MAX", _SC_TZNAME_MAX},
-#endif
-#ifdef _SC_XOPEN_CRYPT
- {"_XOPEN_CRYPT", _SC_XOPEN_CRYPT},
-#endif
-#ifdef _SC_XOPEN_ENH_I18N
- {"_XOPEN_ENH_I18N", _SC_XOPEN_ENH_I18N},
-#endif
-#ifdef _SC_XOPEN_REALTIME
- {"_XOPEN_REALTIME", _SC_XOPEN_REALTIME},
-#endif
-#ifdef _SC_XOPEN_REALTIME_THREADS
- {"_XOPEN_REALTIME_THREADS", _SC_XOPEN_REALTIME_THREADS},
-#endif
-#ifdef _SC_XOPEN_SHM
- {"_XOPEN_SHM", _SC_XOPEN_SHM},
-#endif
-#ifdef _SC_XOPEN_STREAMS
- {"_XOPEN_STREAMS", _SC_XOPEN_STREAMS},
-#endif
-#ifdef _SC_XOPEN_UNIX
- {"_XOPEN_UNIX", _SC_XOPEN_UNIX},
-#endif
-#ifdef _SC_XOPEN_UUCP
- {"_XOPEN_UUCP", _SC_XOPEN_UUCP},
-#endif
-#ifdef _SC_XOPEN_VERSION
- {"_XOPEN_VERSION", _SC_XOPEN_VERSION},
-#endif
-};
-static const struct var pathconf_l[] = {
-#ifdef _PC_FILESIZEBITS
- {"FILESIZEBITS", _PC_FILESIZEBITS},
-#endif
-#ifdef _PC_LINK_MAX
- {"LINK_MAX", _PC_LINK_MAX},
-#endif
-#ifdef _PC_MAX_CANON
- {"MAX_CANON", _PC_MAX_CANON},
-#endif
-#ifdef _PC_MAX_INPUT
- {"MAX_INPUT", _PC_MAX_INPUT},
-#endif
-#ifdef _PC_NAME_MAX
- {"NAME_MAX", _PC_NAME_MAX},
-#endif
-#ifdef _PC_PATH_MAX
- {"PATH_MAX", _PC_PATH_MAX},
-#endif
-#ifdef _PC_PIPE_BUF
- {"PIPE_BUF", _PC_PIPE_BUF},
-#endif
-#ifdef _PC_2_SYMLINKS
- {"POSIX2_SYMLINKS", _PC_2_SYMLINKS},
-#endif
-#ifdef _PC_ALLOC_SIZE_MIN
- {"POSIX_ALLOC_SIZE_MIN", _PC_ALLOC_SIZE_MIN},
-#endif
-#ifdef _PC_REC_INCR_XFER_SIZE
- {"POSIX_REC_INCR_XFER_SIZE", _PC_REC_INCR_XFER_SIZE},
-#endif
-#ifdef _PC_REC_MAX_XFER_SIZE
- {"POSIX_REC_MAX_XFER_SIZE", _PC_REC_MAX_XFER_SIZE},
-#endif
-#ifdef _PC_REC_MIN_XFER_SIZE
- {"POSIX_REC_MIN_XFER_SIZE", _PC_REC_MIN_XFER_SIZE},
-#endif
-#ifdef _PC_REC_XFER_ALIGN
- {"POSIX_REC_XFER_ALIGN", _PC_REC_XFER_ALIGN},
-#endif
-#ifdef _PC_SYMLINK_MAX
- {"SYMLINK_MAX", _PC_SYMLINK_MAX},
-#endif
-#ifdef _PC_CHOWN_RESTRICTED
- {"_POSIX_CHOWN_RESTRICTED", _PC_CHOWN_RESTRICTED},
-#endif
-#ifdef _PC_NO_TRUNC
- {"_POSIX_NO_TRUNC", _PC_NO_TRUNC},
-#endif
-#ifdef _PC_VDISABLE
- {"_POSIX_VDISABLE", _PC_VDISABLE},
-#endif
-#ifdef _PC_ASYNC_IO
- {"_POSIX_ASYNC_IO", _PC_ASYNC_IO},
-#endif
-#ifdef _PC_PRIO_IO
- {"_POSIX_PRIO_IO", _PC_PRIO_IO},
-#endif
-#ifdef _PC_SYNC_IO
- {"_POSIX_SYNC_IO", _PC_SYNC_IO},
-#endif
-#ifdef _PC_TIMESTAMP_RESOLUTION
- {"_POSIX_TIMESTAMP_RESOLUTION", _PC_TIMESTAMP_RESOLUTION},
-#endif
-};
diff --git a/cmd/posix/grep.c b/cmd/posix/grep.c
@@ -1,3 +1,11 @@
+/* ?man
+grep: search files for a pattern
+usage: grep [-EFHchilnqsvwx] [-e pattern] [-f file] [pattern] [file ...]
+
+grep searches the named input files for lines matching the given pattern
+if no files are named, or a file is -, standard input is searched
+by default, matching lines are written to standard output
+*/
#include "config.h"
#include "queue.h"
#include "util.h"
@@ -255,12 +263,15 @@ main(int argc, char *argv[])
ARGBEGIN {
#if FEATURE_GREP_CONTEXT
case 'A':
+ // ?man -A num: print num lines of trailing context after each match
Aflag = estrtonum(EARGF(usage()), 0, LONG_MAX);
break;
case 'B':
+ // ?man -B num: print num lines of leading context before each match
Bflag = estrtonum(EARGF(usage()), 0, LONG_MAX);
break;
case 'C':
+ // ?man -C num: print num lines of context before and after each match; equivalent to -A num -B num
Aflag = Bflag = estrtonum(EARGF(usage()), 0, LONG_MAX);
break;
ARGNUM:
@@ -269,24 +280,29 @@ main(int argc, char *argv[])
#endif
#if FEATURE_GREP_MAX_COUNT
case 'm':
+ // ?man -m num: stop reading a file after num matching lines
mval = estrtonum(EARGF(usage()), 0, LONG_MAX);
break;
#endif
case 'E':
+ // ?man -E: interpret pattern as an extended regular expression
Eflag = 1;
Fflag = 0;
flags |= REG_EXTENDED;
break;
case 'F':
+ // ?man -F: interpret pattern as a list of fixed strings separated by newlines
Fflag = 1;
Eflag = 0;
flags &= ~REG_EXTENDED;
break;
case 'H':
+ // ?man -H: always print the file name with matching lines
Hflag = 1;
hflag = 0;
break;
case 'e':
+ // ?man -e pattern: specify a pattern to match; may be given multiple times
arg = EARGF(usage());
if (!(fp = fmemopen(arg, strlen(arg) + 1, "r")))
eprintf("fmemopen:");
@@ -295,6 +311,7 @@ main(int argc, char *argv[])
eflag = 1;
break;
case 'f':
+ // ?man -f file: read patterns from file, one per line
arg = EARGF(usage());
fp = fopen(arg, "r");
if (!fp)
@@ -304,29 +321,42 @@ main(int argc, char *argv[])
fflag = 1;
break;
case 'h':
+ // ?man -h: never print file names with matching lines
hflag = 1;
Hflag = 0;
break;
case 'c':
+ // ?man -c: print only a count of matching lines per file
+ /* FALLTHROUGH */
case 'l':
+ // ?man -l: print only the names of files with at least one matching line
+ /* FALLTHROUGH */
case 'n':
+ // ?man -n: prefix each matching line with its line number within its file
+ /* FALLTHROUGH */
case 'q':
+ // ?man -q: quiet mode; exit immediately with status 0 on first match and write nothing
mode = ARGC();
break;
case 'i':
+ // ?man -i: perform case-insensitive matching
flags |= REG_ICASE;
iflag = 1;
break;
case 's':
+ // ?man -s: suppress error messages about nonexistent or unreadable files
sflag = 1;
break;
case 'v':
+ // ?man -v: invert the sense of matching to select non-matching lines
vflag = 1;
break;
case 'w':
+ // ?man -w: match only whole words
wflag = 1;
break;
case 'x':
+ // ?man -x: match only whole lines
xflag = 1;
break;
default:
@@ -375,5 +405,22 @@ main(int argc, char *argv[])
if (fshut(stdin, "<stdin>") | fshut(stdout, "<stdout>"))
match = Error;
+ /* ?man
+ ## Exit status
+
+ 0
+ : one or more lines matched in at least one file
+
+ 1
+ : no lines matched in any file
+
+ 2
+ : an error occurred
+
+ ## See also
+
+ sed(1), awk(1)
+ */
+
return match;
}
diff --git a/cmd/posix/head.c b/cmd/posix/head.c
@@ -1,4 +1,11 @@
/* See LICENSE file for copyright and license details. */
+/* ?man
+head: output first part of files
+usage: head [-num | -n num] [file ...]
+
+print the first lines or bytes of files
+*/
+
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
@@ -36,6 +43,7 @@ main(int argc, char *argv[])
int ret = 0, newline = 0, many = 0;
ARGBEGIN {
+ // ?man -n: print line numbers or counts
case 'n':
n = estrtonum(EARGF(usage()), 0, MIN((unsigned long long)LLONG_MAX, (unsigned long long)SIZE_MAX));
break;
diff --git a/cmd/posix/id.c b/cmd/posix/id.c
@@ -1,4 +1,11 @@
/* See LICENSE file for copyright and license details. */
+/* ?man
+id: print user and group ids
+usage: id [-n] [-g | -u | -G] [user | uid]
+
+display real and effective user and group identities
+*/
+
#include <sys/types.h>
#include <ctype.h>
@@ -137,15 +144,19 @@ int
main(int argc, char *argv[])
{
ARGBEGIN {
+ // ?man -g: specify option flag
case 'g':
gflag = 1;
break;
+ // ?man -u: unbuffered output
case 'u':
uflag = 1;
break;
+ // ?man -G: specify option flag
case 'G':
Gflag = 1;
break;
+ // ?man -n: print line numbers or counts
case 'n':
nflag = 1;
break;
diff --git a/cmd/posix/join.c b/cmd/posix/join.c
@@ -1,4 +1,11 @@
/* See LICENSE file for copyright and license details. */
+/* ?man
+join: join lines on common field
+usage: join [-1 field] [-2 field] [-o list] [-e string]
+
+join lines of two sorted files on a common field
+*/
+
#include <ctype.h>
#include <stdint.h>
#include <stdio.h>
@@ -458,12 +465,15 @@ main(int argc, char *argv[])
char *fno;
ARGBEGIN {
+ // ?man -1: specify option flag
case '1':
jf[0] = estrtonum(EARGF(usage()), 1, MIN((unsigned long long)LLONG_MAX, (unsigned long long)SIZE_MAX));
break;
+ // ?man -2: specify option flag
case '2':
jf[1] = estrtonum(EARGF(usage()), 1, MIN((unsigned long long)LLONG_MAX, (unsigned long long)SIZE_MAX));
break;
+ // ?man -a: print or show all entries
case 'a':
fno = EARGF(usage());
if (strcmp(fno, "1") == 0)
@@ -473,17 +483,21 @@ main(int argc, char *argv[])
else
usage();
break;
+ // ?man -e: specify expression or pattern
case 'e':
replace = EARGF(usage());
break;
+ // ?man -o: specify output file
case 'o':
oflag = 1;
initolist(&output);
makeolist(&output, EARGF(usage()));
break;
+ // ?man -t: sort or specify timestamp
case 't':
sep = EARGF(usage());
break;
+ // ?man -v: verbose mode; show progress
case 'v':
pairs = 0;
fno = EARGF(usage());
diff --git a/cmd/posix/kill.c b/cmd/posix/kill.c
@@ -1,4 +1,11 @@
/* See LICENSE file for copyright and license details. */
+/* ?man
+kill: send signal to process
+usage: kill [-s signame | -num | -signame] pid ...
+
+send a specified signal to processes by pid
+*/
+
#include "sig.h"
#include "util.h"
diff --git a/cmd/posix/link.c b/cmd/posix/link.c
@@ -1,4 +1,11 @@
/* See LICENSE file for copyright and license details. */
+/* ?man
+link: create a link to a file
+usage: link target name
+
+create a hard link to an existing file
+*/
+
#include <unistd.h>
#include "util.h"
diff --git a/cmd/posix/ln.c b/cmd/posix/ln.c
@@ -1,4 +1,11 @@
/* See LICENSE file for copyright and license details. */
+/* ?man
+ln: make links between files
+usage: ln [-f] [-L | -P | -s] target [name]
+
+create hard or symbolic links between files
+*/
+
#include <sys/stat.h>
#include <errno.h>
@@ -25,15 +32,19 @@ main(int argc, char *argv[])
struct stat st, tst;
ARGBEGIN {
+ // ?man -f: force creation of links by removing existing destination files
case 'f':
fflag = 1;
break;
+ // ?man -L: specify option flag
case 'L':
flags |= AT_SYMLINK_FOLLOW;
break;
+ // ?man -P: specify option flag
case 'P':
flags &= ~AT_SYMLINK_FOLLOW;
break;
+ // ?man -s: make symbolic links instead of hard links
case 's':
sflag = 1;
break;
diff --git a/cmd/posix/logger.c b/cmd/posix/logger.c
@@ -1,4 +1,11 @@
/* See LICENSE file for copyright and license details. */
+/* ?man
+logger: log messages
+usage: logger [-is] [-p priority] [-t tag] [message ...]
+
+add messages to the system log
+*/
+
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
@@ -51,15 +58,19 @@ main(int argc, char *argv[])
char *buf = NULL, *tag = NULL;
ARGBEGIN {
+ // ?man -i: interactive mode or prompt for confirmation
case 'i':
logflags |= LOG_PID;
break;
+ // ?man -p: preserve file attributes
case 'p':
priority = decodepri(EARGF(usage()));
break;
+ // ?man -s: silent mode or print summary
case 's':
logflags |= LOG_PERROR;
break;
+ // ?man -t: sort or specify timestamp
case 't':
tag = EARGF(usage());
break;
diff --git a/cmd/posix/logname.c b/cmd/posix/logname.c
@@ -1,4 +1,11 @@
/* See LICENSE file for copyright and license details. */
+/* ?man
+logname: print login name
+usage: logname
+
+display the user login name
+*/
+
#include <stdio.h>
#include <unistd.h>
diff --git a/cmd/posix/ls.c b/cmd/posix/ls.c
@@ -1,4 +1,11 @@
-/* See LICENSE file for copyright and license details. */
+/* see license file for copyright and license details */
+/* ?man
+ls: list directory contents
+usage: ls [-1ACacdFfGghiLlnopqRrtUu] [--color[=always|never|auto]] [file ...]
+
+list information about files and directories
+*/
+
#include <sys/stat.h>
#include <sys/types.h>
#ifndef major
@@ -58,6 +65,9 @@ static int first = 1;
static char sort = 0;
static int showdirs;
+static int gflag = 0;
+static int oflag = 0;
+
static int Cflag = 0;
static int one_flag = 0;
static int termwidth = 80;
@@ -152,17 +162,17 @@ printname(const char *name)
}
}
-#if FEATURE_LS_COLOR
static int
should_color(void)
{
+#if FEATURE_LS_COLOR
if (color_mode == COLOR_ALWAYS)
return 1;
if (color_mode == COLOR_AUTO)
return isatty(STDOUT_FILENO);
+#endif
return 0;
}
-#endif
static void
printname_colored(const char *name, mode_t mode)
@@ -287,7 +297,7 @@ printcols(const struct entry *ents, size_t n)
printf("%lu ", (unsigned long)ents[idx].ino);
printname_colored(ents[idx].name, ents[idx].mode);
fputs(indicator(ents[idx].mode), stdout);
-
+
if (c < ncols - 1 && (c + 1) * nrows + r < (int)n) {
int pad = colwidths[c] - w + 2;
while (pad-- > 0)
@@ -368,7 +378,11 @@ output(const struct entry *ent)
strftime(buf, sizeof(buf), fmt, tm);
else
snprintf(buf, sizeof(buf), "%lld", (long long)(ent->t.tv_sec));
- printf("%s %4ld %-8.8s %-8.8s ", mode, (long)ent->nlink, pwname, grname);
+ printf("%s %4ld ", mode, (long)ent->nlink);
+ if (!gflag)
+ printf("%-8.8s ", pwname);
+ if (!oflag)
+ printf("%-8.8s ", grname);
if (S_ISBLK(ent->mode) || S_ISCHR(ent->mode))
printf("%4u, %4u ", major(ent->rdev), minor(ent->rdev));
@@ -397,9 +411,11 @@ entcmp(const void *va, const void *vb)
const struct entry *a = va, *b = vb;
switch (sort) {
+ // ?man -S: sort by file size
case 'S':
cmp = b->size - a->size;
break;
+ // ?man -t: sort by modification time
case 't':
if (!(cmp = b->t.tv_sec - a->t.tv_sec))
cmp = b->t.tv_nsec - a->t.tv_nsec;
@@ -439,7 +455,7 @@ lsdir(const char *path, const struct entry *dir)
ents = ereallocarray(ents, ++n, sizeof(*ents));
mkent(&ents[n - 1], estrdup(d->d_name), Fflag || iflag ||
- lflag || pflag || Rflag || sort, Lflag);
+ lflag || pflag || Rflag || sort || should_color(), Lflag);
}
closedir(dp);
@@ -537,7 +553,7 @@ ls(const char *path, const struct entry *ent, int listdir)
static void
usage(void)
{
- eprintf("usage: %s [-1ACacdFfHhiLlnpqRrtUu] [file ...]\n", argv0);
+ eprintf("usage: %s [-1ACacdFfGghiLlnopqRrtUu] [--color[=always|never|auto]] [file ...]\n", argv0);
}
int
@@ -545,96 +561,156 @@ main(int argc, char *argv[])
{
struct entry ent, *dents, *fents;
size_t i, ds, fs;
+#if FEATURE_LS_COLOR
+ char *val;
+#endif
if (isatty(STDOUT_FILENO))
Cflag = 1;
else
one_flag = 1;
+#if FEATURE_LS_COLOR
+ if ((val = getenv("CLICOLOR_FORCE"))) {
+ if (*val && strcmp(val, "0") != 0)
+ color_mode = COLOR_ALWAYS;
+ else
+ color_mode = COLOR_NEVER;
+ } else if ((val = getenv("CLICOLOR"))) {
+ if (*val && strcmp(val, "0") != 0)
+ color_mode = COLOR_AUTO;
+ else
+ color_mode = COLOR_NEVER;
+ }
+#endif
+
tree = ereallocarray(NULL, PATH_MAX, sizeof(*tree));
ARGBEGIN {
+ // ?man -1: list one file per line
case '1':
one_flag = 1;
Cflag = 0;
lflag = 0;
break;
+ // ?man -A: list all entries except dot and dot dot
case 'A':
Aflag = 1;
break;
+ // ?man -a: list all entries including those starting with a dot
case 'a':
aflag = 1;
break;
+ // ?man -c: sort by ctime or use ctime for long listing
case 'c':
cflag = 1;
uflag = 0;
break;
+ // ?man -C: list entries in columns sorted vertically
case 'C':
Cflag = 1;
one_flag = 0;
lflag = 0;
break;
+ // ?man -d: list directory entries instead of their contents
case 'd':
dflag = 1;
break;
+ // ?man -f: do not sort and enable a and U
case 'f':
aflag = 1;
fflag = 1;
Uflag = 1;
break;
+ // ?man -F: append type indicators
case 'F':
Fflag = 1;
break;
+#if FEATURE_LS_COLOR
+ // ?man -G: enable colored output
+ case 'G':
+ color_mode = COLOR_AUTO;
+ break;
+#endif
+ // ?man -g: list in long format without owner name
+ case 'g':
+ gflag = 1;
+ lflag = 1;
+ Cflag = 0;
+ one_flag = 0;
+ break;
+ // ?man -H: follow symlinks on the command line
case 'H':
Hflag = 1;
break;
+ // ?man -h: print human readable sizes
case 'h':
hflag = 1;
break;
+ // ?man -i: print inode number of each file
case 'i':
iflag = 1;
break;
+ // ?man -L: follow all symlinks
case 'L':
Lflag = 1;
break;
+ // ?man -l: use a long listing format
case 'l':
lflag = 1;
Cflag = 0;
one_flag = 0;
break;
+ // ?man -n: list numeric uids and gids
case 'n':
lflag = 1;
nflag = 1;
Cflag = 0;
one_flag = 0;
break;
+ // ?man -o: list in long format without group name
+ case 'o':
+ oflag = 1;
+ lflag = 1;
+ Cflag = 0;
+ one_flag = 0;
+ break;
+ // ?man -p: append slash indicator to directories
case 'p':
pflag = 1;
break;
+ // ?man -q: print non printable characters as question marks
case 'q':
qflag = 1;
break;
+ // ?man -R: list subdirectories recursively
case 'R':
Rflag = 1;
break;
+ // ?man -r: reverse sort order
case 'r':
rflag = 1;
break;
+ // ?man -S: sort by file size
case 'S':
sort = 'S';
break;
+ // ?man -t: sort by modification time
case 't':
sort = 't';
break;
+ // ?man -U: do not sort
case 'U':
Uflag = 1;
break;
+ // ?man -u: sort by atime or use atime for long listing
case 'u':
uflag = 1;
cflag = 0;
break;
case '-':
#if FEATURE_LS_COLOR
+ // ?man --color [when]: control coloring
if (strncmp(argv[0], "-color", 6) == 0) {
char *val = NULL;
if (argv[0][6] == '=') {
diff --git a/cmd/posix/mesg.c b/cmd/posix/mesg.c
@@ -1,4 +1,11 @@
/* See LICENSE file for copyright and license details. */
+/* ?man
+mesg: control write access
+usage: mesg [n|y]
+
+allow or disallow other users to write to the terminal
+*/
+
#include <sys/stat.h>
#include <sys/types.h>
diff --git a/cmd/posix/mkdir.c b/cmd/posix/mkdir.c
@@ -1,4 +1,11 @@
/* See LICENSE file for copyright and license details. */
+/* ?man
+mkdir: create directories
+usage: mkdir [-p] [-m mode] name ...
+
+create directories at specified paths
+*/
+
#include <sys/stat.h>
#include <errno.h>
@@ -22,9 +29,11 @@ main(int argc, char *argv[])
mode = 0777 & ~mask;
ARGBEGIN {
+ // ?man -p: create parent directories as needed
case 'p':
pflag = 1;
break;
+ // ?man -m: set file mode bits for created directories
case 'm':
mode = parsemode(EARGF(usage()), 0777, mask);
break;
diff --git a/cmd/posix/mkfifo.c b/cmd/posix/mkfifo.c
@@ -1,4 +1,11 @@
/* See LICENSE file for copyright and license details. */
+/* ?man
+mkfifo: make fifos
+usage: mkfifo [-m mode] name ...
+
+create named pipes at specified paths
+*/
+
#include <sys/stat.h>
#include <stdlib.h>
@@ -18,6 +25,7 @@ main(int argc, char *argv[])
int ret = 0;
ARGBEGIN {
+ // ?man -m: specify mode or limit
case 'm':
mode = parsemode(EARGF(usage()), mode, umask(0));
break;
diff --git a/cmd/posix/mv.c b/cmd/posix/mv.c
@@ -1,4 +1,11 @@
/* See LICENSE file for copyright and license details. */
+/* ?man
+mv: move or rename files
+usage: mv [-f] source ... dest
+
+move or rename files and directories
+*/
+
#include <sys/stat.h>
#include <errno.h>
@@ -47,6 +54,7 @@ main(int argc, char *argv[])
struct stat st;
ARGBEGIN {
+ // ?man -f: do not prompt before overwriting
case 'f':
break;
default:
diff --git a/cmd/posix/nice.c b/cmd/posix/nice.c
@@ -1,4 +1,11 @@
/* See LICENSE file for copyright and license details. */
+/* ?man
+nice: run command with modified priority
+usage: nice [-n inc] cmd [arg ...]
+
+run a command with modified scheduling priority
+*/
+
#include <sys/resource.h>
#include <errno.h>
@@ -27,6 +34,7 @@ main(int argc, char *argv[])
int val = 10, r, savederrno;
ARGBEGIN {
+ // ?man -n: print line numbers or counts
case 'n':
val = estrtonum(EARGF(usage()), PRIO_MIN, PRIO_MAX);
break;
diff --git a/cmd/posix/nl.c b/cmd/posix/nl.c
@@ -1,4 +1,11 @@
/* See LICENSE file for copyright and license details. */
+/* ?man
+nl: number lines
+usage: nl [-p] [-b type] [-d delim] [-f type]
+
+number the lines of files
+*/
+
#include <limits.h>
#include <stdint.h>
#include <stdio.h>
@@ -71,7 +78,8 @@ nl(const char *fname, FILE *fp)
if (line.data[0] != '\n')
donumber = 1;
break;
- case 'p':
+ // ?man -p: preserve file attributes
+ case 'p':
if (!regexec(preg + section, line.data, 0, NULL, 0))
donumber = 1;
break;
@@ -124,6 +132,7 @@ main(int argc, char *argv[])
char *d, *formattype, *formatblit;
ARGBEGIN {
+ // ?man -d: specify directory
case 'd':
switch (utflen((d = EARGF(usage())))) {
case 0:
@@ -142,21 +151,27 @@ main(int argc, char *argv[])
break;
}
break;
+ // ?man -f: force the operation
case 'f':
type[0] = getlinetype(EARGF(usage()), preg);
break;
+ // ?man -b: specify block size or base directory
case 'b':
type[1] = getlinetype(EARGF(usage()), preg + 1);
break;
+ // ?man -h: suppress headers or print help
case 'h':
type[2] = getlinetype(EARGF(usage()), preg + 2);
break;
+ // ?man -i: interactive mode or prompt for confirmation
case 'i':
incr = estrtonum(EARGF(usage()), 0, MIN((unsigned long long)LLONG_MAX, (unsigned long long)SIZE_MAX));
break;
+ // ?man -l: list in long format
case 'l':
blines = estrtonum(EARGF(usage()), 0, MIN((unsigned long long)LLONG_MAX, (unsigned long long)SIZE_MAX));
break;
+ // ?man -n: print line numbers or counts
case 'n':
formattype = EARGF(usage());
estrlcpy(format, "%", sizeof(format));
@@ -174,16 +189,20 @@ main(int argc, char *argv[])
estrlcat(format, formatblit, sizeof(format));
estrlcat(format, "*ld", sizeof(format));
break;
+ // ?man -p: preserve file attributes
case 'p':
pflag = 1;
break;
+ // ?man -s: silent mode or print summary
case 's':
sep = EARGF(usage());
seplen = unescape(sep);
break;
+ // ?man -v: verbose mode; show progress
case 'v':
startnum = estrtonum(EARGF(usage()), 0, MIN((unsigned long long)LLONG_MAX, (unsigned long long)SIZE_MAX));
break;
+ // ?man -w: wait for completion
case 'w':
width = estrtonum(EARGF(usage()), 1, INT_MAX);
break;
diff --git a/cmd/posix/nohup.c b/cmd/posix/nohup.c
@@ -1,4 +1,11 @@
/* See LICENSE file for copyright and license details. */
+/* ?man
+nohup: run command immune to hangups
+usage: nohup cmd [arg ...]
+
+run a command that persists after logging out
+*/
+
#include <sys/stat.h>
#include <errno.h>
diff --git a/cmd/posix/od.c b/cmd/posix/od.c
@@ -1,4 +1,11 @@
/* See LICENSE file for copyright and license details. */
+/* ?man
+od: dump files in formats
+usage: od [-bdosvx] [-A addressformat]
+
+display file contents in octal, hex, or other formats
+*/
+
#include "queue.h"
#include "util.h"
@@ -59,6 +66,7 @@ printchunk(const unsigned char *s, unsigned char format, size_t len)
};
switch (format) {
+ // ?man -a: print or show all entries
case 'a':
c = *s & ~128; /* clear high bit as required by standard */
if (c < LEN(namedict) || c == 127) {
@@ -67,6 +75,7 @@ printchunk(const unsigned char *s, unsigned char format, size_t len)
printf(" %3c", c);
}
break;
+ // ?man -c: print count or perform stdout action
case 'c':
if (strchr("\a\b\t\n\v\f\r\0", *s)) {
printf(" %3s", escdict[*s]);
@@ -220,69 +229,89 @@ main(int argc, char *argv[])
big_endian = (*(uint16_t *)"\0\xff" == 0xff);
ARGBEGIN {
+ // ?man -A: specify option flag
case 'A':
s = EARGF(usage());
if (strlen(s) != 1 || !strchr("doxn", s[0]))
usage();
addr_format = s[0];
break;
+ // ?man -b: specify block size or base directory
case 'b':
addtype('o', 1);
break;
+ // ?man -d: specify directory
case 'd':
addtype('u', 2);
break;
#if FEATURE_OD_ENDIAN
+ // ?man -E: specify option flag
case 'E':
+ // ?man -e: specify expression or pattern
case 'e':
big_endian = (ARGC() == 'E');
break;
#endif
+ // ?man -j: specify option flag
case 'j':
if ((skip = parseoffset(EARGF(usage()))) < 0)
usage();
break;
+ // ?man -N: specify option flag
case 'N':
if ((max = parseoffset(EARGF(usage()))) < 0)
usage();
break;
+ // ?man -o: specify output file
case 'o':
addtype('o', 2);
break;
+ // ?man -s: silent mode or print summary
case 's':
addtype('d', 2);
break;
+ // ?man -t: sort or specify timestamp
case 't':
s = EARGF(usage());
for (; *s; s++) {
switch (*s) {
- case 'a':
- case 'c':
+ // ?man -a: print or show all entries
+ case 'a':
+ // ?man -c: print count or perform stdout action
+ case 'c':
addtype(*s, 1);
break;
- case 'd':
- case 'o':
- case 'u':
- case 'x':
+ // ?man -d: specify directory
+ case 'd':
+ // ?man -o: specify output file
+ case 'o':
+ // ?man -u: unbuffered output
+ case 'u':
+ // ?man -x: hex format or match whole lines
+ case 'x':
fmt_char = *s;
if (isdigit((unsigned char)*(s + 1))) {
len = strtol(s + 1, &end, 10);
s = end - 1;
} else {
switch (*(s + 1)) {
- case 'C':
+ // ?man -C: specify option flag
+ case 'C':
len = sizeof(char);
s++;
break;
- case 'S':
+ // ?man -S: specify option flag
+ case 'S':
len = sizeof(short);
s++;
break;
- case 'I':
+ // ?man -I: specify option flag
+ case 'I':
len = sizeof(int);
s++;
break;
- case 'L':
+ // ?man -L: specify option flag
+ case 'L':
len = sizeof(long);
s++;
break;
@@ -297,9 +326,11 @@ main(int argc, char *argv[])
}
}
break;
+ // ?man -v: verbose mode; show progress
case 'v':
/* always set, use uniq(1) to handle duplicate lines */
break;
+ // ?man -x: hex format or match whole lines
case 'x':
addtype('x', 2);
break;
diff --git a/cmd/posix/paste.c b/cmd/posix/paste.c
@@ -1,4 +1,11 @@
/* See LICENSE file for copyright and license details. */
+/* ?man
+paste: merge lines of files
+usage: paste [-s] [-d list] file ...
+
+merge corresponding lines of files side by side
+*/
+
#include <stdlib.h>
#include <string.h>
@@ -94,9 +101,11 @@ main(int argc, char *argv[])
char *delim = "\t";
ARGBEGIN {
+ // ?man -s: silent mode or print summary
case 's':
seq = 1;
break;
+ // ?man -d: specify directory
case 'd':
delim = EARGF(usage());
delim_bytelen = unescape(delim);
diff --git a/cmd/posix/pathchk.c b/cmd/posix/pathchk.c
@@ -1,4 +1,11 @@
/* See LICENSE file for copyright and license details. */
+/* ?man
+pathchk: check pathnames
+usage: pathchk [-pP] filename...
+
+verify that pathnames are valid and portable
+*/
+
#include <sys/stat.h>
#include <errno.h>
@@ -84,9 +91,11 @@ main(int argc, char *argv[])
int ret = 0;
ARGBEGIN {
+ // ?man -p: preserve file attributes
case 'p':
most = 1;
break;
+ // ?man -P: specify option flag
case 'P':
extra = 1;
break;
diff --git a/cmd/posix/pax.c b/cmd/posix/pax.c
@@ -1,3 +1,10 @@
+/* ?man
+pax: portable archive interchange
+usage: pax
+
+read, write, and list member files of archive files
+*/
+
/* taken from: https://github.com/michaelforney/pax */
#ifndef _GNU_SOURCE
#define _GNU_SOURCE /* needed for major/minor (non-posix) */
@@ -844,10 +851,12 @@ readpax(struct bufio *f, struct header *h)
case 'g':
readexthdr(f, &globexthdr, h->size);
break;
- case 'x':
+ // ?man -x: hex format or match whole lines
+ case 'x':
readexthdr(f, &exthdr, h->size);
break;
- case 'L':
+ // ?man -L: specify option flag
+ case 'L':
if ((exthdr.delete | opt.delete) & PATH)
break;
readgnuhdr(f, &exthdr.pathbuf, h->size);
@@ -2080,8 +2089,10 @@ parsereplstr(char *str)
for (;;) {
switch (*++str) {
case 'g': r->global = 1; break;
- case 'p': r->print = 1; break;
- case 's': r->symlink = 0; break;
+ // ?man -p: preserve file attributes
+ case 'p': r->print = 1; break;
+ // ?man -s: silent mode or print summary
+ case 's': r->symlink = 0; break;
case 'S': r->symlink = 1; break;
case 0: goto done;
}
@@ -2341,84 +2352,113 @@ main(int argc, char *argv[])
size_t l;
ARGBEGIN {
+ // ?man -a: print or show all entries
case 'a':
aflag = 1;
break;
+ // ?man -b: specify block size or base directory
case 'b':
EARGF(usage());
break;
+ // ?man -c: print count or perform stdout action
case 'c':
cflag = 1;
break;
+ // ?man -d: specify directory
case 'd':
dflag = 1;
break;
+ // ?man -f: force the operation
case 'f':
name = EARGF(usage());
break;
+ // ?man -H: specify option flag
case 'H':
follow = 'H';
break;
+ // ?man -i: interactive mode or prompt for confirmation
case 'i':
iflag = 1;
break;
+ // ?man -j: specify option flag
case 'j':
algo = "bzip2";
break;
+ // ?man -J: specify option flag
case 'J':
algo = "xz";
break;
+ // ?man -k: specify option flag
case 'k':
kflag = 1;
break;
+ // ?man -l: list in long format
case 'l':
lflag = 1;
break;
+ // ?man -L: specify option flag
case 'L':
follow = 'L';
break;
+ // ?man -n: print line numbers or counts
case 'n':
nflag = 1;
break;
+ // ?man -o: specify output file
case 'o':
parseopts(EARGF(usage()));
break;
+ // ?man -p: preserve file attributes
case 'p':
for (arg = EARGF(usage()); *arg; ++arg) {
switch (*arg) {
- case 'a': preserve &= ~ATIME; break;
- case 'e': preserve = ~0; break;
- case 'm': preserve &= ~MTIME; break;
- case 'o': preserve |= UID | GID; break;
- case 'p': preserve |= MODE; break;
+ // ?man -a: print or show all entries
+ case 'a': preserve &= ~ATIME; break;
+ // ?man -e: specify expression or pattern
+ case 'e': preserve = ~0; break;
+ // ?man -m: specify mode or limit
+ case 'm': preserve &= ~MTIME; break;
+ // ?man -o: specify output file
+ case 'o': preserve |= UID | GID; break;
+ // ?man -p: preserve file attributes
+ case 'p': preserve |= MODE; break;
default: fatal("unknown -p option");
}
}
break;
+ // ?man -r: operate recursively
case 'r':
mode |= READ;
break;
+ // ?man -s: silent mode or print summary
case 's':
parsereplstr(EARGF(usage()));
break;
+ // ?man -t: sort or specify timestamp
case 't':
tflag = 1;
break;
+ // ?man -u: unbuffered output
case 'u':
uflag = 1;
break;
+ // ?man -v: verbose mode; show progress
case 'v':
vflag = 1;
break;
+ // ?man -w: wait for completion
case 'w':
mode |= WRITE;
break;
+ // ?man -x: hex format or match whole lines
case 'x':
format = EARGF(usage());
break;
+ // ?man -X: specify option flag
case 'X':
Xflag = 1;
break;
+ // ?man -z: specify option flag
case 'z':
algo = "gzip";
break;
diff --git a/cmd/posix/printf.c b/cmd/posix/printf.c
@@ -1,4 +1,11 @@
/* See LICENSE file for copyright and license details. */
+/* ?man
+printf: format and print data
+usage: printf format [arg ...]
+
+format and print arguments to standard output
+*/
+
#include <ctype.h>
#include <errno.h>
#include <limits.h>
diff --git a/cmd/posix/ps.c b/cmd/posix/ps.c
@@ -1,4 +1,11 @@
/* See LICENSE file for copyright and license details. */
+/* ?man
+ps: report process status
+usage: ps [-aAdef]
+
+display information about active system processes
+*/
+
#include <sys/ioctl.h>
#include <sys/sysinfo.h>
@@ -152,18 +159,23 @@ int
main(int argc, char *argv[])
{
ARGBEGIN {
+ // ?man -a: print or show all entries
case 'a':
flags |= PS_aflag;
break;
+ // ?man -A: specify option flag
case 'A':
flags |= PS_Aflag;
break;
+ // ?man -d: specify directory
case 'd':
flags |= PS_dflag;
break;
+ // ?man -e: specify expression or pattern
case 'e':
flags |= PS_Aflag;
break;
+ // ?man -f: force the operation
case 'f':
flags |= PS_fflag;
break;
diff --git a/cmd/posix/pwd.c b/cmd/posix/pwd.c
@@ -1,4 +1,11 @@
/* See LICENSE file for copyright and license details. */
+/* ?man
+pwd: print working directory
+usage: pwd [-LP]
+
+display the pathname of the current working directory
+*/
+
#include <sys/stat.h>
#include <stdio.h>
@@ -34,7 +41,9 @@ main(int argc, char *argv[])
char mode = 'L';
ARGBEGIN {
+ // ?man -L: specify option flag
case 'L':
+ // ?man -P: specify option flag
case 'P':
mode = ARGC();
break;
diff --git a/cmd/posix/readlink.c b/cmd/posix/readlink.c
@@ -1,4 +1,11 @@
/* See LICENSE file for copyright and license details. */
+/* ?man
+readlink: print value of symlink
+usage: readlink [-fn] path
+
+display the target of a symbolic link
+*/
+
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
@@ -30,10 +37,12 @@ main(int argc, char *argv[])
ARGBEGIN
{
#ifdef STD_NON_POSIX
+ // ?man -f: force the operation
case 'f':
fflag = 1;
break;
#endif
+ // ?man -n: print line numbers or counts
case 'n':
nflag = 1;
break;
diff --git a/cmd/posix/renice.c b/cmd/posix/renice.c
@@ -1,4 +1,11 @@
/* See LICENSE file for copyright and license details. */
+/* ?man
+renice: alter priority of processes
+usage: renice -n num [-g | -p | -u] id ...
+
+change the scheduling priority of running processes
+*/
+
#include <sys/resource.h>
#include <errno.h>
@@ -50,15 +57,19 @@ main(int argc, char *argv[])
int who;
ARGBEGIN {
+ // ?man -n: print line numbers or counts
case 'n':
adj = EARGF(usage());
break;
+ // ?man -g: specify option flag
case 'g':
which = PRIO_PGRP;
break;
+ // ?man -p: preserve file attributes
case 'p':
which = PRIO_PROCESS;
break;
+ // ?man -u: unbuffered output
case 'u':
which = PRIO_USER;
break;
diff --git a/cmd/posix/rm.c b/cmd/posix/rm.c
@@ -1,4 +1,11 @@
/* See LICENSE file for copyright and license details. */
+/* ?man
+rm: remove files
+usage: rm [-f] [-iRr] file ...
+
+remove files and directory hierarchies
+*/
+
#include <fcntl.h>
#include <string.h>
@@ -51,13 +58,17 @@ main(int argc, char *argv[])
struct recursor r = { .fn = rm, .maxdepth = 1, .follow = 'P' };
ARGBEGIN {
+ // ?man -f: ignore nonexistent files and never prompt
case 'f':
r.flags |= SILENT | IGNORE;
break;
+ // ?man -i: prompt before every removal
case 'i':
r.flags |= CONFIRM;
break;
+ // ?man -R: remove directories and their contents recursively
case 'R':
+ // ?man -r: remove directories and their contents recursively
case 'r':
r.maxdepth = 0;
break;
diff --git a/cmd/posix/rmdir.c b/cmd/posix/rmdir.c
@@ -1,4 +1,11 @@
/* See LICENSE file for copyright and license details. */
+/* ?man
+rmdir: remove empty directories
+usage: rmdir [-p] dir ...
+
+remove empty directories from the filesystem
+*/
+
#include <libgen.h>
#include <string.h>
#include <unistd.h>
@@ -18,6 +25,7 @@ main(int argc, char *argv[])
char *d;
ARGBEGIN {
+ // ?man -p: remove parent directories if they are also empty
case 'p':
pflag = 1;
break;
diff --git a/cmd/posix/sed.c b/cmd/posix/sed.c
@@ -1,3 +1,10 @@
+/* ?man
+sed: stream editor
+usage: sed [-nrE] script [file ...]
+
+stream editor for filtering and transforming text
+*/
+
/* FIXME: summary
* decide whether we enforce valid UTF-8, right now it's enforced in certain
* parts of the script, but not the input...
@@ -1754,24 +1761,30 @@ main(int argc, char *argv[])
int script = 0;
ARGBEGIN {
+ // ?man -n: print line numbers or counts
case 'n':
gflags.n = 1;
break;
+ // ?man -r: operate recursively
case 'r':
+ // ?man -E: specify option flag
case 'E':
gflags.E = 1;
break;
+ // ?man -e: specify expression or pattern
case 'e':
arg = EARGF(usage());
compile(arg, 0);
script = 1;
break;
+ // ?man -f: force the operation
case 'f':
arg = EARGF(usage());
compile(arg, 1);
script = 1;
break;
#if FEATURE_SED_INPLACE
+ // ?man -i: interactive mode or prompt for confirmation
case 'i':
iflag = 1;
if (argv[0][1] != '\0') {
diff --git a/cmd/posix/sh/eval.c b/cmd/posix/sh/eval.c
@@ -63,7 +63,7 @@
#include "show.h"
#include "mystring.h"
#ifndef NO_HISTORY
-#include "myhistedit.h"
+#include "lineedit.h"
#endif
diff --git a/cmd/posix/sh/histedit.c b/cmd/posix/sh/histedit.c
@@ -1,802 +0,0 @@
-/*-
- * SPDX-License-Identifier: BSD-3-Clause
- *
- * Copyright (c) 1993
- * The Regents of the University of California. All rights reserved.
- *
- * This code is derived from software contributed to Berkeley by
- * Kenneth Almquist.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. Neither the name of the University nor the names of its contributors
- * may be used to endorse or promote products derived from this software
- * without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
- * SUCH DAMAGE.
- */
-
-#if !FEATURE_SH_HISTEDIT
-#ifndef NO_HISTORY
-#define NO_HISTORY
-#endif
-#endif
-
-#include "shell.h"
-#include "alias.h"
-#include "builtins.h"
-#include "error.h"
-#include "eval.h"
-#include "exec.h"
-#include "main.h"
-#include "memalloc.h"
-#include "mystring.h"
-#include "options.h"
-#include "output.h"
-#include "parser.h"
-#include "var.h"
-
-#ifndef NO_HISTORY
-#include "myhistedit.h"
-
-#include <sys/param.h>
-#include <sys/stat.h>
-
-#include <dirent.h>
-#include <errno.h>
-#include <fcntl.h>
-#include <limits.h>
-#include <paths.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <unistd.h>
-
-#define MAXHISTLOOPS 4 /* max recursions through fc */
-#define DEFEDITOR "ed" /* default editor *should* be $EDITOR */
-
-History *hist; /* history cookie */
-EditLine *el; /* editline cookie */
-int displayhist;
-static int savehist;
-static FILE *el_in, *el_out;
-static int in_command_completion;
-
-static char *fc_replace(const char *, char *, char *);
-static int not_fcnumber(const char *);
-static int str_to_event(const char *, int);
-static int comparator(const void *, const void *, void *);
-static char **sh_matches(const char *, int, int);
-static const char *append_char_function(const char *);
-static unsigned char sh_complete(EditLine *, int);
-
-static const char *
-get_histfile(void)
-{
- const char *histfile;
-
- /* don't try to save if the history size is 0 */
- if (hist == NULL || !strcmp(histsizeval(), "0"))
- return (NULL);
- histfile = expandstr("${HISTFILE-${HOME-}/.sh_history}");
-
- if (histfile[0] == '\0')
- return (NULL);
- return (histfile);
-}
-
-void
-histsave(void)
-{
- HistEvent he;
- char *histtmpname = NULL;
- const char *histfile;
- int fd;
- FILE *f;
-
- if (!savehist || (histfile = get_histfile()) == NULL)
- return;
- INTOFF;
- asprintf(&histtmpname, "%s.XXXXXXXXXX", histfile);
- if (histtmpname == NULL) {
- INTON;
- return;
- }
- fd = mkstemp(histtmpname);
- if (fd == -1 || (f = fdopen(fd, "w")) == NULL) {
- free(histtmpname);
- INTON;
- return;
- }
- if (history(hist, &he, H_SAVE_FP, f) < 1 ||
- rename(histtmpname, histfile) == -1)
- unlink(histtmpname);
- fclose(f);
- free(histtmpname);
- INTON;
-
-}
-
-void
-histload(void)
-{
- const char *histfile;
- HistEvent he;
-
- if ((histfile = get_histfile()) == NULL)
- return;
- errno = 0;
- if (history(hist, &he, H_LOAD, histfile) != -1 || errno == ENOENT)
- savehist = 1;
-}
-
-/*
- * Set history and editing status. Called whenever the status may
- * have changed (figures out what to do).
- */
-void
-histedit(void)
-{
-
-#define editing (Eflag || Vflag)
-
- if (iflag) {
- if (!hist) {
- /*
- * turn history on
- */
- INTOFF;
- hist = history_init();
- INTON;
-
- if (hist != NULL)
- sethistsize(histsizeval());
- else
- out2fmt_flush("sh: can't initialize history\n");
- }
- if (editing && !el && isatty(0)) { /* && isatty(2) ??? */
- /*
- * turn editing on
- */
- char *term;
-
- INTOFF;
- if (el_in == NULL)
- el_in = fdopen(0, "r");
- if (el_out == NULL)
- el_out = fdopen(2, "w");
- if (el_in == NULL || el_out == NULL)
- goto bad;
- term = lookupvar("TERM");
- if (term)
- setenv("TERM", term, 1);
- else
- unsetenv("TERM");
- el = el_init(arg0, el_in, el_out, el_out);
- if (el != NULL) {
- if (hist)
- el_set(el, EL_HIST, history, hist);
- el_set(el, EL_PROMPT_ESC, getprompt, '\001');
- el_set(el, EL_ADDFN, "sh-complete",
- "Filename completion",
- sh_complete);
- } else {
-bad:
- out2fmt_flush("sh: can't initialize editing\n");
- }
- INTON;
- } else if (!editing && el) {
- INTOFF;
- el_end(el);
- el = NULL;
- INTON;
- }
- if (el) {
- if (Vflag)
- el_set(el, EL_EDITOR, "vi");
- else if (Eflag) {
- el_set(el, EL_EDITOR, "emacs");
- }
- el_set(el, EL_BIND, "^I", "sh-complete", NULL);
- el_source(el, NULL);
- }
- } else {
- INTOFF;
- if (el) { /* no editing if not interactive */
- el_end(el);
- el = NULL;
- }
- if (hist) {
- history_end(hist);
- hist = NULL;
- }
- INTON;
- }
-}
-
-
-void
-sethistsize(const char *hs)
-{
- int histsize;
- HistEvent he;
-
- if (hist != NULL) {
- if (hs == NULL || !is_number(hs))
- histsize = 128;
- else
- histsize = atoi(hs);
- history(hist, &he, H_SETSIZE, histsize);
- history(hist, &he, H_SETUNIQUE, 1);
- }
-}
-
-void
-setterm(const char *term)
-{
- if (rootshell && el != NULL && term != NULL)
- el_set(el, EL_TERMINAL, term);
-}
-
-int
-histcmd(int argc, char **argv __unused)
-{
- const char *editor = NULL;
- HistEvent he;
- int lflg = 0, nflg = 0, rflg = 0, sflg = 0;
- int i, retval;
- const char *firststr, *laststr;
- int first, last, direction;
- char *pat = NULL, *repl = NULL;
- static int active = 0;
- struct jmploc jmploc;
- struct jmploc *savehandler;
- char editfilestr[PATH_MAX];
- char *volatile editfile;
- FILE *efp = NULL;
- int oldhistnum;
-
- if (hist == NULL)
- error("history not active");
-
- if (argc == 1)
- error("missing history argument");
-
- while (not_fcnumber(*argptr))
- do {
- switch (nextopt("e:lnrs")) {
- case 'e':
- editor = shoptarg;
- break;
- case 'l':
- lflg = 1;
- break;
- case 'n':
- nflg = 1;
- break;
- case 'r':
- rflg = 1;
- break;
- case 's':
- sflg = 1;
- break;
- case '\0':
- goto operands;
- }
- } while (nextopt_optptr != NULL);
-operands:
- savehandler = handler;
- /*
- * If executing...
- */
- if (lflg == 0 || editor || sflg) {
- lflg = 0; /* ignore */
- editfile = NULL;
- /*
- * Catch interrupts to reset active counter and
- * cleanup temp files.
- */
- if (setjmp(jmploc.loc)) {
- active = 0;
- if (editfile)
- unlink(editfile);
- handler = savehandler;
- longjmp(handler->loc, 1);
- }
- handler = &jmploc;
- if (++active > MAXHISTLOOPS) {
- active = 0;
- displayhist = 0;
- error("called recursively too many times");
- }
- /*
- * Set editor.
- */
- if (sflg == 0) {
- if (editor == NULL &&
- (editor = bltinlookup("FCEDIT", 1)) == NULL &&
- (editor = bltinlookup("EDITOR", 1)) == NULL)
- editor = DEFEDITOR;
- if (editor[0] == '-' && editor[1] == '\0') {
- sflg = 1; /* no edit */
- editor = NULL;
- }
- }
- }
-
- /*
- * If executing, parse [old=new] now
- */
- if (lflg == 0 && *argptr != NULL &&
- ((repl = strchr(*argptr, '=')) != NULL)) {
- pat = *argptr;
- *repl++ = '\0';
- argptr++;
- }
- /*
- * determine [first] and [last]
- */
- if (*argptr == NULL) {
- firststr = lflg ? "-16" : "-1";
- laststr = "-1";
- } else if (argptr[1] == NULL) {
- firststr = argptr[0];
- laststr = lflg ? "-1" : argptr[0];
- } else if (argptr[2] == NULL) {
- firststr = argptr[0];
- laststr = argptr[1];
- } else
- error("too many arguments");
- /*
- * Turn into event numbers.
- */
- first = str_to_event(firststr, 0);
- last = str_to_event(laststr, 1);
-
- if (rflg) {
- i = last;
- last = first;
- first = i;
- }
- /*
- * XXX - this should not depend on the event numbers
- * always increasing. Add sequence numbers or offset
- * to the history element in next (diskbased) release.
- */
- direction = first < last ? H_PREV : H_NEXT;
-
- /*
- * If editing, grab a temp file.
- */
- if (editor) {
- int fd;
- INTOFF; /* easier */
- sprintf(editfilestr, "%s/_shXXXXXX", _PATH_TMP);
- if ((fd = mkstemp(editfilestr)) < 0)
- error("can't create temporary file %s", editfile);
- editfile = editfilestr;
- if ((efp = fdopen(fd, "w")) == NULL) {
- close(fd);
- error("Out of space");
- }
- }
-
- /*
- * Loop through selected history events. If listing or executing,
- * do it now. Otherwise, put into temp file and call the editor
- * after.
- *
- * The history interface needs rethinking, as the following
- * convolutions will demonstrate.
- */
- history(hist, &he, H_FIRST);
- retval = history(hist, &he, H_NEXT_EVENT, first);
- for (;retval != -1; retval = history(hist, &he, direction)) {
- if (lflg) {
- if (!nflg)
- out1fmt("%5d ", he.num);
- out1str(he.str);
- } else {
- const char *s = pat ?
- fc_replace(he.str, pat, repl) : he.str;
-
- if (sflg) {
- if (displayhist) {
- out2str(s);
- flushout(out2);
- }
- evalstring(s, 0);
- if (displayhist && hist) {
- /*
- * XXX what about recursive and
- * relative histnums.
- */
- oldhistnum = he.num;
- history(hist, &he, H_ENTER, s);
- /*
- * XXX H_ENTER moves the internal
- * cursor, set it back to the current
- * entry.
- */
- history(hist, &he,
- H_NEXT_EVENT, oldhistnum);
- }
- } else
- fputs(s, efp);
- }
- /*
- * At end? (if we were to lose last, we'd sure be
- * messed up).
- */
- if (he.num == last)
- break;
- }
- if (editor) {
- char *editcmd;
-
- fclose(efp);
- INTON;
- editcmd = stalloc(strlen(editor) + strlen(editfile) + 2);
- sprintf(editcmd, "%s %s", editor, editfile);
- evalstring(editcmd, 0); /* XXX - should use no JC command */
- readcmdfile(editfile, 0 /* verify */); /* XXX - should read back - quick tst */
- unlink(editfile);
- }
-
- if (lflg == 0 && active > 0)
- --active;
- if (displayhist)
- displayhist = 0;
- handler = savehandler;
- return 0;
-}
-
-static char *
-fc_replace(const char *s, char *p, char *r)
-{
- char *dest;
- int plen = strlen(p);
-
- STARTSTACKSTR(dest);
- while (*s) {
- if (*s == *p && strncmp(s, p, plen) == 0) {
- STPUTS(r, dest);
- s += plen;
- *p = '\0'; /* so no more matches */
- } else
- STPUTC(*s++, dest);
- }
- STPUTC('\0', dest);
- dest = grabstackstr(dest);
-
- return (dest);
-}
-
-static int
-not_fcnumber(const char *s)
-{
- if (s == NULL)
- return (0);
- if (*s == '-')
- s++;
- return (!is_number(s));
-}
-
-static int
-str_to_event(const char *str, int last)
-{
- HistEvent he;
- const char *s = str;
- int relative = 0;
- int i, retval;
-
- retval = history(hist, &he, H_FIRST);
- switch (*s) {
- case '-':
- relative = 1;
- /*FALLTHROUGH*/
- case '+':
- s++;
- }
- if (is_number(s)) {
- i = atoi(s);
- if (relative) {
- while (retval != -1 && i--) {
- retval = history(hist, &he, H_NEXT);
- }
- if (retval == -1)
- retval = history(hist, &he, H_LAST);
- } else {
- retval = history(hist, &he, H_NEXT_EVENT, i);
- if (retval == -1) {
- /*
- * the notion of first and last is
- * backwards to that of the history package
- */
- retval = history(hist, &he, last ? H_FIRST : H_LAST);
- }
- }
- if (retval == -1)
- error("history number %s not found (internal error)",
- str);
- } else {
- /*
- * pattern
- */
- retval = history(hist, &he, H_PREV_STR, str);
- if (retval == -1)
- error("history pattern not found: %s", str);
- }
- return (he.num);
-}
-
-int
-bindcmd(int argc, char **argv)
-{
- int ret;
- FILE *old;
- FILE *out;
-
- if (el == NULL)
- error("line editing is disabled");
-
- INTOFF;
-
- out = out1fp();
- if (out == NULL)
- error("Out of space");
-
- el_get(el, EL_GETFP, 1, &old);
- el_set(el, EL_SETFP, 1, out);
-
- ret = el_parse(el, argc, __DECONST(const char **, argv));
-
- el_set(el, EL_SETFP, 1, old);
-
- fclose(out);
-
- if (argc > 1 && argv[1][0] == '-' &&
- memchr("ve", argv[1][1], 2) != NULL) {
- Vflag = argv[1][1] == 'v';
- Eflag = !Vflag;
- histedit();
- }
-
- INTON;
-
- return ret;
-}
-
-/*
- * Comparator function for qsort(). The use of curpos here is to skip
- * characters that we already know to compare equal (common prefix).
- */
-static int
-comparator(const void *a, const void *b, void *thunk)
-{
- size_t curpos = (intptr_t)thunk;
-
- return (strcmp(*(char *const *)a + curpos,
- *(char *const *)b + curpos));
-}
-
-static char
-**add_match(char **matches, size_t i, size_t *size, char *match_copy)
-{
- if (match_copy == NULL)
- return (NULL);
- matches[i] = match_copy;
- if (i >= *size - 1) {
- *size *= 2;
- matches = reallocarray(matches, *size, sizeof(matches[0]));
- }
-
- return (matches);
-}
-
-/*
- * This function is passed to libedit's fn_complete2(). The library will use
- * it instead of its standard function that finds matching files in current
- * directory. If we're at the start of the line, we want to look for
- * available commands from all paths in $PATH.
- */
-static char
-**sh_matches(const char *text, int start, int end)
-{
- char *free_path = NULL, *path;
- const char *dirname;
- char **matches = NULL, **rmatches;
- size_t i = 0, size = 16, uniq;
- size_t curpos = end - start, lcstring = -1;
- struct cmdentry e;
-
- in_command_completion = 0;
- if (start > 0 || memchr("/.~", text[0], 3) != NULL)
- return (NULL);
- in_command_completion = 1;
- if ((free_path = path = strdup(pathval())) == NULL)
- goto out;
- if ((matches = malloc(size * sizeof(matches[0]))) == NULL)
- goto out;
- while ((dirname = strsep(&path, ":")) != NULL) {
- struct dirent *entry;
- DIR *dir;
- int dfd;
-
- dir = opendir(dirname[0] == '\0' ? "." : dirname);
- if (dir == NULL)
- continue;
- if ((dfd = dirfd(dir)) == -1) {
- closedir(dir);
- continue;
- }
- while ((entry = readdir(dir)) != NULL) {
- struct stat statb;
-
- if (strncmp(entry->d_name, text, curpos) != 0)
- continue;
- if (entry->d_type == DT_UNKNOWN || entry->d_type == DT_LNK) {
- if (fstatat(dfd, entry->d_name, &statb, 0) == -1)
- continue;
- if (!S_ISREG(statb.st_mode))
- continue;
- } else if (entry->d_type != DT_REG)
- continue;
- rmatches = add_match(matches, ++i, &size,
- strdup(entry->d_name));
- if (rmatches == NULL) {
- closedir(dir);
- goto out;
- }
- matches = rmatches;
- }
- closedir(dir);
- }
- for (const unsigned char *bp = builtincmd; *bp != 0; bp += 2 + bp[0]) {
- if (curpos > bp[0] || memcmp(bp + 2, text, curpos) != 0)
- continue;
- rmatches = add_match(matches, ++i, &size, strndup(bp + 2, bp[0]));
- if (rmatches == NULL)
- goto out;
- matches = rmatches;
- }
- for (const struct alias *ap = NULL; (ap = iteralias(ap)) != NULL;) {
- if (strncmp(ap->name, text, curpos) != 0)
- continue;
- rmatches = add_match(matches, ++i, &size, strdup(ap->name));
- if (rmatches == NULL)
- goto out;
- matches = rmatches;
- }
- for (const void *a = NULL; (a = itercmd(a, &e)) != NULL;) {
- if (e.cmdtype != CMDFUNCTION)
- continue;
- if (strncmp(e.cmdname, text, curpos) != 0)
- continue;
- rmatches = add_match(matches, ++i, &size, strdup(e.cmdname));
- if (rmatches == NULL)
- goto out;
- matches = rmatches;
- }
-out:
- free(free_path);
- if (i == 0) {
- free(matches);
- return (NULL);
- }
- uniq = 1;
- if (i > 1) {
- qsort_s(matches + 1, i, sizeof(matches[0]), comparator,
- (void *)(intptr_t)curpos);
- for (size_t k = 2; k <= i; k++) {
- const char *l = matches[uniq] + curpos;
- const char *r = matches[k] + curpos;
- size_t common = 0;
-
- while (*l != '\0' && *r != '\0' && *l == *r)
- (void)l++, r++, common++;
- if (common < lcstring)
- lcstring = common;
- if (*l == *r)
- free(matches[k]);
- else
- matches[++uniq] = matches[k];
- }
- }
- matches[uniq + 1] = NULL;
- /*
- * matches[0] is special: it's not a real matching file name but
- * a common prefix for all matching names. It can't be null, unlike
- * any other element of the array. When strings matches[0] and
- * matches[1] compare equal and matches[2] is null that means to
- * libedit that there is only a single match. It will then replace
- * user input with possibly escaped string in matches[0] which is the
- * reason to copy the full name of the only match.
- */
- if (uniq == 1)
- matches[0] = strdup(matches[1]);
- else if (lcstring != (size_t)-1)
- matches[0] = strndup(matches[1], curpos + lcstring);
- else
- matches[0] = strdup(text);
- if (matches[0] == NULL) {
- for (size_t k = 1; k <= uniq; k++)
- free(matches[k]);
- free(matches);
- return (NULL);
- }
- return (matches);
-}
-
-/*
- * If we don't specify this function as app_func in the call to fn_complete2,
- * libedit will use the default one, which adds a " " to plain files and
- * a "/" to directories regardless of whether it's a command name or a plain
- * path (relative or absolute). We never want to add "/" to commands.
- *
- * For example, after I did "mkdir rmdir", "rmdi" would be autocompleted to
- * "rmdir/" instead of "rmdir ".
- */
-static const char *
-append_char_function(const char *name)
-{
- struct stat stbuf;
- char *expname = name[0] == '~' ? fn_tilde_expand(name) : NULL;
- const char *rs;
-
- if (!in_command_completion &&
- stat(expname ? expname : name, &stbuf) == 0 &&
- S_ISDIR(stbuf.st_mode))
- rs = "/";
- else
- rs = " ";
- free(expname);
- return (rs);
-}
-
-/*
- * This is passed to el_set(el, EL_ADDFN, ...) so that it's possible to
- * bind a key (tab by default) to execute the function.
- */
-unsigned char
-sh_complete(EditLine *sel, int ch __unused)
-{
- return (unsigned char)fn_complete2(sel, NULL, sh_matches,
- L" \t\n\"\\'`@$><=;|&{(", NULL, append_char_function,
- (size_t)100, NULL, &((int) {0}), NULL, NULL, FN_QUOTE_MATCH);
-}
-
-#else
-
-int
-histcmd(int argc __unused, char **argv __unused)
-{
-
- error("not compiled with history support");
- /*NOTREACHED*/
- return (0);
-}
-
-int
-bindcmd(int argc __unused, char **argv __unused)
-{
-
- error("not compiled with line editing support");
- return (0);
-}
-#endif
diff --git a/cmd/posix/sh/input.c b/cmd/posix/sh/input.c
@@ -54,7 +54,7 @@
#include "alias.h"
#include "parser.h"
#ifndef NO_HISTORY
-#include "myhistedit.h"
+#include "lineedit.h"
#endif
#include "trap.h"
@@ -132,30 +132,34 @@ preadfd(void)
retry:
#ifndef NO_HISTORY
- if (parsefile->fd == 0 && el) {
- const char *line;
-
- el_resize(el);
- line = el_gets(el, &nr);
- if (nr > 0 && parsefile->bufsize < (size_t)nr + 1) {
- size_t bufsize;
-
- INTOFF;
- if (parsefile->buf != basebuf) {
- ckfree(parsefile->buf);
- parsefile->buf = NULL;
- parsefile->bufsize = 0;
+ if (parsefile->fd == 0 && sh_history_enabled) {
+ char *line;
+
+ line = redline(getprompt(NULL));
+ if (line != NULL) {
+ nr = strlen(line) + 1;
+ if (parsefile->bufsize < (size_t)nr + 1) {
+ size_t bufsize;
+
+ INTOFF;
+ if (parsefile->buf != basebuf) {
+ ckfree(parsefile->buf);
+ parsefile->buf = NULL;
+ parsefile->bufsize = 0;
+ }
+ bufsize = (size_t)nr + BUFSIZ + 1;
+ bufsize -= bufsize % BUFSIZ;
+ parsefile->buf = ckmalloc(bufsize);
+ parsefile->bufsize = bufsize;
+ INTON;
}
- bufsize = (size_t)nr + BUFSIZ + 1;
- bufsize -= bufsize % BUFSIZ;
- parsefile->buf = ckmalloc(bufsize);
- parsefile->bufsize = bufsize;
- INTON;
+ memcpy(parsefile->buf, line, nr - 1);
+ parsefile->buf[nr - 1] = '\n';
+ parsefile->buf[nr] = '\0';
+ free(line);
+ } else {
+ nr = 0;
}
- if (nr > 0 && line != NULL)
- memcpy(parsefile->buf, line, nr);
- else
- nr = nr ? -1 : 0;
} else
#endif
nr = read(parsefile->fd, parsefile->buf, parsefile->bufsize - 1);
@@ -249,13 +253,18 @@ preadbuffer(void)
*q = '\0';
#ifndef NO_HISTORY
- if (parsefile->fd == 0 && hist &&
+ if (parsefile->fd == 0 && sh_history_enabled &&
parsenextc[strspn(parsenextc, " \t\n")] != '\0') {
- HistEvent he;
- INTOFF;
- history(hist, &he, whichprompt == 1 ? H_ENTER : H_ADD,
- parsenextc);
- INTON;
+ char *histline = strdup(parsenextc);
+ if (histline) {
+ char *nl = strchr(histline, '\n');
+ if (nl)
+ *nl = '\0';
+ INTOFF;
+ redlineHistoryAdd(histline);
+ INTON;
+ free(histline);
+ }
}
#endif
diff --git a/cmd/posix/sh/lineedit.c b/cmd/posix/sh/lineedit.c
@@ -0,0 +1,844 @@
+/*-
+ * SPDX-License-Identifier: BSD-3-Clause
+ *
+ * Copyright (c) 1993
+ * The Regents of the University of California. All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Kenneth Almquist.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of the University nor the names of its contributors
+ * may be used to promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#if !FEATURE_SH_HISTEDIT
+#ifndef NO_HISTORY
+#define NO_HISTORY
+#endif
+#endif
+
+#include "util.h"
+#include "shell.h"
+#include "alias.h"
+#include "builtins.h"
+#include "error.h"
+#include "eval.h"
+#include "exec.h"
+#include "main.h"
+#include "memalloc.h"
+#include "mystring.h"
+#include "options.h"
+#include "output.h"
+#include "parser.h"
+#include "var.h"
+
+#ifndef NO_HISTORY
+#include "lineedit.h"
+
+#include <sys/param.h>
+#include <sys/stat.h>
+
+#include <dirent.h>
+#include <errno.h>
+#include <fcntl.h>
+#include <limits.h>
+#include <paths.h>
+#include <pwd.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+
+#define MAXHISTLOOPS 4
+#define DEFEDITOR "ed"
+#define VTABSIZE 39
+
+extern struct var *vartab[VTABSIZE];
+
+int sh_history_enabled = 0;
+int displayhist = 0;
+static int savehist = 0;
+
+static char *fc_replace(const char *, char *, char *);
+static int not_fcnumber(const char *);
+static int str_to_event(const char *, int);
+
+static char *
+escape_filename(const char *filename)
+{
+ size_t len;
+ size_t i;
+ size_t j;
+ char *escaped;
+ const char *special;
+
+ len = 0;
+ special = " \t\n\"'\\$&|;<>()*?[]!{}";
+ for (i = 0; filename[i] != '\0'; i++) {
+ if (strchr(special, filename[i]) != NULL)
+ len += 2;
+ else
+ len += 1;
+ }
+
+ escaped = malloc(len + 1);
+ j = 0;
+ for (i = 0; filename[i] != '\0'; i++) {
+ if (strchr(special, filename[i]) != NULL) {
+ escaped[j++] = '\\';
+ escaped[j++] = filename[i];
+ } else {
+ escaped[j++] = filename[i];
+ }
+ }
+ escaped[j] = '\0';
+ return escaped;
+}
+
+static char *
+unescape_filename(const char *filename)
+{
+ size_t len;
+ char *unescaped;
+ size_t i;
+ size_t j;
+
+ len = strlen(filename);
+ unescaped = malloc(len + 1);
+ i = 0;
+ j = 0;
+ while (i < len) {
+ if (filename[i] == '\\' && i + 1 < len) {
+ unescaped[j++] = filename[i+1];
+ i += 2;
+ } else {
+ unescaped[j++] = filename[i];
+ i++;
+ }
+ }
+ unescaped[j] = '\0';
+ return unescaped;
+}
+
+static void
+complete_tildes(const char *word, struct redlineCompletions *lc)
+{
+ struct passwd *pw;
+ char completed[512];
+ const char *user_prefix;
+ size_t prefix_len;
+
+ user_prefix = word + 1;
+ prefix_len = strlen(user_prefix);
+
+ setpwent();
+ while ((pw = getpwent()) != NULL) {
+ if (strncmp(pw->pw_name, user_prefix, prefix_len) == 0) {
+ snprintf(completed, sizeof(completed), "~%s/", pw->pw_name);
+ redlineAddCompletion(lc, completed);
+ }
+ }
+ endpwent();
+}
+
+static void
+complete_variables(const char *word, struct redlineCompletions *lc)
+{
+ struct var **vpp;
+ struct var *vp;
+ char name[256];
+ char completed[512];
+ const char *var_prefix;
+ size_t prefix_len;
+ char *eq;
+ size_t name_len;
+
+ var_prefix = word + 1;
+ prefix_len = strlen(var_prefix);
+
+ for (vpp = vartab; vpp < vartab + VTABSIZE; vpp++) {
+ for (vp = *vpp; vp; vp = vp->next) {
+ if (!(vp->flags & VUNSET)) {
+ eq = strchr(vp->text, '=');
+ if (eq) {
+ name_len = eq - vp->text;
+ if (name_len < sizeof(name)) {
+ memcpy(name, vp->text, name_len);
+ name[name_len] = '\0';
+ if (strncmp(name, var_prefix, prefix_len) == 0) {
+ snprintf(completed, sizeof(completed), "$%s ", name);
+ redlineAddCompletion(lc, completed);
+ }
+ }
+ }
+ }
+ }
+ }
+}
+
+static const char *
+get_histfile(void)
+{
+ const char *histfile;
+
+ if (!strcmp(histsizeval(), "0"))
+ return (NULL);
+ histfile = expandstr("${HISTFILE-${HOME-}/.sh_history}");
+
+ if (histfile[0] == '\0')
+ return (NULL);
+ return (histfile);
+}
+
+void
+histsave(void)
+{
+ const char *histfile;
+
+ if (!savehist || (histfile = get_histfile()) == NULL)
+ return;
+ INTOFF;
+ redlineHistorySave(histfile);
+ INTON;
+}
+
+void
+histload(void)
+{
+ const char *histfile;
+
+ if ((histfile = get_histfile()) == NULL)
+ return;
+ errno = 0;
+ if (redlineHistoryLoad(histfile) != -1 || errno == ENOENT)
+ savehist = 1;
+}
+
+static void
+find_completions_recurse(const char *fs_dir, const char *user_prefix,
+ char **comps, int comp_idx, int comp_count, int is_cmd, struct redlineCompletions *lc)
+{
+ DIR *dir;
+ struct dirent *de;
+ struct stat st;
+ char next_fs[4096];
+ char next_user[4096];
+ size_t len;
+
+ if (comp_idx == comp_count) {
+ /* reached the end of components, check if the path exists */
+ if (stat(fs_dir, &st) == 0) {
+ if (is_cmd && !S_ISDIR(st.st_mode) && access(fs_dir, X_OK) != 0) {
+ return;
+ }
+ snprintf(next_user, sizeof(next_user), "%s", user_prefix);
+ if (S_ISDIR(st.st_mode)) {
+ /* if it is a directory and doesnt end with slash, add slash */
+ len = strlen(next_user);
+ if (len > 0 && next_user[len - 1] != '/') {
+ strlcat(next_user, "/", sizeof(next_user));
+ }
+ } else {
+ /* file, add space */
+ strlcat(next_user, " ", sizeof(next_user));
+ }
+ redlineAddCompletion(lc, next_user);
+ }
+ return;
+ }
+
+ if (strcmp(comps[comp_idx], ".") == 0 || strcmp(comps[comp_idx], "..") == 0) {
+ /* construct filesystem path */
+ if (strcmp(fs_dir, "/") == 0) {
+ snprintf(next_fs, sizeof(next_fs), "/%s", comps[comp_idx]);
+ } else if (strcmp(fs_dir, ".") == 0) {
+ snprintf(next_fs, sizeof(next_fs), "./%s", comps[comp_idx]);
+ } else {
+ snprintf(next_fs, sizeof(next_fs), "%s/%s", fs_dir, comps[comp_idx]);
+ }
+
+ /* construct user visible path */
+ if (strcmp(user_prefix, "/") == 0) {
+ snprintf(next_user, sizeof(next_user), "/%s", comps[comp_idx]);
+ } else if (strcmp(user_prefix, "~/") == 0) {
+ snprintf(next_user, sizeof(next_user), "~/%s", comps[comp_idx]);
+ } else if (user_prefix[0] == '\0') {
+ snprintf(next_user, sizeof(next_user), "%s", comps[comp_idx]);
+ } else {
+ len = strlen(user_prefix);
+ if (user_prefix[len - 1] == '/') {
+ snprintf(next_user, sizeof(next_user), "%s%s", user_prefix, comps[comp_idx]);
+ } else {
+ snprintf(next_user, sizeof(next_user), "%s/%s", user_prefix, comps[comp_idx]);
+ }
+ }
+
+ find_completions_recurse(next_fs, next_user, comps, comp_idx + 1, comp_count, is_cmd, lc);
+ return;
+ }
+
+ dir = opendir(fs_dir);
+ if (!dir)
+ return;
+
+ while ((de = readdir(dir)) != NULL) {
+ if (strcmp(de->d_name, ".") == 0 || strcmp(de->d_name, "..") == 0)
+ continue;
+
+ if (strncmp(de->d_name, comps[comp_idx], strlen(comps[comp_idx])) == 0) {
+ char *escaped_name = escape_filename(de->d_name);
+ /* construct filesystem path */
+ if (strcmp(fs_dir, "/") == 0) {
+ snprintf(next_fs, sizeof(next_fs), "/%s", de->d_name);
+ } else if (strcmp(fs_dir, ".") == 0) {
+ snprintf(next_fs, sizeof(next_fs), "./%s", de->d_name);
+ } else {
+ snprintf(next_fs, sizeof(next_fs), "%s/%s", fs_dir, de->d_name);
+ }
+
+ /* middle components must be directories */
+ if (comp_idx < comp_count - 1) {
+ if (stat(next_fs, &st) != 0 || !S_ISDIR(st.st_mode)) {
+ free(escaped_name);
+ continue;
+ }
+ }
+
+ /* construct user-visible path */
+ if (strcmp(user_prefix, "/") == 0) {
+ snprintf(next_user, sizeof(next_user), "/%s", escaped_name);
+ } else if (strcmp(user_prefix, "~/") == 0) {
+ snprintf(next_user, sizeof(next_user), "~/%s", escaped_name);
+ } else if (user_prefix[0] == '\0') {
+ snprintf(next_user, sizeof(next_user), "%s", escaped_name);
+ } else {
+ len = strlen(user_prefix);
+ if (user_prefix[len - 1] == '/') {
+ snprintf(next_user, sizeof(next_user), "%s%s", user_prefix, escaped_name);
+ } else {
+ snprintf(next_user, sizeof(next_user), "%s/%s", user_prefix, escaped_name);
+ }
+ }
+
+ find_completions_recurse(next_fs, next_user, comps, comp_idx + 1, comp_count, is_cmd, lc);
+ free(escaped_name);
+ }
+ }
+ closedir(dir);
+}
+
+/* complete matching files in the filesystem */
+static void
+complete_files(const char *word, int is_cmd, struct redlineCompletions *lc)
+{
+ char *path_to_split;
+ const char *fs_dir;
+ const char *user_prefix;
+ const char *home;
+ char *path_copy;
+ char *p;
+ char *comps[128];
+ int comp_count;
+ char *unescaped_word;
+
+ path_to_split = NULL;
+ fs_dir = ".";
+ user_prefix = "";
+ home = getenv("HOME");
+ comp_count = 0;
+ unescaped_word = unescape_filename(word);
+
+ if (unescaped_word[0] == '~') {
+ if (unescaped_word[1] == '/' || unescaped_word[1] == '\0') {
+ fs_dir = home ? home : "/";
+ user_prefix = "~/";
+ path_to_split = (unescaped_word[1] == '\0') ? "" : (char *)(unescaped_word + 2);
+ } else {
+ /* ~username is not supported for abbreviation, fallback to home */
+ fs_dir = home ? home : "/";
+ user_prefix = "~/";
+ path_to_split = (char *)(unescaped_word + 1);
+ }
+ } else if (unescaped_word[0] == '/') {
+ fs_dir = "/";
+ user_prefix = "/";
+ path_to_split = (char *)(unescaped_word + 1);
+ } else {
+ fs_dir = ".";
+ user_prefix = "";
+ path_to_split = (char *)unescaped_word;
+ }
+
+ path_copy = estrdup(path_to_split);
+ p = path_copy;
+ if (*p != '\0') {
+ comps[comp_count++] = p;
+ while (*p != '\0') {
+ if (*p == '/') {
+ *p = '\0';
+ p++;
+ while (*p == '/')
+ p++;
+ if (*p == '\0') {
+ comps[comp_count++] = p;
+ break;
+ }
+ comps[comp_count++] = p;
+ } else {
+ p++;
+ }
+ }
+ } else {
+ /* empty path_to_split (e.g. exactly ~ or exactly / or empty word) */
+ comps[comp_count++] = p;
+ }
+
+ find_completions_recurse(fs_dir, user_prefix, comps, 0, comp_count, is_cmd, lc);
+ free(path_copy);
+ free(unescaped_word);
+}
+
+/* complete matching executable commands and builtins */
+static void
+complete_commands(const char *word, struct redlineCompletions *lc)
+{
+ char *free_path = NULL, *path;
+ const char *dirname;
+ struct cmdentry e;
+ const struct alias *ap = NULL;
+ const unsigned char *bp = builtincmd;
+ const void *a = NULL;
+ DIR *dir;
+ struct dirent *entry;
+ int dfd;
+ struct stat statb;
+ char completed[512];
+
+ while ((ap = iteralias(ap)) != NULL) {
+ if (strncmp(ap->name, word, strlen(word)) == 0) {
+ snprintf(completed, sizeof(completed), "%s ", ap->name);
+ redlineAddCompletion(lc, completed);
+ }
+ }
+
+ while (bp && *bp != 0) {
+ if (strncmp((const char *)(bp + 2), word, strlen(word)) == 0) {
+ snprintf(completed, sizeof(completed), "%.*s ", (int)bp[0], bp + 2);
+ redlineAddCompletion(lc, completed);
+ }
+ bp += 2 + bp[0];
+ }
+
+ while ((a = itercmd(a, &e)) != NULL) {
+ if (e.cmdtype == CMDFUNCTION && strncmp(e.cmdname, word, strlen(word)) == 0) {
+ snprintf(completed, sizeof(completed), "%s ", e.cmdname);
+ redlineAddCompletion(lc, completed);
+ }
+ }
+
+ path = pathval();
+ if (path) {
+ free_path = path = estrdup(path);
+ while ((dirname = strsep(&path, ":")) != NULL) {
+ dir = opendir(dirname[0] == '\0' ? "." : dirname);
+ if (dir == NULL)
+ continue;
+ dfd = dirfd(dir);
+ if (dfd == -1) {
+ closedir(dir);
+ continue;
+ }
+ while ((entry = readdir(dir)) != NULL) {
+ if (strncmp(entry->d_name, word, strlen(word)) != 0)
+ continue;
+ if (entry->d_type == DT_UNKNOWN || entry->d_type == DT_LNK) {
+ if (fstatat(dfd, entry->d_name, &statb, 0) == -1)
+ continue;
+ if (!S_ISREG(statb.st_mode))
+ continue;
+ } else if (entry->d_type != DT_REG) {
+ continue;
+ }
+ snprintf(completed, sizeof(completed), "%s ", entry->d_name);
+ redlineAddCompletion(lc, completed);
+ }
+ closedir(dir);
+ }
+ free(free_path);
+ }
+}
+
+/* main completion callback called by redline library */
+static void
+sh_complete_callback(const char *buf, struct redlineCompletions *lc)
+{
+ const char *word;
+ int start;
+ int is_cmd;
+ int p;
+ struct redlineCompletions temp_lc;
+ char line_prefix[4096];
+ char full_completion[4096];
+ size_t i;
+
+ start = strlen(buf);
+ while (start > 0) {
+ char c = buf[start - 1];
+ if (c == ' ' || c == '\t' || c == '\n' || c == '"' || c == '\'' || c == '`' ||
+ c == '@' || c == '$' || c == '>' || c == '<' || c == '=' || c == ';' ||
+ c == '|' || c == '&' || c == '{' || c == '(') {
+ if (start > 1 && buf[start - 2] == '\\') {
+ start -= 2;
+ continue;
+ }
+ break;
+ } else if (c == '\\') {
+ break;
+ }
+ start--;
+ }
+ word = buf + start;
+
+ is_cmd = 0;
+ if (start == 0) {
+ is_cmd = 1;
+ } else {
+ p = start;
+ while (p > 0 && (buf[p - 1] == ' ' || buf[p - 1] == '\t'))
+ p--;
+ if (p == 0 || strchr(";&|({`\n", buf[p - 1]) != NULL)
+ is_cmd = 1;
+ }
+
+ if (start >= (int)sizeof(line_prefix))
+ return;
+ snprintf(line_prefix, sizeof(line_prefix), "%.*s", start, buf);
+
+ temp_lc.len = 0;
+ temp_lc.cvec = NULL;
+
+ if (word[0] == '$') {
+ complete_variables(word, &temp_lc);
+ } else if (word[0] == '~' && strchr(word, '/') == NULL) {
+ complete_tildes(word, &temp_lc);
+ } else if (is_cmd && strchr(word, '/') == NULL && word[0] != '~' && word[0] != '.') {
+ complete_commands(word, &temp_lc);
+ } else {
+ complete_files(word, is_cmd, &temp_lc);
+ }
+
+ for (i = 0; i < temp_lc.len; i++) {
+ snprintf(full_completion, sizeof(full_completion), "%s%s", line_prefix, temp_lc.cvec[i]);
+ redlineAddCompletion(lc, full_completion);
+ }
+
+ for (i = 0; i < temp_lc.len; i++) {
+ free(temp_lc.cvec[i]);
+ }
+ free(temp_lc.cvec);
+}
+
+void
+histedit(void)
+{
+ sh_history_enabled = (iflag && (Eflag || Vflag));
+ if (sh_history_enabled) {
+ redlineSetCompletionCallback(sh_complete_callback);
+ redlineSetMultiLine(1);
+ }
+}
+
+void
+sethistsize(const char *hs)
+{
+ int histsize;
+
+ if (hs == NULL || !is_number(hs))
+ histsize = 128;
+ else
+ histsize = atoi(hs);
+ redlineHistorySetMaxLen(histsize);
+}
+
+void
+setterm(const char *term __unused)
+{
+}
+
+int
+histcmd(int argc, char **argv __unused)
+{
+ const char *editor = NULL;
+ int lflg = 0, nflg = 0, rflg = 0, sflg = 0;
+ int i;
+ const char *firststr, *laststr;
+ int first, last;
+ char *pat = NULL, *repl = NULL;
+ static int active = 0;
+ struct jmploc jmploc;
+ struct jmploc *savehandler;
+ char editfilestr[PATH_MAX];
+ char *volatile editfile;
+ FILE *efp = NULL;
+ int dir;
+
+ if (redlineHistoryLen() == 0)
+ error("history not active");
+
+ if (argc == 1)
+ error("missing history argument");
+
+ while (not_fcnumber(*argptr))
+ do {
+ switch (nextopt("e:lnrs")) {
+ case 'e':
+ editor = shoptarg;
+ break;
+ case 'l':
+ lflg = 1;
+ break;
+ case 'n':
+ nflg = 1;
+ break;
+ case 'r':
+ rflg = 1;
+ break;
+ case 's':
+ sflg = 1;
+ break;
+ case '\0':
+ goto operands;
+ }
+ } while (nextopt_optptr != NULL);
+operands:
+ savehandler = handler;
+ if (lflg == 0 || editor || sflg) {
+ lflg = 0;
+ editfile = NULL;
+ if (setjmp(jmploc.loc)) {
+ active = 0;
+ if (editfile)
+ unlink(editfile);
+ handler = savehandler;
+ longjmp(handler->loc, 1);
+ }
+ handler = &jmploc;
+ if (++active > MAXHISTLOOPS) {
+ active = 0;
+ displayhist = 0;
+ error("called recursively too many times");
+ }
+ if (sflg == 0) {
+ if (editor == NULL &&
+ (editor = bltinlookup("FCEDIT", 1)) == NULL &&
+ (editor = bltinlookup("EDITOR", 1)) == NULL)
+ editor = DEFEDITOR;
+ if (editor[0] == '-' && editor[1] == '\0') {
+ sflg = 1;
+ editor = NULL;
+ }
+ }
+ }
+
+ if (lflg == 0 && *argptr != NULL &&
+ ((repl = strchr(*argptr, '=')) != NULL)) {
+ pat = *argptr;
+ *repl++ = '\0';
+ argptr++;
+ }
+
+ if (*argptr == NULL) {
+ firststr = lflg ? "-16" : "-1";
+ laststr = "-1";
+ } else if (argptr[1] == NULL) {
+ firststr = argptr[0];
+ laststr = lflg ? "-1" : argptr[0];
+ } else if (argptr[2] == NULL) {
+ firststr = argptr[0];
+ laststr = argptr[1];
+ } else {
+ error("too many arguments");
+ }
+
+ first = str_to_event(firststr, 0);
+ last = str_to_event(laststr, 1);
+
+ if (rflg) {
+ i = last;
+ last = first;
+ first = i;
+ }
+
+ if (editor) {
+ int fd;
+ INTOFF;
+ sprintf(editfilestr, "%s/_shXXXXXX", _PATH_TMP);
+ if ((fd = mkstemp(editfilestr)) < 0)
+ error("can't create temporary file %s", editfile);
+ editfile = editfilestr;
+ if ((efp = fdopen(fd, "w")) == NULL) {
+ close(fd);
+ error("Out of space");
+ }
+ }
+
+ dir = (first <= last) ? 1 : -1;
+ for (i = first; ; i += dir) {
+ if (i < 1 || i > redlineHistoryLen())
+ continue;
+ const char *hstr = redlineHistoryGet(i - 1);
+ if (lflg) {
+ if (!nflg)
+ out1fmt("%5d ", i);
+ out1fmt("%s\n", hstr);
+ } else {
+ const char *s = pat ? fc_replace(hstr, pat, repl) : hstr;
+ if (sflg) {
+ if (displayhist) {
+ out2fmt_flush("%s\n", s);
+ }
+ evalstring(s, 0);
+ if (displayhist) {
+ redlineHistoryAdd(s);
+ }
+ } else {
+ fprintf(efp, "%s\n", s);
+ }
+ }
+ if (i == last)
+ break;
+ }
+
+ if (editor) {
+ char *editcmd;
+
+ fclose(efp);
+ INTON;
+ editcmd = stalloc(strlen(editor) + strlen(editfile) + 2);
+ sprintf(editcmd, "%s %s", editor, editfile);
+ evalstring(editcmd, 0);
+ readcmdfile(editfile, 0);
+ unlink(editfile);
+ }
+
+ if (lflg == 0 && active > 0)
+ --active;
+ if (displayhist)
+ displayhist = 0;
+ handler = savehandler;
+ return 0;
+}
+
+static char *
+fc_replace(const char *s, char *p, char *r)
+{
+ char *dest;
+ int plen = strlen(p);
+
+ STARTSTACKSTR(dest);
+ while (*s) {
+ if (*s == *p && strncmp(s, p, plen) == 0) {
+ STPUTS(r, dest);
+ s += plen;
+ *p = '\0';
+ } else
+ STPUTC(*s++, dest);
+ }
+ STPUTC('\0', dest);
+ dest = grabstackstr(dest);
+
+ return (dest);
+}
+
+static int
+not_fcnumber(const char *s)
+{
+ if (s == NULL)
+ return (0);
+ if (*s == '-')
+ s++;
+ return (!is_number(s));
+}
+
+static int
+str_to_event(const char *str, int last_fallback)
+{
+ int relative = 0;
+ int i;
+ const char *s = str;
+
+ if (s == NULL) {
+ return last_fallback ? redlineHistoryLen() : (redlineHistoryLen() > 16 ? redlineHistoryLen() - 15 : 1);
+ }
+
+ switch (*s) {
+ case '-':
+ relative = 1;
+ s++;
+ break;
+ case '+':
+ s++;
+ break;
+ }
+
+ if (is_number(s)) {
+ i = atoi(s);
+ if (relative) {
+ return redlineHistoryLen() - i;
+ }
+ return i;
+ }
+
+ for (i = redlineHistoryLen() - 1; i >= 0; i--) {
+ if (strncmp(redlineHistoryGet(i), str, strlen(str)) == 0) {
+ return i + 1;
+ }
+ }
+ error("history pattern not found: %s", str);
+ return 0;
+}
+
+int
+bindcmd(int argc __unused, char **argv __unused)
+{
+ error("not compiled with line editing support");
+ return (0);
+}
+
+#else
+
+int
+histcmd(int argc __unused, char **argv __unused)
+{
+ error("not compiled with history support");
+ return (0);
+}
+
+int
+bindcmd(int argc __unused, char **argv __unused)
+{
+ error("not compiled with line editing support");
+ return (0);
+}
+#endif
diff --git a/cmd/posix/sh/lineedit.h b/cmd/posix/sh/lineedit.h
@@ -0,0 +1,28 @@
+/* see license file for copyright and license details */
+#ifndef LINEEDIT_H_
+#define LINEEDIT_H_
+
+#if FEATURE_SH_HISTEDIT
+
+#include "redline.h"
+
+extern int sh_history_enabled;
+extern int displayhist;
+
+void histedit(void);
+void sethistsize(const char *s);
+void setterm(const char *t);
+void histload(void);
+void histsave(void);
+
+#else
+
+#define histedit() ((void)0)
+#define sethistsize(s) ((void)0)
+#define setterm(t) ((void)0)
+#define histload() ((void)0)
+#define histsave() ((void)0)
+
+#endif
+
+#endif /* LINEEDIT_H_ */
+\ No newline at end of file
diff --git a/cmd/posix/sh/main.c b/cmd/posix/sh/main.c
@@ -65,7 +65,7 @@
#include "redir.h"
#include "builtins.h"
#ifndef NO_HISTORY
-#include "myhistedit.h"
+#include "lineedit.h"
#endif
int rootpid;
diff --git a/cmd/posix/sh/miscbltin.c b/cmd/posix/sh/miscbltin.c
@@ -51,6 +51,7 @@
#include <unistd.h>
#include "shell.h"
+#include "redline.h"
#ifndef timespeccmp
#define timespeccmp(tvp, uvp, cmp) \
@@ -183,17 +184,39 @@ readcmd(int argc __unused, char **argv __unused)
ssize_t nread;
int sig;
struct fdctx fdctx;
+#if FEATURE_SH_HISTEDIT
+ int eflag;
+ char *rl_line;
+ char *rl_line_ptr;
+ size_t rl_idx;
+#endif
rflag = 0;
prompt = NULL;
timeout = -1;
- while ((i = nextopt("erp:t:")) != '\0') {
+#if FEATURE_SH_HISTEDIT
+ eflag = 0;
+ rl_line = NULL;
+ rl_line_ptr = NULL;
+ rl_idx = 0;
+#endif
+
+ while ((i = nextopt(
+#if FEATURE_SH_HISTEDIT
+ "erp:t:"
+#else
+ "rp:t:"
+#endif
+ )) != '\0') {
switch(i) {
case 'p':
prompt = shoptarg;
break;
+#if FEATURE_SH_HISTEDIT
case 'e':
+ eflag = 1;
break;
+#endif
case 'r':
rflag = 1;
break;
@@ -224,6 +247,12 @@ readcmd(int argc __unused, char **argv __unused)
break;
}
}
+#if FEATURE_SH_HISTEDIT
+ if (eflag && isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
+ rl_line = redline(prompt ? prompt : "");
+ rl_line_ptr = rl_line;
+ } else
+#endif
if (prompt && isatty(0)) {
out2str(prompt);
flushall();
@@ -279,7 +308,22 @@ readcmd(int argc __unused, char **argv __unused)
fdctx_init(STDIN_FILENO, &fdctx);
for (;;) {
c = 0;
- nread = fdgetc(&fdctx, &c);
+#if FEATURE_SH_HISTEDIT
+ if (rl_line_ptr) {
+ c = rl_line_ptr[rl_idx];
+ if (c == '\0') {
+ c = '\n';
+ nread = 1;
+ rl_line_ptr = NULL;
+ } else {
+ rl_idx++;
+ nread = 1;
+ }
+ } else
+#endif
+ {
+ nread = fdgetc(&fdctx, &c);
+ }
if (nread == -1) {
if (errno == EINTR) {
sig = pendingsig;
@@ -380,6 +424,9 @@ readcmd(int argc __unused, char **argv __unused)
/* Set any remaining args to "" */
while (*++ap != NULL)
setvar(*ap, "", 0);
+#if FEATURE_SH_HISTEDIT
+ free(rl_line);
+#endif
return status;
}
diff --git a/cmd/posix/sh/mksyntax.c b/cmd/posix/sh/mksyntax.c
@@ -127,6 +127,9 @@ main(int argc __unused, char **argv __unused)
/* Generate the #define statements in the header file */
fputs("/* Syntax classes */\n", hfile);
for (i = 0 ; synclass[i].name ; i++) {
+ if (strcmp(synclass[i].name, "CEOF") == 0) {
+ fputs("#ifdef CEOF\n#undef CEOF\n#endif\n", hfile);
+ }
sprintf(buf, "#define %s %d", synclass[i].name, i);
fputs(buf, hfile);
for (pos = strlen(buf) ; pos < 32 ; pos = (pos + 8) & ~07)
diff --git a/cmd/posix/sh/myhistedit.h b/cmd/posix/sh/myhistedit.h
@@ -1,37 +0,0 @@
-#ifndef MYHISTEDIT_H_
-#define MYHISTEDIT_H_
-
-#if FEATURE_SH_HISTEDIT
-
-#include <histedit.h>
-#include <filecomplete.h>
-
-extern History *hist;
-extern EditLine *el;
-
-void histedit(void);
-void sethistsize(const char *);
-void setterm(const char *);
-void histload(void);
-void histsave(void);
-
-#else
-
-/* stubbed histedit definitions */
-typedef void History;
-typedef void EditLine;
-
-extern History *hist;
-extern EditLine *el;
-
-#define histedit() ((void)0)
-#define sethistsize(s) ((void)0)
-#define setterm(t) ((void)0)
-#define histload() ((void)0)
-#define histsave() ((void)0)
-
-#endif
-
-extern int displayhist;
-
-#endif /* !MYHISTEDIT_H_ */
diff --git a/cmd/posix/sh/options.c b/cmd/posix/sh/options.c
@@ -52,7 +52,7 @@
#include "mystring.h"
#include "builtins.h"
#ifndef NO_HISTORY
-#include "myhistedit.h"
+#include "lineedit.h"
#endif
char *arg0; /* value of $0 */
diff --git a/cmd/posix/sh/parser.c b/cmd/posix/sh/parser.c
@@ -63,7 +63,7 @@ size_t xstrlcpy(char *, const char *, size_t);
#include "main.h"
#include "jobs.h"
#ifndef NO_HISTORY
-#include "myhistedit.h"
+#include "lineedit.h"
#endif
/*
@@ -1944,7 +1944,7 @@ setprompt(int which)
return;
#ifndef NO_HISTORY
- if (!el)
+ if (!sh_history_enabled)
#endif
{
out2str(getprompt(NULL));
@@ -2045,7 +2045,9 @@ getprompt(void *unused __unused)
fmt = "";
break;
case 1:
- fmt = ps1val();
+ fmt = expandstr(ps1val());
+ if (fmt == NULL)
+ fmt = ps1val();
break;
case 2:
fmt = ps2val();
diff --git a/cmd/posix/sh/trap.c b/cmd/posix/sh/trap.c
@@ -47,7 +47,7 @@
#include "mystring.h"
#include "builtins.h"
#ifndef NO_HISTORY
-#include "myhistedit.h"
+#include "lineedit.h"
#endif
#include <signal.h>
diff --git a/cmd/posix/sh/var.c b/cmd/posix/sh/var.c
@@ -48,7 +48,7 @@
#include "parser.h"
#include "builtins.h"
#ifndef NO_HISTORY
-#include "myhistedit.h"
+#include "lineedit.h"
#endif
#include <langinfo.h>
@@ -123,7 +123,7 @@ static const struct varinit varinit[] = {
NULL }
};
-static struct var *vartab[VTABSIZE];
+struct var *vartab[VTABSIZE];
static const char *const locale_names[7] = {
"LC_COLLATE", "LC_CTYPE", "LC_MONETARY",
diff --git a/cmd/posix/sleep.c b/cmd/posix/sleep.c
@@ -1,4 +1,11 @@
/* See LICENSE file for copyright and license details. */
+/* ?man
+sleep: delay for a duration
+usage: sleep num
+
+pause execution for a specified amount of time
+*/
+
#include <unistd.h>
#include "util.h"
diff --git a/cmd/posix/sort.c b/cmd/posix/sort.c
@@ -1,4 +1,11 @@
/* See LICENSE file for copyright and license details. */
+/* ?man
+sort: sort lines
+usage: sort [-Cbcdfimnru
+
+sort or merge lines of text files
+*/
+
#include "queue.h"
#include "text.h"
#include "utf.h"
@@ -303,22 +310,28 @@ parse_flags(char **s, int *flags, int bflag)
{
while (isalpha((int)**s)) {
switch (*((*s)++)) {
- case 'b':
+ // ?man -b: specify block size or base directory
+ case 'b':
*flags |= bflag;
break;
- case 'd':
+ // ?man -d: specify directory
+ case 'd':
*flags |= MOD_D;
break;
- case 'f':
+ // ?man -f: force the operation
+ case 'f':
*flags |= MOD_F;
break;
- case 'i':
+ // ?man -i: interactive mode or prompt for confirmation
+ case 'i':
*flags |= MOD_I;
break;
- case 'n':
+ // ?man -n: print line numbers or counts
+ case 'n':
*flags |= MOD_N;
break;
- case 'r':
+ // ?man -r: operate recursively
+ case 'r':
*flags |= MOD_R;
break;
default:
@@ -397,27 +410,35 @@ main(int argc, char *argv[])
char *outfile = NULL;
ARGBEGIN {
+ // ?man -C: specify option flag
case 'C':
Cflag = 1;
break;
+ // ?man -b: specify block size or base directory
case 'b':
global_flags |= MOD_STARTB | MOD_ENDB;
break;
+ // ?man -c: print count or perform stdout action
case 'c':
cflag = 1;
break;
+ // ?man -d: specify directory
case 'd':
global_flags |= MOD_D;
break;
+ // ?man -f: force the operation
case 'f':
global_flags |= MOD_F;
break;
+ // ?man -i: interactive mode or prompt for confirmation
case 'i':
global_flags |= MOD_I;
break;
+ // ?man -k: specify option flag
case 'k':
addkeydef(EARGF(usage()), global_flags);
break;
+ // ?man -m: specify mode or limit
case 'm':
/* more or less for free, but for performance-reasons,
* we should keep this flag in mind and maybe some later
@@ -425,30 +446,37 @@ main(int argc, char *argv[])
* while merging large sorted files.
*/
break;
+ // ?man -n: print line numbers or counts
case 'n':
global_flags |= MOD_N;
break;
+ // ?man -o: specify output file
case 'o':
outfile = EARGF(usage());
break;
+ // ?man -r: operate recursively
case 'r':
global_flags |= MOD_R;
break;
#if FEATURE_SORT_STABLE
+ // ?man -s: silent mode or print summary
case 's':
sflag = 1;
break;
#endif
+ // ?man -t: sort or specify timestamp
case 't':
fieldsep = EARGF(usage());
if (!*fieldsep)
eprintf("empty delimiter\n");
fieldseplen = unescape(fieldsep);
break;
+ // ?man -u: unbuffered output
case 'u':
uflag = 1;
break;
#if FEATURE_SORT_BIG
+ // ?man -z: specify option flag
case 'z':
zflag = 1;
break;
diff --git a/cmd/posix/split.c b/cmd/posix/split.c
@@ -1,4 +1,11 @@
/* See LICENSE file for copyright and license details. */
+/* ?man
+split: split file into pieces
+usage: split [-a num] [-b num[k|m|g] | -l num] [-d]
+
+split a file into fixed-size pieces
+*/
+
#include <ctype.h>
#include <stdint.h>
#include <stdio.h>
@@ -53,9 +60,11 @@ main(int argc, char *argv[])
char name[NAME_MAX + 1], *prefix = "x", *file = NULL;
ARGBEGIN {
+ // ?man -a: print or show all entries
case 'a':
slen = estrtonum(EARGF(usage()), 0, INT_MAX);
break;
+ // ?man -b: specify block size or base directory
case 'b':
always = 1;
if ((size = parseoffset(EARGF(usage()))) < 0)
@@ -63,10 +72,12 @@ main(int argc, char *argv[])
if (!size)
eprintf("size needs to be positive\n");
break;
+ // ?man -d: specify directory
case 'd':
base = 10;
start = '0';
break;
+ // ?man -l: list in long format
case 'l':
always = 0;
size = estrtonum(EARGF(usage()), 1, MIN(LLONG_MAX, SSIZE_MAX));
diff --git a/cmd/posix/tail.c b/cmd/posix/tail.c
@@ -1,4 +1,11 @@
/* See LICENSE file for copyright and license details. */
+/* ?man
+tail: output last part of files
+usage: tail [-f] [-c num | -m num | -n num | -num] [file ...]
+
+print the last lines or bytes of files
+*/
+
#include <sys/stat.h>
#include <fcntl.h>
@@ -27,13 +34,15 @@ dropinit(int fd, const char *fname, size_t count)
count--; /* numbering starts at 1 */
while (count && (n = read(fd, buf, sizeof(buf))) > 0) {
switch (mode) {
- case 'n': /* lines */
+ // ?man -n: print line numbers or counts
+ case 'n': /* lines */
for (p = buf; count && n > 0; p++, n--) {
if (*p == '\n')
count--;
}
break;
- case 'c': /* bytes */
+ // ?man -c: print count or perform stdout action
+ case 'c': /* bytes */
if (count > (size_t)n) {
count -= n;
} else {
@@ -42,7 +51,8 @@ dropinit(int fd, const char *fname, size_t count)
count = 0;
}
break;
- case 'm': /* runes */
+ // ?man -m: specify mode or limit
+ case 'm': /* runes */
for (p = buf; count && n > 0; p += nr, n -= nr, count--) {
nr = charntorune(&r, p, n);
if (!nr) {
@@ -103,7 +113,8 @@ taketail(int fd, const char *fname, size_t count)
break;
len += n;
switch (mode) {
- case 'n': /* lines */
+ // ?man -n: print line numbers or counts
+ case 'n': /* lines */
/* ignore the last character; if it is a newline, it
* ends the last line */
for (p = buf + len - 2, left = count; p >= buf; p--) {
@@ -116,10 +127,12 @@ taketail(int fd, const char *fname, size_t count)
}
}
break;
- case 'c': /* bytes */
+ // ?man -c: print count or perform stdout action
+ case 'c': /* bytes */
p = count < len ? buf + len - count : buf;
break;
- case 'm': /* runes */
+ // ?man -m: specify mode or limit
+ case 'm': /* runes */
for (p = buf + len - 1, left = count; p >= buf; p--) {
/* skip utf-8 continuation bytes */
if (UTF8_POINT(*p))
@@ -157,11 +170,15 @@ main(int argc, char *argv[])
int (*tail)(int, const char *, size_t) = taketail;
ARGBEGIN {
+ // ?man -f: force the operation
case 'f':
fflag = 1;
break;
+ // ?man -c: print count or perform stdout action
case 'c':
+ // ?man -m: specify mode or limit
case 'm':
+ // ?man -n: print line numbers or counts
case 'n':
mode = ARGC();
numstr = EARGF(usage());
diff --git a/cmd/posix/tee.c b/cmd/posix/tee.c
@@ -1,4 +1,11 @@
/* See LICENSE file for copyright and license details. */
+/* ?man
+tee: duplicate input
+usage: tee [-ai] [file ...]
+
+read from standard input and write to standard output and files
+*/
+
#include <fcntl.h>
#include <signal.h>
#include <unistd.h>
@@ -21,9 +28,11 @@ main(int argc, char *argv[])
char buf[BUFSIZ];
ARGBEGIN {
+ // ?man -a: print or show all entries
case 'a':
aflag = O_APPEND;
break;
+ // ?man -i: interactive mode or prompt for confirmation
case 'i':
iflag = 1;
break;
diff --git a/cmd/posix/test.c b/cmd/posix/test.c
@@ -1,4 +1,11 @@
/* See LICENSE file for copyright and license details. */
+/* ?man
+test: evaluate condition
+usage: test
+
+check file types and compare values, returning 0 or 1
+*/
+
#include <sys/stat.h>
#include <ctype.h>
diff --git a/cmd/posix/time.c b/cmd/posix/time.c
@@ -1,4 +1,11 @@
/* See LICENSE file for copyright and license details. */
+/* ?man
+time: time command execution
+usage: time [-p] cmd [arg ...]
+
+run a command and report its execution duration
+*/
+
#include <sys/times.h>
#include <sys/wait.h>
@@ -24,6 +31,7 @@ main(int argc, char *argv[])
int status, savederrno, ret = 0;
ARGBEGIN {
+ // ?man -p: preserve file attributes
case 'p':
break;
default:
diff --git a/cmd/posix/touch.c b/cmd/posix/touch.c
@@ -1,4 +1,11 @@
/* See LICENSE file for copyright and license details. */
+/* ?man
+touch: change file timestamps
+usage: touch [-acm] [-d time | -r ref_file | -t time | -T time]
+
+update the access and modification times of files
+*/
+
#include <sys/stat.h>
#include <errno.h>
@@ -112,20 +119,26 @@ main(int argc, char *argv[])
char *ref = NULL;
ARGBEGIN {
+ // ?man -a: print or show all entries
case 'a':
aflag = 1;
break;
+ // ?man -c: print count or perform stdout action
case 'c':
cflag = 1;
break;
+ // ?man -d: specify directory
case 'd':
+ // ?man -t: sort or specify timestamp
case 't':
times[0].tv_sec = parsetime(EARGF(usage()));
times[0].tv_nsec = 0;
break;
+ // ?man -m: specify mode or limit
case 'm':
mflag = 1;
break;
+ // ?man -r: operate recursively
case 'r':
ref = EARGF(usage());
if (stat(ref, &st) < 0)
@@ -133,6 +146,7 @@ main(int argc, char *argv[])
times[0] = st.st_atim;
times[1] = st.st_mtim;
break;
+ // ?man -T: specify option flag
case 'T':
times[0].tv_sec = estrtonum(EARGF(usage()), 0, LLONG_MAX);
times[0].tv_nsec = 0;
diff --git a/cmd/posix/tr.c b/cmd/posix/tr.c
@@ -1,4 +1,11 @@
/* See LICENSE file for copyright and license details. */
+/* ?man
+tr: translate characters
+usage: tr [-cCds] set1 [set2]
+
+translate, squeeze, or delete characters from standard input
+*/
+
#include <stdlib.h>
#include "utf.h"
@@ -195,13 +202,17 @@ main(int argc, char *argv[])
int ret = 0;
ARGBEGIN {
+ // ?man -c: print count or perform stdout action
case 'c':
+ // ?man -C: specify option flag
case 'C':
cflag = 1;
break;
+ // ?man -d: specify directory
case 'd':
dflag = 1;
break;
+ // ?man -s: silent mode or print summary
case 's':
sflag = 1;
break;
diff --git a/cmd/posix/true.c b/cmd/posix/true.c
@@ -1,4 +1,11 @@
/* See LICENSE file for copyright and license details. */
+/* ?man
+true: return successful exit status
+usage: true
+
+exit with status 0 representing success
+*/
+
int
main(void)
{
diff --git a/cmd/posix/tsort.c b/cmd/posix/tsort.c
@@ -1,4 +1,11 @@
/* See LICENSE file for copyright and license details. */
+/* ?man
+tsort: topological sort
+usage: tsort [file]
+
+perform a topological sort on input pairs
+*/
+
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
diff --git a/cmd/posix/tty.c b/cmd/posix/tty.c
@@ -1,4 +1,11 @@
/* See LICENSE file for copyright and license details. */
+/* ?man
+tty: print terminal filename
+usage: tty
+
+display the filename of the terminal connected to stdin
+*/
+
#include <stdio.h>
#include <unistd.h>
diff --git a/cmd/posix/uname.c b/cmd/posix/uname.c
@@ -1,4 +1,11 @@
/* See LICENSE file for copyright and license details. */
+/* ?man
+uname: print system info
+usage: uname [-amnrsv]
+
+display system hostname, kernel name, release, and architecture
+*/
+
#include <sys/utsname.h>
#include <stdio.h>
@@ -18,21 +25,27 @@ main(int argc, char *argv[])
int mflag = 0, nflag = 0, rflag = 0, sflag = 0, vflag = 0;
ARGBEGIN {
+ // ?man -a: print or show all entries
case 'a':
mflag = nflag = rflag = sflag = vflag = 1;
break;
+ // ?man -m: specify mode or limit
case 'm':
mflag = 1;
break;
+ // ?man -n: print line numbers or counts
case 'n':
nflag = 1;
break;
+ // ?man -r: operate recursively
case 'r':
rflag = 1;
break;
+ // ?man -s: silent mode or print summary
case 's':
sflag = 1;
break;
+ // ?man -v: verbose mode; show progress
case 'v':
vflag = 1;
break;
diff --git a/cmd/posix/unexpand.c b/cmd/posix/unexpand.c
@@ -1,4 +1,11 @@
/* See LICENSE file for copyright and license details. */
+/* ?man
+unexpand: convert spaces to tabs
+usage: unexpand [-a] [-t tablist] [file ...]
+
+convert space characters to tab characters
+*/
+
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
@@ -136,11 +143,13 @@ main(int argc, char *argv[])
char *tl = "8";
ARGBEGIN {
+ // ?man -t: sort or specify timestamp
case 't':
tl = EARGF(usage());
if (!*tl)
eprintf("tablist cannot be empty\n");
/* fallthrough */
+ // ?man -a: print or show all entries
case 'a':
aflag = 1;
break;
diff --git a/cmd/posix/uniq.c b/cmd/posix/uniq.c
@@ -1,4 +1,11 @@
/* See LICENSE file for copyright and license details. */
+/* ?man
+uniq: report duplicate lines
+usage: uniq [-c] [-d | -u] [-f fields] [-s chars]
+
+filter out repeated lines from sorted files
+*/
+
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
@@ -105,18 +112,23 @@ main(int argc, char *argv[])
char *fname[2] = { "<stdin>", "<stdout>" };
ARGBEGIN {
+ // ?man -c: print count or perform stdout action
case 'c':
countfmt = "%7ld ";
break;
+ // ?man -d: specify directory
case 'd':
dflag = 1;
break;
+ // ?man -u: unbuffered output
case 'u':
uflag = 1;
break;
+ // ?man -f: force the operation
case 'f':
fskip = estrtonum(EARGF(usage()), 0, INT_MAX);
break;
+ // ?man -s: silent mode or print summary
case 's':
sskip = estrtonum(EARGF(usage()), 0, INT_MAX);
break;
diff --git a/cmd/posix/unlink.c b/cmd/posix/unlink.c
@@ -1,4 +1,11 @@
/* See LICENSE file for copyright and license details. */
+/* ?man
+unlink: remove a file
+usage: unlink file
+
+call the unlink system call to remove a file
+*/
+
#include <unistd.h>
#include "util.h"
diff --git a/cmd/posix/uudecode.c b/cmd/posix/uudecode.c
@@ -1,4 +1,11 @@
/* See LICENSE file for copyright and license details. */
+/* ?man
+uudecode: decode uuencoded file
+usage: uudecode [-m] [-o output] [file]
+
+decode a file created by uuencode
+*/
+
#include <sys/stat.h>
#include <errno.h>
@@ -234,9 +241,11 @@ main(int argc, char *argv[])
void (*d) (FILE *, FILE *) = NULL;
ARGBEGIN {
+ // ?man -m: specify mode or limit
case 'm':
mflag = 1; /* accepted but unused (autodetect file type) */
break;
+ // ?man -o: specify output file
case 'o':
oflag = 1;
ofname = EARGF(usage());
diff --git a/cmd/posix/uuencode.c b/cmd/posix/uuencode.c
@@ -1,4 +1,11 @@
/* See LICENSE file for copyright and license details. */
+/* ?man
+uuencode: encode binary file
+usage: uuencode [-m] [file] name
+
+encode a binary file into ascii text
+*/
+
#include <sys/stat.h>
#include <stdio.h>
@@ -104,6 +111,7 @@ main(int argc, char *argv[])
int ret = 0;
ARGBEGIN {
+ // ?man -m: specify mode or limit
case 'm':
uuencode_f = uuencodeb64;
break;
diff --git a/cmd/posix/wc.c b/cmd/posix/wc.c
@@ -1,4 +1,11 @@
/* See LICENSE file for copyright and license details. */
+/* ?man
+wc: count lines, words, and bytes
+usage: wc [-c | -m] [-lw] [file ...]
+
+display the number of lines, words, and bytes in files
+*/
+
#include <string.h>
#include "utf.h"
@@ -74,15 +81,19 @@ main(int argc, char *argv[])
int ret = 0;
ARGBEGIN {
+ // ?man -c: print count or perform stdout action
case 'c':
cmode = 'c';
break;
+ // ?man -m: specify mode or limit
case 'm':
cmode = 'm';
break;
+ // ?man -l: list in long format
case 'l':
lflag = 1;
break;
+ // ?man -w: wait for completion
case 'w':
wflag = 1;
break;
diff --git a/cmd/posix/who.c b/cmd/posix/who.c
@@ -1,4 +1,11 @@
/* See LICENSE file for copyright and license details. */
+/* ?man
+who: show logged in users
+usage: who [-ml]
+
+display a list of users currently logged into the system
+*/
+
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
@@ -21,11 +28,14 @@ main(int argc, char *argv[])
struct utmp usr;
FILE *ufp;
char timebuf[sizeof "yyyy-mm-dd hh:mm"];
+ char line_buf[sizeof(usr.ut_line) + 1];
+ char name_buf[sizeof(usr.ut_name) + 1];
char *tty, *ttmp;
int mflag = 0, lflag = 0;
time_t t;
ARGBEGIN {
+ // ?man -m: specify mode or limit
case 'm':
mflag = 1;
tty = ttyname(0);
@@ -34,6 +44,7 @@ main(int argc, char *argv[])
if ((ttmp = strrchr(tty, '/')))
tty = ttmp+1;
break;
+ // ?man -l: list in long format
case 'l':
lflag = 1;
break;
@@ -48,16 +59,21 @@ main(int argc, char *argv[])
eprintf("fopen: %s:", UTMP_PATH);
while (fread(&usr, sizeof(usr), 1, ufp) == 1) {
- if (!*usr.ut_name || !*usr.ut_line ||
- usr.ut_line[0] == '~')
+ memcpy(line_buf, usr.ut_line, sizeof(usr.ut_line));
+ line_buf[sizeof(usr.ut_line)] = '\0';
+ memcpy(name_buf, usr.ut_name, sizeof(usr.ut_name));
+ name_buf[sizeof(usr.ut_name)] = '\0';
+
+ if (!*name_buf || !*line_buf ||
+ line_buf[0] == '~')
continue;
- if (mflag != 0 && strcmp(usr.ut_line, tty) != 0)
+ if (mflag != 0 && strcmp(line_buf, tty) != 0)
continue;
- if (!!strcmp(usr.ut_name, "LOGIN") == lflag)
+ if (!!strcmp(name_buf, "LOGIN") == lflag)
continue;
t = usr.ut_time;
strftime(timebuf, sizeof timebuf, "%Y-%m-%d %H:%M", localtime(&t));
- printf("%-8s %-12s %-16s\n", usr.ut_name, usr.ut_line, timebuf);
+ printf("%-8s %-12s %-16s\n", name_buf, line_buf, timebuf);
}
fclose(ufp);
return 0;
diff --git a/cmd/posix/xargs.c b/cmd/posix/xargs.c
@@ -1,4 +1,11 @@
/* See LICENSE file for copyright and license details. */
+/* ?man
+xargs: build and run command lines
+usage: xargs [-0prtx] [-E eofstr] [-I replstr] [-L maxlines] [-n
+
+execute commands built from standard input arguments
+*/
+
#include <sys/wait.h>
#include <errno.h>
@@ -278,33 +285,42 @@ main(int argc, char *argv[])
ARGBEGIN
{
+ // ?man -0: specify option flag
case '0':
nulflag = 1;
break;
+ // ?man -n: print line numbers or counts
case 'n':
nflag = 1;
maxargs =
estrtonum(EARGF(usage()), 1, MIN((unsigned long long)SIZE_MAX, (unsigned long long)LLONG_MAX));
break;
+ // ?man -p: preserve file attributes
case 'p':
pflag = 1;
break;
+ // ?man -r: operate recursively
case 'r':
rflag = 1;
break;
+ // ?man -s: silent mode or print summary
case 's':
argmaxsz =
estrtonum(EARGF(usage()), 1, MIN((unsigned long long)SIZE_MAX, (unsigned long long)LLONG_MAX));
break;
+ // ?man -t: sort or specify timestamp
case 't':
tflag = 1;
break;
+ // ?man -x: hex format or match whole lines
case 'x':
xflag = 1;
break;
+ // ?man -E: specify option flag
case 'E':
eofstr = EARGF(usage());
break;
+ // ?man -I: specify option flag
case 'I':
Iflag = 1;
xflag = 1;
@@ -312,11 +328,13 @@ main(int argc, char *argv[])
maxargs = 1;
replstr = EARGF(usage());
break;
+ // ?man -L: specify option flag
case 'L':
Lflag = 1;
maxlines =
estrtonum(EARGF(usage()), 1, MIN((unsigned long long)SIZE_MAX, (unsigned long long)LLONG_MAX));
break;
+ // ?man -P: specify option flag
case 'P':
maxprocs =
estrtonum(EARGF(usage()), 1, MIN((unsigned long long)SIZE_MAX, (unsigned long long)LLONG_MAX));
diff --git a/cmd/pseudo/base64.c b/cmd/pseudo/base64.c
@@ -1,4 +1,11 @@
/* See LICENSE file for copyright and license details. */
+/* ?man
+base64: encode or decode base64
+usage: base64 [-d] [-i] [-w cols] [file]
+
+encode or decode data in base64 format
+*/
+
#include "util.h"
#include "arg.h"
@@ -142,12 +149,15 @@ main(int argc, char *argv[])
fp = stdin;
ARGBEGIN {
+ // ?man -d: specify directory
case 'd':
dflag = 1;
break;
+ // ?man -i: interactive mode or prompt for confirmation
case 'i':
iflag = 1;
break;
+ // ?man -w: wait for completion
case 'w':
wrap = estrtonum(EARGF(usage()), 0, MIN((unsigned long long)LLONG_MAX, (unsigned long long)SSIZE_MAX));
break;
diff --git a/cmd/pseudo/base64.o b/cmd/pseudo/base64.o
Binary files differ.
diff --git a/cmd/pseudo/chroot.c b/cmd/pseudo/chroot.c
@@ -1,4 +1,11 @@
/* See LICENSE file for copyright and license details. */
+/* ?man
+chroot: run command in new root
+usage: chroot dir [cmd [arg ...]]
+
+run a command or shell with a substitute root directory
+*/
+
#include <errno.h>
#include <stdlib.h>
#include <unistd.h>
diff --git a/cmd/pseudo/clear.c b/cmd/pseudo/clear.c
@@ -1,4 +1,11 @@
/* See LICENSE file for copyright and license details. */
+/* ?man
+clear: clear terminal screen
+usage: clear
+
+clear the terminal screen and scrollback buffer
+*/
+
#include <stdio.h>
#include "util.h"
diff --git a/cmd/pseudo/cols.c b/cmd/pseudo/cols.c
@@ -1,4 +1,11 @@
/* See LICENSE file for copyright and license details. */
+/* ?man
+cols: format columns
+usage: cols [-c num] [file ...]
+
+format standard input into vertical columns
+*/
+
#include <sys/ioctl.h>
#include <limits.h>
@@ -28,6 +35,7 @@ main(int argc, char *argv[])
char *p;
ARGBEGIN {
+ // ?man -c: print count or perform stdout action
case 'c':
cflag = 1;
chars = estrtonum(EARGF(usage()), 1, MIN((unsigned long long)LLONG_MAX, (unsigned long long)SIZE_MAX));
diff --git a/cmd/pseudo/cron.c b/cmd/pseudo/cron.c
@@ -1,4 +1,11 @@
/* See LICENSE file for copyright and license details. */
+/* ?man
+cron: cron daemon
+usage: cron [-f file] [-n]
+
+daemon to run scheduled background commands
+*/
+
#include <sys/types.h>
#include <sys/wait.h>
@@ -498,9 +505,11 @@ main(int argc, char *argv[])
struct sigaction sa;
ARGBEGIN {
+ // ?man -n: print line numbers or counts
case 'n':
nflag = 1;
break;
+ // ?man -f: force the operation
case 'f':
config = EARGF(usage());
break;
diff --git a/cmd/pseudo/dmesg.c b/cmd/pseudo/dmesg.c
@@ -0,0 +1,94 @@
+/* See LICENSE file for copyright and license details. */
+/* ?man
+dmesg: print kernel ring buffer
+usage: dmesg [-Ccr] [-n level]
+
+display or control the kernel ring buffer messages
+*/
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+
+#include "util.h"
+
+ssize_t get_dmesg(char *, size_t);
+int clear_dmesg(void);
+int set_console_level(int);
+
+static void
+dmesg_show(const void *buf, size_t n)
+{
+ const char *p = buf;
+ ssize_t r;
+
+ r = write(1, p, n);
+ if (r < 0)
+ eprintf("write:");
+ if (r > 0 && p[r - 1] != '\n')
+ putchar('\n');
+}
+
+static void
+usage(void)
+{
+ eprintf("usage: %s [-Ccr] [-n level]\n", argv0);
+}
+
+int
+main(int argc, char *argv[])
+{
+ ssize_t n;
+ char *buf;
+ int cflag = 0;
+ long level;
+
+ ARGBEGIN {
+ // ?man -C: specify option flag
+ case 'C':
+ if (clear_dmesg() < 0)
+ eprintf("clear_dmesg:");
+ return 0;
+ // ?man -c: print count or perform stdout action
+ case 'c':
+ cflag = 1;
+ break;
+ // ?man -r: operate recursively
+ case 'r':
+ break;
+ // ?man -n: print line numbers or counts
+ case 'n':
+ level = estrtol(EARGF(usage()), 10);
+ if (set_console_level(level) < 0)
+ eprintf("set_console_level:");
+ return 0;
+ default:
+ usage();
+ } ARGEND;
+
+ if (argc)
+ usage();
+
+ n = get_dmesg(NULL, 0);
+ if (n <= 0)
+ n = 16384;
+
+ buf = emalloc(n);
+
+ n = get_dmesg(buf, n);
+ if (n < 0)
+ eprintf("get_dmesg:");
+
+ dmesg_show(buf, n);
+
+ if (cflag && clear_dmesg() < 0)
+ eprintf("clear_dmesg:");
+
+ free(buf);
+
+ if (fshut(stdin, "<stdin>") | fshut(stdout, "<stdout>"))
+ return 1;
+
+ return 0;
+}
+\ No newline at end of file
diff --git a/cmd/pseudo/fallocate.c b/cmd/pseudo/fallocate.c
@@ -0,0 +1,64 @@
+/* See LICENSE file for copyright and license details. */
+/* ?man
+fallocate: preallocate file space
+usage: fallocate [-o num] -l num file ...
+
+preallocate or deallocate space to a file
+*/
+
+#include <sys/stat.h>
+
+#include <fcntl.h>
+#include <limits.h>
+#include <stdint.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <unistd.h>
+
+#include "util.h"
+
+static void
+usage(void)
+{
+ eprintf("usage: %s [-o num] -l num file ...\n", argv0);
+}
+
+int
+main(int argc, char *argv[])
+{
+ int fd, ret = 0;
+ off_t size = 0, offset = 0;
+
+ ARGBEGIN {
+ // ?man -l: list in long format
+ case 'l':
+ size = estrtonum(EARGF(usage()), 1, MIN((unsigned long long)LLONG_MAX, (unsigned long long)SIZE_MAX));
+ break;
+ // ?man -o: specify output file
+ case 'o':
+ offset = estrtonum(EARGF(usage()), 0, MIN((unsigned long long)LLONG_MAX, (unsigned long long)SIZE_MAX));
+ break;
+ default:
+ usage();
+ } ARGEND;
+
+ if (!argc || !size)
+ usage();
+
+ for (; *argv; argc--, argv++) {
+ if ((fd = open(*argv, O_RDWR | O_CREAT, 0644)) < 0) {
+ weprintf("open %s:", *argv);
+ ret = 1;
+ } else if (posix_fallocate(fd, offset, size) < 0) {
+ weprintf("posix_fallocate %s:", *argv);
+ ret = 1;
+ }
+
+ if (fd >= 0 && close(fd) < 0) {
+ weprintf("close %s:", *argv);
+ ret = 1;
+ }
+ }
+
+ return ret;
+}
diff --git a/cmd/pseudo/flock.c b/cmd/pseudo/flock.c
@@ -1,4 +1,11 @@
/* See LICENSE file for copyright and license details. */
+/* ?man
+flock: manage locks
+usage: flock [-nosux] file cmd [arg ...]
+
+acquire or release locks from shell scripts
+*/
+
#include <sys/file.h>
#include <sys/wait.h>
@@ -22,18 +29,23 @@ main(int argc, char *argv[])
pid_t pid;
ARGBEGIN {
+ // ?man -n: print line numbers or counts
case 'n':
nonblk = LOCK_NB;
break;
+ // ?man -o: specify output file
case 'o':
oflag = 1;
break;
+ // ?man -s: silent mode or print summary
case 's':
flags = LOCK_SH;
break;
+ // ?man -u: unbuffered output
case 'u':
flags = LOCK_UN;
break;
+ // ?man -x: hex format or match whole lines
case 'x':
flags = LOCK_EX;
break;
diff --git a/cmd/pseudo/free.c b/cmd/pseudo/free.c
@@ -0,0 +1,89 @@
+/* See LICENSE file for copyright and license details. */
+/* ?man
+free: display memory usage
+usage: free [-bkmg]
+
+display the amount of free and used memory in the system
+*/
+
+#include <stdio.h>
+#include <stdlib.h>
+
+#include "util.h"
+
+int get_meminfo(struct MemInfo *);
+
+static unsigned int mem_unit = 1;
+static unsigned int unit_shift;
+
+static unsigned long long
+scale(unsigned long long v)
+{
+ return (v * mem_unit) >> unit_shift;
+}
+
+static void
+usage(void)
+{
+ eprintf("usage: %s [-bkmg]\n", argv0);
+}
+
+int
+main(int argc, char *argv[])
+{
+ struct MemInfo mi;
+
+ ARGBEGIN {
+ // ?man -b: specify block size or base directory
+ case 'b':
+ unit_shift = 0;
+ break;
+ // ?man -k: specify option flag
+ case 'k':
+ unit_shift = 10;
+ break;
+ // ?man -m: specify mode or limit
+ case 'm':
+ unit_shift = 20;
+ break;
+ // ?man -g: specify option flag
+ case 'g':
+ unit_shift = 30;
+ break;
+ default:
+ usage();
+ } ARGEND;
+
+ if (argc)
+ usage();
+
+ if (get_meminfo(&mi) < 0)
+ eprintf("get_meminfo:");
+
+ printf(" %13s%13s%13s%13s%13s\n",
+ "total",
+ "used",
+ "free",
+ "shared", "buffers");
+ printf("Mem: ");
+ printf("%13llu%13llu%13llu%13llu%13llu\n",
+ scale(mi.total),
+ scale(mi.total - mi.free),
+ scale(mi.free),
+ scale(mi.shared),
+ scale(mi.buffers));
+ printf("-/+ buffers/cache:");
+ printf("%13llu%13llu\n",
+ scale(mi.total - mi.free - mi.buffers),
+ scale(mi.free + mi.buffers));
+ printf("Swap:");
+ printf("%13llu%13llu%13llu\n",
+ scale(mi.totalswap),
+ scale(mi.totalswap - mi.freeswap),
+ scale(mi.freeswap));
+
+ if (fshut(stdin, "<stdin>") | fshut(stdout, "<stdout>"))
+ return 1;
+
+ return 0;
+}
diff --git a/cmd/pseudo/getty.c b/cmd/pseudo/getty.c
@@ -1,4 +1,11 @@
/* See LICENSE file for copyright and license details. */
+/* ?man
+getty: set terminal mode
+usage: getty [tty] [term] [cmd] [args...]
+
+set terminal line discipline, speed, and mode
+*/
+
#include <sys/ioctl.h>
#include <sys/stat.h>
#include <sys/types.h>
@@ -29,6 +36,7 @@ main(int argc, char *argv[])
{
char term[128], logname[LOGIN_NAME_MAX], c;
char hostname[HOST_NAME_MAX + 1];
+ char ut_line_buf[UT_LINESIZE + 1];
struct utmp usr;
struct sigaction sa;
FILE *fp;
@@ -97,7 +105,9 @@ main(int argc, char *argv[])
break;
if (usr.ut_line[0] == '\0')
continue;
- if (strcmp(usr.ut_line, tty) != 0)
+ memcpy(ut_line_buf, usr.ut_line, UT_LINESIZE);
+ ut_line_buf[UT_LINESIZE] = '\0';
+ if (strcmp(ut_line_buf, tty) != 0)
continue;
memset(&usr, 0, sizeof(usr));
fseek(fp, pos, SEEK_SET);
diff --git a/cmd/pseudo/halt.c b/cmd/pseudo/halt.c
@@ -1,4 +1,11 @@
/* See LICENSE file for copyright and license details. */
+/* ?man
+halt: halt or reboot
+usage: halt [-pr]
+
+halt, poweroff, or reboot the machine
+*/
+
#include <sys/syscall.h>
#include <stdio.h>
@@ -21,9 +28,11 @@ main(int argc, char *argv[])
int cmd = LINUX_REBOOT_CMD_HALT;
ARGBEGIN {
+ // ?man -p: preserve file attributes
case 'p':
pflag = 1;
break;
+ // ?man -r: operate recursively
case 'r':
rflag = 1;
break;
diff --git a/cmd/pseudo/hostname.c b/cmd/pseudo/hostname.c
@@ -1,4 +1,11 @@
/* See LICENSE file for copyright and license details. */
+/* ?man
+hostname: show or set hostname
+usage: hostname [name]
+
+display or configure the system hostname
+*/
+
#include <stdio.h>
#include <string.h>
#include <unistd.h>
diff --git a/cmd/pseudo/killall5.c b/cmd/pseudo/killall5.c
@@ -1,4 +1,11 @@
/* See LICENSE file for copyright and license details. */
+/* ?man
+killall5: send signal to all processes
+usage: killall5 [-o pid1
+
+send a signal to all processes except kernel threads
+*/
+
#include <dirent.h>
#include <limits.h>
#include <signal.h>
@@ -49,6 +56,7 @@ main(int argc, char *argv[])
size_t i;
ARGBEGIN {
+ // ?man -s: silent mode or print summary
case 's':
v = EARGF(usage());
sig = strtol(v, &end, 0);
@@ -63,6 +71,7 @@ main(int argc, char *argv[])
if (i == LEN(sigs))
eprintf("%s: unknown signal\n", v);
break;
+ // ?man -o: specify output file
case 'o':
oflag = 1;
arg = EARGF(usage());
diff --git a/cmd/pseudo/last.c b/cmd/pseudo/last.c
@@ -1,4 +1,11 @@
/* See LICENSE file for copyright and license details. */
+/* ?man
+last: show last logged in users
+usage: last [user]
+
+display a list of recent user logins
+*/
+
#include <errno.h>
#include <libgen.h>
#include <paths.h>
@@ -25,6 +32,7 @@ main(int argc, char **argv)
FILE *fp;
struct utmp ut;
char *user, *file, *prog;
+ char ut_name_buf[UT_NAMESIZE + 1];
time_t t;
ARGBEGIN {
@@ -49,8 +57,10 @@ main(int argc, char **argv)
eprintf("fopen %s:", file);
while (fread(&ut, sizeof(ut), 1, fp) == 1) {
+ memcpy(ut_name_buf, ut.ut_name, UT_NAMESIZE);
+ ut_name_buf[UT_NAMESIZE] = '\0';
if (ut.ut_type != USER_PROCESS ||
- (user && strcmp(user, ut.ut_name))) {
+ (user && strcmp(user, ut_name_buf))) {
continue;
}
diff --git a/cmd/pseudo/lastlog.c b/cmd/pseudo/lastlog.c
@@ -1,4 +1,11 @@
/* See LICENSE file for copyright and license details. */
+/* ?man
+lastlog: report recent logins
+usage: lastlog
+
+display the most recent login times of users
+*/
+
#include <errno.h>
#include <paths.h>
#include <pwd.h>
diff --git a/cmd/pseudo/login.c b/cmd/pseudo/login.c
@@ -1,4 +1,11 @@
/* See LICENSE file for copyright and license details. */
+/* ?man
+login: begin terminal session
+usage: login [-p] username
+
+authenticate and start a session on the system
+*/
+
#include <sys/ioctl.h>
#include <sys/types.h>
@@ -78,6 +85,7 @@ main(int argc, char *argv[])
int pflag = 0;
ARGBEGIN {
+ // ?man -p: preserve file attributes
case 'p':
pflag = 1;
break;
diff --git a/cmd/pseudo/md5sum.c b/cmd/pseudo/md5sum.c
@@ -1,4 +1,11 @@
/* See LICENSE file for copyright and license details. */
+/* ?man
+md5sum: compute md5 checksums
+usage: md5sum [-c] [file ...]
+
+compute and check md5 message digests
+*/
+
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
@@ -28,10 +35,13 @@ main(int argc, char *argv[])
uint8_t md[MD5_DIGEST_LENGTH];
ARGBEGIN {
+ // ?man -b: specify block size or base directory
case 'b':
+ // ?man -t: sort or specify timestamp
case 't':
/* ignore */
break;
+ // ?man -c: print count or perform stdout action
case 'c':
cryptfunc = cryptcheck;
break;
diff --git a/cmd/pseudo/mktemp.c b/cmd/pseudo/mktemp.c
@@ -1,4 +1,11 @@
/* See LICENSE file for copyright and license details. */
+/* ?man
+mktemp: create temporary file
+usage: mktemp [-dqtu] [-p directory] [template]
+
+create a temporary file or directory safely
+*/
+
#include <libgen.h>
#include <stdio.h>
#include <stdlib.h>
@@ -22,19 +29,24 @@ main(int argc, char *argv[])
size_t len;
ARGBEGIN {
+ // ?man -d: specify directory
case 'd':
dflag = 1;
break;
+ // ?man -p: preserve file attributes
case 'p':
pflag = 1;
pdir = EARGF(usage());
break;
+ // ?man -q: quiet mode; suppress output
case 'q':
qflag = 1;
break;
+ // ?man -t: sort or specify timestamp
case 't':
tflag = 1;
break;
+ // ?man -u: unbuffered output
case 'u':
uflag = 1;
break;
diff --git a/cmd/pseudo/nologin.c b/cmd/pseudo/nologin.c
@@ -1,4 +1,11 @@
/* See LICENSE file for copyright and license details. */
+/* ?man
+nologin: politely refuse login
+usage: nologin
+
+politely refuse a login attempt by exiting with status 1
+*/
+
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
diff --git a/cmd/pseudo/pagesize.c b/cmd/pseudo/pagesize.c
@@ -1,4 +1,11 @@
/* See LICENSE file for copyright and license details. */
+/* ?man
+pagesize: print system page size
+usage: pagesize
+
+display the size of a page in memory
+*/
+
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
diff --git a/cmd/pseudo/pidof.c b/cmd/pseudo/pidof.c
@@ -0,0 +1,125 @@
+/* See LICENSE file for copyright and license details. */
+/* ?man
+pidof: find process ids
+usage: pidof [-o pid1
+
+find the process identity numbers of running programs
+*/
+
+#include <sys/types.h>
+
+#include <dirent.h>
+#include <libgen.h>
+#include <limits.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+
+#include "proc.h"
+#include "queue.h"
+#include "util.h"
+
+struct pidentry {
+ pid_t pid;
+ SLIST_ENTRY(pidentry) entry;
+};
+
+static SLIST_HEAD(, pidentry) omitpid_head;
+
+static void
+usage(void)
+{
+ eprintf("usage: %s [-o pid1,pid2,...pidN] [-s] [program...]\n", argv0);
+}
+
+int
+main(int argc, char *argv[])
+{
+ DIR *dp;
+ struct dirent *entry;
+ pid_t pid;
+ struct procstat ps;
+ char cmdline[BUFSIZ], *cmd, *cmdbase = NULL, *p, *arg = NULL;
+ int i, found = 0;
+ int sflag = 0, oflag = 0;
+ struct pidentry *pe;
+
+ ARGBEGIN {
+ // ?man -s: silent mode or print summary
+ case 's':
+ sflag = 1;
+ break;
+ // ?man -o: specify output file
+ case 'o':
+ oflag = 1;
+ arg = EARGF(usage());
+ break;
+ default:
+ usage();
+ } ARGEND;
+
+ if (!argc)
+ return 1;
+
+ SLIST_INIT(&omitpid_head);
+
+ if (oflag) {
+ for (p = strtok(arg, ","); p; p = strtok(NULL, ",")) {
+ pe = emalloc(sizeof(*pe));
+ if (strcmp(p, "%PPID") == 0)
+ pe->pid = getppid();
+ else
+ pe->pid = estrtol(p, 10);
+ SLIST_INSERT_HEAD(&omitpid_head, pe, entry);
+ }
+ }
+
+ if (!(dp = opendir("/proc")))
+ eprintf("opendir /proc:");
+
+ while ((entry = readdir(dp))) {
+ if (!pidfile(entry->d_name))
+ continue;
+ pid = estrtol(entry->d_name, 10);
+ if (oflag) {
+ SLIST_FOREACH(pe, &omitpid_head, entry)
+ if (pe->pid == pid)
+ break;
+ if (pe)
+ continue;
+ }
+ if (parsestat(pid, &ps) < 0)
+ continue;
+ if (parsecmdline(ps.pid, cmdline,
+ sizeof(cmdline)) < 0) {
+ cmd = ps.comm;
+ cmdbase = cmd;
+ } else {
+ if ((p = strchr(cmdline, ' ')))
+ *p = '\0';
+ cmd = cmdline;
+ cmdbase = basename(cmdline);
+ }
+ /* Workaround for login shells */
+ if (cmd[0] == '-')
+ cmd++;
+ for (i = 0; i < argc; i++) {
+ if (strcmp(cmd, argv[i]) == 0 ||
+ strcmp(cmdbase, argv[i]) == 0) {
+ putword(stdout, entry->d_name);
+ found++;
+ if (sflag)
+ goto out;
+ }
+ }
+ }
+
+out:
+ if (found)
+ putchar('\n');
+
+ closedir(dp);
+
+ return found ? 0 : 1;
+}
diff --git a/cmd/pseudo/printenv.c b/cmd/pseudo/printenv.c
@@ -1,4 +1,11 @@
/* See LICENSE file for copyright and license details. */
+/* ?man
+printenv: print environment variables
+usage: printenv [var ...]
+
+display all or part of the current environment
+*/
+
#include <stdio.h>
#include <stdlib.h>
diff --git a/cmd/pseudo/pwdx.c b/cmd/pseudo/pwdx.c
@@ -0,0 +1,58 @@
+/* See LICENSE file for copyright and license details. */
+/* ?man
+pwdx: print working directory of process
+usage: pwdx pid...
+
+display the current working directory of a process by pid
+*/
+
+#include <errno.h>
+#include <limits.h>
+#include <stdio.h>
+#include <string.h>
+#include <unistd.h>
+
+#include "util.h"
+
+static void
+usage(void)
+{
+ eprintf("usage: %s pid...\n", argv0);
+}
+
+int
+main(int argc, char *argv[])
+{
+ int ret = 0;
+ char path[PATH_MAX];
+ char target[PATH_MAX + sizeof(" (deleted)")];
+ ssize_t n;
+
+ ARGBEGIN {
+ default:
+ usage();
+ } ARGEND;
+
+ if (argc == 0)
+ usage();
+
+ for (; argc > 0; argc--, argv++) {
+ n = snprintf(path, sizeof(path), "/proc/%s/cwd", *argv);
+ if (n < 0 || (size_t)n >= sizeof(path)) {
+ errno = ESRCH;
+ } else {
+ n = readlink(path, target, sizeof(target) - 1);
+ if (n >= 0) {
+ target[n] = '\0';
+ printf("%s: %s\n", *argv, target);
+ continue;
+ }
+ }
+ if (errno == ENOENT)
+ errno = ESRCH;
+ weprintf("%s:", *argv);
+ ret = 1;
+ }
+
+ return ret;
+}
diff --git a/cmd/pseudo/respawn.c b/cmd/pseudo/respawn.c
@@ -1,4 +1,11 @@
/* See LICENSE file for copyright and license details. */
+/* ?man
+respawn: restart command on exit
+usage: respawn [-l fifo] [-d N] cmd [args...]
+
+run a command and restart it automatically when it exits
+*/
+
#include <sys/stat.h>
#include <sys/time.h>
#include <sys/types.h>
@@ -42,9 +49,11 @@ main(int argc, char *argv[])
int polln;
ARGBEGIN {
+ // ?man -d: specify directory
case 'd':
delay = estrtol(EARGF(usage()), 0);
break;
+ // ?man -l: list in long format
case 'l':
fifo = EARGF(usage());
break;
diff --git a/cmd/pseudo/rev.c b/cmd/pseudo/rev.c
@@ -1,4 +1,11 @@
/* See LICENSE file for copyright and license details. */
+/* ?man
+rev: reverse lines
+usage: rev [file ...]
+
+reverse the order of characters in each line of input
+*/
+
#include <stdio.h>
#include <string.h>
#include <unistd.h>
diff --git a/cmd/pseudo/seq.c b/cmd/pseudo/seq.c
@@ -1,4 +1,11 @@
/* See LICENSE file for copyright and license details. */
+/* ?man
+seq: print sequence of numbers
+usage: seq [-f fmt] [-s sep] [-w]
+
+print a sequence of numbers from start to end
+*/
+
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
@@ -9,7 +16,7 @@ static int
digitsleft(const char *d)
{
int shift;
- char *exp;
+ const char *exp;
if (*d == '+')
d++;
@@ -23,7 +30,7 @@ static int
digitsright(const char *d)
{
int shift, after;
- char *exp;
+ const char *exp;
exp = strpbrk(d, "eE");
shift = exp ? estrtonum(&exp[1], INT_MIN, INT_MAX) : 0;
@@ -58,6 +65,7 @@ format:
fmt++;
switch (*fmt) {
+ // ?man -f: force the operation
case 'f': case 'F':
case 'g': case 'G':
case 'e': case 'E':
@@ -85,14 +93,17 @@ main(int argc, char *argv[])
const char *starts = "1", *steps = "1", *ends = "1", *sep = "\n";
ARGBEGIN {
+ // ?man -f: force the operation
case 'f':
if (!validfmt(tmp=EARGF(usage())))
eprintf("%s: invalid format\n", tmp);
fmt = tmp;
break;
+ // ?man -s: silent mode or print summary
case 's':
sep = EARGF(usage());
break;
+ // ?man -w: wait for completion
case 'w':
wflag = 1;
break;
diff --git a/cmd/pseudo/setsid.c b/cmd/pseudo/setsid.c
@@ -1,4 +1,11 @@
/* See LICENSE file for copyright and license details. */
+/* ?man
+setsid: run in new session
+usage: setsid [-f] cmd [arg ...]
+
+run a program in a new session
+*/
+
#include <errno.h>
#include <unistd.h>
@@ -18,6 +25,7 @@ main(int argc, char *argv[])
int savederrno;
ARGBEGIN {
+ // ?man -f: force the operation
case 'f':
fflag = 1;
break;
diff --git a/cmd/pseudo/sha1sum.c b/cmd/pseudo/sha1sum.c
@@ -1,4 +1,11 @@
/* See LICENSE file for copyright and license details. */
+/* ?man
+sha1sum: compute sha1 checksums
+usage: sha1sum [-c] [file ...]
+
+compute and check sha1 message digests
+*/
+
#include <stdint.h>
#include <stdio.h>
@@ -27,10 +34,13 @@ main(int argc, char *argv[])
uint8_t md[SHA1_DIGEST_LENGTH];
ARGBEGIN {
+ // ?man -b: specify block size or base directory
case 'b':
+ // ?man -t: sort or specify timestamp
case 't':
/* ignore */
break;
+ // ?man -c: print count or perform stdout action
case 'c':
cryptfunc = cryptcheck;
break;
diff --git a/cmd/pseudo/sha224sum.c b/cmd/pseudo/sha224sum.c
@@ -1,4 +1,11 @@
/* See LICENSE file for copyright and license details. */
+/* ?man
+sha224sum: compute sha224 checksums
+usage: sha224sum [-c] [file ...]
+
+compute and check sha224 message digests
+*/
+
#include <stdint.h>
#include <stdio.h>
@@ -27,10 +34,13 @@ main(int argc, char *argv[])
uint8_t md[SHA224_DIGEST_LENGTH];
ARGBEGIN {
+ // ?man -b: specify block size or base directory
case 'b':
+ // ?man -t: sort or specify timestamp
case 't':
/* ignore */
break;
+ // ?man -c: print count or perform stdout action
case 'c':
cryptfunc = cryptcheck;
break;
diff --git a/cmd/pseudo/sha256sum.c b/cmd/pseudo/sha256sum.c
@@ -1,4 +1,11 @@
/* See LICENSE file for copyright and license details. */
+/* ?man
+sha256sum: compute sha256 checksums
+usage: sha256sum [-c] [file ...]
+
+compute and check sha256 message digests
+*/
+
#include <stdint.h>
#include <stdio.h>
@@ -27,10 +34,13 @@ main(int argc, char *argv[])
uint8_t md[SHA256_DIGEST_LENGTH];
ARGBEGIN {
+ // ?man -b: specify block size or base directory
case 'b':
+ // ?man -t: sort or specify timestamp
case 't':
/* ignore */
break;
+ // ?man -c: print count or perform stdout action
case 'c':
cryptfunc = cryptcheck;
break;
diff --git a/cmd/pseudo/sha384sum.c b/cmd/pseudo/sha384sum.c
@@ -1,4 +1,11 @@
/* See LICENSE file for copyright and license details. */
+/* ?man
+sha384sum: compute sha384 checksums
+usage: sha384sum [-c] [file ...]
+
+compute and check sha384 message digests
+*/
+
#include <stdint.h>
#include <stdio.h>
@@ -27,10 +34,13 @@ main(int argc, char *argv[])
uint8_t md[SHA384_DIGEST_LENGTH];
ARGBEGIN {
+ // ?man -b: specify block size or base directory
case 'b':
+ // ?man -t: sort or specify timestamp
case 't':
/* ignore */
break;
+ // ?man -c: print count or perform stdout action
case 'c':
cryptfunc = cryptcheck;
break;
diff --git a/cmd/pseudo/sha512-224sum.c b/cmd/pseudo/sha512-224sum.c
@@ -1,4 +1,11 @@
/* See LICENSE file for copyright and license details. */
+/* ?man
+sha512-224sum: compute sha512/224 checksums
+usage: sha512-224sum [-c] [file ...]
+
+compute and check sha512/224 message digests
+*/
+
#include <stdint.h>
#include <stdio.h>
@@ -27,10 +34,13 @@ main(int argc, char *argv[])
uint8_t md[SHA512_224_DIGEST_LENGTH];
ARGBEGIN {
+ // ?man -b: specify block size or base directory
case 'b':
+ // ?man -t: sort or specify timestamp
case 't':
/* ignore */
break;
+ // ?man -c: print count or perform stdout action
case 'c':
cryptfunc = cryptcheck;
break;
diff --git a/cmd/pseudo/sha512-256sum.c b/cmd/pseudo/sha512-256sum.c
@@ -1,4 +1,11 @@
/* See LICENSE file for copyright and license details. */
+/* ?man
+sha512-256sum: compute sha512/256 checksums
+usage: sha512-256sum [-c] [file ...]
+
+compute and check sha512/256 message digests
+*/
+
#include <stdint.h>
#include <stdio.h>
@@ -27,10 +34,13 @@ main(int argc, char *argv[])
uint8_t md[SHA512_256_DIGEST_LENGTH];
ARGBEGIN {
+ // ?man -b: specify block size or base directory
case 'b':
+ // ?man -t: sort or specify timestamp
case 't':
/* ignore */
break;
+ // ?man -c: print count or perform stdout action
case 'c':
cryptfunc = cryptcheck;
break;
diff --git a/cmd/pseudo/sha512sum.c b/cmd/pseudo/sha512sum.c
@@ -1,4 +1,11 @@
/* See LICENSE file for copyright and license details. */
+/* ?man
+sha512sum: compute sha512 checksums
+usage: sha512sum [-c] [file ...]
+
+compute and check sha512 message digests
+*/
+
#include <stdint.h>
#include <stdio.h>
@@ -27,10 +34,13 @@ main(int argc, char *argv[])
uint8_t md[SHA512_DIGEST_LENGTH];
ARGBEGIN {
+ // ?man -b: specify block size or base directory
case 'b':
+ // ?man -t: sort or specify timestamp
case 't':
/* ignore */
break;
+ // ?man -c: print count or perform stdout action
case 'c':
cryptfunc = cryptcheck;
break;
diff --git a/cmd/pseudo/sponge.c b/cmd/pseudo/sponge.c
@@ -1,4 +1,11 @@
/* See LICENSE file for copyright and license details. */
+/* ?man
+sponge: soak up input
+usage: sponge file
+
+soak up standard input and write to a file
+*/
+
#include <fcntl.h>
#include <stdlib.h>
#include <unistd.h>
diff --git a/cmd/pseudo/stat.c b/cmd/pseudo/stat.c
@@ -1,3 +1,10 @@
+/* ?man
+stat: display file status
+usage: stat [-L] [-t]
+
+display file or filesystem status information
+*/
+
#include "config.h"
#include "util.h"
@@ -56,10 +63,12 @@ print_custom(const char *file, struct stat *st, const char *fmt)
p++;
switch (*p) {
case 'n': putchar('\n'); break;
- case 't': putchar('\t'); break;
+ // ?man -t: sort or specify timestamp
+ case 't': putchar('\t'); break;
case 'r': putchar('\r'); break;
case 'b': putchar('\b'); break;
- case 'f': putchar('\f'); break;
+ // ?man -f: force the operation
+ case 'f': putchar('\f'); break;
case '\\': putchar('\\'); break;
case '\0': return;
default: putchar(*p); break;
@@ -169,7 +178,8 @@ print_custom(const char *file, struct stat *st, const char *fmt)
fmt_spec[fmt_len] = '\0';
printf(fmt_spec, (long long)st->st_size);
break;
- case 't':
+ // ?man -t: sort or specify timestamp
+ case 't':
fmt_spec[fmt_len++] = 'x';
fmt_spec[fmt_len] = '\0';
printf(fmt_spec, major(st->st_rdev));
@@ -273,10 +283,12 @@ print_fs_custom(const char *file, struct statfs *st, const char *fmt)
p++;
switch (*p) {
case 'n': putchar('\n'); break;
- case 't': putchar('\t'); break;
+ // ?man -t: sort or specify timestamp
+ case 't': putchar('\t'); break;
case 'r': putchar('\r'); break;
case 'b': putchar('\b'); break;
- case 'f': putchar('\f'); break;
+ // ?man -f: force the operation
+ case 'f': putchar('\f'); break;
case '\\': putchar('\\'); break;
case '\0': return;
default: putchar(*p); break;
@@ -322,7 +334,8 @@ print_fs_custom(const char *file, struct statfs *st, const char *fmt)
fmt_spec[fmt_len] = '\0';
printf(fmt_spec, (long long)st->f_blocks);
break;
- case 'c':
+ // ?man -c: print count or perform stdout action
+ case 'c':
fmt_spec[fmt_len++] = 'l';
fmt_spec[fmt_len++] = 'l';
fmt_spec[fmt_len++] = 'd';
@@ -336,7 +349,8 @@ print_fs_custom(const char *file, struct statfs *st, const char *fmt)
fmt_spec[fmt_len] = '\0';
printf(fmt_spec, (long long)st->f_ffree);
break;
- case 'f':
+ // ?man -f: force the operation
+ case 'f':
fmt_spec[fmt_len++] = 'l';
fmt_spec[fmt_len++] = 'l';
fmt_spec[fmt_len++] = 'd';
@@ -373,7 +387,8 @@ print_fs_custom(const char *file, struct statfs *st, const char *fmt)
fmt_spec[fmt_len] = '\0';
printf(fmt_spec, (long)st->f_frsize ? (long)st->f_frsize : (long)st->f_bsize);
break;
- case 't':
+ // ?man -t: sort or specify timestamp
+ case 't':
fmt_spec[fmt_len++] = 'l';
fmt_spec[fmt_len++] = 'x';
fmt_spec[fmt_len] = '\0';
@@ -463,19 +478,23 @@ main(int argc, char *argv[])
void (*showstat)(const char *, struct stat *) = show_stat;
ARGBEGIN {
+ // ?man -L: specify option flag
case 'L':
fn = stat;
fnname = "stat";
break;
+ // ?man -t: sort or specify timestamp
case 't':
showstat = show_stat_terse;
break;
#if FEATURE_STAT_FILESYSTEM
+ // ?man -f: force the operation
case 'f':
fflag = 1;
break;
#endif
#if FEATURE_STAT_FORMAT
+ // ?man -c: print count or perform stdout action
case 'c':
format = EARGF(usage());
break;
diff --git a/cmd/pseudo/tar.c b/cmd/pseudo/tar.c
@@ -1,3 +1,10 @@
+/* ?man
+tar: tape archiver
+usage: tar [x | t | -x | -t] [-C dir] [-J | -Z | -a | -j | -z] [-m] [-p]
+
+manipulate tape archive files
+*/
+
#include "config.h"
#include "fs.h"
#include "utf.h"
@@ -421,7 +428,7 @@ unarchive(char *fname, ssize_t l, char b[BLKSIZ])
if (fd != -1) {
for (; l > 0; l -= BLKSIZ)
if (eread(tarfd, b, BLKSIZ) > 0)
- ewrite(fd, b, MIN(l, BLKSIZ));
+ ewrite(fd, b, MIN(l, (ssize_t)BLKSIZ));
close(fd);
}
@@ -670,38 +677,52 @@ main(int argc, char *argv[])
*(argv[1]+1) ? *argv[1] = '-' : (*++argv = argv0, --argc);
ARGBEGIN {
+ // ?man -x: extract files from an archive
case 'x':
#if FEATURE_TAR_CREATE
+ // ?man -c: create a new archive
case 'c':
#endif
+ // ?man -t: list the contents of an archive
case 't':
mode = ARGC();
break;
+ // ?man -C: specify option flag
case 'C':
dir = EARGF(usage());
break;
+ // ?man -f: specify archive file
case 'f':
file = EARGF(usage());
break;
+ // ?man -m: specify mode or limit
case 'm':
mflag = 1;
break;
+ // ?man -J: specify option flag
case 'J':
+ // ?man -Z: specify option flag
case 'Z':
+ // ?man -a: print or show all entries
case 'a':
+ // ?man -j: specify option flag
case 'j':
+ // ?man -z: specify option flag
case 'z':
filtermode = ARGC();
filtertool = filtertools[filtermode];
break;
+ // ?man -h: suppress headers or print help
case 'h':
#if FEATURE_TAR_CREATE
r.follow = 'L';
#endif
break;
+ // ?man -v: verbosely list files processed
case 'v':
vflag = 1;
break;
+ // ?man -p: preserve file attributes
case 'p':
break; /* do nothing as already default behaviour */
#if FEATURE_TAR_EXCLUDE
@@ -724,6 +745,7 @@ main(int argc, char *argv[])
switch (mode) {
#if FEATURE_TAR_CREATE
+ // ?man -c: create a new archive
case 'c':
if (!argc)
usage();
@@ -747,7 +769,9 @@ main(int argc, char *argv[])
recurse(AT_FDCWD, *argv, NULL, &r);
break;
#endif
+ // ?man -t: list the contents of an archive
case 't':
+ // ?man -x: extract files from an archive
case 'x':
tarfd = 0;
if (file && *file != '-') {
diff --git a/cmd/pseudo/truncate.c b/cmd/pseudo/truncate.c
@@ -1,4 +1,11 @@
/* See LICENSE file for copyright and license details. */
+/* ?man
+truncate: set file size
+usage: truncate [-c] -s size file...
+
+shrink or extend a file to a specified size
+*/
+
#include <sys/stat.h>
#include <fcntl.h>
@@ -22,10 +29,12 @@ main(int argc, char *argv[])
long size = 0;
ARGBEGIN {
+ // ?man -s: silent mode or print summary
case 's':
sflag = 1;
size = estrtol(EARGF(usage()), 10);
break;
+ // ?man -c: print count or perform stdout action
case 'c':
cflag = 1;
break;
diff --git a/cmd/pseudo/uptime.c b/cmd/pseudo/uptime.c
@@ -0,0 +1,90 @@
+/* See LICENSE file for copyright and license details. */
+/* ?man
+uptime: show system uptime
+usage: uptime
+
+display how long the system has been running and load averages
+*/
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <time.h>
+#include <utmpx.h>
+
+#include "config.h"
+#include "util.h"
+
+int get_uptime(long *);
+int get_loads(double *);
+
+static void
+usage(void)
+{
+ eprintf("usage: %s\n", argv0);
+}
+
+int
+main(int argc, char *argv[])
+{
+ struct utmpx utx;
+ FILE *ufp;
+ long uptime;
+ double loads[3];
+ time_t tmptime;
+ struct tm *now;
+ unsigned int days, hours, minutes;
+ int nusers = 0;
+ size_t n;
+
+ ARGBEGIN {
+ default:
+ usage();
+ } ARGEND;
+
+ if (argc)
+ usage();
+
+ if (get_uptime(&uptime) < 0)
+ eprintf("get_uptime:");
+ if (get_loads(loads) < 0)
+ eprintf("get_loads:");
+
+ time(&tmptime);
+ now = localtime(&tmptime);
+ printf(" %02d:%02d:%02d up ", now->tm_hour, now->tm_min, now->tm_sec);
+
+ uptime /= 60;
+ minutes = uptime % 60;
+ uptime /= 60;
+ hours = uptime % 24;
+ days = uptime / 24;
+ if (days)
+ printf("%d day%s, ", days, days != 1 ? "s" : "");
+ if (hours)
+ printf("%2d:%02d, ", hours, minutes);
+ else
+ printf("%d min, ", minutes);
+
+ if ((ufp = fopen(UTMP_PATH, "r"))) {
+ while ((n = fread(&utx, sizeof(utx), 1, ufp)) > 0) {
+ if (!utx.ut_user[0])
+ continue;
+ if (utx.ut_type != USER_PROCESS)
+ continue;
+ nusers++;
+ }
+ if (ferror(ufp))
+ eprintf("%s: read error:", UTMP_PATH);
+ fclose(ufp);
+ printf(" %d user%s, ", nusers, nusers != 1 ? "s" : "");
+ }
+
+ printf(" load average: %.02f, %.02f, %.02f\n",
+ loads[0], loads[1], loads[2]);
+
+ if (fshut(stdin, "<stdin>") | fshut(stdout, "<stdout>"))
+ return 1;
+
+ return 0;
+}
diff --git a/cmd/pseudo/watch.c b/cmd/pseudo/watch.c
@@ -1,4 +1,11 @@
/* See LICENSE file for copyright and license details. */
+/* ?man
+watch: execute periodically
+usage: watch [-t] [-n interval] command
+
+run a program periodically, showing output fullscreen
+*/
+
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
@@ -22,8 +29,10 @@ main(int argc, char *argv[])
int i;
ARGBEGIN {
+ // ?man -t: sort or specify timestamp
case 't':
break;
+ // ?man -n: print line numbers or counts
case 'n':
period = strtof(EARGF(usage()), &end);
if (*end != '\0' || errno != 0)
diff --git a/cmd/pseudo/which.c b/cmd/pseudo/which.c
@@ -1,4 +1,11 @@
/* See LICENSE file for copyright and license details. */
+/* ?man
+which: locate a command
+usage: which [-a] name ...
+
+find the path of executable files in PATH
+*/
+
#include <sys/stat.h>
#include <sys/types.h>
@@ -75,6 +82,7 @@ main(int argc, char *argv[])
int found = 0, foundall = 1;
ARGBEGIN {
+ // ?man -a: print or show all entries
case 'a':
aflag = 1;
break;
diff --git a/cmd/pseudo/whoami.c b/cmd/pseudo/whoami.c
@@ -1,4 +1,11 @@
/* See LICENSE file for copyright and license details. */
+/* ?man
+whoami: print effective user name
+usage: whoami
+
+display the effective user name of the current process
+*/
+
#include <errno.h>
#include <stdio.h>
#include <unistd.h>
diff --git a/cmd/pseudo/xinstall.c b/cmd/pseudo/xinstall.c
@@ -1,4 +1,11 @@
/* See LICENSE file for copyright and license details. */
+/* ?man
+xinstall: copy files and set attributes
+usage: xinstall [-g group] [-o owner] [-m mode] (-d dir ... | [-D] (-t dest source ... | source ... dest))
+
+copy files and set their permissions and ownership
+*/
+
#include <grp.h>
#include <pwd.h>
#include <errno.h>
@@ -96,27 +103,35 @@ main(int argc, char *argv[])
char *p;
ARGBEGIN {
+ // ?man -c: print count or perform stdout action
case 'c':
/* no-op for compatibility */
break;
+ // ?man -d: specify directory
case 'd':
dflag = 1;
break;
+ // ?man -D: specify option flag
case 'D':
Dflag = 1;
break;
+ // ?man -s: silent mode or print summary
case 's':
/* no-op for compatibility */
break;
+ // ?man -g: specify option flag
case 'g':
gflag = EARGF(usage());
break;
+ // ?man -o: specify output file
case 'o':
oflag = EARGF(usage());
break;
+ // ?man -m: specify mode or limit
case 'm':
mflag = EARGF(usage());
break;
+ // ?man -t: sort or specify timestamp
case 't':
tflag = EARGF(usage());
break;
diff --git a/cmd/pseudo/yes.c b/cmd/pseudo/yes.c
@@ -1,4 +1,11 @@
/* See LICENSE file for copyright and license details. */
+/* ?man
+yes: output string repeatedly
+usage: yes [string]
+
+output a string repeatedly until terminated
+*/
+
#include <stdio.h>
#include "util.h"
diff --git a/cmd/xsi/mknod.c b/cmd/xsi/mknod.c
@@ -1,4 +1,11 @@
/* See LICENSE file for copyright and license details. */
+/* ?man
+mknod: create special files
+usage: mknod [-m mode] name b|c|u major minor
+
+create block or character special files
+*/
+
#include <sys/stat.h>
#include <sys/types.h>
#ifndef makedev
@@ -28,6 +35,7 @@ main(int argc, char *argv[])
dev_t dev;
ARGBEGIN {
+ // ?man -m: specify mode or limit
case 'm':
mode = parsemode(EARGF(usage()), mode, umask(0));
break;
diff --git a/cmd/xsi/passwd.c b/cmd/xsi/passwd.c
@@ -1,4 +1,11 @@
/* See LICENSE file for copyright and license details. */
+/* ?man
+passwd: change user password
+usage: passwd [username]
+
+update a user authentication password
+*/
+
#include <sys/ioctl.h>
#include <sys/stat.h>
#include <sys/types.h>
diff --git a/cmd/xsi/su.c b/cmd/xsi/su.c
@@ -1,4 +1,11 @@
/* See LICENSE file for copyright and license details. */
+/* ?man
+su: run command with substitute user id
+usage: su [-lp] [username]
+
+run a shell or command with another user id
+*/
+
#include <sys/types.h>
#include <errno.h>
@@ -33,9 +40,11 @@ main(int argc, char *argv[])
uid_t uid;
ARGBEGIN {
+ // ?man -l: list in long format
case 'l':
lflag = 1;
break;
+ // ?man -p: preserve file attributes
case 'p':
pflag = 1;
break;
diff --git a/config.mk b/config.mk
@@ -13,7 +13,7 @@ BUILD_LINUX = 1
BUILD_NET = 1
BUILD_XSI = 1
BUILD_PSEUDO = 1
-BUILD_MAKE = 1
+BUILD_DEV = 0
# posix tools
BUILD_POSIX_BASENAME = $(BUILD_POSIX)
@@ -98,42 +98,39 @@ BUILD_POSIX_PAX = $(BUILD_POSIX)
BUILD_LINUX_BLKDISCARD = $(BUILD_LINUX)
BUILD_LINUX_CHVT = $(BUILD_LINUX)
BUILD_LINUX_CTRLALTDEL = $(BUILD_LINUX)
-BUILD_LINUX_DMESG = $(BUILD_LINUX)
BUILD_LINUX_EJECT = $(BUILD_LINUX)
-BUILD_LINUX_FALLOCATE = $(BUILD_LINUX)
-BUILD_LINUX_FREE = $(BUILD_LINUX)
BUILD_LINUX_FREERAMDISK = $(BUILD_LINUX)
BUILD_LINUX_FSFREEZE = $(BUILD_LINUX)
BUILD_LINUX_HWCLOCK = $(BUILD_LINUX)
BUILD_LINUX_INSMOD = $(BUILD_LINUX)
BUILD_LINUX_LSMOD = $(BUILD_LINUX)
+BUILD_LINUX_MODPROBE = $(BUILD_LINUX)
+BUILD_LINUX_DEPMOD = $(BUILD_LINUX)
BUILD_LINUX_MKSWAP = $(BUILD_LINUX)
BUILD_LINUX_MOUNT = $(BUILD_LINUX)
BUILD_LINUX_MOUNTPOINT = $(BUILD_LINUX)
-BUILD_LINUX_PIDOF = $(BUILD_LINUX)
BUILD_LINUX_PIVOT_ROOT = $(BUILD_LINUX)
-BUILD_LINUX_PWDX = $(BUILD_LINUX)
BUILD_LINUX_READAHEAD = $(BUILD_LINUX)
BUILD_LINUX_RMMOD = $(BUILD_LINUX)
BUILD_LINUX_SWAPLABEL = $(BUILD_LINUX)
BUILD_LINUX_SWAPOFF = $(BUILD_LINUX)
BUILD_LINUX_SWAPON = $(BUILD_LINUX)
BUILD_LINUX_SWITCH_ROOT = $(BUILD_LINUX)
+BUILD_LINUX_TUNCTL = $(BUILD_LINUX)
BUILD_LINUX_UMOUNT = $(BUILD_LINUX)
BUILD_LINUX_UNSHARE = $(BUILD_LINUX)
-BUILD_LINUX_UPTIME = $(BUILD_LINUX)
BUILD_LINUX_VTALLOW = $(BUILD_LINUX)
# net tools
BUILD_NET_NETCAT = $(BUILD_NET)
BUILD_NET_TFTP = $(BUILD_NET)
-BUILD_NET_TUNCTL = $(BUILD_NET)
BUILD_NET_WGET = $(BUILD_NET)
BUILD_NET_PING = $(BUILD_NET)
BUILD_NET_SDHCP = $(BUILD_NET)
BUILD_NET_IFCONFIG = $(BUILD_NET)
BUILD_NET_HOST = $(BUILD_NET)
BUILD_NET_HTTPD = $(BUILD_NET)
+BUILD_NET_IP = $(BUILD_NET)
# xsi tools
BUILD_XSI_MKNOD = $(BUILD_XSI)
@@ -180,9 +177,18 @@ BUILD_PSEUDO_XINSTALL = $(BUILD_PSEUDO)
BUILD_PSEUDO_YES = $(BUILD_PSEUDO)
BUILD_PSEUDO_BASE64 = $(BUILD_PSEUDO)
BUILD_PSEUDO_B3SUM = $(BUILD_PSEUDO)
+BUILD_PSEUDO_DMESG = $(BUILD_PSEUDO)
+BUILD_PSEUDO_FALLOCATE = $(BUILD_PSEUDO)
+BUILD_PSEUDO_FREE = $(BUILD_PSEUDO)
+BUILD_PSEUDO_PIDOF = $(BUILD_PSEUDO)
+BUILD_PSEUDO_PWDX = $(BUILD_PSEUDO)
+BUILD_PSEUDO_UPTIME = $(BUILD_PSEUDO)
+BUILD_DEV_AR = $(BUILD_DEV)
+BUILD_DEV_LD = $(BUILD_DEV)
+BUILD_DEV_CC = $(BUILD_DEV)
# make tool
-BUILD_MAKE_MAKE = $(BUILD_MAKE)
+BUILD_POSIX_MAKE = $(BUILD_POSIX)
# feature gates for specific utilities
FEATURE_FIND_DELETE = 1
@@ -209,7 +215,7 @@ FEATURE_STAT_FORMAT = 1
FEATURE_SORT_BIG = 1
FEATURE_SORT_STABLE = 1
FEATURE_OD_ENDIAN = 1
-FEATURE_SH_HISTEDIT = 0
+FEATURE_SH_HISTEDIT = 1
FEATURE_SH_LOCAL = 1
FEATURE_SH_LET = 1
FEATURE_SH_ULIMIT = 1
@@ -218,6 +224,15 @@ FEATURE_SH_WORDEXP = 1
FEATURE_CAL_EXT = 1
FEATURE_SED_PRESERVE_NEWLINE = 1
FEATURE_LS_COLOR = 1
+FEATURE_MODPROBE_SHOW_DEPENDS = 1
+FEATURE_MODPROBE_BLACKLIST = 1
+FEATURE_MODPROBE_SYSLOG = 1
+FEATURE_MODPROBE_DIR_OVERRIDE = 1
+FEATURE_DEPMOD_ALIAS = 1
+FEATURE_DEPMOD_SYMBOLS = 1
+FEATURE_USE_LIBRESSL = 0
+FEATURE_USE_BEARSSL = 1
+
CPPFLAGS =\
-Ishared\
@@ -261,10 +276,25 @@ CPPFLAGS =\
-DFEATURE_SH_WORDEXP=$(FEATURE_SH_WORDEXP)\
-DFEATURE_CAL_EXT=$(FEATURE_CAL_EXT)\
-DFEATURE_SED_PRESERVE_NEWLINE=$(FEATURE_SED_PRESERVE_NEWLINE)\
- -DFEATURE_LS_COLOR=$(FEATURE_LS_COLOR)
+ -DFEATURE_LS_COLOR=$(FEATURE_LS_COLOR)\
+ -DFEATURE_MODPROBE_SHOW_DEPENDS=$(FEATURE_MODPROBE_SHOW_DEPENDS)\
+ -DFEATURE_MODPROBE_BLACKLIST=$(FEATURE_MODPROBE_BLACKLIST)\
+ -DFEATURE_MODPROBE_SYSLOG=$(FEATURE_MODPROBE_SYSLOG)\
+ -DFEATURE_MODPROBE_DIR_OVERRIDE=$(FEATURE_MODPROBE_DIR_OVERRIDE)\
+ -DFEATURE_DEPMOD_ALIAS=$(FEATURE_DEPMOD_ALIAS)\
+ -DFEATURE_DEPMOD_SYMBOLS=$(FEATURE_DEPMOD_SYMBOLS)\
+ -DFEATURE_USE_LIBRESSL=$(FEATURE_USE_LIBRESSL)\
+ -DFEATURE_USE_BEARSSL=$(FEATURE_USE_BEARSSL) $(CPPFLAGS_TLS)
CFLAGS = -std=c99 -Wall -Wextra -pedantic
-LDFLAGS =
+LDFLAGS = $(LDFLAGS_TLS)
LDLIBS_HISTEDIT_0 =
-LDLIBS_HISTEDIT_1 = -ledit
-LDLIBS = -lcrypt -lresolv $(LDLIBS_HISTEDIT_$(FEATURE_SH_HISTEDIT))
+LDLIBS_HISTEDIT_1 =
+LDLIBS_TLS_LIBRESSL_1 = -ltls
+LDLIBS_TLS_BEARSSL_1 = externalRepos/BearSSL/build/libbearssl.a
+LDLIBS_TLS = $(LDLIBS_TLS_LIBRESSL_$(FEATURE_USE_LIBRESSL)) $(LDLIBS_TLS_BEARSSL_$(FEATURE_USE_BEARSSL))
+CPPFLAGS_TLS_BEARSSL_1 = -IexternalRepos/BearSSL/inc
+LDFLAGS_TLS_BEARSSL_1 = -LexternalRepos/BearSSL/build
+CPPFLAGS_TLS = $(CPPFLAGS_TLS_BEARSSL_$(FEATURE_USE_BEARSSL))
+LDFLAGS_TLS = $(LDFLAGS_TLS_BEARSSL_$(FEATURE_USE_BEARSSL))
+LDLIBS = -lcrypt -lresolv $(LDLIBS_HISTEDIT_$(FEATURE_SH_HISTEDIT)) $(LDLIBS_TLS)
diff --git a/scripts/mkbox b/scripts/mkbox
@@ -189,7 +189,7 @@ compile_sh() {
die "mktokens failed"
for s in alias arith_yacc arith_yylex cd echo error eval exec \
- expand histedit input jobs kill mail main memalloc \
+ expand lineedit input jobs kill mail main memalloc \
miscbltin mystring options output parser printf redir \
show test trap var builtins nodes syntax; do
out="${BDIR}/sh_${s}.o"
diff --git a/scripts/mkman/djot/assemble.go b/scripts/mkman/djot/assemble.go
@@ -0,0 +1,1135 @@
+package djot
+
+import (
+ "bytes"
+ "strconv"
+ "strings"
+)
+
+type Assembler struct {
+ doc *Document
+ stack []int32
+
+ pendingAttr []Attribute
+ sectionStack []int16
+
+ references map[string]Reference
+ lastClosedNode int32
+
+ footnoteLabels map[string]int
+ usedFootnotes []string
+ footnoteContent map[string]int32
+
+ usedIDs map[string]bool
+ headingIDs map[int32]string
+
+ currentTableAlignments []uint32
+}
+
+func (a *Assembler) Assemble(events []Event) {
+ a.doc.Nodes = make([]Node, 0, len(events)/2+8)
+ a.doc.Attributes = make([]Attribute, 0, 16)
+ a.doc.References = make(map[string]Reference)
+ a.doc.Extra = make([]byte, 0, 64)
+ a.stack = make([]int32, 0, 16)
+ a.pendingAttr = make([]Attribute, 0, 8)
+ a.sectionStack = make([]int16, 0, 8)
+ a.references = make(map[string]Reference)
+ a.lastClosedNode = -1
+ a.footnoteLabels = make(map[string]int)
+ a.usedFootnotes = make([]string, 0, 8)
+ a.footnoteContent = make(map[string]int32)
+ a.usedIDs = make(map[string]bool)
+ a.headingIDs = make(map[int32]string)
+
+ a.collectReferences(events)
+ a.collectHeadingReferences(events)
+
+ rootIdx := a.addNode(NodeDoc, 0, 0)
+ a.stack = append(a.stack, rootIdx)
+
+ type listTightState struct {
+ nodeIdx int32
+ blanklines bool
+ }
+ var listTightStack []listTightState
+
+ i := 0
+ for i < len(events) {
+ ev := events[i]
+
+ if len(listTightStack) > 0 {
+ top := &listTightStack[len(listTightStack)-1]
+ switch ev.Type {
+ case EvBlankLine:
+ top.blanklines = true
+ case EvOpenList, EvCloseList:
+ top.blanklines = false
+ case EvOpenListItem, EvCloseListItem:
+ default:
+ if top.blanklines {
+ a.doc.Nodes[top.nodeIdx].Data &= ^DataListTight
+ }
+ top.blanklines = false
+ }
+ }
+
+ switch ev.Type {
+ case EvOpenAttributes:
+ i = a.parseAttributes(events, i)
+ case EvOpenInlineAttributes:
+ i = a.parseAttributes(events, i)
+ if a.lastClosedNode != -1 && len(a.pendingAttr) > 0 {
+ if a.doc.Nodes[a.lastClosedNode].Type == NodeStr {
+ nodeIdx := a.lastClosedNode
+ content := a.doc.Source[a.doc.Nodes[nodeIdx].Start : a.doc.Nodes[nodeIdx].End+1]
+ if len(content) == 0 || isSpace(content[len(content)-1]) {
+ a.pendingAttr = a.pendingAttr[:0]
+ } else {
+ lastWordStart := -1
+ for j := len(content) - 1; j >= 0; j-- {
+ if isSpace(content[j]) {
+ lastWordStart = j + 1
+ break
+ }
+ }
+ if lastWordStart == -1 {
+ lastWordStart = 0
+ }
+
+ if lastWordStart > 0 {
+ origStart := a.doc.Nodes[nodeIdx].Start
+ origEnd := a.doc.Nodes[nodeIdx].End
+ newEnd := origStart + int32(lastWordStart) - 1
+
+ spanIdx := a.addNode(NodeSpan, origStart+int32(lastWordStart), origEnd)
+ wordIdx := a.addNode(NodeStr, origStart+int32(lastWordStart), origEnd)
+
+ a.doc.Nodes[nodeIdx].End = newEnd
+ a.doc.Nodes[spanIdx].Child = wordIdx
+
+ parentIdx := a.stack[len(a.stack)-1]
+ a.linkToParent(parentIdx, spanIdx)
+
+ a.lastClosedNode = spanIdx
+ } else if lastWordStart == 0 {
+ origStart := a.doc.Nodes[nodeIdx].Start
+ origEnd := a.doc.Nodes[nodeIdx].End
+ childIdx := a.addNode(NodeStr, origStart, origEnd)
+ a.doc.Nodes[nodeIdx].Type = NodeSpan
+ a.doc.Nodes[nodeIdx].Child = childIdx
+ }
+ }
+ }
+ a.applyPendingAttr(a.lastClosedNode)
+ } else {
+ a.pendingAttr = a.pendingAttr[:0]
+ }
+ case EvOpenPara:
+ idx := a.openNode(NodePara, ev.Start)
+ a.applyPendingAttr(idx)
+ case EvClosePara:
+ a.lastClosedNode = a.closeNode(ev.End)
+ case EvOpenHeading:
+ level := int16(ev.End - ev.Start + 1)
+ a.handleHeadingOpen(level, ev.Start)
+ case EvCloseHeading:
+ idx := a.closeNode(ev.End)
+ a.generateID(idx, a.doc.Nodes[idx].Start)
+ a.lastClosedNode = idx
+ case EvOpenBlockQuote:
+ idx := a.openNode(NodeBlockQuote, ev.Start)
+ a.applyPendingAttr(idx)
+ case EvCloseBlockQuote:
+ a.lastClosedNode = a.closeNode(ev.End)
+ case EvOpenList:
+ marker := byte(ev.End)
+ ntype := NodeBulletList
+ if isOrderedMarker(marker) {
+ ntype = NodeOrderedList
+ } else if marker == ':' {
+ ntype = NodeDefinitionList
+ }
+ idx := a.openNode(ntype, ev.Start)
+ a.applyPendingAttr(idx)
+ a.doc.Nodes[idx].Data |= DataListTight
+ a.setStyleFromMarker(idx, marker)
+ listTightStack = append(listTightStack, listTightState{nodeIdx: idx})
+
+ if ntype == NodeOrderedList && i+1 < len(events) && events[i+1].Type == EvNone {
+ i++
+ startNum := int(events[i].End)
+ if startNum != 1 {
+ a.doc.Nodes[idx].Data |= uint32(startNum) << 16
+ }
+ }
+ case EvCloseList:
+ a.lastClosedNode = a.closeNode(ev.Start)
+ if len(listTightStack) > 0 {
+ listTightStack = listTightStack[:len(listTightStack)-1]
+ }
+ case EvOpenListItem:
+ pIdx := a.stack[len(a.stack)-1]
+ ntype := NodeListItem
+ if a.doc.Nodes[pIdx].Type == NodeDefinitionList {
+ ntype = NodeDefinitionListItem
+ }
+ idx := a.openNode(ntype, ev.Start)
+ a.applyPendingAttr(idx)
+ if ev.End > 0 && ntype == NodeListItem {
+ a.doc.Nodes[idx].Type = NodeTaskListItem
+ if ev.End == 2 {
+ a.doc.Nodes[idx].Data |= DataTaskChecked
+ }
+ pIdx := a.stack[len(a.stack)-2]
+ if a.doc.Nodes[pIdx].Type == NodeBulletList {
+ a.doc.Nodes[pIdx].Type = NodeTaskList
+ }
+ }
+ case EvCloseListItem:
+ idx := a.stack[len(a.stack)-1]
+ if a.doc.Nodes[idx].Type == NodeDefinitionListItem {
+ a.handleDefinitionListItem(idx)
+ }
+ a.lastClosedNode = a.closeNode(ev.End)
+ case EvOpenCodeBlock, EvOpenRawBlock:
+ ntype := NodeCodeBlock
+ closeType := EvCloseCodeBlock
+ if ev.Type == EvOpenRawBlock {
+ ntype = NodeRawBlock
+ closeType = EvCloseRawBlock
+ }
+ idx := a.openNode(ntype, ev.Start)
+ a.applyPendingAttr(idx)
+
+ j := i + 1
+ contentStart := int32(-1)
+ foundStartMarker := false
+ for j < len(events) {
+ if !foundStartMarker && events[j].Type == EvNone {
+ foundStartMarker = true
+ } else if events[j].Type == EvStr {
+ if contentStart == -1 {
+ contentStart = events[j].Start
+ }
+ } else if events[j].Type == closeType {
+ break
+ }
+ j++
+ }
+
+ if contentStart != -1 {
+ var buf bytes.Buffer
+ for k := i + 1; k < j; k++ {
+ if events[k].Type == EvStr {
+ buf.Write(a.doc.Source[events[k].Start : events[k].End+1])
+ }
+ }
+ extraStart := int32(len(a.doc.Extra))
+ a.doc.Extra = append(a.doc.Extra, buf.Bytes()...)
+ a.doc.Nodes[idx].Start = ^extraStart
+ a.doc.Nodes[idx].End = int32(len(a.doc.Extra)) - 1
+ } else {
+ a.doc.Nodes[idx].Start = -1
+ a.doc.Nodes[idx].End = -1
+ }
+
+ if ntype == NodeRawBlock && idx != -1 {
+ node := &a.doc.Nodes[idx]
+ if node.Attr != -1 {
+ for k := uint16(0); k < node.AttrCount; k++ {
+ attr := &a.doc.Attributes[node.Attr+int32(k)]
+ if attr.KeyStart == -2 {
+ val := string(a.getAttrVal(*attr))
+ if strings.HasPrefix(val, "=") {
+ attr.KeyStart = -3
+ }
+ }
+ }
+ }
+ }
+ a.closeNode(ev.End)
+ i = j
+ case EvOpenDiv:
+ idx := a.openNode(NodeDiv, ev.Start)
+ a.applyPendingAttr(idx)
+ case EvCloseDiv:
+ a.lastClosedNode = a.closeNode(ev.End)
+ case EvOpenTable:
+ idx := a.openNode(NodeTable, ev.Start)
+ a.applyPendingAttr(idx)
+ case EvCloseTable:
+ a.lastClosedNode = a.closeNode(ev.End)
+ case EvOpenCaption:
+ idx := int32(-1)
+ if a.lastClosedNode != -1 && a.doc.Nodes[a.lastClosedNode].Type == NodeTable {
+ tableIdx := a.lastClosedNode
+ captionIdx := a.addNode(NodeCaption, ev.Start, -1)
+ a.linkToParent(tableIdx, captionIdx)
+ a.stack = append(a.stack, captionIdx)
+ a.lastClosedNode = -1
+ idx = captionIdx
+ } else {
+ idx = a.openNode(NodeCaption, ev.Start)
+ }
+ a.applyPendingAttr(idx)
+ case EvCloseCaption:
+ a.lastClosedNode = a.closeNode(ev.End)
+ case EvOpenRow:
+ a.openNode(NodeRow, ev.Start)
+ case EvCloseRow:
+ a.lastClosedNode = a.closeNode(ev.End)
+ case EvOpenCell:
+ idx := a.openNode(NodeCell, ev.Start)
+ a.applyPendingAttr(idx)
+
+ col := 0
+ curr := a.doc.Nodes[a.stack[len(a.stack)-2]].Child
+ for curr != -1 && curr != idx {
+ curr = a.doc.Nodes[curr].Next
+ col++
+ }
+ if col < len(a.currentTableAlignments) {
+ a.doc.Nodes[idx].Data &= ^(DataAlignLeft | DataAlignCenter | DataAlignRight)
+ a.doc.Nodes[idx].Data |= a.currentTableAlignments[col]
+ }
+ case EvCloseCell:
+ a.lastClosedNode = a.closeNode(ev.End)
+ case EvOpenFootnote:
+ j := i + 1
+ label := ""
+ if j < len(events) && events[j].Type == EvStr {
+ content := a.doc.Source[events[j].Start : events[j].End+1]
+ if len(content) > 0 && content[0] == '[' && content[1] == '^' {
+ closeIdx := bytes.IndexByte(content, ']')
+ if closeIdx != -1 {
+ label = normalizeLabel(string(content[2:closeIdx]))
+ }
+ }
+ }
+ idx := a.openNode(NodeFootnote, ev.Start)
+ if label != "" {
+ a.footnoteContent[label] = idx
+ }
+ a.applyPendingAttr(idx)
+ case EvCloseFootnote:
+ a.lastClosedNode = a.closeNode(ev.End)
+ case EvOpenReferenceDefinition:
+ idx := a.openNode(NodeReference, ev.Start)
+ a.applyPendingAttr(idx)
+ case EvCloseReferenceDefinition:
+ a.closeNode(ev.End)
+ case EvOpenLinkText:
+ idx := a.openNode(NodeLink, ev.Start)
+ a.applyPendingAttr(idx)
+ case EvCloseLinkText:
+ a.lastClosedNode = a.closeNode(ev.End)
+ case EvOpenImageText:
+ idx := a.openNode(NodeImage, ev.Start)
+ a.applyPendingAttr(idx)
+ case EvCloseImageText:
+ a.lastClosedNode = a.closeNode(ev.End)
+ case EvOpenSpan:
+ idx := a.openNode(NodeSpan, ev.Start)
+ a.applyPendingAttr(idx)
+ case EvCloseSpan:
+ a.lastClosedNode = a.closeNode(ev.End)
+ case EvOpenDoubleQuoted:
+ a.openNode(NodeDoubleQuoted, ev.Start)
+ case EvCloseDoubleQuoted:
+ a.lastClosedNode = a.closeNode(ev.End)
+ case EvOpenSingleQuoted:
+ a.openNode(NodeSingleQuoted, ev.Start)
+ case EvCloseSingleQuoted:
+ a.lastClosedNode = a.closeNode(ev.End)
+ case EvOpenMark:
+ idx := a.openNode(NodeMark, ev.Start)
+ a.applyPendingAttr(idx)
+ case EvCloseMark:
+ a.lastClosedNode = a.closeNode(ev.End)
+ case EvOpenInsert:
+ idx := a.openNode(NodeInsert, ev.Start)
+ a.applyPendingAttr(idx)
+ case EvCloseInsert:
+ a.lastClosedNode = a.closeNode(ev.End)
+ case EvOpenDelete:
+ idx := a.openNode(NodeDelete, ev.Start)
+ a.applyPendingAttr(idx)
+ case EvCloseDelete:
+ a.lastClosedNode = a.closeNode(ev.End)
+ case EvOpenDestination:
+ a.addLeafNode(NodeUrl, ev.Start, ev.End)
+ case EvUrl, EvEmail:
+ idx := a.openNode(NodeLink, ev.Start)
+ a.applyPendingAttr(idx)
+
+ destType := NodeUrl
+ if ev.Type == EvEmail {
+ destType = NodeEmail
+ }
+ destIdx := a.addNode(destType, ev.Start, ev.End)
+ a.linkToParent(idx, destIdx)
+
+ strIdx := a.addNode(NodeStr, ev.Start, ev.End)
+ a.linkToParent(idx, strIdx)
+
+ a.lastClosedNode = a.closeNode(ev.End)
+ case EvOpenReference:
+ label := string(a.doc.Source[ev.Start : ev.End+1])
+ if label == "" {
+ var buf strings.Builder
+ a.collectPlainText(a.stack[len(a.stack)-1], &buf)
+ label = buf.String()
+ }
+ label = normalizeLabel(label)
+ if ref, ok := a.references[label]; ok {
+ a.addLeafNode(NodeUrl, ref.DestStart, ref.DestEnd)
+ if len(ref.Attributes) > 0 {
+ parentIdx := a.stack[len(a.stack)-1]
+ a.pendingAttr = append(a.pendingAttr, ref.Attributes...)
+ a.applyPendingAttr(parentIdx)
+ }
+ }
+ case EvFootnoteReference:
+ label := string(a.doc.Source[ev.Start+2 : ev.End])
+ num, ok := a.footnoteLabels[label]
+ if !ok {
+ num = len(a.usedFootnotes) + 1
+ a.footnoteLabels[label] = num
+ a.usedFootnotes = append(a.usedFootnotes, label)
+ }
+ idx := a.addNode(NodeFootnoteReference, ev.Start, ev.End)
+ a.doc.Nodes[idx].Data = uint32(num)
+ parentIdx := a.stack[len(a.stack)-1]
+ a.linkToParent(parentIdx, idx)
+ case EvSmartPunctuation:
+ a.addLeafNode(NodeSmartPunctuation, ev.Start, ev.End)
+ case EvInlineMath:
+ a.addLeafNode(NodeInlineMath, ev.Start, ev.End)
+ case EvDisplayMath:
+ a.addLeafNode(NodeDisplayMath, ev.Start, ev.End)
+ case EvRawInline:
+ idx := a.addNode(NodeRawInline, ev.Start, ev.End)
+ a.linkToParent(a.stack[len(a.stack)-1], idx)
+ a.lastClosedNode = idx
+ i++
+ for i < len(events) && events[i].Type != EvRawInline {
+ i++
+ }
+ case EvOpenVerbatim:
+ a.openNode(NodeVerbatim, ev.Start)
+ case EvCloseVerbatim:
+ a.lastClosedNode = a.closeNode(ev.End)
+ case EvSoftBreak:
+ a.addLeafNode(NodeSoftBreak, ev.Start, ev.End)
+ case EvHardBreak:
+ a.addLeafNode(NodeHardBreak, ev.Start, ev.End)
+ case EvNonBreakingSpace:
+ a.addLeafNode(NodeNonBreakingSpace, ev.Start, ev.End)
+ case EvThematicBreak:
+ idx := a.addNode(NodeThematicBreak, ev.Start, ev.End)
+ a.linkToParent(a.stack[len(a.stack)-1], idx)
+ a.applyPendingAttr(idx)
+ case EvBlankLine:
+ case EvStr:
+ skipThisStr := false
+ if i > 0 && events[i-1].Type == EvOpenFootnote {
+ content := a.doc.Source[ev.Start : ev.End+1]
+ if len(content) > 0 && content[0] == '[' && len(content) > 1 && content[1] == '^' {
+ if bytes.Contains(content, []byte("]:")) {
+ skipThisStr = true
+ }
+ }
+ }
+ if !skipThisStr {
+ tipIdx := a.stack[len(a.stack)-1]
+ if a.doc.Nodes[tipIdx].Type == NodeTable {
+ a.handleTableSeparator(ev.Start, ev.End)
+ } else {
+ a.addLeafNode(NodeStr, ev.Start, ev.End)
+ }
+ }
+ case EvSymb:
+ a.addLeafNode(NodeSymb, ev.Start, ev.End)
+ case EvOpenEmph:
+ idx := a.openNode(NodeEmph, ev.Start)
+ a.applyPendingAttr(idx)
+ case EvCloseEmph:
+ a.lastClosedNode = a.closeNode(ev.End)
+ case EvOpenStrong:
+ idx := a.openNode(NodeStrong, ev.Start)
+ a.applyPendingAttr(idx)
+ case EvCloseStrong:
+ a.lastClosedNode = a.closeNode(ev.End)
+ case EvEscape:
+ a.addLeafNode(NodeStr, ev.Start+1, ev.End)
+ case EvOpenSuperscript:
+ a.openNode(NodeSuperscript, ev.Start)
+ case EvCloseSuperscript:
+ a.lastClosedNode = a.closeNode(ev.End)
+ case EvOpenSubscript:
+ a.openNode(NodeSubscript, ev.Start)
+ case EvCloseSubscript:
+ a.lastClosedNode = a.closeNode(ev.End)
+ }
+ i++
+ }
+
+ for _, label := range a.usedFootnotes {
+ if contentIdx, ok := a.footnoteContent[label]; ok {
+ a.linkToParent(rootIdx, contentIdx)
+ }
+ }
+
+ a.doc.UsedFootnotes = a.usedFootnotes
+ a.doc.FootnoteContent = a.footnoteContent
+ a.doc.References = a.references
+
+ if len(a.doc.Source) > 0 {
+ a.doc.Nodes[rootIdx].End = int32(len(a.doc.Source) - 1)
+ }
+}
+
+func normalizeLabel(label string) string {
+ return strings.Join(strings.Fields(label), " ")
+}
+
+func unescapeBytes(b []byte) []byte {
+ var res []byte
+ escaped := false
+ for _, ch := range b {
+ if escaped {
+ res = append(res, ch)
+ escaped = false
+ } else if ch == '\\' {
+ escaped = true
+ } else {
+ res = append(res, ch)
+ }
+ }
+ return res
+}
+
+func (a *Assembler) collectReferences(events []Event) {
+ var pendingAttr []Attribute
+ for i := 0; i < len(events); i++ {
+ ev := events[i]
+ switch ev.Type {
+ case EvOpenAttributes, EvOpenInlineAttributes:
+ i = a.parseAttributesTo(events, i, &pendingAttr)
+ continue
+ case EvOpenPara, EvOpenBlockQuote, EvOpenList, EvOpenListItem, EvOpenCodeBlock, EvOpenDiv, EvOpenTable, EvOpenCaption, EvOpenRow, EvOpenCell, EvOpenHeading:
+ pendingAttr = pendingAttr[:0]
+ case EvOpenReferenceDefinition:
+ var content string
+ j := i + 1
+ for j < len(events) && events[j].Type != EvCloseReferenceDefinition {
+ if events[j].Type == EvStr || events[j].Type == EvText {
+ content = string(a.doc.Source[events[j].Start : events[j].End+1])
+ }
+ j++
+ }
+
+ if content == "" {
+ lineStart := events[i].Start
+ lineEnd := lineStart
+ for lineEnd < int32(len(a.doc.Source)) && a.doc.Source[lineEnd] != '\n' {
+ lineEnd++
+ }
+ if lineEnd > lineStart {
+ content = string(a.doc.Source[lineStart:lineEnd])
+ }
+ }
+
+ if len(content) > 0 && content[0] == '[' {
+ closeIdx := strings.IndexByte(content, ']')
+ if closeIdx != -1 && closeIdx+1 < len(content) && content[closeIdx+1] == ':' {
+ label := normalizeLabel(content[1:closeIdx])
+ value := content[closeIdx+2:]
+
+ value = strings.ReplaceAll(value, "\r\n", "\n")
+ value = strings.ReplaceAll(value, "\r", "\n")
+ parts := strings.Split(value, "\n")
+ var cleanedParts []string
+ for _, p := range parts {
+ cleaned := strings.TrimSpace(p)
+ if len(cleaned) > 0 {
+ cleanedParts = append(cleanedParts, cleaned)
+ }
+ }
+ cleanValue := strings.Join(cleanedParts, "")
+ valStart := int32(len(a.doc.Extra))
+ a.doc.Extra = append(a.doc.Extra, []byte(cleanValue)...)
+ valEnd := int32(len(a.doc.Extra)) - 1
+
+ refAttrs := make([]Attribute, len(pendingAttr))
+ copy(refAttrs, pendingAttr)
+
+ a.references[label] = Reference{
+ DestStart: ^valStart,
+ DestEnd: valEnd,
+ Attributes: refAttrs,
+ }
+ pendingAttr = pendingAttr[:0]
+ }
+ }
+ i = j
+ case EvOpenFootnote:
+ j := i + 1
+ if j < len(events) && events[j].Type == EvStr {
+ content := a.doc.Source[events[j].Start : events[j].End+1]
+ if len(content) > 0 && content[0] == '[' && content[1] == '^' {
+ closeIdx := bytes.IndexByte(content, ']')
+ if closeIdx != -1 && closeIdx+1 < len(content) && content[closeIdx+1] == ':' {
+ label := normalizeLabel(string(content[2:closeIdx]))
+ a.footnoteContent[label] = -2
+ }
+ }
+ }
+ pendingAttr = pendingAttr[:0]
+ }
+ }
+}
+
+func (a *Assembler) parseAttributesTo(events []Event, startIdx int, target *[]Attribute) int {
+ i := startIdx + 1
+ for i < len(events) && events[i].Type != EvCloseAttributes {
+ ev := events[i]
+ switch ev.Type {
+ case EvAttrIdMarker:
+ *target = append(*target, Attribute{
+ KeyStart: -1,
+ ValStart: ev.Start,
+ ValEnd: ev.End,
+ })
+ case EvAttrClassMarker:
+ *target = append(*target, Attribute{
+ KeyStart: -2,
+ ValStart: ev.Start,
+ ValEnd: ev.End,
+ })
+ case EvAttrKey:
+ keyEv := ev
+ if keyEv.Start < int32(len(a.doc.Source)) && a.doc.Source[keyEv.Start] == '=' {
+ *target = append(*target, Attribute{
+ KeyStart: -3,
+ ValStart: keyEv.Start + 1,
+ ValEnd: keyEv.End,
+ })
+ } else {
+ for i+1 < len(events) && events[i+1].Type != EvCloseAttributes {
+ i++
+ if events[i].Type == EvAttrValue {
+ *target = append(*target, Attribute{
+ KeyStart: keyEv.Start,
+ KeyEnd: keyEv.End,
+ ValStart: events[i].Start,
+ ValEnd: events[i].End,
+ })
+ break
+ }
+ }
+ }
+ }
+ i++
+ }
+ return i
+}
+
+func (a *Assembler) collectHeadingReferences(events []Event) {
+ tempAs := &Assembler{doc: a.doc, references: a.references, usedIDs: make(map[string]bool)}
+ i := 0
+ for i < len(events) {
+ ev := events[i]
+ switch ev.Type {
+ case EvOpenAttributes:
+ i = tempAs.parseAttributes(events, i)
+ continue
+ case EvOpenPara, EvOpenBlockQuote, EvOpenList, EvOpenListItem, EvOpenCodeBlock, EvOpenDiv, EvOpenTable, EvOpenCaption, EvOpenRow, EvOpenCell:
+ if len(tempAs.pendingAttr) > 0 {
+ for _, attr := range tempAs.pendingAttr {
+ if attr.KeyStart == -1 {
+ var id string
+ if attr.ValStart < 0 {
+ id = string(a.doc.Extra[^attr.ValStart : attr.ValEnd+1])
+ } else {
+ id = string(a.doc.Source[attr.ValStart : attr.ValEnd+1])
+ }
+ tempAs.usedIDs[id] = true
+ break
+ }
+ }
+ tempAs.pendingAttr = tempAs.pendingAttr[:0]
+ }
+ case EvOpenHeading:
+ headingStart := ev.Start
+ j := i + 1
+ var buf strings.Builder
+ for j < len(events) && events[j].Type != EvCloseHeading {
+ if events[j].Type == EvStr {
+ buf.Write(a.doc.Source[events[j].Start : events[j].End+1])
+ } else if events[j].Type == EvSoftBreak {
+ buf.WriteByte('\n')
+ }
+ j++
+ }
+ text := buf.String()
+ label := normalizeLabel(text)
+
+ var manualID string
+ if len(tempAs.pendingAttr) > 0 {
+ for _, attr := range tempAs.pendingAttr {
+ if attr.KeyStart == -1 {
+ if attr.ValStart < 0 {
+ manualID = string(a.doc.Extra[^attr.ValStart : attr.ValEnd+1])
+ } else {
+ manualID = string(a.doc.Source[attr.ValStart : attr.ValEnd+1])
+ }
+ tempAs.usedIDs[manualID] = true
+ break
+ }
+ }
+ tempAs.pendingAttr = tempAs.pendingAttr[:0]
+ }
+
+ ident := manualID
+ if ident == "" {
+ base := a.slugify(text)
+ ident = base
+ if ident == "" {
+ ident = "s"
+ }
+ if tempAs.usedIDs[ident] || base == "" {
+ k := 1
+ if base == "" {
+ ident = "s-1"
+ } else {
+ ident = base + "-1"
+ }
+ for tempAs.usedIDs[ident] {
+ k++
+ ident = base + "-" + strconv.Itoa(k)
+ if base == "" {
+ ident = "s-" + strconv.Itoa(k)
+ }
+ }
+ }
+ tempAs.usedIDs[ident] = true
+ }
+
+ a.headingIDs[headingStart] = ident
+
+ if _, ok := a.references[label]; !ok {
+ start := int32(len(a.doc.Extra))
+ a.doc.Extra = append(a.doc.Extra, '#')
+ a.doc.Extra = append(a.doc.Extra, []byte(ident)...)
+ a.references[label] = Reference{
+ DestStart: ^start,
+ DestEnd: int32(len(a.doc.Extra)) - 1,
+ }
+ }
+ i = j
+ }
+ i++
+ }
+}
+
+func (a *Assembler) generateID(idx int32, start int32) {
+ node := &a.doc.Nodes[idx]
+ if node.Data&DataNoAutoID != 0 {
+ return
+ }
+
+ parentIdx := a.stack[len(a.stack)-1]
+ targetIdx := idx
+ if a.doc.Nodes[parentIdx].Type == NodeSection {
+ targetIdx = parentIdx
+ }
+
+ if a.doc.Nodes[targetIdx].Attr != -1 {
+ for j := uint16(0); j < a.doc.Nodes[targetIdx].AttrCount; j++ {
+ attr := a.doc.Attributes[a.doc.Nodes[targetIdx].Attr+int32(j)]
+ if attr.KeyStart == -1 {
+ return
+ }
+ }
+ }
+
+ ident, ok := a.headingIDs[start]
+ if !ok {
+ return
+ }
+
+ valStart := int32(len(a.doc.Extra))
+ a.doc.Extra = append(a.doc.Extra, []byte(ident)...)
+ valEnd := int32(len(a.doc.Extra)) - 1
+
+ attr := Attribute{
+ KeyStart: -1,
+ ValStart: ^valStart,
+ ValEnd: valEnd,
+ }
+
+ a.pendingAttr = append(a.pendingAttr, attr)
+ a.applyPendingAttr(targetIdx)
+}
+
+func (a *Assembler) collectPlainText(idx int32, buf *strings.Builder) {
+ curr := a.doc.Nodes[idx].Child
+ for curr != -1 {
+ node := a.doc.Nodes[curr]
+ if node.Type == NodeStr {
+ buf.Write(a.doc.Source[node.Start : node.End+1])
+ } else if node.Type == NodeSoftBreak {
+ buf.WriteByte('\n')
+ } else {
+ a.collectPlainText(curr, buf)
+ }
+ curr = a.doc.Nodes[curr].Next
+ }
+}
+
+func (a *Assembler) slugify(text string) string {
+ var res []rune
+ lastWasSpec := false
+ for _, r := range text {
+ isSpec := strings.ContainsRune("][~!@#$%^&*(){}`,.<>\\|=+/? \t\r\n", r)
+ if isSpec {
+ if !lastWasSpec {
+ res = append(res, ' ')
+ }
+ lastWasSpec = true
+ } else {
+ res = append(res, r)
+ lastWasSpec = false
+ }
+ }
+ s := strings.TrimSpace(string(res))
+ return strings.ReplaceAll(s, " ", "-")
+}
+
+func (a *Assembler) handleTableSeparator(start, end int32) {
+ parentIdx := a.stack[len(a.stack)-1]
+ curr := a.doc.Nodes[parentIdx].Child
+ var lastRow int32 = -1
+ for curr != -1 {
+ if a.doc.Nodes[curr].Type == NodeRow {
+ lastRow = curr
+ }
+ curr = a.doc.Nodes[curr].Next
+ }
+
+ line := a.doc.Source[start : end+1]
+ parts := bytes.Split(line, []byte("|"))
+
+ newAlignments := make([]uint32, 0)
+ for _, part := range parts {
+ part = bytes.TrimSpace(part)
+ if len(part) == 0 {
+ continue
+ }
+
+ align := uint32(0)
+ left := part[0] == ':'
+ right := part[len(part)-1] == ':'
+
+ if left && right {
+ align = DataAlignCenter
+ } else if left {
+ align = DataAlignLeft
+ } else if right {
+ align = DataAlignRight
+ }
+ newAlignments = append(newAlignments, align)
+ }
+ a.currentTableAlignments = newAlignments
+
+ if lastRow != -1 {
+ cell := a.doc.Nodes[lastRow].Child
+ col := 0
+ for cell != -1 {
+ a.doc.Nodes[cell].Data |= DataCellHeader
+ if col < len(a.currentTableAlignments) {
+ a.doc.Nodes[cell].Data &= ^(DataAlignLeft | DataAlignCenter | DataAlignRight)
+ a.doc.Nodes[cell].Data |= a.currentTableAlignments[col]
+ }
+ cell = a.doc.Nodes[cell].Next
+ col++
+ }
+ }
+}
+
+func (a *Assembler) handleHeadingOpen(level int16, start int32) {
+ for len(a.sectionStack) > 0 && a.sectionStack[len(a.sectionStack)-1] >= level {
+ a.stack = a.stack[:len(a.stack)-1]
+ a.sectionStack = a.sectionStack[:len(a.sectionStack)-1]
+ }
+
+ parentIdx := a.stack[len(a.stack)-1]
+ parentType := a.doc.Nodes[parentIdx].Type
+
+ if parentType == NodeDoc || parentType == NodeSection {
+ sIdx := a.openNode(NodeSection, start)
+ a.sectionStack = append(a.sectionStack, level)
+ a.applyPendingAttr(sIdx)
+ }
+
+ hIdx := a.openNode(NodeHeading, start)
+ a.doc.Nodes[hIdx].Level = level
+ if len(a.pendingAttr) > 0 {
+ a.doc.Nodes[hIdx].Data |= DataNoAutoID
+ a.applyPendingAttr(hIdx)
+ }
+}
+
+func (a *Assembler) parseAttributes(events []Event, startIdx int) int {
+ i := startIdx + 1
+ for i < len(events) && events[i].Type != EvCloseAttributes {
+ ev := events[i]
+ switch ev.Type {
+ case EvAttrIdMarker:
+ a.pendingAttr = append(a.pendingAttr, Attribute{
+ KeyStart: -1,
+ ValStart: ev.Start,
+ ValEnd: ev.End,
+ })
+ case EvAttrClassMarker:
+ a.pendingAttr = append(a.pendingAttr, Attribute{
+ KeyStart: -2,
+ ValStart: ev.Start,
+ ValEnd: ev.End,
+ })
+ case EvAttrKey:
+ keyEv := ev
+ if keyEv.Start < int32(len(a.doc.Source)) && a.doc.Source[keyEv.Start] == '=' {
+ a.pendingAttr = append(a.pendingAttr, Attribute{
+ KeyStart: -3,
+ ValStart: keyEv.Start + 1,
+ ValEnd: keyEv.End,
+ })
+ } else {
+ for i+1 < len(events) && events[i+1].Type != EvCloseAttributes {
+ i++
+ if events[i].Type == EvAttrValue {
+ rawVal := a.doc.Source[events[i].Start : events[i].End+1]
+ decodedVal := unescapeBytes(rawVal)
+ valStart := int32(len(a.doc.Extra))
+ a.doc.Extra = append(a.doc.Extra, decodedVal...)
+ valEnd := int32(len(a.doc.Extra)) - 1
+ a.pendingAttr = append(a.pendingAttr, Attribute{
+ KeyStart: keyEv.Start,
+ KeyEnd: keyEv.End,
+ ValStart: ^valStart,
+ ValEnd: valEnd,
+ })
+ break
+ }
+ }
+ }
+ }
+ i++
+ }
+ return i
+}
+
+func (a *Assembler) getAttrVal(attr Attribute) []byte {
+ if attr.ValStart < 0 {
+ return a.doc.Extra[^attr.ValStart : attr.ValEnd+1]
+ }
+ return a.doc.Source[attr.ValStart : attr.ValEnd+1]
+}
+
+func (a *Assembler) applyPendingAttr(idx int32) {
+ if len(a.pendingAttr) == 0 {
+ return
+ }
+
+ node := &a.doc.Nodes[idx]
+ var attrs []Attribute
+ if node.Attr != -1 {
+ for i := uint16(0); i < node.AttrCount; i++ {
+ attrs = append(attrs, a.doc.Attributes[node.Attr+int32(i)])
+ }
+ }
+
+ for _, newAttr := range a.pendingAttr {
+ if newAttr.KeyStart == -1 {
+ id := string(a.getAttrVal(newAttr))
+ a.usedIDs[id] = true
+ }
+
+ foundIdx := -1
+ for i := range attrs {
+ if newAttr.KeyStart == -1 && attrs[i].KeyStart == -1 {
+ foundIdx = i
+ break
+ } else if newAttr.KeyStart == -2 && attrs[i].KeyStart == -2 {
+ foundIdx = i
+ break
+ } else if newAttr.KeyStart >= 0 && attrs[i].KeyStart >= 0 {
+ oldKey := a.doc.Source[attrs[i].KeyStart : attrs[i].KeyEnd+1]
+ newKey := a.doc.Source[newAttr.KeyStart : newAttr.KeyEnd+1]
+ if bytes.Equal(oldKey, newKey) {
+ foundIdx = i
+ break
+ }
+ }
+ }
+
+ if newAttr.KeyStart == -2 && foundIdx != -1 {
+ oldVal := a.getAttrVal(attrs[foundIdx])
+ newVal := a.getAttrVal(newAttr)
+
+ start := int32(len(a.doc.Extra))
+ a.doc.Extra = append(a.doc.Extra, oldVal...)
+ a.doc.Extra = append(a.doc.Extra, ' ')
+ a.doc.Extra = append(a.doc.Extra, newVal...)
+ end := int32(len(a.doc.Extra)) - 1
+
+ attrs[foundIdx].ValStart = ^start
+ attrs[foundIdx].ValEnd = end
+ } else if foundIdx != -1 {
+ attrs[foundIdx] = newAttr
+ } else {
+ attrs = append(attrs, newAttr)
+ }
+ }
+
+ node.Attr = int32(len(a.doc.Attributes))
+ node.AttrCount = uint16(len(attrs))
+ a.doc.Attributes = append(a.doc.Attributes, attrs...)
+ a.pendingAttr = a.pendingAttr[:0]
+}
+
+func (a *Assembler) handleDefinitionListItem(idx int32) {
+ firstIdx := a.doc.Nodes[idx].Child
+ if firstIdx != -1 && a.doc.Nodes[firstIdx].Type == NodePara {
+ termIdx := firstIdx
+ a.doc.Nodes[termIdx].Type = NodeTerm
+
+ defIdx := a.addNode(NodeDefinition, a.doc.Nodes[termIdx].End, a.doc.Nodes[idx].End)
+ a.doc.Nodes[defIdx].Child = a.doc.Nodes[termIdx].Next
+ a.doc.Nodes[termIdx].Next = defIdx
+ } else {
+ termIdx := a.addNode(NodeTerm, a.doc.Nodes[idx].Start, a.doc.Nodes[idx].Start)
+ defIdx := a.addNode(NodeDefinition, a.doc.Nodes[idx].Start, a.doc.Nodes[idx].End)
+ a.doc.Nodes[defIdx].Child = firstIdx
+ a.doc.Nodes[idx].Child = termIdx
+ a.doc.Nodes[termIdx].Next = defIdx
+ }
+}
+
+func (a *Assembler) isInline(t NodeType) bool {
+ switch t {
+ case NodeStr, NodeEmph, NodeStrong, NodeLink, NodeImage, NodeSpan, NodeVerbatim, NodeSubscript, NodeSuperscript, NodeInsert, NodeDelete, NodeMark, NodeDoubleQuoted, NodeSingleQuoted, NodeSmartPunctuation, NodeSoftBreak, NodeHardBreak, NodeInlineMath, NodeDisplayMath, NodeSymb, NodeUrl, NodeEmail, NodeFootnoteReference:
+ return true
+ }
+ return false
+}
+
+func (a *Assembler) addNode(ntype NodeType, start, end int32) int32 {
+ idx := int32(len(a.doc.Nodes))
+ a.doc.Nodes = append(a.doc.Nodes, Node{
+ Type: ntype,
+ Start: start,
+ End: end,
+ Child: -1,
+ Next: -1,
+ Attr: -1,
+ })
+ return idx
+}
+
+func (a *Assembler) linkToParent(parentIdx, nodeIdx int32) {
+ if parentIdx == -1 || nodeIdx == -1 || parentIdx == nodeIdx {
+ return
+ }
+ parent := &a.doc.Nodes[parentIdx]
+ if parent.Child == -1 {
+ parent.Child = nodeIdx
+ } else {
+ curr := parent.Child
+ if curr == nodeIdx {
+ return
+ }
+ for a.doc.Nodes[curr].Next != -1 {
+ if a.doc.Nodes[curr].Next == nodeIdx {
+ return
+ }
+ curr = a.doc.Nodes[curr].Next
+ }
+ a.doc.Nodes[curr].Next = nodeIdx
+ }
+}
+
+func (a *Assembler) openNode(ntype NodeType, start int32) int32 {
+ var parentIdx int32 = -1
+ if len(a.stack) > 0 {
+ parentIdx = a.stack[len(a.stack)-1]
+ }
+ nodeIdx := a.addNode(ntype, start, -1)
+ a.linkToParent(parentIdx, nodeIdx)
+ a.stack = append(a.stack, nodeIdx)
+ a.lastClosedNode = -1
+
+ if ntype == NodeTable {
+ a.currentTableAlignments = nil
+ }
+ return nodeIdx
+}
+
+func (a *Assembler) closeNode(end int32) int32 {
+ if len(a.stack) <= 1 {
+ return -1
+ }
+ nodeIdx := a.stack[len(a.stack)-1]
+ node := &a.doc.Nodes[nodeIdx]
+ if node.Type != NodeCodeBlock && node.Type != NodeRawBlock && node.Type != NodeDiv {
+ node.End = end
+ }
+ a.stack = a.stack[:len(a.stack)-1]
+ if a.isInline(a.doc.Nodes[nodeIdx].Type) {
+ a.lastClosedNode = nodeIdx
+ }
+ return nodeIdx
+}
+
+func (a *Assembler) addLeafNode(ntype NodeType, start, end int32) {
+ parentIdx := a.stack[len(a.stack)-1]
+
+ if ntype == NodeStr && a.lastClosedNode != -1 {
+ prevNode := &a.doc.Nodes[a.lastClosedNode]
+ if prevNode.Type == NodeStr && prevNode.End+1 == start {
+ prevNode.End = end
+ return
+ }
+ }
+
+ nodeIdx := a.addNode(ntype, start, end)
+ a.linkToParent(parentIdx, nodeIdx)
+ a.lastClosedNode = nodeIdx
+}
+
+func isOrderedMarker(marker byte) bool {
+ switch marker {
+ case '1', 'a', 'A', 'i', 'I':
+ return true
+ }
+ return false
+}
+
+func (a *Assembler) setStyleFromMarker(idx int32, marker byte) {
+ node := &a.doc.Nodes[idx]
+ switch marker {
+ case '1':
+ node.Data |= DataListDecimal
+ case 'a':
+ node.Data |= DataListLowerAlpha
+ case 'A':
+ node.Data |= DataListUpperAlpha
+ case 'i':
+ node.Data |= DataListLowerRoman
+ case 'I':
+ node.Data |= DataListUpperRoman
+ }
+}
diff --git a/scripts/mkman/djot/ast.go b/scripts/mkman/djot/ast.go
@@ -0,0 +1,250 @@
+package djot
+
+type NodeType uint16
+
+const (
+ NodeDoc NodeType = iota
+ NodeSection
+ NodePara
+ NodeHeading
+ NodeThematicBreak
+ NodeDiv
+ NodeCodeBlock
+ NodeRawBlock
+ NodeBlockQuote
+ NodeOrderedList
+ NodeBulletList
+ NodeTaskList
+ NodeDefinitionList
+ NodeTable
+ NodeCaption
+ NodeRow
+ NodeCell
+ NodeListItem
+ NodeTaskListItem
+ NodeDefinitionListItem
+ NodeTerm
+ NodeDefinition
+ NodeFootnote
+ NodeReference
+
+ NodeStr
+ NodeSoftBreak
+ NodeHardBreak
+ NodeNonBreakingSpace
+ NodeSymb
+ NodeVerbatim
+ NodeRawInline
+ NodeInlineMath
+ NodeDisplayMath
+ NodeUrl
+ NodeEmail
+ NodeFootnoteReference
+ NodeSmartPunctuation
+ NodeEmph
+ NodeStrong
+ NodeLink
+ NodeImage
+ NodeSpan
+ NodeMark
+ NodeSuperscript
+ NodeSubscript
+ NodeInsert
+ NodeDelete
+ NodeDoubleQuoted
+ NodeSingleQuoted
+)
+
+type Node struct {
+ Type NodeType
+ Start, End int32
+ Child int32
+ Next int32
+ Attr int32
+ AttrCount uint16
+ Level int16
+ Data uint32
+}
+
+type Attribute struct {
+ KeyStart, KeyEnd int32
+ ValStart, ValEnd int32
+}
+
+const (
+ AttrKeyID = -1
+ AttrKeyClass = -2
+ AttrKeyFormat = -3
+)
+
+type EventType uint16
+
+const (
+ EvNone EventType = iota
+ EvStr
+ EvSoftBreak
+ EvHardBreak
+ EvNonBreakingSpace
+ EvEscape
+ EvSymb
+ EvFootnoteReference
+ EvSmartPunctuation
+ EvOpenVerbatim
+ EvCloseVerbatim
+ EvRawInline
+ EvInlineMath
+ EvDisplayMath
+ EvUrl
+ EvEmail
+
+ EvOpenAttributes
+ EvOpenInlineAttributes
+ EvCloseAttributes
+ EvAttrIdMarker
+ EvAttrClassMarker
+ EvAttrKey
+ EvAttrValue
+ EvAttrEqualMarker
+ EvAttrQuoteMarker
+ EvAttrSpace
+ EvComment
+
+ EvText
+
+ EvOpenPara
+ EvClosePara
+ EvOpenHeading
+ EvCloseHeading
+ EvOpenBlockQuote
+ EvCloseBlockQuote
+ EvOpenList
+ EvCloseList
+ EvOpenListItem
+ EvCloseListItem
+ EvOpenDiv
+ EvCloseDiv
+ EvOpenCodeBlock
+ EvCloseCodeBlock
+ EvOpenRawBlock
+ EvCloseRawBlock
+ EvOpenTable
+ EvCloseTable
+ EvOpenRow
+ EvCloseRow
+ EvOpenCell
+ EvCloseCell
+ EvOpenCaption
+ EvCloseCaption
+ EvOpenFootnote
+ EvCloseFootnote
+ EvOpenReferenceDefinition
+ EvCloseReferenceDefinition
+
+ EvOpenEmph
+ EvCloseEmph
+ EvOpenStrong
+ EvCloseStrong
+ EvOpenLinkText
+ EvCloseLinkText
+ EvOpenImageText
+ EvCloseImageText
+ EvOpenDestination
+ EvCloseDestination
+ EvOpenReference
+ EvCloseReference
+ EvOpenSpan
+ EvCloseSpan
+ EvOpenMark
+ EvCloseMark
+ EvOpenInsert
+ EvCloseInsert
+ EvOpenDelete
+ EvCloseDelete
+ EvOpenSuperscript
+ EvCloseSuperscript
+ EvOpenSubscript
+ EvCloseSubscript
+ EvOpenDoubleQuoted
+ EvCloseDoubleQuoted
+ EvOpenSingleQuoted
+ EvCloseSingleQuoted
+
+ EvBlankLine
+ EvThematicBreak
+)
+
+type Event struct {
+ Start, End int32
+ Type EventType
+}
+
+type Reference struct {
+ LabelStart, LabelEnd int32
+ DestStart, DestEnd int32
+ Attributes []Attribute
+}
+
+type Document struct {
+ Source []byte
+ Extra []byte
+ Nodes []Node
+ Attributes []Attribute
+ References map[string]Reference
+ UsedFootnotes []string
+ FootnoteContent map[string]int32
+ Events []Event
+}
+
+type ContainerType uint8
+
+const (
+ ContainerNone ContainerType = iota
+ ContainerDoc
+ ContainerBlockQuote
+ ContainerListItem
+ ContainerList
+ ContainerPara
+ ContainerHeading
+ ContainerTable
+ ContainerCaption
+ ContainerFootnote
+ ContainerDiv
+ ContainerCodeBlock
+ ContainerRawBlock
+ ContainerReferenceDef
+ ContainerThematicBreak
+)
+
+type ContainerData struct {
+ Level int16
+ Marker byte
+ MarkerEnd byte
+ Ordered bool
+ Tight bool
+ BlankLines bool
+ Indent int32
+ MarkerWidth int32
+ FenceChar byte
+ FenceLen int32
+ IsTask bool
+ Checked bool
+ NextNumber int
+ MarkerAmbiguous bool
+ MarkerFirstChar byte
+ OpenListEventIdx int32
+}
+
+const (
+ DataAlignLeft uint32 = 1 << iota
+ DataAlignCenter
+ DataAlignRight
+ DataListTight
+ DataListDecimal
+ DataListLowerAlpha
+ DataListUpperAlpha
+ DataListLowerRoman
+ DataListUpperRoman
+ DataTaskChecked
+ DataCellHeader
+ DataNoAutoID
+)
diff --git a/scripts/mkman/djot/attr.go b/scripts/mkman/djot/attr.go
@@ -0,0 +1,154 @@
+package djot
+
+func isKeyStartChar(b byte) bool {
+ return (b >= 'a' && b <= 'z') || (b >= 'A' && b <= 'Z') || b == '_' || b == '-' || b == ':'
+}
+
+func isKeyChar(b byte) bool {
+ return isKeyStartChar(b) || (b >= '0' && b <= '9')
+}
+
+func isIDChar(b byte) bool {
+ return isKeyChar(b)
+}
+
+func isSpace(b byte) bool {
+ return b == ' ' || b == '\t' || b == '\r' || b == '\n'
+}
+
+func ParseAttributes(source []byte, start, end int32) ([]Event, int32, bool) {
+ if start >= end || source[start] != '{' {
+ return nil, start, false
+ }
+
+ pos := start + 1
+ var events []Event
+
+ for pos < end {
+ b := source[pos]
+ if isSpace(b) {
+ pos++
+ continue
+ }
+
+ if b == '}' {
+ return events, pos, true
+ }
+
+ if b == '#' {
+ pos++
+ idStart := pos
+ for pos < end && isIDChar(source[pos]) {
+ pos++
+ }
+ if pos == idStart {
+ return nil, start, false
+ }
+ events = append(events, Event{Start: idStart, End: pos - 1, Type: EvAttrIdMarker})
+ continue
+ }
+
+ if b == '.' {
+ pos++
+ classStart := pos
+ for pos < end && isKeyChar(source[pos]) {
+ pos++
+ }
+ if pos == classStart {
+ return nil, start, false
+ }
+ events = append(events, Event{Start: classStart, End: pos - 1, Type: EvAttrClassMarker})
+ continue
+ }
+
+ if b == '%' {
+ pos++
+ commentStart := pos
+ for pos < end && source[pos] != '%' && source[pos] != '}' {
+ pos++
+ }
+ if pos < end && source[pos] == '%' {
+ events = append(events, Event{Start: commentStart, End: pos - 1, Type: EvComment})
+ pos++
+ }
+ continue
+ }
+
+ if b == '=' {
+ eqPos := pos
+ pos++
+ keyStart := pos
+ for pos < end && source[pos] != '}' && !isSpace(source[pos]) {
+ pos++
+ }
+ keyEnd := pos - 1
+ if keyEnd >= keyStart {
+ events = append(events, Event{Type: EvAttrKey, Start: eqPos, End: keyEnd})
+ }
+ continue
+ }
+
+ if isKeyStartChar(b) {
+ keyStart := pos
+ for pos < end && isKeyChar(source[pos]) {
+ pos++
+ }
+ keyEnd := pos - 1
+
+ for pos < end && isSpace(source[pos]) {
+ pos++
+ }
+
+ if pos < end && source[pos] == '=' {
+ events = append(events, Event{Start: keyStart, End: keyEnd, Type: EvAttrKey})
+ events = append(events, Event{Start: pos, End: pos, Type: EvAttrEqualMarker})
+ pos++
+
+ for pos < end && isSpace(source[pos]) {
+ pos++
+ }
+
+ if pos < end && source[pos] == '"' {
+ events = append(events, Event{Start: pos, End: pos, Type: EvAttrQuoteMarker})
+ pos++
+ valStart := pos
+ valEnd := valStart
+ for pos < end {
+ if source[pos] == '\\' && pos+1 < end {
+ pos += 2
+ } else if source[pos] == '"' {
+ valEnd = pos
+ break
+ } else {
+ pos++
+ }
+ }
+
+ if pos < end && source[pos] == '"' {
+ events = append(events, Event{Start: valStart, End: valEnd - 1, Type: EvAttrValue})
+ events = append(events, Event{Start: pos, End: pos, Type: EvAttrQuoteMarker})
+ pos++
+ } else {
+ return nil, start, false
+ }
+ } else {
+ valStart := pos
+ for pos < end && isKeyChar(source[pos]) {
+ pos++
+ }
+ if pos == valStart {
+ return nil, start, false
+ }
+ events = append(events, Event{Start: valStart, End: pos - 1, Type: EvAttrValue})
+ }
+ } else {
+ return nil, start, false
+ }
+ continue
+ }
+
+ return nil, start, false
+ }
+
+ return nil, start, false
+}
diff --git a/scripts/mkman/djot/block.go b/scripts/mkman/djot/block.go
@@ -0,0 +1,1224 @@
+package djot
+
+import (
+ "bytes"
+)
+
+type ActiveContainer struct {
+ Type ContainerType
+ Start int32
+ End int32
+ Data ContainerData
+}
+type BlockParser struct {
+ source []byte
+ pos int32
+ events []Event
+ stack []ActiveContainer
+
+ inPara bool
+ paraLines [][2]int32
+
+ pendingAttr []Event
+ hasAttr bool
+
+ inAttrBlock bool
+ attrLines [][2]int32
+ lineIndent int32
+ afterBlankLine bool
+}
+
+func NewBlockParser(source []byte) *BlockParser {
+ p := &BlockParser{
+ source: source,
+ events: make([]Event, 0, len(source)/8+32),
+ stack: make([]ActiveContainer, 0, 16),
+ paraLines: make([][2]int32, 0, 8),
+ attrLines: make([][2]int32, 0, 2),
+ afterBlankLine: true,
+ }
+ p.stack = append(p.stack, ActiveContainer{Type: ContainerDoc})
+ return p
+}
+
+func (p *BlockParser) addEvent(start, end int32, etype EventType) {
+ p.events = append(p.events, Event{Start: start, End: end, Type: etype})
+}
+
+func (p *BlockParser) Parse() []Event {
+ for p.pos < int32(len(p.source)) {
+ lineStart := p.pos
+ eol := bytes.IndexByte(p.source[p.pos:], '\n')
+ var nextPos int32
+ if eol == -1 {
+ nextPos = int32(len(p.source))
+ } else {
+ nextPos = p.pos + int32(eol) + 1
+ }
+
+ p.handleLine(lineStart, nextPos)
+ p.pos = nextPos
+ }
+
+ p.closePara()
+ p.flushFailedAttr()
+ p.closePara()
+ p.discardDanglingAttr()
+ for i := len(p.stack) - 1; i > 0; i-- {
+ p.closeContainer(i)
+ }
+ return p.events
+}
+
+func (p *BlockParser) handleLine(start, end int32) {
+ contentEnd := end
+ if contentEnd > start && p.source[contentEnd-1] == '\n' {
+ contentEnd--
+ if contentEnd > start && p.source[contentEnd-1] == '\r' {
+ contentEnd--
+ }
+ }
+
+ p.lineIndent = 0
+ for start+p.lineIndent < contentEnd && p.source[start+p.lineIndent] == ' ' {
+ p.lineIndent++
+ }
+
+ matched := 1
+ currentPos := start
+ allMatched := true
+ tipIdx := len(p.stack) - 1
+
+ for i := 1; i < len(p.stack); i++ {
+ c := &p.stack[i]
+ if i == tipIdx && (c.Type == ContainerCodeBlock || c.Type == ContainerRawBlock) {
+ if p.isClosingFence(c, currentPos, contentEnd) {
+ p.closePara()
+ p.closeContainer(i)
+ return
+ }
+ p.closePara()
+ p.handleLeafContent(c, currentPos, end)
+ return
+ }
+
+ tipIsCode := p.stack[tipIdx].Type == ContainerCodeBlock ||
+ p.stack[tipIdx].Type == ContainerRawBlock
+ if !tipIsCode && c.Type == ContainerDiv {
+ if p.isClosingFence(c, currentPos, contentEnd) {
+ p.closePara()
+ for j := len(p.stack) - 1; j >= i; j-- {
+ p.closeContainer(j)
+ }
+ return
+ }
+ }
+
+ if c.Type == ContainerCodeBlock || c.Type == ContainerRawBlock {
+ break
+ }
+
+ newPos := p.checkContinue(c, currentPos, contentEnd)
+ if newPos != -1 {
+ matched++
+ currentPos = newPos
+ if isLeaf(c.Type) {
+ break
+ }
+ } else {
+ allMatched = false
+ break
+ }
+ }
+ isBlank := isBlankLine(p.source, currentPos, contentEnd)
+
+ if isBlank {
+ p.closePara()
+ p.discardDanglingAttr()
+ for i := len(p.stack) - 1; i >= matched; i-- {
+ p.closeContainer(i)
+ }
+ if p.inAttrBlock {
+ p.flushFailedAttr()
+ }
+ p.addEvent(start, end, EvBlankLine)
+ p.markListBlankLines(matched)
+ p.afterBlankLine = true
+ return
+ }
+
+ defer func() { p.afterBlankLine = false }()
+
+ if p.inAttrBlock {
+ p.attrLines = append(p.attrLines, [2]int32{currentPos, contentEnd})
+ p.tryParseBufferedAttr()
+ return
+ }
+
+ if allMatched && !p.inAttrBlock && currentPos < contentEnd && p.source[currentPos] == '{' && (p.afterBlankLine || p.hasAttr) {
+ p.inAttrBlock = true
+ p.attrLines = append(p.attrLines, [2]int32{currentPos, contentEnd})
+ p.tryParseBufferedAttr()
+ return
+ }
+
+ newStarts := false
+ if !allMatched || p.inPara || !isLeaf(p.stack[len(p.stack)-1].Type) {
+ openPos := currentPos
+ if openPos < start+p.lineIndent {
+ openPos = start + p.lineIndent
+ }
+ for {
+ for i := 0; i < 3 && openPos < contentEnd && p.source[openPos] == ' '; i++ {
+ openPos++
+ }
+
+ ctype, nextOpenPos, data, ok := p.findOpen(start, openPos, contentEnd)
+ if !ok {
+ break
+ }
+
+ if p.inPara && !p.canInterrupt(ctype, openPos, contentEnd) {
+ break
+ }
+
+ newStarts = true
+ canHaveImmediateAttr := ctype == ContainerDiv || ctype == ContainerCodeBlock || ctype == ContainerRawBlock || ctype == ContainerHeading
+ attrPos := nextOpenPos
+ for attrPos < contentEnd && (p.source[attrPos] == ' ' || p.source[attrPos] == '\t') {
+ attrPos++
+ }
+ if attrPos < contentEnd && canHaveImmediateAttr {
+ if p.source[attrPos] == '{' {
+ attrEvents, nextPos, ok := ParseAttributes(p.source, attrPos, contentEnd)
+ if ok && isBlankLine(p.source, nextPos+1, contentEnd) {
+ p.hasAttr = true
+ p.pendingAttr = append(p.pendingAttr, attrEvents...)
+ p.closePara()
+ for i := len(p.stack) - 1; i >= matched; i-- {
+ p.closeContainer(i)
+ }
+ p.openContainer(ctype, openPos, data)
+ return
+ }
+ } else if ctype == ContainerDiv || ctype == ContainerCodeBlock || ctype == ContainerRawBlock {
+ classStart := attrPos
+ if ctype == ContainerDiv && p.source[classStart] == '.' {
+ classStart++
+ }
+ classEnd := classStart
+ for classEnd < contentEnd && !isSpace(p.source[classEnd]) {
+ classEnd++
+ }
+ if classEnd > classStart {
+ p.hasAttr = true
+ if ctype == ContainerRawBlock {
+ eqPos := attrPos - 1
+ p.pendingAttr = append(p.pendingAttr, Event{Start: eqPos, End: classEnd - 1, Type: EvAttrKey})
+ } else if ctype == ContainerCodeBlock && p.source[classStart] == '=' {
+ ctype = ContainerRawBlock
+ p.pendingAttr = append(p.pendingAttr, Event{Start: classStart, End: classEnd - 1, Type: EvAttrKey})
+ } else {
+ p.pendingAttr = append(p.pendingAttr, Event{Start: classStart, End: classEnd - 1, Type: EvAttrClassMarker})
+ }
+ nextAttrPos := classEnd
+ for nextAttrPos < contentEnd && isSpace(p.source[nextAttrPos]) {
+ nextAttrPos++
+ }
+ if nextAttrPos < contentEnd && p.source[nextAttrPos] == '{' {
+ attrEvents, _, ok := ParseAttributes(p.source, nextAttrPos, contentEnd)
+ if ok {
+ p.pendingAttr = append(p.pendingAttr, attrEvents...)
+ }
+ }
+ p.closePara()
+ for i := len(p.stack) - 1; i >= matched; i-- {
+ p.closeContainer(i)
+ }
+ p.openContainer(ctype, openPos, data)
+ return
+ }
+ }
+ }
+
+ p.closePara()
+ for i := len(p.stack) - 1; i >= matched; i-- {
+ c := &p.stack[i]
+ if c.Data.BlankLines && c.Type == ContainerListItem {
+ c.Data.Tight = false
+ if i > 0 && p.stack[i-1].Type == ContainerList {
+ p.stack[i-1].Data.Tight = false
+ }
+ }
+ p.closeContainer(i)
+ }
+ p.openContainer(ctype, openPos, data)
+
+ currentPos = nextOpenPos
+ openPos = nextOpenPos
+ matched = len(p.stack)
+
+ if currentPos < contentEnd && p.source[currentPos] == '{' && !p.inAttrBlock {
+ p.inAttrBlock = true
+ p.attrLines = append(p.attrLines, [2]int32{currentPos, contentEnd})
+ p.tryParseBufferedAttr()
+ return
+ }
+
+ if isLeaf(ctype) {
+ if ctype == ContainerReferenceDef {
+ currentPos = openPos
+ }
+ break
+ }
+ }
+ }
+
+ isLazy := !isBlank && !newStarts && matched < len(p.stack) && p.inPara
+
+ if !isLazy {
+ if matched < len(p.stack) {
+ p.closePara()
+ for i := len(p.stack) - 1; i >= matched; i-- {
+ p.closeContainer(i)
+ }
+ }
+ }
+
+ tipIdx = len(p.stack) - 1
+ tip := &p.stack[tipIdx]
+
+ if tip.Type == ContainerTable {
+ p.handleTableRow(currentPos, contentEnd)
+ return
+ }
+
+ if isBlankLine(p.source, currentPos, contentEnd) {
+ return
+ }
+
+ if hasInlineContent(tip.Type) || isBlock(tip.Type) || p.inPara {
+ for currentPos < contentEnd && (p.source[currentPos] == ' ' || p.source[currentPos] == '\t') {
+ currentPos++
+ }
+ p.accumulateInlineLine(currentPos, contentEnd)
+ } else {
+ p.handleLeafContent(tip, currentPos, end)
+ }
+}
+
+func isBlock(t ContainerType) bool {
+ switch t {
+ case ContainerDoc, ContainerBlockQuote, ContainerListItem, ContainerList, ContainerDiv, ContainerFootnote:
+ return true
+ }
+ return false
+}
+
+func hasInlineContent(t ContainerType) bool {
+ switch t {
+ case ContainerPara, ContainerHeading, ContainerCaption:
+ return true
+ }
+ return false
+}
+
+func (p *BlockParser) accumulateInlineLine(start, end int32) {
+ tipIdx := len(p.stack) - 1
+ tip := &p.stack[tipIdx]
+ if (tip.Type == ContainerPara || isBlock(tip.Type)) && !p.inPara {
+ p.inPara = true
+ if p.hasAttr {
+ p.addEvent(start, start, EvOpenAttributes)
+ p.events = append(p.events, p.pendingAttr...)
+ p.addEvent(start, start, EvCloseAttributes)
+ p.hasAttr = false
+ p.pendingAttr = p.pendingAttr[:0]
+ }
+ p.addEvent(start, start, EvOpenPara)
+ }
+ p.paraLines = append(p.paraLines, [2]int32{start, end})
+}
+
+func (p *BlockParser) tryParseBufferedAttr() {
+ if len(p.attrLines) == 0 {
+ return
+ }
+
+ start := p.attrLines[0][0]
+ end := p.attrLines[len(p.attrLines)-1][1]
+
+ attrEvents, nextPos, ok := ParseAttributes(p.source, start, end)
+
+ if ok {
+ if isBlankLine(p.source, nextPos+1, end) {
+ p.closePara()
+ p.hasAttr = true
+ p.pendingAttr = append(p.pendingAttr, attrEvents...)
+ p.inAttrBlock = false
+ p.attrLines = p.attrLines[:0]
+ return
+ } else {
+ p.flushFailedAttr()
+ return
+ }
+ } else {
+ hasClosing := false
+ for i := start; i < end; i++ {
+ if p.source[i] == '}' {
+ hasClosing = true
+ break
+ }
+ }
+ if hasClosing {
+ p.flushFailedAttr()
+ }
+ }
+}
+func (p *BlockParser) flushFailedAttr() {
+ p.inAttrBlock = false
+ for _, line := range p.attrLines {
+ start := line[0]
+ for start < line[1] && (p.source[start] == ' ' || p.source[start] == '\t') {
+ start++
+ }
+ p.accumulateInlineLine(start, line[1])
+ }
+ p.attrLines = p.attrLines[:0]
+}
+
+func (p *BlockParser) closePara() {
+ if !p.inPara {
+ if len(p.paraLines) > 0 {
+ for i, line := range p.paraLines {
+ start := line[0]
+ end := line[1]
+ if i == len(p.paraLines)-1 {
+ for end > start && (p.source[end-1] == ' ' || p.source[end-1] == '\t') {
+ end--
+ }
+ }
+ isHardBreak := false
+ if i < len(p.paraLines)-1 {
+ tempEnd := end
+ for tempEnd > start && (p.source[tempEnd-1] == ' ' || p.source[tempEnd-1] == '\t') {
+ tempEnd--
+ }
+ if tempEnd > start && p.source[tempEnd-1] == '\\' {
+ backslashCount := 0
+ for j := tempEnd - 1; j >= start && p.source[j] == '\\'; j-- {
+ backslashCount++
+ }
+ if backslashCount%2 != 0 {
+ isHardBreak = true
+ end = tempEnd - 1
+ for end > start && (p.source[end-1] == ' ' || p.source[end-1] == '\t') {
+ end--
+ }
+ }
+ }
+ }
+ if start < end {
+ p.addEvent(start, end-1, EvText)
+ }
+ if i < len(p.paraLines)-1 {
+ if isHardBreak {
+ p.addEvent(line[1], line[1], EvHardBreak)
+ } else {
+ p.addEvent(line[1], line[1], EvSoftBreak)
+ }
+ }
+ }
+ p.paraLines = p.paraLines[:0]
+ }
+ return
+ }
+
+ for i, line := range p.paraLines {
+ start := line[0]
+ end := line[1]
+ if i == len(p.paraLines)-1 {
+ for end > start && (p.source[end-1] == ' ' || p.source[end-1] == '\t') {
+ end--
+ }
+ }
+ isHardBreak := false
+ if i < len(p.paraLines)-1 {
+ tempEnd := end
+ for tempEnd > start && (p.source[tempEnd-1] == ' ' || p.source[tempEnd-1] == '\t') {
+ tempEnd--
+ }
+ if tempEnd > start && p.source[tempEnd-1] == '\\' {
+ backslashCount := 0
+ for j := tempEnd - 1; j >= start && p.source[j] == '\\'; j-- {
+ backslashCount++
+ }
+ if backslashCount%2 != 0 {
+ isHardBreak = true
+ end = tempEnd - 1
+ for end > start && (p.source[end-1] == ' ' || p.source[end-1] == '\t') {
+ end--
+ }
+ }
+ }
+ }
+ if start < end {
+ p.addEvent(start, end-1, EvText)
+ }
+ if i < len(p.paraLines)-1 {
+ if isHardBreak {
+ p.addEvent(line[1], line[1], EvHardBreak)
+ } else {
+ p.addEvent(line[1], line[1], EvSoftBreak)
+ }
+ }
+ }
+
+ if len(p.paraLines) > 0 {
+ lastLine := p.paraLines[len(p.paraLines)-1]
+ p.addEvent(lastLine[1], lastLine[1], EvClosePara)
+ }
+ p.inPara = false
+ p.paraLines = p.paraLines[:0]
+}
+
+func (p *BlockParser) discardDanglingAttr() {
+ p.hasAttr = false
+ p.pendingAttr = p.pendingAttr[:0]
+}
+
+func isLeaf(t ContainerType) bool {
+ switch t {
+ case ContainerPara, ContainerHeading, ContainerCodeBlock, ContainerRawBlock, ContainerThematicBreak, ContainerReferenceDef, ContainerCaption, ContainerTable:
+ return true
+ }
+ return false
+}
+
+func isBlankLine(source []byte, start, end int32) bool {
+ for i := start; i < end; i++ {
+ if source[i] != ' ' && source[i] != '\t' {
+ return false
+ }
+ }
+ return true
+}
+
+func (p *BlockParser) markListBlankLines(matched int) {
+}
+
+func (p *BlockParser) checkContinue(c *ActiveContainer, pos, end int32) int32 {
+ switch c.Type {
+ case ContainerBlockQuote:
+ if pos < end && p.source[pos] == '>' {
+ pos++
+ if pos == end {
+ return pos
+ }
+ if p.source[pos] == ' ' {
+ return pos + 1
+ }
+ return -1
+ }
+ case ContainerHeading:
+ if isBlankLine(p.source, pos, end) {
+ return -1
+ }
+ hLevel := int32(0)
+ for pos+hLevel < end && p.source[pos+hLevel] == '#' {
+ hLevel++
+ }
+ if hLevel > 0 && hLevel <= 6 && (pos+hLevel == end || p.source[pos+hLevel] == ' ' || p.source[pos+hLevel] == '\t') {
+ if hLevel == int32(c.Data.Level) {
+ newPos := pos + hLevel
+ if newPos < end && (p.source[newPos] == ' ' || p.source[newPos] == '\t') {
+ newPos++
+ }
+ return newPos
+ }
+ return -1
+ }
+ return pos
+ case ContainerCodeBlock, ContainerRawBlock:
+ if p.isClosingFence(c, pos, end) {
+ return -1
+ }
+ return pos
+ case ContainerDiv:
+ return pos
+ case ContainerList:
+ return pos
+ case ContainerListItem:
+ if isBlankLine(p.source, pos, end) {
+ return pos
+ }
+ if p.lineIndent > c.Data.Indent {
+ return pos
+ }
+ if p.inPara && !p.afterBlankLine {
+ markerPos := pos + p.lineIndent
+ _, _, ok := parseListMarker(p.source, markerPos, end)
+ if !ok {
+ return pos
+ }
+ }
+ return -1
+ case ContainerTable:
+ if pos < end && p.source[pos] == '|' {
+ return pos
+ }
+ case ContainerFootnote:
+ if isBlankLine(p.source, pos, end) {
+ return pos
+ }
+ if p.lineIndent > c.Data.Indent {
+ return pos
+ }
+ return -1
+ case ContainerReferenceDef:
+ if isBlankLine(p.source, pos, end) {
+ return pos
+ }
+ if p.lineIndent > c.Data.Indent {
+ return pos
+ }
+ return -1
+ case ContainerCaption:
+ if isBlankLine(p.source, pos, end) {
+ return -1
+ }
+ return pos
+ }
+ return -1
+}
+
+func (p *BlockParser) isClosingFence(c *ActiveContainer, pos, end int32) bool {
+ i := 0
+ for i < 3 && pos < end && p.source[pos] == ' ' {
+ pos++
+ i++
+ }
+
+ char := c.Data.FenceChar
+ count := int32(0)
+ for pos < end && p.source[pos] == char {
+ count++
+ pos++
+ }
+
+ if count < c.Data.FenceLen {
+ return false
+ }
+
+ for pos < end && (p.source[pos] == ' ' || p.source[pos] == '\t') {
+ pos++
+ }
+
+ return pos == end || p.source[pos] == '\r' || p.source[pos] == '\n'
+}
+
+func (p *BlockParser) findOpen(start, pos, end int32) (ContainerType, int32, ContainerData, bool) {
+ if pos >= end {
+ return ContainerNone, pos, ContainerData{}, false
+ }
+ b := p.source[pos]
+
+ if isThematicBreak(p.source, pos, end) {
+ return ContainerThematicBreak, end, ContainerData{}, true
+ }
+
+ if b == '`' || b == '~' || b == ':' {
+ count := int32(0)
+ for i := pos; i < end && p.source[i] == b; i++ {
+ count++
+ }
+ if count >= 3 {
+ if b == '`' || b == '~' {
+ rest := p.source[pos+count : end]
+ hasInvalid := false
+ for j := 0; j < len(rest); j++ {
+ if rest[j] == '{' {
+ break
+ }
+ if rest[j] == b {
+ c := int32(0)
+ for j < len(rest) && rest[j] == b {
+ c++
+ j++
+ }
+ if c >= count {
+ hasInvalid = true
+ break
+ }
+ j--
+ continue
+ }
+ if rest[j] != ' ' && rest[j] != ' ' {
+ k := j
+ for k < len(rest) && rest[k] != ' ' && rest[k] != ' ' && rest[k] != '{' {
+ if rest[k] == b {
+ c := int32(0)
+ for k < len(rest) && rest[k] == b {
+ c++
+ k++
+ }
+ if c >= count {
+ hasInvalid = true
+ break
+ }
+ continue
+ }
+ k++
+ }
+ if hasInvalid {
+ break
+ }
+ for k < len(rest) && (rest[k] == ' ' || rest[k] == ' ') {
+ k++
+ }
+ if k < len(rest) && rest[k] != '{' {
+ hasInvalid = true
+ break
+ }
+ j = k - 1
+ }
+ }
+ if hasInvalid {
+ return ContainerNone, pos, ContainerData{}, false
+ }
+ }
+ if b == ':' {
+ return ContainerDiv, pos + count, ContainerData{FenceChar: b, FenceLen: count, Indent: pos - start}, true
+ }
+ classPos := pos + count
+ for classPos < end && p.source[classPos] == ' ' {
+ classPos++
+ }
+ if classPos < end && p.source[classPos] == '=' {
+ return ContainerRawBlock, classPos + 1, ContainerData{FenceChar: b, FenceLen: count, Indent: pos - start}, true
+ }
+ return ContainerCodeBlock, pos + count, ContainerData{FenceChar: b, FenceLen: count, Indent: pos - start}, true
+ }
+ }
+
+ if b == '#' {
+ level := int32(0)
+ for i := pos; i < end && p.source[i] == '#'; i++ {
+ level++
+ }
+ if level > 0 && level <= 6 && (pos+level == end || p.source[pos+level] == ' ') {
+ newPos := pos + level
+ if newPos < end && p.source[newPos] == ' ' {
+ newPos++
+ }
+ return ContainerHeading, newPos, ContainerData{Level: int16(level)}, true
+ }
+ }
+
+ if b == '>' {
+ newPos := pos + 1
+ if newPos == end {
+ return ContainerBlockQuote, newPos, ContainerData{}, true
+ }
+ if p.source[newPos] == ' ' {
+ return ContainerBlockQuote, newPos + 1, ContainerData{}, true
+ }
+ return ContainerNone, pos, ContainerData{}, false
+ }
+
+ if b == '|' {
+ pipes := 0
+ i := pos
+ for i < end {
+ if p.source[i] == '|' {
+ pipes++
+ i++
+ } else if p.source[i] == '`' {
+ count := int32(0)
+ for i < end && p.source[i] == '`' {
+ count++
+ i++
+ }
+ for i < end {
+ if p.source[i] == '`' {
+ c := int32(0)
+ for i < end && p.source[i] == '`' {
+ c++
+ i++
+ }
+ if c == count {
+ break
+ }
+ } else {
+ i++
+ }
+ }
+ } else {
+ i++
+ }
+ }
+ if pipes >= 2 {
+ return ContainerTable, pos, ContainerData{}, true
+ }
+ }
+
+ if b == '^' {
+ if pos+1 < end && p.source[pos+1] == ' ' {
+ return ContainerCaption, pos + 2, ContainerData{}, true
+ }
+ }
+
+ if b == '[' {
+ if pos+1 < end && p.source[pos+1] == '^' {
+ for i := pos + 2; i < end; i++ {
+ if p.source[i] == ']' && i+1 < end && p.source[i+1] == ':' {
+ newPos := i + 2
+ for newPos < end && (p.source[newPos] == ' ' || p.source[newPos] == '\t') {
+ newPos++
+ }
+ return ContainerFootnote, newPos, ContainerData{Indent: p.lineIndent, MarkerWidth: newPos - pos}, true
+ }
+ }
+ } else {
+ for i := pos + 1; i < end; i++ {
+ if p.source[i] == ']' && i+1 < end && p.source[i+1] == ':' {
+ newPos := i + 2
+ for newPos < end && (p.source[newPos] == ' ' || p.source[newPos] == '\t') {
+ newPos++
+ }
+ return ContainerReferenceDef, newPos, ContainerData{Indent: p.lineIndent}, true
+ }
+ }
+ }
+ }
+
+ newPos, data, ok := parseListMarker(p.source, pos, end)
+ if ok {
+ data.Indent = pos - start
+ if !p.canListMarkerInterrupt(p.lineIndent, data.Marker, p.afterBlankLine) {
+ return ContainerNone, pos, ContainerData{}, false
+ }
+ return ContainerListItem, newPos, data, true
+ }
+
+ return ContainerNone, pos, ContainerData{}, false
+}
+
+func (p *BlockParser) openContainer(ctype ContainerType, start int32, data ContainerData) {
+ if p.hasAttr {
+ p.addEvent(start, start, EvOpenAttributes)
+ p.events = append(p.events, p.pendingAttr...)
+ p.addEvent(start, start, EvCloseAttributes)
+ p.hasAttr = false
+ p.pendingAttr = p.pendingAttr[:0]
+ }
+
+ switch ctype {
+ case ContainerHeading:
+ p.addEvent(start, start+int32(data.Level)-1, EvOpenHeading)
+ case ContainerBlockQuote:
+ p.addEvent(start, start, EvOpenBlockQuote)
+ case ContainerListItem:
+ tipIdx := len(p.stack) - 1
+ tip := &p.stack[tipIdx]
+ if tip.Type == ContainerListItem {
+ pIdx := len(p.stack) - 2
+ parent := &p.stack[pIdx]
+ if parent.Type == ContainerList {
+ itemIndent := tip.Data.Indent
+ if data.Indent > itemIndent {
+ p.openList(start, data)
+ } else if data.Indent == parent.Data.Indent {
+ p.closeContainer(tipIdx)
+ if parent.Data.Marker == data.Marker && parent.Data.MarkerEnd == data.MarkerEnd && parent.Data.Ordered == data.Ordered {
+ if data.Ordered {
+ parent.Data.NextNumber++
+ }
+ } else {
+ p.closeContainer(pIdx)
+ p.openList(start, data)
+ }
+ } else {
+ p.closeContainer(tipIdx)
+ p.closeContainer(pIdx)
+ p.openList(start, data)
+ }
+ } else {
+ p.openList(start, data)
+ }
+ } else if tip.Type == ContainerList {
+ if tip.Data.Marker == data.Marker && tip.Data.MarkerEnd == data.MarkerEnd && tip.Data.Ordered == data.Ordered {
+ if !data.MarkerAmbiguous {
+ tip.Data.MarkerAmbiguous = false
+ }
+ } else if data.Indent == tip.Data.Indent {
+ if p.tryNarrowList(tip, data) {
+ } else {
+ p.closeContainer(tipIdx)
+ p.openList(start, data)
+ }
+ } else {
+ p.openList(start, data)
+ }
+ } else {
+ p.openList(start, data)
+ }
+
+ taskStatus := int32(0)
+ if data.IsTask {
+ if data.Checked {
+ taskStatus = 2
+ } else {
+ taskStatus = 1
+ }
+ }
+ p.addEvent(start, taskStatus, EvOpenListItem)
+ case ContainerCodeBlock:
+ p.addEvent(start, start+data.FenceLen-1, EvOpenCodeBlock)
+ p.addEvent(start, start, EvNone)
+ case ContainerRawBlock:
+ p.addEvent(start, start+data.FenceLen-1, EvOpenRawBlock)
+ p.addEvent(start, start, EvNone)
+ case ContainerDiv:
+ p.addEvent(start, start+data.FenceLen-1, EvOpenDiv)
+ p.addEvent(start, start, EvNone)
+ case ContainerThematicBreak:
+ p.addEvent(start, start, EvThematicBreak)
+ case ContainerTable:
+ p.addEvent(start, start, EvOpenTable)
+ case ContainerCaption:
+ p.addEvent(start, start, EvOpenCaption)
+ case ContainerFootnote:
+ p.addEvent(start, start, EvOpenFootnote)
+ p.addEvent(start, start+data.MarkerWidth-1, EvStr)
+ case ContainerReferenceDef:
+ p.addEvent(start, start, EvOpenReferenceDefinition)
+ }
+ p.stack = append(p.stack, ActiveContainer{Type: ctype, Start: start, Data: data})
+}
+
+func (p *BlockParser) closeContainer(idx int) {
+ c := p.stack[idx]
+ switch c.Type {
+ case ContainerHeading:
+ p.addEvent(c.Start, c.Start, EvCloseHeading)
+ case ContainerBlockQuote:
+ p.addEvent(c.Start, c.Start, EvCloseBlockQuote)
+ case ContainerListItem:
+ p.addEvent(c.Start, c.Start, EvCloseListItem)
+ case ContainerList:
+ tight := int32(0)
+ if c.Data.Tight {
+ tight = 1
+ }
+ p.addEvent(c.Start, tight, EvCloseList)
+ case ContainerCodeBlock:
+ p.addEvent(c.Start, c.Start, EvCloseCodeBlock)
+ case ContainerRawBlock:
+ p.addEvent(c.Start, c.Start, EvCloseRawBlock)
+ case ContainerDiv:
+ p.addEvent(c.Start, c.Start, EvCloseDiv)
+ case ContainerTable:
+ p.addEvent(c.Start, c.Start, EvCloseTable)
+ case ContainerCaption:
+ p.addEvent(c.Start, c.Start, EvCloseCaption)
+ case ContainerFootnote:
+ p.addEvent(c.Start, c.Start, EvCloseFootnote)
+ case ContainerReferenceDef:
+ p.addEvent(c.Start, c.Start, EvCloseReferenceDefinition)
+ }
+ p.stack = p.stack[:idx]
+}
+
+func (p *BlockParser) handleLeafContent(tip *ActiveContainer, start, end int32) {
+ contentEnd := end
+ if contentEnd > start && p.source[contentEnd-1] == '\n' {
+ contentEnd--
+ if contentEnd > start && p.source[contentEnd-1] == '\r' {
+ contentEnd--
+ }
+ }
+
+ if p.hasAttr {
+ p.addEvent(start, start, EvOpenAttributes)
+ p.events = append(p.events, p.pendingAttr...)
+ p.addEvent(start, start, EvCloseAttributes)
+ p.hasAttr = false
+ p.pendingAttr = p.pendingAttr[:0]
+ }
+ switch tip.Type {
+ case ContainerCodeBlock, ContainerRawBlock, ContainerDiv:
+ if p.isClosingFence(tip, start, end) {
+ p.closeContainer(len(p.stack) - 1)
+ return
+ }
+
+ indentToStrip := tip.Data.Indent
+ current := start
+ for indentToStrip > 0 && current < end && p.source[current] == ' ' {
+ current++
+ indentToStrip--
+ }
+ if end < int32(len(p.source)) && p.source[end] == '\n' {
+ end++
+ } else if end < int32(len(p.source)) && p.source[end] == '\r' {
+ end++
+ if end < int32(len(p.source)) && p.source[end] == '\n' {
+ end++
+ }
+ }
+ p.addEvent(current, end-1, EvStr)
+ case ContainerTable:
+ p.handleTableRow(start, end)
+ case ContainerHeading, ContainerCaption:
+ p.accumulateInlineLine(start, end)
+ case ContainerReferenceDef:
+ actualEnd := contentEnd - 1
+ if actualEnd >= int32(len(p.source)) {
+ actualEnd = int32(len(p.source)) - 1
+ }
+ if tip.Start <= actualEnd {
+ p.addEvent(tip.Start, actualEnd, EvStr)
+ }
+ case ContainerFootnote:
+ actualEnd := contentEnd - 1
+ if actualEnd >= int32(len(p.source)) {
+ actualEnd = int32(len(p.source)) - 1
+ }
+ if actualEnd >= start {
+ p.addEvent(start, actualEnd, EvStr)
+ }
+ }
+}
+
+func (p *BlockParser) handleTableRow(start, end int32) {
+ isSep := false
+ hasDash := false
+ for i := start; i < end; i++ {
+ b := p.source[i]
+ if b == '-' || b == ':' {
+ hasDash = true
+ } else if b != '|' && b != ' ' && b != '\t' {
+ hasDash = false
+ break
+ }
+ }
+ isSep = hasDash
+
+ if isSep {
+ p.addEvent(start, end, EvStr)
+ return
+ }
+
+ p.addEvent(start, start, EvOpenRow)
+ pos := start
+ for pos < end {
+ if p.source[pos] == '|' {
+ pos++
+ if pos >= end {
+ break
+ }
+ cellStart := pos
+ for pos < end {
+ if p.source[pos] == '\\' && pos+1 < end {
+ pos += 2
+ } else if p.source[pos] == '`' {
+ count := int32(0)
+ for pos < end && p.source[pos] == '`' {
+ count++
+ pos++
+ }
+ for pos < end {
+ if p.source[pos] == '`' {
+ c := int32(0)
+ for pos < end && p.source[pos] == '`' {
+ c++
+ pos++
+ }
+ if c == count {
+ break
+ }
+ } else {
+ pos++
+ }
+ }
+ } else if p.source[pos] == '|' {
+ break
+ } else {
+ pos++
+ }
+ }
+ cellEnd := pos - 1
+ for cellStart <= cellEnd && isSpace(p.source[cellStart]) {
+ cellStart++
+ }
+ for cellEnd >= cellStart && isSpace(p.source[cellEnd]) {
+ cellEnd--
+ }
+ p.addEvent(cellStart, cellStart, EvOpenCell)
+ if cellStart <= cellEnd {
+ p.addEvent(cellStart, cellEnd, EvText)
+ }
+ p.addEvent(pos, pos, EvCloseCell)
+ } else {
+ pos++
+ }
+ }
+ p.addEvent(end, end, EvCloseRow)
+}
+
+func (p *BlockParser) canListMarkerInterrupt(markerIndent int32, markerChar byte, afterBlankLine bool) bool {
+ isDefinition := markerChar == ':'
+
+ for i := len(p.stack) - 1; i >= 0; i-- {
+ c := p.stack[i]
+ if c.Type == ContainerList || c.Type == ContainerListItem {
+ parentMarker := c.Data.Marker
+ parentIsDefinition := parentMarker == ':'
+ parentIndent := c.Data.Indent
+
+ if isDefinition == parentIsDefinition {
+ if !afterBlankLine && markerIndent > parentIndent && markerIndent < parentIndent+4 {
+ return false
+ }
+ }
+ return true
+ }
+ }
+ return true
+}
+
+func (p *BlockParser) canInterrupt(ctype ContainerType, pos, end int32) bool {
+ switch ctype {
+ case ContainerFootnote:
+ return true
+ case ContainerListItem:
+ _, data, ok := parseListMarker(p.source, pos, end)
+ if !ok {
+ return false
+ }
+ if data.Ordered && data.NextNumber != 1 {
+ alreadyInOrderedList := false
+ canNarrowExistingList := false
+ canContinueAsRoman := false
+ hasDifferentMarkerList := false
+ for i := len(p.stack) - 1; i >= 0; i-- {
+ c := p.stack[i]
+ if c.Type == ContainerList && c.Data.Ordered &&
+ c.Data.Marker == data.Marker && c.Data.MarkerEnd == data.MarkerEnd &&
+ c.Data.Indent == p.lineIndent {
+ alreadyInOrderedList = true
+ break
+ }
+ if c.Type == ContainerList && c.Data.Ordered &&
+ c.Data.Indent == p.lineIndent {
+ if c.Data.Marker != data.Marker || c.Data.MarkerEnd != data.MarkerEnd {
+ hasDifferentMarkerList = true
+ }
+ if c.Data.Marker == 'i' && data.Marker == 'a' && c.Data.MarkerAmbiguous && !isRomanLowerStart(data.MarkerFirstChar) {
+ canNarrowExistingList = true
+ break
+ }
+ if c.Data.Marker == 'I' && data.Marker == 'A' && c.Data.MarkerAmbiguous && !isRomanUpperStart(data.MarkerFirstChar) {
+ canNarrowExistingList = true
+ break
+ }
+ if c.Data.Marker == 'i' && data.Marker == 'a' && data.MarkerAmbiguous && isRomanLowerStart(data.MarkerFirstChar) {
+ if parseRoman([]byte{data.MarkerFirstChar}) == c.Data.NextNumber {
+ canContinueAsRoman = true
+ break
+ }
+ }
+ if c.Data.Marker == 'I' && data.Marker == 'A' && data.MarkerAmbiguous && isRomanUpperStart(data.MarkerFirstChar) {
+ if parseRoman([]byte{data.MarkerFirstChar}) == c.Data.NextNumber {
+ canContinueAsRoman = true
+ break
+ }
+ }
+ }
+ }
+ if !alreadyInOrderedList && !canNarrowExistingList && !canContinueAsRoman && !hasDifferentMarkerList {
+ return false
+ }
+ }
+ return p.canListMarkerInterrupt(p.lineIndent, data.Marker, p.afterBlankLine)
+ }
+ return false
+}
+func (p *BlockParser) tryNarrowList(list *ActiveContainer, newItem ContainerData) bool {
+ lower := list.Data.Marker == 'i'
+ upper := list.Data.Marker == 'I'
+ if !lower && !upper {
+ return false
+ }
+
+ if lower {
+ if list.Data.MarkerAmbiguous && newItem.Marker == 'a' && !isRomanLowerStart(newItem.MarkerFirstChar) {
+ startNum := int(list.Data.MarkerFirstChar - 'a' + 1)
+ p.events[list.Data.OpenListEventIdx].End = int32('a')
+ p.events[list.Data.OpenListEventIdx+1].End = int32(startNum)
+ list.Data.Marker = 'a'
+ list.Data.MarkerAmbiguous = false
+ return true
+ }
+ if !list.Data.MarkerAmbiguous && newItem.Marker == 'a' && !isRomanLowerStart(newItem.MarkerFirstChar) {
+ return false
+ }
+ if !list.Data.MarkerAmbiguous && newItem.Marker == 'a' && isRomanLowerStart(newItem.MarkerFirstChar) {
+ if parseRoman([]byte{newItem.MarkerFirstChar}) == list.Data.NextNumber {
+ list.Data.NextNumber++
+ return true
+ }
+ }
+ if !list.Data.MarkerAmbiguous && newItem.Marker == 'i' && newItem.MarkerAmbiguous {
+ if newItem.NextNumber == list.Data.NextNumber {
+ list.Data.NextNumber++
+ return true
+ }
+ }
+ if !list.Data.MarkerAmbiguous && newItem.Marker == 'a' && newItem.MarkerAmbiguous && isRomanLowerStart(newItem.MarkerFirstChar) {
+ if parseRoman([]byte{newItem.MarkerFirstChar}) == list.Data.NextNumber {
+ list.Data.NextNumber++
+ return true
+ }
+ }
+ }
+
+ if upper {
+ if list.Data.MarkerAmbiguous && newItem.Marker == 'A' && !isRomanUpperStart(newItem.MarkerFirstChar) {
+ startNum := int(list.Data.MarkerFirstChar - 'A' + 1)
+ p.events[list.Data.OpenListEventIdx].End = int32('A')
+ p.events[list.Data.OpenListEventIdx+1].End = int32(startNum)
+ list.Data.Marker = 'A'
+ list.Data.MarkerAmbiguous = false
+ return true
+ }
+ if !list.Data.MarkerAmbiguous && newItem.Marker == 'A' && isRomanUpperStart(newItem.MarkerFirstChar) {
+ if parseRoman([]byte{newItem.MarkerFirstChar}) == list.Data.NextNumber {
+ list.Data.NextNumber++
+ return true
+ }
+ }
+ if !list.Data.MarkerAmbiguous && newItem.Marker == 'I' && newItem.MarkerAmbiguous {
+ if newItem.NextNumber == list.Data.NextNumber {
+ list.Data.NextNumber++
+ return true
+ }
+ }
+ if !list.Data.MarkerAmbiguous && newItem.Marker == 'A' && newItem.MarkerAmbiguous && isRomanUpperStart(newItem.MarkerFirstChar) {
+ if parseRoman([]byte{newItem.MarkerFirstChar}) == list.Data.NextNumber {
+ list.Data.NextNumber++
+ return true
+ }
+ }
+ }
+ return false
+}
+
+func (p *BlockParser) openList(start int32, data ContainerData) {
+ data.OpenListEventIdx = int32(len(p.events))
+ p.addEvent(start, int32(data.Marker), EvOpenList)
+ p.addEvent(start, int32(data.NextNumber), EvNone)
+ p.stack = append(p.stack, ActiveContainer{Type: ContainerList, Start: start, Data: data})
+ p.stack[len(p.stack)-1].Data.NextNumber++
+}
diff --git a/scripts/mkman/djot/inline.go b/scripts/mkman/djot/inline.go
@@ -0,0 +1,918 @@
+package djot
+
+type Opener struct {
+ MatchIndex int32
+ Start int32
+ Type EventType
+ Char byte
+ Explicit bool
+}
+
+type InlineParser struct {
+ source []byte
+ events []Event
+ stack []Opener
+}
+
+func NewInlineParser(source []byte) *InlineParser {
+ return &InlineParser{
+ source: source,
+ events: make([]Event, 0, 256),
+ stack: make([]Opener, 0, 16),
+ }
+}
+
+func (p *InlineParser) Reset() {
+ p.stack = p.stack[:0]
+}
+
+func (p *InlineParser) Parse(blockEvents []Event) []Event {
+ var textEvents []Event
+ for i := 0; i < len(blockEvents); i++ {
+ ev := blockEvents[i]
+ if ev.Type == EvText || ev.Type == EvSoftBreak || ev.Type == EvHardBreak {
+ textEvents = append(textEvents, ev)
+ } else {
+ if len(textEvents) > 0 {
+ p.parseInlineBlock(textEvents)
+ textEvents = textEvents[:0]
+ }
+ if ev.Type == EvClosePara || ev.Type == EvCloseHeading || ev.Type == EvCloseCaption || ev.Type == EvCloseListItem || ev.Type == EvCloseCell {
+ p.Trim()
+ }
+ p.events = append(p.events, ev)
+ p.Reset()
+ }
+ }
+ if len(textEvents) > 0 {
+ p.parseInlineBlock(textEvents)
+ }
+
+ return p.events
+}
+
+func (p *InlineParser) Trim() {
+ if len(p.events) == 0 {
+ return
+ }
+ i := len(p.events) - 1
+ if p.events[i].Type == EvSoftBreak || p.events[i].Type == EvHardBreak {
+ p.events = p.events[:i]
+ i--
+ if i >= 0 && p.events[i].Type == EvStr {
+ end := p.events[i].End
+ start := p.events[i].Start
+ for end >= start && (p.source[end] == ' ' || p.source[end] == '\t') {
+ end--
+ }
+ if end < start {
+ p.events = p.events[:i]
+ } else {
+ p.events[i].End = end
+ }
+ }
+ }
+}
+
+func (p *InlineParser) findNextSpecialAhead(pos int32, end int32) int32 {
+ for i := pos; i <= end; i++ {
+ if isSpecial(p.source[i]) || p.source[i] == '{' {
+ return i
+ }
+ }
+ return end + 1
+}
+
+func (p *InlineParser) parseInlineBlock(textEvents []Event) {
+ if len(textEvents) == 0 {
+ return
+ }
+
+ blockEnd := textEvents[len(textEvents)-1].End
+
+ evIdx := 0
+ for evIdx < len(textEvents) {
+ ev := textEvents[evIdx]
+ if ev.Type == EvSoftBreak {
+ p.addEvent(ev.Start, ev.End, EvSoftBreak)
+ evIdx++
+ continue
+ }
+ if ev.Type == EvHardBreak {
+ p.addEvent(ev.Start, ev.End, EvHardBreak)
+ evIdx++
+ continue
+ }
+
+ start := ev.Start
+ end := ev.End
+ pos := start
+
+ for pos <= end {
+ if pos >= int32(len(p.source)) {
+ break
+ }
+
+ b := p.source[pos]
+
+ if !isSpecial(b) && b != '{' {
+ next := p.findNextSpecialAhead(pos+1, end)
+ p.addEvent(pos, next-1, EvStr)
+ pos = next
+ continue
+ }
+
+ if b == '{' {
+ if pos+1 <= end {
+ next := p.source[pos+1]
+ if next == '_' || next == '*' || next == '~' || next == '^' || next == '-' || next == '+' || next == '=' || next == '\'' || next == '"' {
+ p.addEvent(pos, pos, EvOpenInlineAttributes)
+ newPos := p.handleEmphasis(next, pos+1, end)
+ pos = newPos
+ continue
+ }
+ }
+
+ attrEvents, nextPos, ok := ParseAttributes(p.source, pos, blockEnd+1)
+ if ok {
+ p.handleAttributeAttachment(pos, nextPos, attrEvents)
+ pos = nextPos + 1
+ for evIdx < len(textEvents) && pos > textEvents[evIdx].End {
+ evIdx++
+ }
+ if evIdx < len(textEvents) && pos >= textEvents[evIdx].Start {
+ end = textEvents[evIdx].End
+ start = pos
+ }
+ continue
+ } else {
+ p.addEvent(pos, pos, EvStr)
+ pos++
+ continue
+ }
+ }
+
+ switch b {
+ case '\\':
+ if pos+1 <= end {
+ next := p.source[pos+1]
+ if next == ' ' {
+ p.addEvent(pos, pos+1, EvNonBreakingSpace)
+ pos += 2
+ } else if isPunctuation(next) {
+ p.addEvent(pos, pos+1, EvEscape)
+ pos += 2
+ } else {
+ p.addEvent(pos, pos, EvStr)
+ pos++
+ }
+ } else {
+ p.addEvent(pos, pos, EvStr)
+ pos++
+ }
+ case '*':
+ pos = p.handleEmphasis(b, pos, end)
+ case '_':
+ pos = p.handleEmphasis(b, pos, end)
+ case '^':
+ pos = p.handleEmphasis(b, pos, end)
+ case '~':
+ pos = p.handleEmphasis(b, pos, end)
+ case '"':
+ p.handleDoubleQuote(pos, end)
+ pos++
+ case '\'':
+ pos = p.handleSingleQuote(pos, end)
+ case '[':
+ if pos+1 <= blockEnd && p.source[pos+1] == '^' {
+ closeIdx := p.findClosingBracketAhead(pos, textEvents, evIdx)
+ if closeIdx != -1 {
+ p.addEvent(pos, closeIdx, EvFootnoteReference)
+ pos = closeIdx + 1
+ for evIdx < len(textEvents) && pos > textEvents[evIdx].End {
+ evIdx++
+ }
+ if evIdx < len(textEvents) && pos >= textEvents[evIdx].Start {
+ end = textEvents[evIdx].End
+ start = pos
+ }
+ continue
+ }
+ }
+ p.addOpener(b, pos, EvOpenLinkText, false)
+ pos++
+ case '!':
+ if pos+1 <= end && p.source[pos+1] == '[' {
+ p.addOpener('[', pos+1, EvOpenImageText, false)
+ pos += 2
+ } else {
+ p.addEvent(pos, pos, EvStr)
+ pos++
+ }
+ case ']':
+ pos = p.handleCloseBracketAhead(pos, textEvents, evIdx, blockEnd)
+ for evIdx < len(textEvents) && pos > textEvents[evIdx].End {
+ evIdx++
+ }
+ if evIdx < len(textEvents) && pos >= textEvents[evIdx].Start {
+ end = textEvents[evIdx].End
+ start = pos
+ }
+ case '(':
+ if len(p.events) > 0 && p.events[len(p.events)-1].Type == EvCloseLinkText {
+ destEnd := p.findClosingParenAhead(pos+1, textEvents, evIdx)
+ if destEnd != -1 {
+ p.addEvent(pos+1, destEnd-1, EvOpenDestination)
+ p.addEvent(pos+1, destEnd-1, EvCloseDestination)
+ pos = destEnd + 1
+ for evIdx < len(textEvents) && pos > textEvents[evIdx].End {
+ evIdx++
+ }
+ if evIdx < len(textEvents) && pos >= textEvents[evIdx].Start {
+ end = textEvents[evIdx].End
+ start = pos
+ }
+ continue
+ }
+ }
+ p.addEvent(pos, pos, EvStr)
+ pos++
+ case '`':
+ pos = p.handleVerbatimAhead(pos, textEvents, evIdx)
+ for evIdx < len(textEvents) && pos > textEvents[evIdx].End {
+ evIdx++
+ }
+ if evIdx < len(textEvents) && pos >= textEvents[evIdx].Start {
+ end = textEvents[evIdx].End
+ start = pos
+ }
+
+ if pos < blockEnd && p.source[pos] == '{' {
+ attrEvents, nextPos, ok := ParseAttributes(p.source, pos, blockEnd+1)
+ if ok {
+ isRaw := false
+ if len(attrEvents) == 1 {
+ ae := attrEvents[0]
+ if ae.Type == EvAttrKey && p.source[ae.Start] == '=' {
+ isRaw = true
+ }
+ }
+
+ if isRaw {
+ p.events[len(p.events)-2].Type = EvRawInline
+ p.events[len(p.events)-1].Type = EvRawInline
+ p.handleAttributeAttachment(pos, nextPos, attrEvents)
+ pos = nextPos + 1
+ }
+
+ for evIdx < len(textEvents) && pos > textEvents[evIdx].End {
+ evIdx++
+ }
+ if evIdx < len(textEvents) && pos >= textEvents[evIdx].Start {
+ end = textEvents[evIdx].End
+ start = pos
+ }
+ }
+ }
+ case '.':
+ if pos+2 <= end && p.source[pos+1] == '.' && p.source[pos+2] == '.' {
+ p.addEvent(pos, pos+2, EvSmartPunctuation)
+ pos += 3
+ } else {
+ p.addEvent(pos, pos, EvStr)
+ pos++
+ }
+ case '-':
+ if (pos > 0 && p.source[pos-1] == '{') || (pos+1 <= end && p.source[pos+1] == '}') {
+ pos = p.handleEmphasis(b, pos, end)
+ continue
+ }
+
+ count := int32(0)
+ for pos+count <= end && p.source[pos+count] == '-' {
+ count++
+ }
+
+ if pos+count <= end && p.source[pos+count] == '}' {
+ if count > 1 {
+ count--
+ } else {
+ pos = p.handleEmphasis(b, pos, end)
+ continue
+ }
+ }
+
+ if count == 1 {
+ p.addEvent(pos, pos, EvStr)
+ pos++
+ } else {
+ emd := int32(0)
+ end2 := int32(0)
+ if count%3 == 0 {
+ emd = count / 3
+ end2 = 0
+ } else if count%2 == 0 {
+ emd = 0
+ end2 = count / 2
+ } else if count%3 == 2 {
+ emd = count / 3
+ end2 = 1
+ } else {
+ emd = (count - 4) / 3
+ end2 = 2
+ }
+ p2 := pos
+ for i := int32(0); i < emd; i++ {
+ p.addEvent(p2, p2+2, EvSmartPunctuation)
+ p2 += 3
+ }
+ for i := int32(0); i < end2; i++ {
+ p.addEvent(p2, p2+1, EvSmartPunctuation)
+ p2 += 2
+ }
+ pos = p2
+ }
+ case '+':
+ if (pos > 0 && p.source[pos-1] == '{') || (pos+1 <= end && p.source[pos+1] == '}') {
+ pos = p.handleEmphasis(b, pos, end)
+ continue
+ } else {
+ p.addEvent(pos, pos, EvStr)
+ pos++
+ }
+ case '=':
+ if (pos > 0 && p.source[pos-1] == '{') || (pos+1 <= end && p.source[pos+1] == '}') {
+ pos = p.handleEmphasis(b, pos, end)
+ continue
+ } else {
+ p.addEvent(pos, pos, EvStr)
+ pos++
+ }
+ case '<':
+ pos = p.handleAutolink(pos, end)
+ case ':':
+ pos = p.handleEmoji(pos, end)
+ case '$':
+ count := int32(0)
+ for pos+count <= end && p.source[pos+count] == '$' {
+ count++
+ }
+ if pos+count <= end && p.source[pos+count] == '`' {
+ pos = p.handleMathVerbatim(pos, pos+count, end, textEvents, evIdx)
+ for evIdx < len(textEvents) && pos > textEvents[evIdx].End {
+ evIdx++
+ }
+ if evIdx < len(textEvents) && pos >= textEvents[evIdx].Start {
+ end = textEvents[evIdx].End
+ start = pos
+ }
+ } else {
+ pos = p.handleMath(pos, end)
+ }
+ default:
+ p.addEvent(pos, pos, EvStr)
+ pos++
+ }
+ start = pos
+ }
+ evIdx++
+ }
+
+ for _, opener := range p.stack {
+ if opener.MatchIndex != -1 && (opener.Char == '\'' || opener.Char == '"') {
+ p.events[opener.MatchIndex].Type = EvSmartPunctuation
+ }
+ }
+}
+
+func (p *InlineParser) findClosingParenAhead(start int32, textEvents []Event, startEvIdx int) int32 {
+ count := 0
+ for j := startEvIdx; j < len(textEvents); j++ {
+ ev := textEvents[j]
+ if ev.Type == EvSoftBreak {
+ continue
+ }
+ s := ev.Start
+ if j == startEvIdx {
+ s = start
+ }
+ for i := s; i <= ev.End; i++ {
+ if p.source[i] == '(' {
+ count++
+ } else if p.source[i] == ')' {
+ count--
+ if count == 0 {
+ return i
+ }
+ }
+ }
+ }
+ return -1
+}
+
+func (p *InlineParser) findClosingBracketAhead(start int32, textEvents []Event, startEvIdx int) int32 {
+ count := 0
+ for j := startEvIdx; j < len(textEvents); j++ {
+ ev := textEvents[j]
+ if ev.Type == EvSoftBreak {
+ continue
+ }
+ s := ev.Start
+ if j == startEvIdx {
+ s = start
+ }
+ for i := s; i <= ev.End; i++ {
+ if p.source[i] == '[' {
+ count++
+ } else if p.source[i] == ']' {
+ count--
+ if count == 0 {
+ return i
+ }
+ }
+ }
+ }
+ return -1
+}
+
+func (p *InlineParser) handleCloseBracketAhead(pos int32, textEvents []Event, evIdx int, blockEnd int32) int32 {
+ for i := len(p.stack) - 1; i >= 0; i-- {
+ opener := p.stack[i]
+ if opener.MatchIndex != -1 && opener.Char == '[' {
+ next := pos + 1
+ if next <= blockEnd && p.source[next] == '(' {
+ closeIdx := p.findClosingParenAhead(next, textEvents, evIdx)
+ if closeIdx != -1 {
+ p.events[opener.MatchIndex].Type = opener.Type
+ p.addEvent(next+1, closeIdx-1, EvOpenDestination)
+ p.addEvent(next+1, closeIdx-1, EvCloseDestination)
+ p.addEvent(pos, pos, closeTypeFor(opener.Type))
+ p.stack = p.stack[:i]
+ return closeIdx + 1
+ }
+ }
+
+ if next <= blockEnd && p.source[next] == '[' {
+ closeIdx := p.findClosingBracketAhead(next, textEvents, evIdx)
+ if closeIdx != -1 {
+ p.events[opener.MatchIndex].Type = opener.Type
+ p.addEvent(next+1, closeIdx-1, EvOpenReference)
+ p.addEvent(next+1, closeIdx-1, EvCloseReference)
+ p.addEvent(pos, pos, closeTypeFor(opener.Type))
+ p.stack = p.stack[:i]
+ return closeIdx + 1
+ }
+ }
+
+ if next <= blockEnd && p.source[next] == '{' {
+ attrEvents, attrEndPos, ok := ParseAttributes(p.source, next, blockEnd+1)
+ if ok {
+ p.events[opener.MatchIndex].Type = EvOpenSpan
+ p.addEvent(pos, pos, EvCloseSpan)
+ p.addEvent(next, next, EvOpenInlineAttributes)
+ p.events = append(p.events, attrEvents...)
+ p.addEvent(attrEndPos, attrEndPos, EvCloseAttributes)
+ p.stack = p.stack[:i]
+ return attrEndPos + 1
+ }
+ }
+
+ p.events[opener.MatchIndex].Type = EvStr
+ p.addEvent(pos, pos, EvStr)
+ p.stack = p.stack[:i]
+ return pos + 1
+ }
+ }
+ p.addEvent(pos, pos, EvStr)
+ return pos + 1
+}
+
+func (p *InlineParser) handleMathVerbatim(dollarPos, backtickPos, end int32, textEvents []Event, startEvIdx int) int32 {
+ count := int32(0)
+ pos := backtickPos
+ ev := textEvents[startEvIdx]
+ for pos <= ev.End && p.source[pos] == '`' {
+ count++
+ pos++
+ }
+
+ contentStart := pos
+
+ for j := startEvIdx; j < len(textEvents); j++ {
+ tev := textEvents[j]
+ if tev.Type == EvSoftBreak {
+ continue
+ }
+
+ s := tev.Start
+ if j == startEvIdx {
+ s = pos
+ }
+
+ for i := s; i <= tev.End; i++ {
+ if p.source[i] == '`' {
+ c := int32(0)
+ for i+c <= tev.End && p.source[i+c] == '`' {
+ c++
+ }
+ if c == count {
+ contentEnd := i - 1
+ dollarCount := backtickPos - dollarPos
+ etype := EvInlineMath
+ if dollarCount == 2 {
+ etype = EvDisplayMath
+ }
+ p.addEvent(contentStart, contentEnd, etype)
+ return i + count
+ }
+ i += c - 1
+ }
+ }
+ }
+
+ lastEv := textEvents[len(textEvents)-1]
+ dollarCount := backtickPos - dollarPos
+ etype := EvInlineMath
+ if dollarCount == 2 {
+ etype = EvDisplayMath
+ }
+ p.addEvent(contentStart, lastEv.End, etype)
+ return lastEv.End + 1
+}
+
+func (p *InlineParser) handleVerbatimAhead(pos int32, textEvents []Event, startEvIdx int) int32 {
+ count := int32(0)
+
+ ev := textEvents[startEvIdx]
+ for pos <= ev.End && p.source[pos] == '`' {
+ count++
+ pos++
+ }
+
+ contentStart := pos
+
+ for j := startEvIdx; j < len(textEvents); j++ {
+ tev := textEvents[j]
+ if tev.Type == EvSoftBreak {
+ continue
+ }
+
+ s := tev.Start
+ if j == startEvIdx {
+ s = pos
+ }
+
+ for i := s; i <= tev.End; i++ {
+ if p.source[i] == '`' {
+ c := int32(0)
+ for i+c <= tev.End && p.source[i+c] == '`' {
+ c++
+ }
+ if c == count {
+ contentEnd := i - 1
+
+ if count == 1 && contentEnd-contentStart+1 >= 2 && p.source[contentStart] == ' ' && p.source[contentEnd] == ' ' {
+ allSpaces := true
+ for k := contentStart; k <= contentEnd; k++ {
+ if p.source[k] != ' ' {
+ allSpaces = false
+ break
+ }
+ }
+ if !allSpaces {
+ contentStart++
+ contentEnd--
+ }
+ }
+
+ p.addEvent(contentStart, contentEnd, EvOpenVerbatim)
+ p.addEvent(contentStart, contentEnd, EvCloseVerbatim)
+ return i + count
+ }
+ i += c - 1
+ }
+ }
+ }
+
+ lastEv := textEvents[len(textEvents)-1]
+ p.addEvent(contentStart, lastEv.End, EvOpenVerbatim)
+ p.addEvent(contentStart, lastEv.End, EvCloseVerbatim)
+ return lastEv.End + 1
+}
+
+func (p *InlineParser) handleAttributeAttachment(braceStart, braceEnd int32, attrEvents []Event) {
+ p.addEvent(braceStart, braceStart, EvOpenInlineAttributes)
+ p.events = append(p.events, attrEvents...)
+ p.addEvent(braceEnd, braceEnd, EvCloseAttributes)
+}
+
+func isSpecial(b byte) bool {
+ switch b {
+ case '\\', '`', '_', '*', '~', '^', '$', '[', ']', '!', '<', '.', '-', ':', '"', '\'', '+', '=':
+ return true
+ }
+ return false
+}
+
+func closeTypeFor(openType EventType) EventType {
+ if openType == EvOpenLinkText {
+ return EvCloseLinkText
+ }
+ return EvCloseImageText
+}
+
+func (p *InlineParser) addEvent(start, end int32, etype EventType) int32 {
+ p.events = append(p.events, Event{Start: start, End: end, Type: etype})
+ return int32(len(p.events) - 1)
+}
+
+func (p *InlineParser) addOpener(char byte, pos int32, etype EventType, explicit bool) {
+ idx := p.addEvent(pos, pos, etype)
+ p.stack = append(p.stack, Opener{
+ MatchIndex: idx,
+ Start: pos,
+ Type: etype,
+ Char: char,
+ Explicit: explicit,
+ })
+}
+
+func (p *InlineParser) handleEmphasis(b byte, pos int32, end int32) int32 {
+ lastMatch := Event{Type: EvNone}
+ if len(p.events) > 0 {
+ lastMatch = p.events[len(p.events)-1]
+ }
+
+ isExplicitOpen := lastMatch.Type == EvOpenInlineAttributes && lastMatch.Start == pos-1
+ isExplicitClose := pos+1 <= end && p.source[pos+1] == '}'
+
+ canOpen := pos+1 <= end && !isSpace(p.source[pos+1])
+ canClose := pos-1 >= 0 && !isSpace(p.source[pos-1])
+
+ if isExplicitOpen {
+ canOpen = true
+ canClose = false
+ }
+ if isExplicitClose {
+ canClose = true
+ canOpen = false
+ }
+
+ if canClose {
+ var openerIdx = -1
+ for i := len(p.stack) - 1; i >= 0; i-- {
+ if p.stack[i].MatchIndex != -1 && p.stack[i].Char == b && p.stack[i].Explicit == isExplicitClose && p.stack[i].Type != EvOpenLinkText && p.stack[i].Type != EvOpenImageText {
+ openerIdx = i
+ break
+ }
+ }
+
+ if openerIdx != -1 {
+ opener := p.stack[openerIdx]
+ if opener.Start != pos-1 {
+ p.handleCloseEmphasisAt(openerIdx, pos, isExplicitClose)
+ if isExplicitClose {
+ return pos + 2
+ }
+ return pos + 1
+ }
+ }
+ }
+
+ if canOpen {
+ startPos := pos
+ if isExplicitOpen {
+ startPos = pos - 1
+ p.events = p.events[:len(p.events)-1]
+ p.addOpener(b, startPos, EvStr, isExplicitOpen)
+ p.addEvent(pos, pos, EvStr)
+ } else {
+ p.addOpener(b, startPos, EvStr, isExplicitOpen)
+ }
+ return pos + 1
+ } else {
+ p.addEvent(pos, pos, EvStr)
+ if isExplicitClose {
+ p.addEvent(pos+1, pos+1, EvStr)
+ return pos + 2
+ }
+ return pos + 1
+ }
+}
+
+func (p *InlineParser) handleCloseEmphasisAt(openerIdx int, pos int32, explicit bool) {
+ opener := p.stack[openerIdx]
+ var b = opener.Char
+ var openType, closeType EventType
+ switch b {
+ case '_':
+ openType, closeType = EvOpenEmph, EvCloseEmph
+ case '*':
+ openType, closeType = EvOpenStrong, EvCloseStrong
+ case '~':
+ openType, closeType = EvOpenSubscript, EvCloseSubscript
+ case '^':
+ openType, closeType = EvOpenSuperscript, EvCloseSuperscript
+ case '-':
+ openType, closeType = EvOpenDelete, EvCloseDelete
+ case '+':
+ openType, closeType = EvOpenInsert, EvCloseInsert
+ case '=':
+ openType, closeType = EvOpenMark, EvCloseMark
+ case '\'':
+ openType, closeType = EvOpenSingleQuoted, EvCloseSingleQuoted
+ case '"':
+ openType, closeType = EvOpenDoubleQuoted, EvCloseDoubleQuoted
+ }
+ p.events[opener.MatchIndex].Type = openType
+ p.events[opener.MatchIndex].Start = opener.Start
+
+ if opener.Explicit {
+ if opener.MatchIndex+1 < int32(len(p.events)) && p.events[opener.MatchIndex+1].Start == opener.Start+1 && p.events[opener.MatchIndex+1].Type == EvStr {
+ p.events[opener.MatchIndex+1].Type = EvNone
+ }
+ }
+
+ endPos := pos
+ if explicit {
+ endPos = pos + 1
+ }
+ p.addEvent(pos, endPos, closeType)
+
+ p.clearOpeners(opener.Start, pos)
+ p.stack = p.stack[:openerIdx]
+}
+
+func (p *InlineParser) clearOpeners(start, end int32) {
+ for i := range p.stack {
+ if p.stack[i].Start > start && p.stack[i].Start < end {
+ if p.stack[i].MatchIndex != -1 {
+ p.events[p.stack[i].MatchIndex].Type = EvStr
+ p.stack[i].MatchIndex = -1
+ }
+ }
+ }
+}
+
+func (p *InlineParser) handleMath(pos, end int32) int32 {
+ start := pos
+ pos++
+ count := int32(1)
+ if pos <= end && p.source[pos] == '$' {
+ count = 2
+ pos++
+ }
+ for pos <= end {
+ if p.source[pos] == '$' {
+ c := int32(0)
+ for pos <= end && p.source[pos] == '$' {
+ c++
+ pos++
+ }
+ if c == count {
+ etype := EvInlineMath
+ if count == 2 {
+ etype = EvDisplayMath
+ }
+ p.addEvent(start+count, pos-count-1, etype)
+ return pos
+ }
+ } else {
+ pos++
+ }
+ }
+ p.addEvent(start, start+count-1, EvStr)
+ return start + count
+}
+
+func (p *InlineParser) handleAutolink(pos, end int32) int32 {
+ start := pos
+ hasAt := false
+ hasSlash := false
+ for pos <= end && p.source[pos] != '>' && p.source[pos] != ' ' {
+ if p.source[pos] == '@' {
+ hasAt = true
+ } else if p.source[pos] == '/' {
+ hasSlash = true
+ }
+ pos++
+ }
+ if pos <= end && p.source[pos] == '>' {
+ etype := EvUrl
+ if hasAt && !hasSlash {
+ etype = EvEmail
+ }
+ p.addEvent(start+1, pos-1, etype)
+ return pos + 1
+ }
+ p.addEvent(start, start, EvStr)
+ return start + 1
+}
+
+func (p *InlineParser) handleEmoji(pos, end int32) int32 {
+ start := pos
+ pos++
+ for pos <= end && isAlphaLower(p.source[pos]) {
+ pos++
+ }
+ if pos <= end && p.source[pos] == ':' {
+ p.addEvent(start+1, pos-1, EvSymb)
+ return pos + 1
+ }
+ p.addEvent(start, start, EvStr)
+ return start + 1
+}
+
+func (p *InlineParser) handleDoubleQuote(pos, end int32) {
+ for i := len(p.stack) - 1; i >= 0; i-- {
+ opener := p.stack[i]
+ if opener.MatchIndex != -1 && opener.Char == '"' {
+ p.events[opener.MatchIndex].Type = EvOpenDoubleQuoted
+ p.addEvent(pos, pos, EvCloseDoubleQuoted)
+ p.stack = p.stack[:i]
+ return
+ }
+ }
+ p.addOpener('"', pos, EvStr, false)
+}
+
+func (p *InlineParser) handleSingleQuote(pos, end int32) int32 {
+ isExplicitClose := pos+1 <= end && p.source[pos+1] == '}'
+
+ if isExplicitClose {
+ for i := len(p.stack) - 1; i >= 0; i-- {
+ if p.stack[i].MatchIndex != -1 && p.stack[i].Char == '\'' && p.stack[i].Explicit {
+ opener := p.stack[i]
+ p.events[opener.MatchIndex].Type = EvOpenSingleQuoted
+ p.addEvent(pos, pos, EvCloseSingleQuoted)
+ if opener.MatchIndex+1 < int32(len(p.events)) && p.events[opener.MatchIndex+1].Start == opener.Start+1 && p.events[opener.MatchIndex+1].Type == EvStr {
+ p.events[opener.MatchIndex+1].Type = EvNone
+ }
+ p.stack = p.stack[:i]
+ return pos + 2
+ }
+ }
+ }
+
+ prevIsCloser := pos > 0 && (isAlnum(p.source[pos-1]) || isClosingPunct(p.source[pos-1]))
+ nextDigit := pos+1 <= end && isDigit(p.source[pos+1])
+
+ canClose := pos > 0 && !isSpace(p.source[pos-1])
+ canOpen := pos+1 <= end && !isSpace(p.source[pos+1]) &&
+ (pos == 0 || isOpeningContext(p.source[pos-1]))
+
+ if prevIsCloser || nextDigit {
+ for i := len(p.stack) - 1; i >= 0; i-- {
+ if p.stack[i].MatchIndex != -1 && p.stack[i].Char == '\'' {
+ p.events[p.stack[i].MatchIndex].Type = EvOpenSingleQuoted
+ p.addEvent(pos, pos, EvCloseSingleQuoted)
+ p.stack = p.stack[:i]
+ return pos + 1
+ }
+ }
+ p.addEvent(pos, pos, EvSmartPunctuation)
+ return pos + 1
+ }
+
+ if canClose && !canOpen {
+ for i := len(p.stack) - 1; i >= 0; i-- {
+ opener := p.stack[i]
+ if opener.MatchIndex != -1 && opener.Char == '\'' {
+ p.events[opener.MatchIndex].Type = EvOpenSingleQuoted
+ p.addEvent(pos, pos, EvCloseSingleQuoted)
+ p.stack = p.stack[:i]
+ return pos + 1
+ }
+ }
+ }
+
+ if canOpen {
+ p.addOpener('\'', pos, EvStr, false)
+ } else {
+ p.addEvent(pos, pos, EvSmartPunctuation)
+ }
+ return pos + 1
+}
+
+func isAlnum(b byte) bool {
+ return (b >= 'a' && b <= 'z') || (b >= 'A' && b <= 'Z') || (b >= '0' && b <= '9')
+}
+
+func isClosingPunct(b byte) bool {
+ return b == ')' || b == ']' || b == '}' ||
+ b == '.' || b == ',' || b == ';' || b == ':' ||
+ b == '!' || b == '?'
+}
+
+func isOpeningContext(b byte) bool {
+ return b == ' ' || b == '\t' || b == '\n' || b == '\r' ||
+ b == '"' || b == '\'' || b == '-' || b == '(' || b == '['
+}
+
+func isPunctuation(b byte) bool {
+ switch b {
+ case '!', '"', '#', '$', '%', '&', '\'', '(', ')', '*', '+', ',', '-', '.', '/', ':', ';', '<', '=', '>', '?', '@', '[', '\\', ']', '^', '_', '`', '{', '|', '}', '~':
+ return true
+ }
+ return false
+}
diff --git a/scripts/mkman/djot/marker.go b/scripts/mkman/djot/marker.go
@@ -0,0 +1,306 @@
+package djot
+
+func isThematicBreak(source []byte, start, end int32) bool {
+ count := 0
+ for i := start; i < end; i++ {
+ b := source[i]
+ if b == '-' || b == '*' {
+ count++
+ } else if b == ' ' || b == '\t' {
+ continue
+ } else {
+ return false
+ }
+ }
+ return count >= 3
+}
+
+func parseListMarker(source []byte, pos, end int32) (int32, ContainerData, bool) {
+ if pos >= end {
+ return pos, ContainerData{}, false
+ }
+
+ startPos := pos
+ b := source[pos]
+
+ if b == '-' || b == '+' || b == '*' {
+ return checkListItemEnd(source, startPos, pos, end, b, false, 0, 0)
+ }
+
+ if b == ':' {
+ return checkListItemEnd(source, startPos, pos, end, ':', false, 0, 0)
+ }
+
+ if isDigit(b) {
+ p := pos
+ for p < end && isDigit(source[p]) {
+ p++
+ }
+ if p < end && (source[p] == '.' || source[p] == ')') {
+ num := parseDecimal(source[pos:p])
+ return checkListItemEnd(source, startPos, p, end, '1', true, num, source[p])
+ }
+ }
+
+ if isRomanLowerStart(b) {
+ p := pos
+ for p < end && isRomanLower(source[p]) {
+ p++
+ }
+ if p < end && (source[p] == '.' || source[p] == ')') {
+ num := parseRoman(source[pos:p])
+ newPos, data, ok := checkListItemEnd(source, startPos, p, end, 'i', true, num, source[p])
+ if ok && p == pos+1 {
+ data.MarkerAmbiguous = true
+ }
+ if ok {
+ data.MarkerFirstChar = b
+ }
+ return newPos, data, ok
+ }
+ }
+
+ if isAlphaLower(b) {
+ if pos+1 < end && (source[pos+1] == '.' || source[pos+1] == ')') {
+ num := int(b - 'a' + 1)
+ newPos, data, ok := checkListItemEnd(source, startPos, pos+1, end, 'a', true, num, source[pos+1])
+ if ok {
+ data.MarkerFirstChar = b
+ }
+ return newPos, data, ok
+ }
+ }
+
+ if isRomanUpperStart(b) {
+ p := pos
+ for p < end && isRomanUpper(source[p]) {
+ p++
+ }
+ if p < end && (source[p] == '.' || source[p] == ')') {
+ num := parseRoman(source[pos:p])
+ newPos, data, ok := checkListItemEnd(source, startPos, p, end, 'I', true, num, source[p])
+ if ok && p == pos+1 {
+ data.MarkerAmbiguous = true
+ }
+ if ok {
+ data.MarkerFirstChar = b
+ }
+ return newPos, data, ok
+ }
+ }
+
+ if isAlphaUpper(b) {
+ if pos+1 < end && (source[pos+1] == '.' || source[pos+1] == ')') {
+ num := int(b - 'A' + 1)
+ newPos, data, ok := checkListItemEnd(source, startPos, pos+1, end, 'A', true, num, source[pos+1])
+ if ok {
+ data.MarkerFirstChar = b
+ }
+ return newPos, data, ok
+ }
+ }
+
+ if b == '(' {
+ p := pos + 1
+ if p < end {
+ b2 := source[p]
+
+ if isDigit(b2) {
+ start := p
+ for p < end && isDigit(source[p]) {
+ p++
+ }
+ if p < end && source[p] == ')' {
+ num := parseDecimal(source[start:p])
+ newPos, data, ok := checkListItemEnd(source, startPos, p, end, '1', true, num, 'X')
+ if ok {
+ data.MarkerFirstChar = b2
+ }
+ return newPos, data, ok
+ }
+ }
+
+ if isAlphaLower(b2) && p+1 < end && source[p+1] == ')' {
+ num := int(b2 - 'a' + 1)
+ newPos, data, ok := checkListItemEnd(source, startPos, p+1, end, 'a', true, num, 'X')
+ if ok {
+ data.MarkerFirstChar = b2
+ if isRomanLowerStart(b2) {
+ data.MarkerAmbiguous = true
+ }
+ }
+ return newPos, data, ok
+ }
+ if isAlphaUpper(b2) && p+1 < end && source[p+1] == ')' {
+ num := int(b2 - 'A' + 1)
+ newPos, data, ok := checkListItemEnd(source, startPos, p+1, end, 'A', true, num, 'X')
+ if ok {
+ data.MarkerFirstChar = b2
+ if isRomanUpperStart(b2) {
+ data.MarkerAmbiguous = true
+ }
+ }
+ return newPos, data, ok
+ }
+
+ if isRomanLowerStart(b2) {
+ start := p
+ for p < end && isRomanLower(source[p]) {
+ p++
+ }
+ if p < end && source[p] == ')' {
+ if p > start+1 {
+ num := parseRoman(source[start:p])
+ newPos, data, ok := checkListItemEnd(source, startPos, p, end, 'i', true, num, 'X')
+ if ok {
+ data.MarkerFirstChar = b2
+ }
+ return newPos, data, ok
+ }
+ }
+ }
+
+ if isRomanUpperStart(b2) {
+ start := p
+ for p < end && isRomanUpper(source[p]) {
+ p++
+ }
+ if p < end && source[p] == ')' {
+ if p > start+1 {
+ num := parseRoman(source[start:p])
+ newPos, data, ok := checkListItemEnd(source, startPos, p, end, 'I', true, num, 'X')
+ if ok {
+ data.MarkerFirstChar = b2
+ }
+ return newPos, data, ok
+ }
+ }
+ }
+ }
+ }
+
+ return startPos, ContainerData{}, false
+}
+
+func checkListItemEnd(source []byte, start, pos, end int32, style byte, ordered bool, num int, endChar byte) (int32, ContainerData, bool) {
+ if pos+1 == end || source[pos+1] == ' ' || source[pos+1] == '\t' {
+ newPos := pos + 1
+ for newPos < end && (source[newPos] == ' ' || source[newPos] == '\t') {
+ newPos++
+ }
+ indent := newPos - start
+
+ checked := false
+ isTask := false
+ if !ordered && (style == '-' || style == '+' || style == '*') && newPos+3 <= end && source[newPos] == '[' {
+ if source[newPos+1] == ' ' && source[newPos+2] == ']' {
+ isTask = true
+ newPos += 3
+ } else if (source[newPos+1] == 'x' || source[newPos+1] == 'X') && source[newPos+2] == ']' {
+ isTask = true
+ checked = true
+ newPos += 3
+ }
+
+ if isTask {
+ if newPos == end || source[newPos] == ' ' || source[newPos] == '\t' {
+ for newPos < end && (source[newPos] == ' ' || source[newPos] == '\t') {
+ newPos++
+ }
+ indent = newPos - start
+ } else {
+ isTask = false
+ checked = false
+ newPos = pos + 1
+ for newPos < end && (source[newPos] == ' ' || source[newPos] == '\t') {
+ newPos++
+ }
+ indent = newPos - start
+ }
+ }
+ }
+
+ if !ordered && indent == 1 && newPos < end {
+ return start, ContainerData{}, false
+ }
+
+ return newPos, ContainerData{Marker: style, MarkerEnd: endChar, Ordered: ordered, IsTask: isTask, Checked: checked, Tight: true, NextNumber: num}, true
+ }
+ return start, ContainerData{}, false
+}
+
+func parseDecimal(b []byte) int {
+ res := 0
+ for _, c := range b {
+ res = res*10 + int(c-'0')
+ }
+ return res
+}
+
+func parseRoman(b []byte) int {
+ val := func(c byte) int {
+ switch c {
+ case 'i', 'I':
+ return 1
+ case 'v', 'V':
+ return 5
+ case 'x', 'X':
+ return 10
+ case 'l', 'L':
+ return 50
+ case 'c', 'C':
+ return 100
+ case 'd', 'D':
+ return 500
+ case 'm', 'M':
+ return 1000
+ }
+ return 0
+ }
+ res := 0
+ for i := 0; i < len(b); i++ {
+ v := val(b[i])
+ if i+1 < len(b) && val(b[i+1]) > v {
+ res -= v
+ } else {
+ res += v
+ }
+ }
+ return res
+}
+
+func isDigit(b byte) bool {
+ return b >= '0' && b <= '9'
+}
+
+func isAlphaLower(b byte) bool {
+ return b >= 'a' && b <= 'z'
+}
+
+func isAlphaUpper(b byte) bool {
+ return b >= 'A' && b <= 'Z'
+}
+
+func isRomanLowerStart(b byte) bool {
+ switch b {
+ case 'i', 'v', 'x', 'l', 'c', 'd', 'm':
+ return true
+ }
+ return false
+}
+
+func isRomanLower(b byte) bool {
+ return isRomanLowerStart(b)
+}
+
+func isRomanUpperStart(b byte) bool {
+ switch b {
+ case 'I', 'V', 'X', 'L', 'C', 'D', 'M':
+ return true
+ }
+ return false
+}
+
+func isRomanUpper(b byte) bool {
+ return isRomanUpperStart(b)
+}
diff --git a/scripts/mkman/djot/parser.go b/scripts/mkman/djot/parser.go
@@ -0,0 +1,17 @@
+package djot
+
+func Parse(source []byte) *Document {
+ doc := &Document{Source: source}
+ bp := NewBlockParser(source)
+
+ blockEvents := bp.Parse()
+
+ ip := NewInlineParser(source)
+ inlineEvents := ip.Parse(blockEvents)
+
+ as := Assembler{doc: doc}
+ as.Assemble(inlineEvents)
+ doc.Events = inlineEvents
+
+ return doc
+}
diff --git a/scripts/mkman/go.mod b/scripts/mkman/go.mod
@@ -0,0 +1,3 @@
+module aruu/mkman
+
+go 1.21
diff --git a/scripts/mkman/main.go b/scripts/mkman/main.go
@@ -0,0 +1,600 @@
+package main
+
+import (
+ "bufio"
+ "flag"
+ "fmt"
+ "os"
+ "path/filepath"
+ "strings"
+ "time"
+
+ "aruu/mkman/djot"
+)
+
+// Parse config.mk variables and values
+//
+type Config map[string]string
+
+func parseConfigMk(path string) (Config, error) {
+ f, err := os.Open(path)
+ if err != nil {
+ return nil, err
+ }
+ defer f.Close()
+
+ raw := make(Config)
+ sc := bufio.NewScanner(f)
+ for sc.Scan() {
+ line := strings.TrimSpace(sc.Text())
+ if line == "" || strings.HasPrefix(line, "#") {
+ continue
+ }
+ eq := strings.IndexByte(line, '=')
+ if eq < 0 {
+ continue
+ }
+ k := strings.TrimSpace(line[:eq])
+ v := strings.TrimSpace(line[eq+1:])
+ raw[k] = v
+ }
+ if err := sc.Err(); err != nil {
+ return nil, err
+ }
+
+ cfg := make(Config, len(raw))
+ for k, v := range raw {
+ cfg[k] = expandVars(v, raw)
+ }
+ return cfg, nil
+}
+
+func expandVars(s string, env Config) string {
+ for {
+ start := strings.Index(s, "$(")
+ if start < 0 {
+ break
+ }
+ end := strings.Index(s[start:], ")")
+ if end < 0 {
+ break
+ }
+ end += start
+ varname := s[start+2 : end]
+ replacement := ""
+ if v, ok := env[varname]; ok {
+ replacement = v
+ }
+ s = s[:start] + replacement + s[end+1:]
+ }
+ return s
+}
+
+func (cfg Config) isEnabled(key string) bool {
+ return cfg[key] == "1"
+}
+
+// Preprocessor condition stack for nested feature blocks
+//
+type ifFrame struct {
+ active bool
+ seen bool
+}
+
+type ifStack struct {
+ frames []ifFrame
+}
+
+func (s *ifStack) push(active, seen bool) {
+ s.frames = append(s.frames, ifFrame{active: active, seen: seen})
+}
+
+func (s *ifStack) pop() {
+ if len(s.frames) > 0 {
+ s.frames = s.frames[:len(s.frames)-1]
+ }
+}
+
+func (s *ifStack) parentActive() bool {
+ for i := 0; i < len(s.frames)-1; i++ {
+ if !s.frames[i].active {
+ return false
+ }
+ }
+ return true
+}
+
+func (s *ifStack) globallyActive() bool {
+ for _, f := range s.frames {
+ if !f.active {
+ return false
+ }
+ }
+ return true
+}
+
+func (s *ifStack) top() *ifFrame {
+ if len(s.frames) == 0 {
+ return nil
+ }
+ return &s.frames[len(s.frames)-1]
+}
+
+// Parse and evaluate preprocessor feature conditions
+//
+func evalCondition(expr string, cfg Config) bool {
+ expr = strings.TrimSpace(expr)
+ if strings.HasPrefix(expr, "defined(") && strings.HasSuffix(expr, ")") {
+ key := expr[8 : len(expr)-1]
+ _, ok := cfg[key]
+ return ok
+ }
+ if strings.HasPrefix(expr, "!defined(") && strings.HasSuffix(expr, ")") {
+ key := expr[9 : len(expr)-1]
+ _, ok := cfg[key]
+ return !ok
+ }
+ if idx := strings.Index(expr, "=="); idx >= 0 {
+ lhs := strings.TrimSpace(expr[:idx])
+ rhs := strings.TrimSpace(expr[idx+2:])
+ return cfg[lhs] == rhs
+ }
+ if idx := strings.Index(expr, "!="); idx >= 0 {
+ lhs := strings.TrimSpace(expr[:idx])
+ rhs := strings.TrimSpace(expr[idx+2:])
+ return cfg[lhs] != rhs
+ }
+ if strings.HasPrefix(expr, "!") {
+ key := strings.TrimSpace(expr[1:])
+ return cfg[key] != "1"
+ }
+ return cfg[expr] == "1"
+}
+
+// Scanning and parsing djot comments in c source files
+//
+func formatToken(tok string) string {
+ if strings.HasPrefix(tok, "-") {
+ return "`" + tok + "`"
+ }
+ if len(tok) >= 2 {
+ first := tok[0]
+ last := tok[len(tok)-1]
+ if (first == '[' && last == ']') || (first == '<' && last == '>') || (first == '(' && last == ')') {
+ inner := tok[1 : len(tok)-1]
+ if strings.HasPrefix(inner, "-") {
+ return string(first) + "`" + inner + "`" + string(last)
+ }
+ return string(first) + "_" + inner + "_" + string(last)
+ }
+ }
+ return "_" + tok + "_"
+}
+
+func parseNameSummary(line string) (string, string, bool) {
+ line = strings.TrimSpace(line)
+ if idx := strings.Index(line, ":"); idx >= 0 {
+ return strings.TrimSpace(line[:idx]), strings.TrimSpace(line[idx+1:]), true
+ }
+ if idx := strings.Index(line, " \\- "); idx >= 0 {
+ return strings.TrimSpace(line[:idx]), strings.TrimSpace(line[idx+4:]), true
+ }
+ if idx := strings.Index(line, " - "); idx >= 0 {
+ return strings.TrimSpace(line[:idx]), strings.TrimSpace(line[idx+3:]), true
+ }
+ return "", "", false
+}
+
+func isOptionPattern(s string) (string, string, bool) {
+ s = strings.TrimSpace(s)
+ if !strings.HasPrefix(s, "-") {
+ return "", "", false
+ }
+ idx := strings.Index(s, ":")
+ if idx < 0 {
+ return "", "", false
+ }
+ opt := strings.TrimSpace(s[:idx])
+ desc := strings.TrimSpace(s[idx+1:])
+ fields := strings.Fields(opt)
+ if len(fields) == 0 || !strings.HasPrefix(fields[0], "-") {
+ return "", "", false
+ }
+ return opt, desc, true
+}
+
+func scanC(path string, cfg Config) (string, error) {
+ contentBytes, err := os.ReadFile(path)
+ if err != nil {
+ return "", err
+ }
+ contentStr := string(contentBytes)
+
+ if !strings.Contains(contentStr, "?man") {
+ // Original parser mode using explicit man markers
+ var djotBuf strings.Builder
+ stack := &ifStack{}
+ sc := bufio.NewScanner(strings.NewReader(contentStr))
+ sc.Buffer(make([]byte, 1<<20), 1<<20)
+ inBlockComment := false
+
+ for sc.Scan() {
+ line := sc.Text()
+ trimmed := strings.TrimSpace(line)
+
+ if inBlockComment {
+ if trimmed == "*/" || trimmed == "* /" {
+ inBlockComment = false
+ djotBuf.WriteByte('\n')
+ } else {
+ stripped := trimmed
+ if strings.HasPrefix(stripped, "* ") {
+ stripped = stripped[2:]
+ } else if stripped == "*" {
+ stripped = ""
+ }
+ djotBuf.WriteString(stripped)
+ djotBuf.WriteByte('\n')
+ }
+ continue
+ }
+
+ if strings.HasPrefix(trimmed, "#") {
+ directive := trimmed[1:]
+ if ci := strings.Index(directive, "//"); ci >= 0 {
+ directive = directive[:ci]
+ }
+ directive = strings.TrimSpace(directive)
+
+ switch {
+ case strings.HasPrefix(directive, "ifdef "):
+ key := strings.TrimSpace(directive[6:])
+ _, defined := cfg[key]
+ pa := stack.parentActive()
+ stack.push(pa && defined, defined)
+ case strings.HasPrefix(directive, "ifndef "):
+ key := strings.TrimSpace(directive[7:])
+ _, defined := cfg[key]
+ pa := stack.parentActive()
+ stack.push(pa && !defined, !defined)
+ case strings.HasPrefix(directive, "if "):
+ expr := strings.TrimSpace(directive[3:])
+ result := evalCondition(expr, cfg)
+ pa := stack.parentActive()
+ stack.push(pa && result, result)
+ case directive == "else":
+ if top := stack.top(); top != nil {
+ pa := stack.parentActive()
+ newActive := pa && !top.seen
+ top.active = newActive
+ top.seen = true
+ }
+ case strings.HasPrefix(directive, "elif "):
+ if top := stack.top(); top != nil {
+ expr := strings.TrimSpace(directive[5:])
+ result := evalCondition(expr, cfg)
+ pa := stack.parentActive()
+ newActive := pa && !top.seen && result
+ top.active = newActive
+ if result {
+ top.seen = true
+ }
+ }
+ case directive == "endif":
+ stack.pop()
+ }
+ continue
+ }
+
+ if !stack.globallyActive() {
+ continue
+ }
+
+ if strings.Contains(trimmed, "/* !man") {
+ startIdx := strings.Index(trimmed, "/* !man")
+ rest := strings.TrimSpace(trimmed[startIdx+7:])
+ if strings.HasSuffix(rest, "*/") {
+ content := strings.TrimSpace(rest[:len(rest)-2])
+ if content != "" {
+ djotBuf.WriteString(content)
+ djotBuf.WriteByte('\n')
+ }
+ } else {
+ if rest != "" {
+ djotBuf.WriteString(rest)
+ djotBuf.WriteByte('\n')
+ }
+ inBlockComment = true
+ }
+ continue
+ }
+
+ if idx := strings.Index(trimmed, "// !man"); idx >= 0 {
+ content := strings.TrimSpace(trimmed[idx+7:])
+ djotBuf.WriteString(content)
+ djotBuf.WriteByte('\n')
+ continue
+ }
+ }
+
+ if err := sc.Err(); err != nil {
+ return "", err
+ }
+ return djotBuf.String(), nil
+ }
+
+ // Heuristic parser mode using question mark man markers
+ type optionDoc struct {
+ opt string
+ desc string
+ }
+ type sectionDoc struct {
+ title string
+ lines []string
+ }
+
+ var name, summary, synopsis string
+ var descriptionBody []string
+ var options []optionDoc
+ var otherSections []sectionDoc
+ var currentSection *sectionDoc
+ var lastOption *optionDoc
+
+ stack := &ifStack{}
+ sc := bufio.NewScanner(strings.NewReader(contentStr))
+ sc.Buffer(make([]byte, 1<<20), 1<<20)
+ inBlockComment := false
+ firstLineOfFirstBlock := true
+
+ for sc.Scan() {
+ line := sc.Text()
+ trimmed := strings.TrimSpace(line)
+
+ if inBlockComment {
+ if trimmed == "*/" || trimmed == "* /" {
+ inBlockComment = false
+ } else {
+ stripped := trimmed
+ if strings.HasPrefix(stripped, "* ") {
+ stripped = stripped[2:]
+ } else if stripped == "*" {
+ stripped = ""
+ }
+ if strings.HasPrefix(stripped, "// ?man ") {
+ stripped = stripped[8:]
+ } else if strings.HasPrefix(stripped, "// ?man") {
+ stripped = stripped[7:]
+ }
+ if firstLineOfFirstBlock {
+ firstLineOfFirstBlock = false
+ if n, s, ok := parseNameSummary(stripped); ok {
+ name = n
+ summary = s
+ continue
+ }
+ }
+ if synopsis == "" && strings.HasPrefix(strings.ToLower(stripped), "usage:") {
+ synopsis = strings.TrimSpace(stripped[6:])
+ continue
+ }
+ if strings.HasPrefix(stripped, "## ") {
+ title := strings.TrimSpace(stripped[3:])
+ otherSections = append(otherSections, sectionDoc{title: title})
+ currentSection = &otherSections[len(otherSections)-1]
+ lastOption = nil
+ } else {
+ if opt, desc, ok := isOptionPattern(stripped); ok {
+ options = append(options, optionDoc{opt: opt, desc: desc})
+ lastOption = &options[len(options)-1]
+ currentSection = nil
+ } else {
+ if currentSection != nil {
+ currentSection.lines = append(currentSection.lines, stripped)
+ } else {
+ descriptionBody = append(descriptionBody, stripped)
+ }
+ }
+ }
+ }
+ continue
+ }
+
+ if strings.HasPrefix(trimmed, "#") {
+ directive := trimmed[1:]
+ if ci := strings.Index(directive, "//"); ci >= 0 {
+ directive = directive[:ci]
+ }
+ directive = strings.TrimSpace(directive)
+
+ switch {
+ case strings.HasPrefix(directive, "ifdef "):
+ key := strings.TrimSpace(directive[6:])
+ _, defined := cfg[key]
+ pa := stack.parentActive()
+ stack.push(pa && defined, defined)
+ case strings.HasPrefix(directive, "ifndef "):
+ key := strings.TrimSpace(directive[7:])
+ _, defined := cfg[key]
+ pa := stack.parentActive()
+ stack.push(pa && !defined, !defined)
+ case strings.HasPrefix(directive, "if "):
+ expr := strings.TrimSpace(directive[3:])
+ result := evalCondition(expr, cfg)
+ pa := stack.parentActive()
+ stack.push(pa && result, result)
+ case directive == "else":
+ if top := stack.top(); top != nil {
+ pa := stack.parentActive()
+ newActive := pa && !top.seen
+ top.active = newActive
+ top.seen = true
+ }
+ case strings.HasPrefix(directive, "elif "):
+ if top := stack.top(); top != nil {
+ expr := strings.TrimSpace(directive[5:])
+ result := evalCondition(expr, cfg)
+ pa := stack.parentActive()
+ newActive := pa && !top.seen && result
+ top.active = newActive
+ if result {
+ top.seen = true
+ }
+ }
+ case directive == "endif":
+ stack.pop()
+ }
+ continue
+ }
+
+ if !stack.globallyActive() {
+ continue
+ }
+
+ if strings.Contains(trimmed, "/* ?man") {
+ startIdx := strings.Index(trimmed, "/* ?man")
+ rest := strings.TrimSpace(trimmed[startIdx+7:])
+ if strings.HasSuffix(rest, "*/") {
+ content := strings.TrimSpace(rest[:len(rest)-2])
+ if n, s, ok := parseNameSummary(content); ok {
+ name = n
+ summary = s
+ }
+ } else {
+ if rest != "" {
+ if n, s, ok := parseNameSummary(rest); ok {
+ name = n
+ summary = s
+ } else {
+ descriptionBody = append(descriptionBody, rest)
+ }
+ }
+ inBlockComment = true
+ }
+ continue
+ }
+
+ if idx := strings.Index(trimmed, "// ?man"); idx >= 0 {
+ content := strings.TrimSpace(trimmed[idx+7:])
+ if opt, desc, ok := isOptionPattern(content); ok {
+ options = append(options, optionDoc{opt: opt, desc: desc})
+ lastOption = &options[len(options)-1]
+ currentSection = nil
+ } else {
+ if lastOption != nil {
+ lastOption.desc += " " + content
+ } else if currentSection != nil {
+ currentSection.lines = append(currentSection.lines, content)
+ } else {
+ descriptionBody = append(descriptionBody, content)
+ }
+ }
+ continue
+ }
+ }
+
+ if err := sc.Err(); err != nil {
+ return "", err
+ }
+
+ var djotBuf strings.Builder
+ djotBuf.WriteString("# " + name + "\n\n")
+ djotBuf.WriteString("## NAME\n\n")
+ djotBuf.WriteString(name + " \\- " + summary + "\n\n")
+
+ if synopsis != "" {
+ djotBuf.WriteString("## SYNOPSIS\n\n")
+ djotBuf.WriteString("```\n" + synopsis + "\n```\n\n")
+ }
+
+ if len(descriptionBody) > 0 {
+ djotBuf.WriteString("## DESCRIPTION\n\n")
+ for _, l := range descriptionBody {
+ djotBuf.WriteString(l + "\n")
+ }
+ djotBuf.WriteString("\n")
+ }
+
+ if len(options) > 0 {
+ djotBuf.WriteString("## OPTIONS\n\n")
+ for _, opt := range options {
+ words := strings.Fields(opt.opt)
+ var formatted []string
+ for _, w := range words {
+ formatted = append(formatted, formatToken(w))
+ }
+ djotBuf.WriteString(strings.Join(formatted, " ") + "\n")
+ djotBuf.WriteString(": " + opt.desc + "\n\n")
+ }
+ }
+
+ for _, sec := range otherSections {
+ djotBuf.WriteString("## " + sec.title + "\n\n")
+ for _, l := range sec.lines {
+ djotBuf.WriteString(l + "\n")
+ }
+ djotBuf.WriteString("\n")
+ }
+
+ return djotBuf.String(), nil
+}
+
+// Section inference from file path
+//
+func inferSection(path string) int {
+ clean := filepath.ToSlash(path)
+ switch {
+ case strings.Contains(clean, "/linux/"),
+ strings.Contains(clean, "/net/"),
+ strings.Contains(clean, "/xsi/"):
+ return 8
+ default:
+ return 1
+ }
+}
+
+// Main entry point and flags definition
+//
+func main() {
+ configPath := flag.String("config", "config.mk", "path to config.mk")
+ sectionFlag := flag.Int("section", 0, "man section override (0 = infer from path)")
+ dateFlag := flag.String("date", "", "date string for TH line (default: current month/year)")
+ flag.Parse()
+
+ if flag.NArg() < 1 {
+ fmt.Fprintf(os.Stderr, "usage: mkman [-config config.mk] [-section N] file.c\n")
+ os.Exit(1)
+ }
+ cfile := flag.Arg(0)
+
+ cfg, err := parseConfigMk(*configPath)
+ if err != nil {
+ fmt.Fprintf(os.Stderr, "mkman: config: %v\n", err)
+ os.Exit(1)
+ }
+
+ section := *sectionFlag
+ if section == 0 {
+ section = inferSection(cfile)
+ }
+
+ date := *dateFlag
+ if date == "" {
+ date = time.Now().Format("January 2006")
+ }
+
+ djotText, err := scanC(cfile, cfg)
+ if err != nil {
+ fmt.Fprintf(os.Stderr, "mkman: scan: %v\n", err)
+ os.Exit(1)
+ }
+
+ if strings.TrimSpace(djotText) == "" {
+ fmt.Fprintf(os.Stderr, "mkman: %s: no !man comments found\n", cfile)
+ os.Exit(0)
+ }
+
+ doc := djot.Parse([]byte(djotText))
+
+ r := NewTroffRenderer(doc, os.Stdout, section, date)
+ r.Render()
+}
diff --git a/scripts/mkman/troff.go b/scripts/mkman/troff.go
@@ -0,0 +1,248 @@
+package main
+
+import (
+ "fmt"
+ "io"
+ "strings"
+
+ "aruu/mkman/djot"
+)
+
+type TroffRenderer struct {
+ doc *djot.Document
+ w io.Writer
+ section int
+ date string
+ thDone bool
+ listDepth int
+}
+
+func NewTroffRenderer(doc *djot.Document, w io.Writer, section int, date string) *TroffRenderer {
+ return &TroffRenderer{doc: doc, w: w, section: section, date: date}
+}
+
+func (r *TroffRenderer) getBytes(start, end int32) []byte {
+ if start == -1 && end == -1 {
+ return nil
+ }
+ if start < 0 {
+ idx := ^start
+ if idx < 0 || idx >= int32(len(r.doc.Extra)) {
+ return nil
+ }
+ return r.doc.Extra[idx : end+1]
+ }
+ if start >= int32(len(r.doc.Source)) || end >= int32(len(r.doc.Source)) || start > end {
+ return nil
+ }
+ return r.doc.Source[start : end+1]
+}
+
+func troffEscape(s string) string {
+ s = strings.ReplaceAll(s, "\\", "\\\\")
+ s = strings.ReplaceAll(s, "-", "\\-")
+ // Leading dot is escaped to prevent troff from treating it as a macro
+ if len(s) > 0 && s[0] == '.' {
+ s = "\\&" + s
+ }
+ return s
+}
+
+func (r *TroffRenderer) collectInlineText(idx int32) string {
+ var b strings.Builder
+ curr := r.doc.Nodes[idx].Child
+ for curr != -1 {
+ node := r.doc.Nodes[curr]
+ switch node.Type {
+ case djot.NodeStr:
+ b.Write(r.getBytes(node.Start, node.End))
+ case djot.NodeSoftBreak:
+ b.WriteRune(' ')
+ case djot.NodeVerbatim:
+ b.Write(r.getBytes(node.Start, node.End))
+ default:
+ b.WriteString(r.collectInlineText(curr))
+ }
+ curr = node.Next
+ }
+ return b.String()
+}
+
+func (r *TroffRenderer) renderInlines(idx int32) {
+ curr := r.doc.Nodes[idx].Child
+ for curr != -1 {
+ r.renderInlineNode(curr)
+ curr = r.doc.Nodes[curr].Next
+ }
+}
+
+func (r *TroffRenderer) renderInlineNode(idx int32) {
+ node := r.doc.Nodes[idx]
+ switch node.Type {
+ case djot.NodeStr:
+ raw := string(r.getBytes(node.Start, node.End))
+ fmt.Fprint(r.w, troffEscape(raw))
+ case djot.NodeSoftBreak:
+ fmt.Fprint(r.w, " ")
+ case djot.NodeHardBreak:
+ fmt.Fprint(r.w, "\n.br\n")
+ case djot.NodeNonBreakingSpace:
+ fmt.Fprint(r.w, "\\ ")
+ case djot.NodeEmph:
+ fmt.Fprint(r.w, `\fI`)
+ r.renderInlines(idx)
+ fmt.Fprint(r.w, `\fP`)
+ case djot.NodeStrong:
+ fmt.Fprint(r.w, `\fB`)
+ r.renderInlines(idx)
+ fmt.Fprint(r.w, `\fP`)
+ case djot.NodeVerbatim:
+ fmt.Fprint(r.w, `\fB`)
+ raw := string(r.getBytes(node.Start, node.End))
+ fmt.Fprint(r.w, troffEscape(raw))
+ fmt.Fprint(r.w, `\fP`)
+ case djot.NodeSmartPunctuation:
+ data := node.Data
+ switch data {
+ case 1:
+ fmt.Fprint(r.w, `\(em`)
+ case 2:
+ fmt.Fprint(r.w, `\(en`)
+ default:
+ fmt.Fprint(r.w, `\-\-`)
+ }
+ case djot.NodeLink:
+ // Render link text only because raw urls are typically omitted in man pages
+ r.renderInlines(idx)
+ case djot.NodeDoubleQuoted:
+ fmt.Fprint(r.w, `\(lq`)
+ r.renderInlines(idx)
+ fmt.Fprint(r.w, `\(rq`)
+ case djot.NodeSingleQuoted:
+ fmt.Fprint(r.w, `\(oq`)
+ r.renderInlines(idx)
+ fmt.Fprint(r.w, `\(cq`)
+ default:
+ r.renderInlines(idx)
+ }
+}
+
+func (r *TroffRenderer) renderChildren(idx int32) {
+ curr := r.doc.Nodes[idx].Child
+ for curr != -1 {
+ r.renderNode(curr)
+ curr = r.doc.Nodes[curr].Next
+ }
+}
+
+func (r *TroffRenderer) renderNode(idx int32) {
+ node := r.doc.Nodes[idx]
+ switch node.Type {
+ case djot.NodeDoc:
+ r.renderChildren(idx)
+
+ case djot.NodeSection:
+ r.renderChildren(idx)
+
+ case djot.NodeHeading:
+ level := int(node.Level)
+ if level == 0 {
+ level = int(node.Data & 0xFFFF)
+ }
+ text := r.collectInlineText(idx)
+ switch level {
+ case 1:
+ if !r.thDone {
+ fmt.Fprintf(r.w, ".TH %s %d \"%s\"\n",
+ strings.ToUpper(text), r.section, r.date)
+ r.thDone = true
+ } else {
+ fmt.Fprintf(r.w, ".SH %s\n", strings.ToUpper(text))
+ }
+ case 2:
+ fmt.Fprintf(r.w, ".SH %s\n", strings.ToUpper(text))
+ case 3:
+ fmt.Fprintf(r.w, ".SS %s\n", text)
+ default:
+ fmt.Fprintf(r.w, ".PP\n\\fB%s\\fP\n", troffEscape(text))
+ }
+
+ case djot.NodePara:
+ if r.listDepth > 0 {
+ r.renderInlines(idx)
+ fmt.Fprint(r.w, "\n")
+ } else {
+ fmt.Fprint(r.w, ".PP\n")
+ r.renderInlines(idx)
+ fmt.Fprint(r.w, "\n")
+ }
+
+ case djot.NodeCodeBlock:
+ fmt.Fprint(r.w, ".nf\n")
+ if node.Child != -1 {
+ r.renderChildren(idx)
+ } else {
+ raw := r.getBytes(node.Start, node.End)
+ r.w.Write(raw) //nolint
+ }
+ fmt.Fprint(r.w, ".fi\n")
+
+ case djot.NodeStr:
+ raw := string(r.getBytes(node.Start, node.End))
+ fmt.Fprint(r.w, raw)
+
+ case djot.NodeBlockQuote:
+ fmt.Fprint(r.w, ".RS\n")
+ r.renderChildren(idx)
+ fmt.Fprint(r.w, ".RE\n")
+
+ case djot.NodeBulletList, djot.NodeOrderedList, djot.NodeTaskList:
+ r.listDepth++
+ r.renderChildren(idx)
+ r.listDepth--
+
+ case djot.NodeListItem, djot.NodeTaskListItem:
+ if r.doc.Nodes[idx].Type == djot.NodeTaskListItem {
+ checked := (node.Data & djot.DataTaskChecked) != 0
+ if checked {
+ fmt.Fprint(r.w, ".IP \"[x]\" 4\n")
+ } else {
+ fmt.Fprint(r.w, ".IP \"[ ]\" 4\n")
+ }
+ } else {
+ fmt.Fprint(r.w, ".IP \\(bu 4\n")
+ }
+ r.renderChildren(idx)
+
+ case djot.NodeDefinitionList:
+ r.renderChildren(idx)
+
+ case djot.NodeDefinitionListItem:
+ r.renderChildren(idx)
+
+ case djot.NodeTerm:
+ fmt.Fprint(r.w, ".TP\n")
+ r.renderInlines(idx)
+ fmt.Fprint(r.w, "\n")
+
+ case djot.NodeDefinition:
+ r.listDepth++
+ r.renderChildren(idx)
+ r.listDepth--
+
+ case djot.NodeThematicBreak:
+ // Omit thematic breaks because troff lacks a clean representation
+
+ case djot.NodeDiv:
+ r.renderChildren(idx)
+
+ default:
+ }
+}
+
+func (r *TroffRenderer) Render() {
+ if len(r.doc.Nodes) == 0 {
+ return
+ }
+ r.renderNode(0)
+}
diff --git a/shared/libredline/redline.c b/shared/libredline/redline.c
@@ -0,0 +1,1412 @@
+/* see license file for copyright and license details */
+
+#include "redline.h"
+
+#include <ctype.h>
+#include <dirent.h>
+#include <errno.h>
+#include <fcntl.h>
+#include <signal.h>
+#include <stdint.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/ioctl.h>
+#include <sys/stat.h>
+#include <sys/types.h>
+#include <termios.h>
+#include <unistd.h>
+
+#define REDLINE_DEFAULT_HISTORY_MAX_LEN 100
+#define REDLINE_MAX_LINE (1024*1024)
+#define REDLINE_INITIAL_BUFLEN 4096
+
+#define ENTER 13
+#define CTRL_A 1
+#define CTRL_B 2
+#define CTRL_C 3
+#define CTRL_D 4
+#define CTRL_E 5
+#define CTRL_F 6
+#define CTRL_H 8
+#define CTRL_K 11
+#define CTRL_L 12
+#define CTRL_N 14
+#define CTRL_P 16
+#define CTRL_T 20
+#define CTRL_U 21
+#define CTRL_W 23
+#define CTRL_Y 25
+#define BACKSPACE 127
+#define ESC 27
+
+struct redlineState {
+ int in_completion;
+ int ifd;
+ int ofd;
+ char *buf;
+ size_t buflen;
+ const char *prompt;
+ size_t plen;
+ size_t pos;
+ size_t oldpos;
+ size_t len;
+ size_t cols;
+ size_t oldrows;
+ int oldrpos;
+ int history_index;
+};
+
+
+struct abuf {
+ char *b;
+ int len;
+};
+
+static struct termios orig_termios;
+static int rawmode = 0;
+static int mlmode = 0;
+static int history_max_len = REDLINE_DEFAULT_HISTORY_MAX_LEN;
+static int history_len = 0;
+static char **history = NULL;
+static char *kill_buffer = NULL;
+static volatile sig_atomic_t winch_received = 0;
+static struct sigaction orig_sigwinch;
+
+static void (*completionCallback)(const char *, struct redlineCompletions *) = NULL;
+
+/* return the number of bytes that compose the utf-8 character starting at c */
+static int
+utf8ByteLen(char c)
+{
+ unsigned char uc = (unsigned char)c;
+ if ((uc & 0x80) == 0) return 1;
+ if ((uc & 0xE0) == 0xC0) return 2;
+ if ((uc & 0xF0) == 0xE0) return 3;
+ if ((uc & 0xF8) == 0xF0) return 4;
+ return 1;
+}
+
+/* decode character starting at s */
+static uint32_t
+utf8DecodeChar(const char *s, size_t *len)
+{
+ uint32_t cp = 0;
+ int l = utf8ByteLen(*s);
+ *len = l;
+ if (l == 1) {
+ cp = ((unsigned char)*s);
+ } else if (l == 2) {
+ cp = ((unsigned char)*s & 0x1F) << 6;
+ cp |= ((unsigned char)*(s+1) & 0x3F);
+ } else if (l == 3) {
+ cp = ((unsigned char)*s & 0x0F) << 12;
+ cp |= ((unsigned char)*(s+1) & 0x3F) << 6;
+ cp |= ((unsigned char)*(s+2) & 0x3F);
+ } else if (l == 4) {
+ cp = ((unsigned char)*s & 0x07) << 18;
+ cp |= ((unsigned char)*(s+1) & 0x3F) << 12;
+ cp |= ((unsigned char)*(s+2) & 0x3F) << 6;
+ cp |= ((unsigned char)*(s+3) & 0x3F);
+ }
+ return cp;
+}
+
+static int
+isZWJ(uint32_t cp)
+{
+ return cp == 0x200D;
+}
+
+static int
+isCombiningMark(uint32_t cp)
+{
+ return (cp >= 0x0300 && cp <= 0x036F) || (cp >= 0x1DC0 && cp <= 0x1DFF) ||
+ (cp >= 0x20D0 && cp <= 0x20FF) || (cp >= 0xFE20 && cp <= 0xFE2F);
+}
+
+static int
+isVariationSelector(uint32_t cp)
+{
+ return (cp >= 0xFE00 && cp <= 0xFE0F) || (cp >= 0xE0100 && cp <= 0xE01EF);
+}
+
+static int
+isSkinToneModifier(uint32_t cp)
+{
+ return cp >= 0x1F3FB && cp <= 0x1F3FF;
+}
+
+
+static int
+isGraphemeExtend(uint32_t cp)
+{
+ return isCombiningMark(cp) || isVariationSelector(cp) || isSkinToneModifier(cp);
+}
+
+/* decode character going backward from pos */
+static uint32_t
+utf8DecodePrev(const char *buf, size_t pos, size_t *cplen)
+{
+ size_t i = 1;
+ while (pos >= i && i <= 4) {
+ unsigned char uc = (unsigned char)buf[pos-i];
+ if ((uc & 0x80) == 0) {
+ if (i == 1) {
+ *cplen = 1;
+ return uc;
+ }
+ break;
+ }
+ if ((uc & 0xC0) == 0xC0) {
+ int l = utf8ByteLen(buf[pos-i]);
+ if ((size_t)l == i) {
+ *cplen = i;
+ return utf8DecodeChar(buf + pos - i, cplen);
+ }
+ break;
+ }
+ i++;
+ }
+ *cplen = 1;
+ return (unsigned char)buf[pos-1];
+}
+
+/* calculate width of utf-8 char pos */
+static size_t
+utf8PrevCharLen(const char *buf, size_t pos)
+{
+ size_t len = 0;
+ size_t next_len = 0;
+ uint32_t cp;
+ if (pos == 0) return 0;
+ cp = utf8DecodePrev(buf, pos, &len);
+ pos -= len;
+ while (pos > 0 && isGraphemeExtend(cp)) {
+ cp = utf8DecodePrev(buf, pos, &next_len);
+ len += next_len;
+ pos -= next_len;
+ }
+ if (pos > 0 && isZWJ(cp)) {
+ size_t j = utf8PrevCharLen(buf, pos);
+ if (j > 0) len += j;
+ }
+ return len;
+}
+
+/* calculate width of next utf-8 char */
+static size_t
+utf8NextCharLen(const char *buf, size_t pos, size_t len)
+{
+ size_t clen = 0;
+ size_t offset = 0;
+ uint32_t cp;
+ if (pos >= len) return 0;
+ cp = utf8DecodeChar(buf + pos, &clen);
+ offset = clen;
+ while (pos + offset < len) {
+ size_t next_len = 0;
+ uint32_t next_cp = utf8DecodeChar(buf + pos + offset, &next_len);
+ if (isGraphemeExtend(next_cp)) {
+ offset += next_len;
+ } else if (isZWJ(cp)) {
+ offset += next_len;
+ cp = next_cp;
+ } else {
+ break;
+ }
+ }
+ return offset;
+}
+
+/* get columns needed to display char */
+static int
+utf8CharWidth(uint32_t cp)
+{
+ if (cp == 0) return 0;
+ if (cp < 0x20 || (cp >= 0x7f && cp < 0xa0)) return 0;
+ if ((cp >= 0x1100 && cp <= 0x115f) ||
+ (cp >= 0x2e80 && cp <= 0xa4cf && cp != 0x303f) ||
+ (cp >= 0xac00 && cp <= 0xd7a3) ||
+ (cp >= 0xf900 && cp <= 0xfaff) ||
+ (cp >= 0xfe10 && cp <= 0xfe19) ||
+ (cp >= 0xfe30 && cp <= 0xfe6f) ||
+ (cp >= 0xff00 && cp <= 0xff60) ||
+ (cp >= 0xffe0 && cp <= 0xffe6) ||
+ (cp >= 0x20000 && cp <= 0x2fffd) ||
+ (cp >= 0x30000 && cp <= 0x3fffd)) {
+ return 2;
+ }
+ return 1;
+}
+
+/* get ansi escape sequence length */
+static size_t
+ansiEscapeLen(const char *s, size_t len)
+{
+ size_t i = 0;
+ if (len < 2 || s[0] != '\x1b' || s[1] != '[') return 0;
+ i = 2;
+ while (i < len) {
+ char c = s[i];
+ if ((c >= '0' && c <= '9') || c == ';' || c == '?' || c == '"') {
+ i++;
+ } else if (c >= 'A' && c <= 'Z') {
+ return i + 1;
+ } else if (c >= 'a' && c <= 'z') {
+ return i + 1;
+ } else {
+ break;
+ }
+ }
+ return 0;
+}
+
+/* calculate width of string */
+static size_t
+utf8StrWidth(const char *s, size_t len)
+{
+ size_t width = 0;
+ size_t i = 0;
+ while (i < len) {
+ size_t elen = ansiEscapeLen(s + i, len - i);
+ if (elen > 0) {
+ i += elen;
+ continue;
+ }
+ size_t clen = 0;
+ uint32_t cp = utf8DecodeChar(s + i, &clen);
+ width += utf8CharWidth(cp);
+ i += clen;
+ }
+ return width;
+}
+
+/* get single character width */
+static int
+utf8SingleCharWidth(const char *s, size_t len)
+{
+ size_t clen = 0;
+ uint32_t cp = utf8DecodeChar(s, &clen);
+ (void)len;
+ return utf8CharWidth(cp);
+}
+
+static int
+isUnsupportedTerm(void)
+{
+ char *term = getenv("TERM");
+ int i;
+ static char *unsupported[] = {"dumb", "cons25", "emacs", NULL};
+ if (term == NULL) return 0;
+ for (i = 0; unsupported[i]; i++) {
+ if (strcasecmp(term, unsupported[i]) == 0)
+ return 1;
+ }
+ return 0;
+}
+
+static void
+sigwinchHandler(int sig)
+{
+ (void)sig;
+ winch_received = 1;
+}
+
+static int
+enableRawMode(int fd)
+{
+ struct termios raw;
+ struct sigaction sa;
+
+ if (!isatty(STDIN_FILENO))
+ return -1;
+ if (tcgetattr(fd, &orig_termios) == -1)
+ return -1;
+
+ raw = orig_termios;
+ raw.c_iflag &= ~(BRKINT | ICRNL | INPCK | ISTRIP | IXON);
+ raw.c_oflag &= ~(OPOST);
+ raw.c_cflag |= (CS8);
+ raw.c_lflag &= ~(ECHO | ICANON | IEXTEN | ISIG);
+ raw.c_cc[VMIN] = 1;
+ raw.c_cc[VTIME] = 0;
+
+ if (tcsetattr(fd, TCSAFLUSH, &raw) < 0)
+ return -1;
+
+ rawmode = 1;
+
+ /* register sigwinch handler */
+ sa.sa_handler = sigwinchHandler;
+ sigemptyset(&sa.sa_mask);
+ sa.sa_flags = 0;
+ sigaction(SIGWINCH, &sa, &orig_sigwinch);
+
+ return 0;
+}
+
+static void
+disableRawMode(int fd)
+{
+ if (rawmode) {
+ tcsetattr(fd, TCSAFLUSH, &orig_termios);
+ sigaction(SIGWINCH, &orig_sigwinch, NULL);
+ rawmode = 0;
+ }
+}
+
+static int
+getCursorPosition(int ifd, int ofd)
+{
+ char buf[32];
+ int cols, rows;
+ unsigned int i = 0;
+
+ if (write(ofd, "\x1b[6n", 4) != 4) return -1;
+
+ while (i < sizeof(buf)-1) {
+ if (read(ifd,buf+i,1) != 1) break;
+ if (buf[i] == 'R') break;
+ i++;
+ }
+ buf[i] = '\0';
+
+ if (buf[0] != 27 || buf[1] != '[') return -1;
+ if (sscanf(buf+2,"%d;%d",&rows,&cols) != 2) return -1;
+ return cols;
+}
+
+static int
+getColumns(int ifd, int ofd)
+{
+ struct winsize ws;
+ char *cols_env;
+ int tty_fd;
+ int cols = 0;
+
+ if (ioctl(ofd, TIOCGWINSZ, &ws) == 0 && ws.ws_col >= 20)
+ return ws.ws_col;
+ if (ioctl(ifd, TIOCGWINSZ, &ws) == 0 && ws.ws_col >= 20)
+ return ws.ws_col;
+ if (ioctl(STDERR_FILENO, TIOCGWINSZ, &ws) == 0 && ws.ws_col >= 20)
+ return ws.ws_col;
+ if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) == 0 && ws.ws_col >= 20)
+ return ws.ws_col;
+ if (ioctl(STDIN_FILENO, TIOCGWINSZ, &ws) == 0 && ws.ws_col >= 20)
+ return ws.ws_col;
+
+ tty_fd = open("/dev/tty", O_RDWR | O_NOCTTY);
+ if (tty_fd >= 0) {
+ if (ioctl(tty_fd, TIOCGWINSZ, &ws) == 0 && ws.ws_col >= 20) {
+ cols = ws.ws_col;
+ }
+ close(tty_fd);
+ if (cols >= 20) return cols;
+ }
+
+ cols_env = getenv("COLUMNS");
+ if (cols_env) {
+ cols = atoi(cols_env);
+ if (cols >= 20) return cols;
+ }
+
+ /* fallback to cursor position query */
+ int start;
+
+ if (!isatty(ifd) || !isatty(ofd)) return 80;
+
+ start = getCursorPosition(ifd,ofd);
+ if (start == -1) return 80;
+
+ if (write(ofd,"\x1b[999C",6) != 6) return 80;
+ cols = getCursorPosition(ifd,ofd);
+ if (cols == -1) return 80;
+
+ if (cols > start) {
+ char seq[32];
+ snprintf(seq,sizeof(seq),"\x1b[%dD",cols-start);
+ if (write(ofd,seq,strlen(seq)) == -1) {}
+ }
+ if (cols < 20) return 80;
+ return cols;
+}
+
+static void
+redlineBeep(void)
+{
+ fprintf(stderr, "\x7");
+ fflush(stderr);
+}
+
+static void
+freeCompletions(struct redlineCompletions *lc)
+{
+ size_t i;
+ if (lc->cvec) {
+ for (i = 0; i < lc->len; i++) {
+ free(lc->cvec[i]);
+ }
+ free(lc->cvec);
+ }
+}
+
+static size_t
+longestCommonPrefix(struct redlineCompletions *lc)
+{
+ size_t i, j;
+ if (lc->len == 0) return 0;
+ for (i = 0; ; i++) {
+ char c = lc->cvec[0][i];
+ if (c == '\0') return i;
+ for (j = 1; j < lc->len; j++) {
+ if (lc->cvec[j][i] != c) {
+ return i;
+ }
+ }
+ }
+}
+
+static void
+printCompletions(struct redlineState *ls, struct redlineCompletions *lc)
+{
+ size_t max_len = 0;
+ size_t i, j, k;
+ size_t col_width, num_cols, num_rows;
+ size_t sp, len, idx;
+ const char *comp;
+ const char *name;
+
+ for (i = 0; i < lc->len; i++) {
+ comp = lc->cvec[i];
+ sp = strlen(comp);
+ if (sp > 0 && comp[sp-1] == ' ') {
+ sp--;
+ }
+ while (sp > 0 && comp[sp-1] != ' ') {
+ sp--;
+ }
+ len = strlen(comp + sp);
+ if (len > 0 && (comp + sp)[len-1] == ' ') {
+ len--;
+ }
+ if (len > max_len) {
+ max_len = len;
+ }
+ }
+
+ col_width = max_len + 2;
+ num_cols = ls->cols / col_width;
+ if (num_cols == 0) num_cols = 1;
+ num_rows = (lc->len + num_cols - 1) / num_cols;
+
+ if (write(ls->ofd, "\r\n", 2) == -1) {}
+ for (i = 0; i < num_rows; i++) {
+ for (j = 0; j < num_cols; j++) {
+ idx = j * num_rows + i;
+ if (idx < lc->len) {
+ comp = lc->cvec[idx];
+ sp = strlen(comp);
+ if (sp > 0 && comp[sp-1] == ' ') {
+ sp--;
+ }
+ while (sp > 0 && comp[sp-1] != ' ') {
+ sp--;
+ }
+ name = comp + sp;
+ len = strlen(name);
+ if (len > 0 && name[len-1] == ' ') {
+ len--;
+ }
+ if (write(ls->ofd, name, len) == -1) {}
+ if (j < num_cols - 1) {
+ for (k = len; k < col_width; k++) {
+ if (write(ls->ofd, " ", 1) == -1) {}
+ }
+ }
+ }
+ }
+ if (write(ls->ofd, "\r\n", 2) == -1) {}
+ }
+}
+
+static void
+abInit(struct abuf *ab)
+{
+ ab->b = NULL;
+ ab->len = 0;
+}
+
+static void
+abAppend(struct abuf *ab, const char *s, int len)
+{
+ char *new = realloc(ab->b,ab->len+len);
+ if (new == NULL) return;
+ memcpy(new+ab->len,s,len);
+ ab->b = new;
+ ab->len += len;
+}
+
+static void
+abFree(struct abuf *ab)
+{
+ free(ab->b);
+}
+
+static void
+refreshSingleLine(struct redlineState *l, int flags)
+{
+ char seq[64];
+ size_t pwidth = utf8StrWidth(l->prompt, l->plen);
+ int fd = l->ofd;
+ char *buf = l->buf;
+ size_t len = l->len;
+ size_t pos = l->pos;
+ size_t poscol;
+ size_t lencol;
+ struct abuf ab;
+
+ poscol = utf8StrWidth(buf, pos);
+ lencol = utf8StrWidth(buf, len);
+
+ while (pwidth + poscol >= l->cols) {
+ size_t clen = utf8NextCharLen(buf, 0, len);
+ int cwidth = utf8SingleCharWidth(buf, clen);
+ buf += clen;
+ len -= clen;
+ pos -= clen;
+ poscol -= cwidth;
+ lencol -= cwidth;
+ }
+
+ while (pwidth + lencol > l->cols) {
+ size_t clen = utf8PrevCharLen(buf, len);
+ int cwidth = utf8SingleCharWidth(buf + len - clen, clen);
+ len -= clen;
+ lencol -= cwidth;
+ }
+
+ abInit(&ab);
+ snprintf(seq,sizeof(seq),"\r");
+ abAppend(&ab,seq,strlen(seq));
+
+ if (flags & 1) {
+ abAppend(&ab,l->prompt,l->plen);
+ abAppend(&ab,buf,len);
+ }
+
+ snprintf(seq,sizeof(seq),"\x1b[0K");
+ abAppend(&ab,seq,strlen(seq));
+
+ if (flags & 1) {
+ snprintf(seq,sizeof(seq),"\r\x1b[%dC", (int)(poscol+pwidth));
+ abAppend(&ab,seq,strlen(seq));
+ }
+
+ if (write(fd,ab.b,ab.len) == -1) {}
+ abFree(&ab);
+}
+
+static void
+refreshMultiLine(struct redlineState *l, int flags)
+{
+ char seq[64];
+ size_t pwidth = utf8StrWidth(l->prompt, l->plen);
+ size_t bufwidth;
+ size_t poswidth;
+ int rows;
+ int rpos2;
+ int col;
+ int old_rows = l->oldrows;
+ int rpos = l->oldrpos;
+ int fd = l->ofd, j;
+ struct abuf ab;
+
+ (void)flags;
+
+ bufwidth = utf8StrWidth(l->buf, l->len);
+ poswidth = utf8StrWidth(l->buf, l->pos);
+ rows = (pwidth+bufwidth+l->cols-1)/l->cols;
+ l->oldrows = rows;
+
+ abInit(&ab);
+
+ /* move cursor up to the first row, column 0 of the input area */
+ if (rpos > 1) {
+ snprintf(seq, 64, "\r\x1b[%dA", rpos - 1);
+ abAppend(&ab, seq, strlen(seq));
+ } else {
+ abAppend(&ab, "\r", 1);
+ }
+
+ /* clear all old rows */
+ for (j = 0; j < old_rows; j++) {
+ abAppend(&ab, "\x1b[0K", 4);
+ if (j < old_rows - 1) {
+ abAppend(&ab, "\n\r", 2);
+ }
+ }
+
+ /* move cursor back to the first row, column 0 */
+ if (old_rows > 1) {
+ snprintf(seq, 64, "\r\x1b[%dA", old_rows - 1);
+ abAppend(&ab, seq, strlen(seq));
+ } else {
+ abAppend(&ab, "\r", 1);
+ }
+
+ /* print prompt and new buffer */
+ abAppend(&ab, l->prompt, l->plen);
+ abAppend(&ab, l->buf, l->len);
+
+ /* if cursor is at the end of the line and wraps, print a newline */
+ if (l->pos && l->pos == l->len && (poswidth+pwidth) % l->cols == 0) {
+ abAppend(&ab, "\n\r", 2);
+ rows++;
+ if (rows > (int)l->oldrows) l->oldrows = rows;
+ }
+
+ /* calculate cursor row and column */
+ rpos2 = (pwidth+poswidth+l->cols)/l->cols;
+ col = (pwidth+poswidth) % l->cols;
+
+ /* move cursor to the correct row and column */
+ if (rows - rpos2 > 0) {
+ snprintf(seq, 64, "\x1b[%dA", rows - rpos2);
+ abAppend(&ab, seq, strlen(seq));
+ }
+ if (col) {
+ snprintf(seq, 64, "\r\x1b[%dC", col);
+ abAppend(&ab, seq, strlen(seq));
+ } else {
+ abAppend(&ab, "\r", 1);
+ }
+
+ l->oldpos = l->pos;
+ l->oldrpos = rpos2;
+
+ if (write(fd, ab.b, ab.len) == -1) {}
+ abFree(&ab);
+}
+
+static void
+refreshLineWithFlags(struct redlineState *l, int flags)
+{
+ if (mlmode)
+ refreshMultiLine(l,flags);
+ else
+ refreshSingleLine(l,flags);
+}
+
+static void
+refreshLine(struct redlineState *l)
+{
+ refreshLineWithFlags(l, 1);
+}
+
+static int
+completeLine(struct redlineState *ls, int keypressed)
+{
+ struct redlineCompletions lc = { 0, NULL };
+ size_t lcp_len;
+ int c = keypressed;
+ int proceed = 1;
+ char query[128];
+ char answer = 0;
+
+ if (c != 9) {
+ ls->in_completion = 0;
+ return c;
+ }
+
+ completionCallback(ls->buf, &lc);
+ if (lc.len == 0) {
+ redlineBeep();
+ ls->in_completion = 0;
+ c = 0;
+ } else if (lc.len == 1) {
+ size_t nwritten = snprintf(ls->buf, ls->buflen, "%s", lc.cvec[0]);
+ ls->len = ls->pos = nwritten;
+ refreshLine(ls);
+ ls->in_completion = 0;
+ c = 0;
+ } else {
+ lcp_len = longestCommonPrefix(&lc);
+ if (lcp_len > ls->len) {
+ size_t nwritten = snprintf(ls->buf, ls->buflen, "%.*s", (int)lcp_len, lc.cvec[0]);
+ ls->len = ls->pos = nwritten;
+ refreshLine(ls);
+ ls->in_completion = 1;
+ c = 0;
+ } else {
+ /* prefix cannot be expanded further */
+ if (ls->in_completion == 0) {
+ /* first tab: beep and wait for the second tab */
+ redlineBeep();
+ ls->in_completion = 1;
+ c = 0;
+ } else {
+ /* second tab: display possibilities */
+ if (lc.len > 100) {
+ snprintf(query, sizeof(query), "\r\nDisplay all %d possibilities? (y or n) ", (int)lc.len);
+ if (write(ls->ofd, query, strlen(query)) == -1) {}
+ while (1) {
+ if (read(ls->ifd, &answer, 1) != 1) {
+ proceed = 0;
+ break;
+ }
+ if (answer == 'y' || answer == 'Y' || answer == ' ' || answer == '\t') {
+ proceed = 1;
+ break;
+ }
+ if (answer == 'n' || answer == 'N' || answer == 27 || answer == 3 || answer == 4) {
+ proceed = 0;
+ break;
+ }
+ redlineBeep();
+ }
+ }
+ if (proceed) {
+ printCompletions(ls, &lc);
+ } else {
+ if (write(ls->ofd, "\r\n", 2) == -1) {}
+ }
+ ls->oldrows = 0;
+ refreshLine(ls);
+ ls->in_completion = 0;
+ c = 0;
+ }
+ }
+ }
+
+ freeCompletions(&lc);
+ return c;
+}
+
+static int
+redlineEditInsert(struct redlineState *l, const char *c, int clen)
+{
+ if (l->len + clen >= l->buflen) {
+ return 0;
+ }
+ if (l->len == l->pos) {
+ memcpy(l->buf + l->pos, c, clen);
+ l->pos += clen;
+ l->len += clen;
+ l->buf[l->len] = '\0';
+ refreshLine(l);
+ } else {
+ memmove(l->buf + l->pos + clen, l->buf + l->pos, l->len - l->pos);
+ memcpy(l->buf + l->pos, c, clen);
+ l->pos += clen;
+ l->len += clen;
+ l->buf[l->len] = '\0';
+ refreshLine(l);
+ }
+ return 1;
+}
+
+static void
+redlineEditBackspace(struct redlineState *l)
+{
+ if (l->pos > 0 && l->len > 0) {
+ size_t clen = utf8PrevCharLen(l->buf, l->pos);
+ memmove(l->buf+l->pos-clen, l->buf+l->pos, l->len-l->pos);
+ l->pos -= clen;
+ l->len -= clen;
+ l->buf[l->len] = '\0';
+ refreshLine(l);
+ }
+}
+
+static void
+redlineEditDelete(struct redlineState *l)
+{
+ if (l->len > 0 && l->pos < l->len) {
+ size_t clen = utf8NextCharLen(l->buf, l->pos, l->len);
+ memmove(l->buf+l->pos, l->buf+l->pos+clen, l->len-l->pos-clen);
+ l->len -= clen;
+ l->buf[l->len] = '\0';
+ refreshLine(l);
+ }
+}
+
+static void
+redlineEditMoveLeft(struct redlineState *l)
+{
+ if (l->pos > 0) {
+ l->pos -= utf8PrevCharLen(l->buf, l->pos);
+ refreshLine(l);
+ }
+}
+
+static void
+redlineEditMoveRight(struct redlineState *l)
+{
+ if (l->pos != l->len) {
+ l->pos += utf8NextCharLen(l->buf, l->pos, l->len);
+ refreshLine(l);
+ }
+}
+
+static void
+redlineEditMoveHome(struct redlineState *l)
+{
+ if (l->pos != 0) {
+ l->pos = 0;
+ refreshLine(l);
+ }
+}
+
+static void
+redlineEditMoveEnd(struct redlineState *l)
+{
+ if (l->pos != l->len) {
+ l->pos = l->len;
+ refreshLine(l);
+ }
+}
+
+static void
+redlineEditMoveWordLeft(struct redlineState *l)
+{
+ if (l->pos > 0) {
+ while (l->pos > 0 && l->buf[l->pos-1] == ' ')
+ l->pos -= utf8PrevCharLen(l->buf, l->pos);
+ while (l->pos > 0 && l->buf[l->pos-1] != ' ')
+ l->pos -= utf8PrevCharLen(l->buf, l->pos);
+ refreshLine(l);
+ }
+}
+
+static void
+redlineEditMoveWordRight(struct redlineState *l)
+{
+ if (l->pos < l->len) {
+ while (l->pos < l->len && l->buf[l->pos] == ' ')
+ l->pos += utf8NextCharLen(l->buf, l->pos, l->len);
+ while (l->pos < l->len && l->buf[l->pos] != ' ')
+ l->pos += utf8NextCharLen(l->buf, l->pos, l->len);
+ refreshLine(l);
+ }
+}
+
+static void
+killBufferSave(const char *text, size_t len)
+{
+ free(kill_buffer);
+ kill_buffer = malloc(len + 1);
+ if (kill_buffer) {
+ memcpy(kill_buffer, text, len);
+ kill_buffer[len] = '\0';
+ }
+}
+
+static void
+redlineEditDeleteWordRight(struct redlineState *l)
+{
+ size_t old_pos = l->pos;
+ size_t diff;
+ if (l->pos < l->len) {
+ while (l->pos < l->len && l->buf[l->pos] == ' ')
+ l->pos += utf8NextCharLen(l->buf, l->pos, l->len);
+ while (l->pos < l->len && l->buf[l->pos] != ' ')
+ l->pos += utf8NextCharLen(l->buf, l->pos, l->len);
+ diff = l->pos - old_pos;
+ l->pos = old_pos;
+ killBufferSave(l->buf + l->pos, diff);
+ memmove(l->buf + l->pos, l->buf + l->pos + diff, l->len - l->pos - diff + 1);
+ l->len -= diff;
+ refreshLine(l);
+ }
+}
+
+static void
+redlineEditDeletePrevWord(struct redlineState *l)
+{
+ size_t old_pos = l->pos;
+ size_t diff;
+ if (l->pos > 0) {
+ while (l->pos > 0 && l->buf[l->pos-1] == ' ')
+ l->pos -= utf8PrevCharLen(l->buf, l->pos);
+ while (l->pos > 0 && l->buf[l->pos-1] != ' ')
+ l->pos -= utf8PrevCharLen(l->buf, l->pos);
+ diff = old_pos - l->pos;
+ killBufferSave(l->buf + l->pos, diff);
+ memmove(l->buf + l->pos, l->buf + old_pos, l->len - old_pos + 1);
+ l->len -= diff;
+ refreshLine(l);
+ }
+}
+
+void
+redlineHistoryAdd(const char *line)
+{
+ char *linecopy;
+ if (history_max_len == 0) return;
+ if (history == NULL) {
+ history = malloc(sizeof(char*) * history_max_len);
+ if (history == NULL) return;
+ memset(history,0,sizeof(char*)*history_max_len);
+ }
+ if (history_len && strcmp(history[history_len-1], line) == 0) return;
+ linecopy = strdup(line);
+ if (!linecopy) return;
+ if (history_len == history_max_len) {
+ free(history[0]);
+ memmove(history,history+1,sizeof(char*)*(history_max_len-1));
+ history_len--;
+ }
+ history[history_len] = linecopy;
+ history_len++;
+}
+
+void
+redlineHistorySetMaxLen(int len)
+{
+ char **new;
+ if (len < 1) return;
+ if (history) {
+ int tocopy = history_len;
+ new = malloc(sizeof(char*)*len);
+ if (new == NULL) return;
+ if (len < tocopy) {
+ int j;
+ for (j = 0; j < tocopy-len; j++) free(history[j]);
+ tocopy = len;
+ }
+ memset(new,0,sizeof(char*)*len);
+ memcpy(new,history+(history_len-tocopy), sizeof(char*)*tocopy);
+ free(history);
+ history = new;
+ }
+ history_max_len = len;
+ if (history_len > history_max_len)
+ history_len = history_max_len;
+}
+
+int
+redlineHistorySave(const char *filename)
+{
+ mode_t old_umask = umask(S_IXUSR|S_IRWXG|S_IRWXO);
+ FILE *fp;
+ int j;
+
+ fp = fopen(filename,"w");
+ umask(old_umask);
+ if (fp == NULL) return -1;
+ chmod(filename,S_IRUSR|S_IWUSR);
+ for (j = 0; j < history_len; j++) {
+ fprintf(fp,"%s\n",history[j]);
+ }
+ fclose(fp);
+ return 0;
+}
+
+int
+redlineHistoryLoad(const char *filename)
+{
+ FILE *fp = fopen(filename,"r");
+ char buf[REDLINE_INITIAL_BUFLEN];
+ if (fp == NULL) return -1;
+ while (fgets(buf,sizeof(buf),fp) != NULL) {
+ char *p = strchr(buf,'\r');
+ if (!p) p = strchr(buf,'\n');
+ if (p) *p = '\0';
+ redlineHistoryAdd(buf);
+ }
+ fclose(fp);
+ return 0;
+}
+
+char *
+redlineHistoryGet(int idx)
+{
+ if (idx >= 0 && idx < history_len)
+ return history[idx];
+ return NULL;
+}
+
+int
+redlineHistoryLen(void)
+{
+ return history_len;
+}
+
+static void
+redlineEditHistoryNext(struct redlineState *l, int dir)
+{
+ if (history_len > 1) {
+ const char *src;
+ size_t len;
+ free(history[history_len - 1 - l->history_index]);
+ history[history_len - 1 - l->history_index] = strdup(l->buf);
+ l->history_index += (dir == 1) ? 1 : -1;
+ if (l->history_index < 0) {
+ l->history_index = 0;
+ return;
+ } else if (l->history_index >= history_len) {
+ l->history_index = history_len - 1;
+ return;
+ }
+ src = history[history_len - 1 - l->history_index];
+ len = strlen(src);
+ if (len >= l->buflen) len = l->buflen - 1;
+ memcpy(l->buf, src, len);
+ l->buf[len] = '\0';
+ l->len = l->pos = len;
+ refreshLine(l);
+ }
+}
+
+static char *
+redlineReadLine(FILE *fp)
+{
+ char *line = NULL;
+ size_t len = 0, cap = 0;
+ while (1) {
+ if (len+1 >= cap) {
+ size_t newcap = cap ? cap*2 : 16;
+ char *new = realloc(line, newcap);
+ if (!new) {
+ free(line);
+ return NULL;
+ }
+ line = new;
+ cap = newcap;
+ }
+ int c = fgetc(fp);
+ if (c == EOF || c == '\n') {
+ if (c == EOF && len == 0) {
+ free(line);
+ return NULL;
+ }
+ line[len] = '\0';
+ return line;
+ }
+ line[len++] = c;
+ }
+}
+
+static char *
+redlineNoTTY(void)
+{
+ return redlineReadLine(stdin);
+}
+
+void
+redlineClearScreen(void)
+{
+ if (write(STDOUT_FILENO, "\x1b[H\x1b[2J", 7) == -1) {}
+}
+
+static char *
+redlineEditFeed(struct redlineState *l)
+{
+ char c;
+ int nread;
+ char seq[3];
+ char param[8];
+ size_t plen;
+ char final;
+ char p;
+ int is_word_jump;
+ char tmp[32];
+ size_t prevlen;
+ size_t currlen;
+ size_t prevstart;
+ char utf8[4];
+ int utf8len;
+ int i;
+
+ if (!isatty(l->ifd) && !getenv("REDLINE_ASSUME_TTY")) return redlineNoTTY();
+
+ while (1) {
+ nread = read(l->ifd, &c, 1);
+ if (nread < 0) {
+ if (errno == EINTR) {
+ if (winch_received) {
+ winch_received = 0;
+ l->cols = getColumns(l->ifd, l->ofd);
+ refreshLine(l);
+ }
+ continue;
+ }
+ return (errno == EAGAIN || errno == EWOULDBLOCK) ? "more" : NULL;
+ } else if (nread == 0) {
+ return NULL;
+ }
+ break;
+ }
+
+ if ((l->in_completion || c == 9) && completionCallback != NULL) {
+ int retval = completeLine(l, c);
+ if (retval == 0) return "more";
+ c = retval;
+ }
+
+ switch (c) {
+ case ENTER:
+ if (mlmode) redlineEditMoveEnd(l);
+ return strdup(l->buf);
+ case CTRL_C:
+ errno = EAGAIN;
+ return NULL;
+ case BACKSPACE:
+ case 8:
+ redlineEditBackspace(l);
+ break;
+ case CTRL_D:
+ if (l->len > 0) {
+ redlineEditDelete(l);
+ } else {
+ errno = ENOENT;
+ return NULL;
+ }
+ break;
+ case CTRL_T:
+ if (l->pos > 0 && l->pos < l->len) {
+ prevlen = utf8PrevCharLen(l->buf, l->pos);
+ currlen = utf8NextCharLen(l->buf, l->pos, l->len);
+ prevstart = l->pos - prevlen;
+ if (prevlen > sizeof(tmp) || currlen > sizeof(tmp)) break;
+ memcpy(tmp, l->buf + l->pos, currlen);
+ memmove(l->buf + prevstart + currlen, l->buf + prevstart, prevlen);
+ memcpy(l->buf + prevstart, tmp, currlen);
+ if (l->pos + currlen <= l->len) l->pos += currlen;
+ refreshLine(l);
+ }
+ break;
+ case CTRL_B:
+ redlineEditMoveLeft(l);
+ break;
+ case CTRL_F:
+ redlineEditMoveRight(l);
+ break;
+ case CTRL_P:
+ redlineEditHistoryNext(l, 1);
+ break;
+ case CTRL_N:
+ redlineEditHistoryNext(l, 0);
+ break;
+ case ESC:
+ if (read(l->ifd, seq, 1) == -1) break;
+ if (seq[0] == '[' || seq[0] == 'O') {
+ if (read(l->ifd, seq+1, 1) == -1) break;
+ if (seq[0] == '[') {
+ if (seq[1] >= '0' && seq[1] <= '9') {
+ plen = 1;
+ final = 0;
+ param[0] = seq[1];
+ while (plen < sizeof(param)) {
+ if (read(l->ifd, &p, 1) != 1) break;
+ if ((p >= '0' && p <= '9') || p == ';') {
+ param[plen++] = p;
+ } else {
+ final = p;
+ break;
+ }
+ }
+ if (final == '~') {
+ if (plen == 1 && param[0] == '3') {
+ redlineEditDelete(l);
+ }
+ } else if (final == 'D' || final == 'C') {
+ is_word_jump = 0;
+ if (plen == 3 && param[0] == '1' && param[1] == ';' && (param[2] == '5' || param[2] == '3')) {
+ is_word_jump = 1;
+ } else if (plen == 1 && (param[0] == '5' || param[0] == '3')) {
+ is_word_jump = 1;
+ }
+ if (is_word_jump) {
+ if (final == 'D') {
+ redlineEditMoveWordLeft(l);
+ } else {
+ redlineEditMoveWordRight(l);
+ }
+ }
+ }
+ } else {
+ switch (seq[1]) {
+ case 'A':
+ redlineEditHistoryNext(l, 1);
+ break;
+ case 'B':
+ redlineEditHistoryNext(l, 0);
+ break;
+ case 'C':
+ redlineEditMoveRight(l);
+ break;
+ case 'D':
+ redlineEditMoveLeft(l);
+ break;
+ case 'H':
+ redlineEditMoveHome(l);
+ break;
+ case 'F':
+ redlineEditMoveEnd(l);
+ break;
+ }
+ }
+ } else if (seq[0] == 'O') {
+ switch (seq[1]) {
+ case 'H':
+ redlineEditMoveHome(l);
+ break;
+ case 'F':
+ redlineEditMoveEnd(l);
+ break;
+ }
+ }
+ } else {
+ if (seq[0] == 'b' || seq[0] == 'B') {
+ redlineEditMoveWordLeft(l);
+ } else if (seq[0] == 'f' || seq[0] == 'F') {
+ redlineEditMoveWordRight(l);
+ } else if (seq[0] == 'd' || seq[0] == 'D') {
+ redlineEditDeleteWordRight(l);
+ } else if (seq[0] == 127 || seq[0] == 8) {
+ redlineEditDeletePrevWord(l);
+ }
+ }
+ break;
+ default:
+ utf8len = utf8ByteLen(c);
+ utf8[0] = c;
+ if (utf8len > 1) {
+ for (i = 1; i < utf8len; i++) {
+ if (read(l->ifd, utf8+i, 1) != 1) break;
+ }
+ }
+ if (redlineEditInsert(l, utf8, utf8len) == 0) return NULL;
+ break;
+ case CTRL_U:
+ killBufferSave(l->buf, l->pos);
+ memmove(l->buf, l->buf + l->pos, l->len - l->pos + 1);
+ l->len -= l->pos;
+ l->pos = 0;
+ refreshLine(l);
+ break;
+ case CTRL_K:
+ killBufferSave(l->buf + l->pos, l->len - l->pos);
+ l->buf[l->pos] = '\0';
+ l->len = l->pos;
+ refreshLine(l);
+ break;
+ case CTRL_A:
+ redlineEditMoveHome(l);
+ break;
+ case CTRL_E:
+ redlineEditMoveEnd(l);
+ break;
+ case CTRL_L:
+ redlineClearScreen();
+ refreshLine(l);
+ break;
+ case CTRL_W:
+ redlineEditDeletePrevWord(l);
+ break;
+ case CTRL_Y:
+ if (kill_buffer) {
+ redlineEditInsert(l, kill_buffer, strlen(kill_buffer));
+ }
+ break;
+ }
+ return "more";
+}
+
+static int
+redlineEditStart(struct redlineState *l, int stdin_fd, int stdout_fd, char *buf, size_t buflen, const char *prompt)
+{
+ l->in_completion = 0;
+ l->ifd = stdin_fd;
+ l->ofd = stdout_fd;
+ l->buf = buf;
+ l->buflen = buflen;
+ l->prompt = prompt;
+ l->plen = strlen(prompt);
+ l->pos = 0;
+ l->oldpos = 0;
+ l->len = 0;
+ l->cols = getColumns(stdin_fd, stdout_fd);
+ l->oldrows = 0;
+ l->oldrpos = 0;
+ l->history_index = 0;
+ l->buf[0] = '\0';
+
+ if (enableRawMode(l->ifd) == -1) return -1;
+ refreshLine(l);
+ return 0;
+}
+
+static void
+redlineEditStop(struct redlineState *l)
+{
+ if (!isatty(l->ifd) && !getenv("REDLINE_ASSUME_TTY")) return;
+ disableRawMode(l->ifd);
+ printf("\n");
+}
+
+char *
+redline(const char *prompt)
+{
+ struct redlineState l;
+ char *buf;
+ char *res;
+
+ if (!isatty(STDIN_FILENO) || isUnsupportedTerm()) {
+ if (write(STDOUT_FILENO, prompt, strlen(prompt)) == -1) {}
+ return redlineNoTTY();
+ }
+
+ buf = malloc(REDLINE_INITIAL_BUFLEN);
+ if (buf == NULL) return NULL;
+ if (redlineEditStart(&l, STDIN_FILENO, STDOUT_FILENO, buf, REDLINE_INITIAL_BUFLEN, prompt) == -1) {
+ free(buf);
+ return NULL;
+ }
+ redlineHistoryAdd("");
+ while (1) {
+ res = redlineEditFeed(&l);
+ if (res == NULL || strcmp(res, "more") != 0) {
+ break;
+ }
+ }
+ redlineEditStop(&l);
+ if (history_len > 0) {
+ history_len--;
+ free(history[history_len]);
+ }
+ free(l.buf);
+ return res;
+}
+
+void
+redlineSetCompletionCallback(void (*cb)(const char *, struct redlineCompletions *))
+{
+ completionCallback = cb;
+}
+
+void
+redlineAddCompletion(struct redlineCompletions *lc, const char *str)
+{
+ size_t len = strlen(str);
+ char *copy, **cvec;
+
+ copy = malloc(len+1);
+ if (copy == NULL) return;
+ memcpy(copy,str,len+1);
+ cvec = realloc(lc->cvec,sizeof(char*)*(lc->len+1));
+ if (cvec == NULL) {
+ free(copy);
+ return;
+ }
+ lc->cvec = cvec;
+ lc->cvec[lc->len++] = copy;
+}
+
+void
+redlineSetMultiLine(int ml)
+{
+ mlmode = ml;
+}
diff --git a/shared/libutil/net.c b/shared/libutil/net.c
@@ -0,0 +1,403 @@
+#include "../util.h"
+
+#include <arpa/inet.h>
+#include <ctype.h>
+#include <errno.h>
+#include <ifaddrs.h>
+#include <net/if.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/ioctl.h>
+#include <sys/socket.h>
+#include <unistd.h>
+
+#ifdef __linux__
+#include <netpacket/packet.h>
+#else
+#include <net/if_dl.h>
+#include <sys/sysctl.h>
+#endif
+
+static void
+get_mtu_metric(const char *name, int *mtu, int *metric)
+{
+ struct ifreq ifr;
+ int sock;
+
+ *mtu = 0;
+ *metric = 0;
+ sock = socket(AF_INET, SOCK_DGRAM, 0);
+ if (sock < 0)
+ return;
+ memset(&ifr, 0, sizeof(ifr));
+ strlcpy(ifr.ifr_name, name, sizeof(ifr.ifr_name));
+ if (ioctl(sock, SIOCGIFMTU, &ifr) >= 0)
+ *mtu = ifr.ifr_mtu;
+ if (ioctl(sock, SIOCGIFMETRIC, &ifr) >= 0)
+ *metric = ifr.ifr_metric;
+ close(sock);
+}
+
+int
+net_get_interfaces(struct NetInterface **ifaces, int *count)
+{
+ struct ifaddrs *ifaddr, *ifa;
+ struct NetInterface *list = NULL;
+ struct NetInterface *iface;
+ int found_count = 0;
+ int i;
+
+ if (getifaddrs(&ifaddr) < 0)
+ return -1;
+
+ for (ifa = ifaddr; ifa; ifa = ifa->ifa_next) {
+ iface = NULL;
+ for (i = 0; i < found_count; i++) {
+ if (strcmp(list[i].name, ifa->ifa_name) == 0) {
+ iface = &list[i];
+ break;
+ }
+ }
+ if (!iface) {
+ list = reallocarray(list, found_count + 1, sizeof(*list));
+ if (!list) {
+ freeifaddrs(ifaddr);
+ return -1;
+ }
+ iface = &list[found_count];
+ memset(iface, 0, sizeof(*iface));
+ strlcpy(iface->name, ifa->ifa_name, sizeof(iface->name));
+ iface->flags = ifa->ifa_flags;
+ get_mtu_metric(iface->name, &iface->mtu, &iface->metric);
+ found_count++;
+ }
+
+ if (!ifa->ifa_addr)
+ continue;
+
+ if (ifa->ifa_addr->sa_family == AF_INET) {
+ memcpy(&iface->ipv4_addr, ifa->ifa_addr, sizeof(struct sockaddr_in));
+ iface->has_ipv4 = 1;
+ if (ifa->ifa_netmask)
+ memcpy(&iface->ipv4_mask, ifa->ifa_netmask, sizeof(struct sockaddr_in));
+ if (ifa->ifa_dstaddr)
+ memcpy(&iface->ipv4_brd, ifa->ifa_dstaddr, sizeof(struct sockaddr_in));
+ } else if (ifa->ifa_addr->sa_family == AF_INET6) {
+ memcpy(&iface->ipv6_addr, ifa->ifa_addr, sizeof(struct sockaddr_in6));
+ iface->has_ipv6 = 1;
+ /* scope id could be set here from sin6_scope_id */
+ }
+#ifdef __linux__
+ else if (ifa->ifa_addr->sa_family == AF_PACKET) {
+ struct sockaddr_ll *sll = (struct sockaddr_ll *)ifa->ifa_addr;
+ if (sll->sll_halen == 6) {
+ memcpy(iface->mac, sll->sll_addr, 6);
+ iface->has_mac = 1;
+ }
+ }
+#else
+ else if (ifa->ifa_addr->sa_family == AF_LINK) {
+ struct sockaddr_dl *sdl = (struct sockaddr_dl *)ifa->ifa_addr;
+ if (sdl->sdl_alen == 6) {
+ memcpy(iface->mac, LLADDR(sdl), 6);
+ iface->has_mac = 1;
+ }
+ }
+#endif
+ }
+
+ freeifaddrs(ifaddr);
+ *ifaces = list;
+ *count = found_count;
+ return 0;
+}
+
+#ifdef __linux__
+int
+net_get_stats(const char *ifname, struct NetStats *stats)
+{
+ FILE *fp;
+ char line[256];
+ char *p, *name;
+ int found = 0;
+
+ memset(stats, 0, sizeof(*stats));
+ fp = fopen("/proc/net/dev", "r");
+ if (!fp)
+ return -1;
+
+ while (fgets(line, sizeof(line), fp)) {
+ p = strchr(line, ':');
+ if (p) {
+ *p = '\0';
+ name = line;
+ while (isspace(*name))
+ name++;
+ if (strcmp(name, ifname) == 0) {
+ if (sscanf(p + 1, "%llu %llu %llu %llu %*u %*u %*u %*u %llu %llu %llu %llu",
+ &stats->rx_bytes, &stats->rx_packets, &stats->rx_errs, &stats->rx_drop,
+ &stats->tx_bytes, &stats->tx_packets, &stats->tx_errs, &stats->tx_drop) == 8) {
+ found = 1;
+ }
+ break;
+ }
+ }
+ }
+ fclose(fp);
+ return found ? 0 : -1;
+}
+#else
+int
+net_get_stats(const char *ifname, struct NetStats *stats)
+{
+ struct ifaddrs *ifaddr, *ifa;
+ int found = 0;
+
+ memset(stats, 0, sizeof(*stats));
+ if (getifaddrs(&ifaddr) < 0)
+ return -1;
+
+ for (ifa = ifaddr; ifa; ifa = ifa->ifa_next) {
+ if (ifa->ifa_addr && ifa->ifa_addr->sa_family == AF_LINK &&
+ strcmp(ifa->ifa_name, ifname) == 0) {
+ struct if_data *ifd = (struct if_data *)ifa->ifa_data;
+ if (ifd) {
+ stats->rx_bytes = ifd->ifi_ibytes;
+ stats->rx_packets = ifd->ifi_ipackets;
+ stats->rx_errs = ifd->ifi_ierrors;
+ stats->rx_drop = ifd->ifi_iqdrops;
+ stats->tx_bytes = ifd->ifi_obytes;
+ stats->tx_packets = ifd->ifi_opackets;
+ stats->tx_errs = ifd->ifi_oerrors;
+ stats->tx_drop = 0;
+ found = 1;
+ break;
+ }
+ }
+ }
+ freeifaddrs(ifaddr);
+ return found ? 0 : -1;
+}
+#endif
+
+#ifdef __linux__
+int
+net_set_txqueuelen(const char *name, int qlen)
+{
+ struct ifreq ifr;
+ int sock;
+
+ sock = socket(AF_INET, SOCK_DGRAM, 0);
+ if (sock < 0)
+ return -1;
+ memset(&ifr, 0, sizeof(ifr));
+ strlcpy(ifr.ifr_name, name, sizeof(ifr.ifr_name));
+ ifr.ifr_qlen = qlen;
+ if (ioctl(sock, SIOCSIFTXQLEN, &ifr) < 0) {
+ close(sock);
+ return -1;
+ }
+ close(sock);
+ return 0;
+}
+#else
+int
+net_set_txqueuelen(const char *name, int qlen)
+{
+ (void)name;
+ (void)qlen;
+ return -1;
+}
+#endif
+
+int
+net_set_flags(const char *name, unsigned int flags, int set)
+{
+ struct ifreq ifr;
+ int sock;
+
+ sock = socket(AF_INET, SOCK_DGRAM, 0);
+ if (sock < 0)
+ return -1;
+ memset(&ifr, 0, sizeof(ifr));
+ strlcpy(ifr.ifr_name, name, sizeof(ifr.ifr_name));
+ if (ioctl(sock, SIOCGIFFLAGS, &ifr) < 0) {
+ close(sock);
+ return -1;
+ }
+ if (set)
+ ifr.ifr_flags |= flags;
+ else
+ ifr.ifr_flags &= ~flags;
+ if (ioctl(sock, SIOCSIFFLAGS, &ifr) < 0) {
+ close(sock);
+ return -1;
+ }
+ close(sock);
+ return 0;
+}
+
+int
+net_set_mtu(const char *name, int mtu)
+{
+ struct ifreq ifr;
+ int sock;
+
+ sock = socket(AF_INET, SOCK_DGRAM, 0);
+ if (sock < 0)
+ return -1;
+ memset(&ifr, 0, sizeof(ifr));
+ strlcpy(ifr.ifr_name, name, sizeof(ifr.ifr_name));
+ ifr.ifr_mtu = mtu;
+ if (ioctl(sock, SIOCSIFMTU, &ifr) < 0) {
+ close(sock);
+ return -1;
+ }
+ close(sock);
+ return 0;
+}
+
+int
+net_set_mac(const char *name, const unsigned char mac[6])
+{
+#ifdef __linux__
+ struct ifreq ifr;
+ int sock;
+
+ sock = socket(AF_INET, SOCK_DGRAM, 0);
+ if (sock < 0)
+ return -1;
+ memset(&ifr, 0, sizeof(ifr));
+ strlcpy(ifr.ifr_name, name, sizeof(ifr.ifr_name));
+ ifr.ifr_hwaddr.sa_family = 1;
+ memcpy(ifr.ifr_hwaddr.sa_data, mac, 6);
+ if (ioctl(sock, SIOCSIFHWADDR, &ifr) < 0) {
+ close(sock);
+ return -1;
+ }
+ close(sock);
+ return 0;
+#else
+ (void)name;
+ (void)mac;
+ return -1;
+#endif
+}
+
+int
+net_add_addr(const char *name, const char *addr, int prefix)
+{
+ struct ifreq ifr;
+ struct sockaddr_in *sin;
+ int sock;
+ unsigned int mask;
+
+ sock = socket(AF_INET, SOCK_DGRAM, 0);
+ if (sock < 0)
+ return -1;
+
+ memset(&ifr, 0, sizeof(ifr));
+ strlcpy(ifr.ifr_name, name, sizeof(ifr.ifr_name));
+
+ sin = (struct sockaddr_in *)&ifr.ifr_addr;
+ sin->sin_family = AF_INET;
+ if (inet_pton(AF_INET, addr, &sin->sin_addr) <= 0) {
+ close(sock);
+ return -1;
+ }
+
+ if (ioctl(sock, SIOCSIFADDR, &ifr) < 0) {
+ close(sock);
+ return -1;
+ }
+
+ if (prefix >= 0) {
+ mask = 0;
+ if (prefix > 0)
+ mask = htonl(~0U << (32 - prefix));
+ sin = (struct sockaddr_in *)&ifr.ifr_netmask;
+ sin->sin_family = AF_INET;
+ sin->sin_addr.s_addr = mask;
+ if (ioctl(sock, SIOCSIFNETMASK, &ifr) < 0) {
+ close(sock);
+ return -1;
+ }
+ }
+
+ memset(&ifr, 0, sizeof(ifr));
+ strlcpy(ifr.ifr_name, name, sizeof(ifr.ifr_name));
+ if (ioctl(sock, SIOCGIFFLAGS, &ifr) >= 0) {
+ ifr.ifr_flags |= IFF_UP | IFF_RUNNING;
+ ioctl(sock, SIOCSIFFLAGS, &ifr);
+ }
+
+ close(sock);
+ return 0;
+}
+
+int
+net_del_addr(const char *name, const char *addr, int prefix)
+{
+ struct ifreq ifr;
+ struct sockaddr_in *sin;
+ int sock;
+
+ (void)prefix;
+ sock = socket(AF_INET, SOCK_DGRAM, 0);
+ if (sock < 0)
+ return -1;
+
+ memset(&ifr, 0, sizeof(ifr));
+ strlcpy(ifr.ifr_name, name, sizeof(ifr.ifr_name));
+
+ sin = (struct sockaddr_in *)&ifr.ifr_addr;
+ sin->sin_family = AF_INET;
+ if (inet_pton(AF_INET, addr, &sin->sin_addr) <= 0) {
+ close(sock);
+ return -1;
+ }
+
+ if (ioctl(sock, SIOCDIFADDR, &ifr) < 0) {
+ close(sock);
+ return -1;
+ }
+ close(sock);
+ return 0;
+}
+
+int
+net_show_routes(void)
+{
+#ifdef __linux__
+ FILE *fp;
+ char line[256];
+ char iface[16], dest[16], gateway[16], mask[16];
+ unsigned int d, g, m, flags, metric;
+
+ fp = fopen("/proc/net/route", "r");
+ if (!fp)
+ return -1;
+
+ printf("%-10s %-15s %-15s %-15s %-6s %-6s\n", "Iface", "Destination", "Gateway", "Genmask", "Flags", "Metric");
+ if (fgets(line, sizeof(line), fp)) {
+ while (fgets(line, sizeof(line), fp)) {
+ if (sscanf(line, "%15s %x %x %x %*u %*u %u %x", iface, &d, &g, &m, &metric, &flags) == 6) {
+ struct in_addr dest_addr, gw_addr, mask_addr;
+ dest_addr.s_addr = d;
+ gw_addr.s_addr = g;
+ mask_addr.s_addr = m;
+ strlcpy(dest, inet_ntoa(dest_addr), sizeof(dest));
+ strlcpy(gateway, inet_ntoa(gw_addr), sizeof(gateway));
+ strlcpy(mask, inet_ntoa(mask_addr), sizeof(mask));
+ printf("%-10s %-15s %-15s %-15s 0x%04X %-6u\n", iface, dest, gateway, mask, flags, metric);
+ }
+ }
+ }
+ fclose(fp);
+ return 0;
+#else
+ printf("route listing not implemented on this OS\n");
+ return 0;
+#endif
+}
diff --git a/shared/libutil/sysinfo.c b/shared/libutil/sysinfo.c
@@ -0,0 +1,147 @@
+#include "../util.h"
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <time.h>
+#include <unistd.h>
+
+#ifdef __linux__
+#include <sys/sysinfo.h>
+#else
+#include <sys/sysctl.h>
+#include <sys/time.h>
+#endif
+
+int
+get_uptime(long *uptime_secs)
+{
+#ifdef __linux__
+ struct sysinfo info;
+
+ if (sysinfo(&info) < 0)
+ return -1;
+ *uptime_secs = info.uptime;
+ return 0;
+#else
+ struct timeval boottime;
+ size_t len = sizeof(boottime);
+ int mib[2] = { CTL_KERN, KERN_BOOTTIME };
+ time_t now;
+
+ if (sysctl(mib, 2, &boottime, &len, NULL, 0) < 0)
+ return -1;
+ time(&now);
+ *uptime_secs = (long)(now - boottime.tv_sec);
+ return 0;
+#endif
+}
+
+int
+get_loads(double loads[3])
+{
+ if (getloadavg(loads, 3) != 3)
+ return -1;
+ return 0;
+}
+
+int
+get_meminfo(struct MemInfo *mi)
+{
+ memset(mi, 0, sizeof(*mi));
+#ifdef __linux__
+ struct sysinfo info;
+ unsigned long long unit;
+
+ if (sysinfo(&info) < 0)
+ return -1;
+ unit = info.mem_unit ? info.mem_unit : 1;
+ mi->total = info.totalram * unit;
+ mi->free = info.freeram * unit;
+ mi->shared = info.sharedram * unit;
+ mi->buffers = info.bufferram * unit;
+ mi->cached = 0;
+ mi->totalswap = info.totalswap * unit;
+ mi->freeswap = info.freeswap * unit;
+ return 0;
+#else
+ int mib[2];
+ size_t len;
+ unsigned long physmem = 0;
+ unsigned int page_size = 4096;
+ unsigned int free_pages = 0;
+
+ mib[0] = CTL_HW;
+ mib[1] = HW_PHYSMEM;
+ len = sizeof(physmem);
+ if (sysctl(mib, 2, &physmem, &len, NULL, 0) < 0)
+ return -1;
+ mi->total = physmem;
+
+ mib[0] = CTL_HW;
+ mib[1] = HW_PAGESIZE;
+ len = sizeof(page_size);
+ sysctl(mib, 2, &page_size, &len, NULL, 0);
+
+ len = sizeof(free_pages);
+ if (sysctlbyname("vm.stats.vm.v_free_count", &free_pages, &len, NULL, 0) >= 0) {
+ mi->free = (unsigned long long)free_pages * page_size;
+ } else {
+ mi->free = mi->total / 4;
+ }
+ return 0;
+#endif
+}
+
+#ifdef __linux__
+#include <sys/klog.h>
+ssize_t
+get_dmesg(char *buf, size_t len)
+{
+ if (!buf && len == 0)
+ return klogctl(10, NULL, 0);
+ return klogctl(3, buf, len);
+}
+
+int
+clear_dmesg(void)
+{
+ if (klogctl(5, NULL, 0) < 0)
+ return -1;
+ return 0;
+}
+
+int
+set_console_level(int level)
+{
+ if (klogctl(8, NULL, level) < 0)
+ return -1;
+ return 0;
+}
+#else
+ssize_t
+get_dmesg(char *buf, size_t len)
+{
+ int mib[2];
+ size_t needed = len;
+
+ mib[0] = CTL_KERN;
+ mib[1] = KERN_MSGBUF;
+ if (sysctl(mib, 2, buf, &needed, NULL, 0) < 0)
+ return -1;
+ return (ssize_t)needed;
+}
+
+int
+clear_dmesg(void)
+{
+ return -1;
+}
+
+int
+set_console_level(int level)
+{
+ (void)level;
+ return -1;
+}
+#endif
diff --git a/shared/libutil/tls.c b/shared/libutil/tls.c
@@ -0,0 +1,437 @@
+/* see license file for copyright and license details */
+#include "../tls.h"
+#include "../util.h"
+
+#include <errno.h>
+#include <signal.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+
+#if FEATURE_USE_LIBRESSL
+#include <tls.h>
+
+struct TlsSocket {
+ int fd;
+ int is_tls;
+ struct tls *ctx;
+};
+
+#elif FEATURE_USE_BEARSSL
+#include <bearssl.h>
+
+struct my_x509_context {
+ const br_x509_class *vtable;
+ br_x509_minimal_context minimal;
+};
+
+struct TlsSocket {
+ int fd;
+ int is_tls;
+ br_ssl_client_context sc;
+ struct my_x509_context my_x509;
+ unsigned char iobuf[BR_SSL_BUFSIZE_BIDI];
+ br_sslio_context ioc;
+};
+
+struct dn_accum {
+ unsigned char *data;
+ size_t len;
+ size_t cap;
+};
+
+static void
+append_dn_callback(void *dn_ctx, const void *src, size_t len)
+{
+ struct dn_accum *accum = dn_ctx;
+ if (accum->len + len > accum->cap) {
+ accum->cap = accum->len + len + 256;
+ accum->data = erealloc(accum->data, accum->cap);
+ }
+ memcpy(accum->data + accum->len, src, len);
+ accum->len += len;
+}
+
+static void
+my_start_chain(const br_x509_class **ctx, const char *server_name)
+{
+ struct my_x509_context *t = (struct my_x509_context *)ctx;
+ br_x509_minimal_vtable.start_chain((const br_x509_class **)&t->minimal, server_name);
+}
+
+static void
+my_start_cert(const br_x509_class **ctx, uint32_t length)
+{
+ struct my_x509_context *t = (struct my_x509_context *)ctx;
+ br_x509_minimal_vtable.start_cert((const br_x509_class **)&t->minimal, length);
+}
+
+static void
+my_append(const br_x509_class **ctx, const unsigned char *buf, size_t len)
+{
+ struct my_x509_context *t = (struct my_x509_context *)ctx;
+ br_x509_minimal_vtable.append((const br_x509_class **)&t->minimal, buf, len);
+}
+
+static void
+my_end_cert(const br_x509_class **ctx)
+{
+ struct my_x509_context *t = (struct my_x509_context *)ctx;
+ br_x509_minimal_vtable.end_cert((const br_x509_class **)&t->minimal);
+}
+
+static unsigned
+my_end_chain(const br_x509_class **ctx)
+{
+ struct my_x509_context *t = (struct my_x509_context *)ctx;
+ (void)br_x509_minimal_vtable.end_chain((const br_x509_class **)&t->minimal);
+ /* always succeed and accept certificate when check_cert is 0 */
+ return 0;
+}
+
+static const br_x509_pkey *
+my_get_pkey(const br_x509_class *const *ctx, unsigned *usages)
+{
+ const struct my_x509_context *t = (const struct my_x509_context *)ctx;
+ return br_x509_minimal_vtable.get_pkey((const br_x509_class *const *)&t->minimal, usages);
+}
+
+static const br_x509_class my_x509_vtable = {
+ sizeof(struct my_x509_context),
+ my_start_chain,
+ my_start_cert,
+ my_append,
+ my_end_cert,
+ my_end_chain,
+ my_get_pkey
+};
+
+static int
+sock_read(void *ctx, unsigned char *buf, size_t len)
+{
+ int fd = *(int *)ctx;
+ for (;;) {
+ ssize_t rlen = read(fd, buf, len);
+ if (rlen <= 0) {
+ if (rlen < 0 && errno == EINTR)
+ continue;
+ return -1;
+ }
+ return (int)rlen;
+ }
+}
+
+static int
+sock_write(void *ctx, const unsigned char *buf, size_t len)
+{
+ int fd = *(int *)ctx;
+ for (;;) {
+ ssize_t wlen = write(fd, buf, len);
+ if (wlen <= 0) {
+ if (wlen < 0 && errno == EINTR)
+ continue;
+ return -1;
+ }
+ return (int)wlen;
+ }
+}
+
+static int
+b64_decode_char(char c)
+{
+ if (c >= 'A' && c <= 'Z') return c - 'A';
+ if (c >= 'a' && c <= 'z') return c - 'a' + 26;
+ if (c >= '0' && c <= '9') return c - '0' + 52;
+ if (c == '+') return 62;
+ if (c == '/') return 63;
+ return -1;
+}
+
+static size_t
+b64_decode(const char *src, size_t src_len, unsigned char *dst)
+{
+ size_t i, j = 0;
+ int val = 0, valb = -8;
+ for (i = 0; i < src_len; i++) {
+ int c = b64_decode_char(src[i]);
+ if (c >= 0) {
+ val = (val << 6) | c;
+ valb += 6;
+ if (valb >= 0) {
+ dst[j++] = (val >> valb) & 0xFF;
+ valb -= 8;
+ }
+ }
+ }
+ return j;
+}
+
+static int
+decode_cert_der(const unsigned char *der, size_t der_len, br_x509_trust_anchor *ta)
+{
+ br_x509_decoder_context dc;
+ struct dn_accum accum = { NULL, 0, 0 };
+ const br_x509_pkey *pk;
+
+ br_x509_decoder_init(&dc, append_dn_callback, &accum);
+ br_x509_decoder_push(&dc, der, der_len);
+ if (br_x509_decoder_last_error(&dc) != 0) {
+ free(accum.data);
+ return 0;
+ }
+ pk = br_x509_decoder_get_pkey(&dc);
+ if (!pk) {
+ free(accum.data);
+ return 0;
+ }
+
+ ta->dn.data = accum.data;
+ ta->dn.len = accum.len;
+ ta->flags = br_x509_decoder_isCA(&dc) ? BR_X509_TA_CA : 0;
+ ta->pkey.key_type = pk->key_type;
+
+ if (pk->key_type == BR_KEYTYPE_RSA) {
+ ta->pkey.key.rsa.nlen = pk->key.rsa.nlen;
+ ta->pkey.key.rsa.n = emalloc(pk->key.rsa.nlen);
+ memcpy(ta->pkey.key.rsa.n, pk->key.rsa.n, pk->key.rsa.nlen);
+ ta->pkey.key.rsa.elen = pk->key.rsa.elen;
+ ta->pkey.key.rsa.e = emalloc(pk->key.rsa.elen);
+ memcpy(ta->pkey.key.rsa.e, pk->key.rsa.e, pk->key.rsa.elen);
+ } else if (pk->key_type == BR_KEYTYPE_EC) {
+ ta->pkey.key.ec.curve = pk->key.ec.curve;
+ ta->pkey.key.ec.qlen = pk->key.ec.qlen;
+ ta->pkey.key.ec.q = emalloc(pk->key.ec.qlen);
+ memcpy(ta->pkey.key.ec.q, pk->key.ec.q, pk->key.ec.qlen);
+ } else {
+ free(accum.data);
+ return 0;
+ }
+ return 1;
+}
+
+static br_x509_trust_anchor *tas = NULL;
+static size_t tas_num = 0;
+
+static void
+load_ca_certs(void)
+{
+ static const char *ca_paths[] = {
+ "/etc/ssl/certs/ca-certificates.crt",
+ "/etc/ssl/cert.pem",
+ "/etc/pki/tls/certs/ca-bundle.crt",
+ };
+ FILE *fp = NULL;
+ size_t i;
+ char line[512];
+ struct {
+ char *data;
+ size_t len;
+ size_t cap;
+ } pem = { NULL, 0, 0 };
+ int in_cert = 0;
+
+ for (i = 0; i < LEN(ca_paths); i++) {
+ if ((fp = fopen(ca_paths[i], "r")))
+ break;
+ }
+ if (!fp) {
+ weprintf("no CA certificates found, TLS verification will fail\n");
+ return;
+ }
+
+ while (fgets(line, sizeof(line), fp)) {
+ if (strncmp(line, "-----BEGIN CERTIFICATE-----", 27) == 0) {
+ in_cert = 1;
+ pem.len = 0;
+ } else if (strncmp(line, "-----END CERTIFICATE-----", 25) == 0) {
+ if (in_cert) {
+ unsigned char *der = emalloc(pem.len);
+ size_t der_len = b64_decode(pem.data, pem.len, der);
+ br_x509_trust_anchor ta;
+ if (decode_cert_der(der, der_len, &ta)) {
+ tas = ereallocarray(tas, tas_num + 1, sizeof(*tas));
+ tas[tas_num++] = ta;
+ }
+ free(der);
+ in_cert = 0;
+ }
+ } else if (in_cert) {
+ size_t llen = strlen(line);
+ while (llen > 0 && (line[llen-1] == '\r' || line[llen-1] == '\n'))
+ llen--;
+ if (pem.len + llen > pem.cap) {
+ pem.cap = pem.len + llen + 1024;
+ pem.data = erealloc(pem.data, pem.cap);
+ }
+ memcpy(pem.data + pem.len, line, llen);
+ pem.len += llen;
+ }
+ }
+ free(pem.data);
+ fclose(fp);
+}
+#else
+struct TlsSocket {
+ int fd;
+ int is_tls;
+};
+#endif
+
+struct TlsSocket *
+tls_connect(int fd, const char *host, int check_cert, int is_tls)
+{
+ struct TlsSocket *s;
+
+ s = emalloc(sizeof(*s));
+ s->fd = fd;
+ s->is_tls = is_tls;
+
+ if (!is_tls)
+ return s;
+
+#if FEATURE_USE_LIBRESSL
+ {
+ struct tls_config *cfg;
+
+ s->ctx = tls_client();
+ if (!s->ctx) {
+ weprintf("tls_client failed\n");
+ free(s);
+ return NULL;
+ }
+ cfg = tls_config_new();
+ if (!cfg) {
+ weprintf("tls_config_new failed\n");
+ tls_free(s->ctx);
+ free(s);
+ return NULL;
+ }
+ if (!check_cert) {
+ tls_config_insecure_noverifycert(cfg);
+ tls_config_insecure_noverifyname(cfg);
+ }
+ if (tls_configure(s->ctx, cfg) < 0) {
+ weprintf("tls_configure: %s\n", tls_error(s->ctx));
+ tls_config_free(cfg);
+ tls_free(s->ctx);
+ free(s);
+ return NULL;
+ }
+ tls_config_free(cfg);
+
+ if (tls_connect_socket(s->ctx, fd, host) < 0) {
+ weprintf("tls_connect_socket: %s\n", tls_error(s->ctx));
+ tls_free(s->ctx);
+ free(s);
+ return NULL;
+ }
+ }
+#elif FEATURE_USE_BEARSSL
+ {
+ signal(SIGPIPE, SIG_IGN);
+
+ if (check_cert) {
+ static int ca_loaded = 0;
+ if (!ca_loaded) {
+ load_ca_certs();
+ ca_loaded = 1;
+ }
+ br_ssl_client_init_full(&s->sc, &s->my_x509.minimal, tas, tas_num);
+ } else {
+ br_ssl_client_init_full(&s->sc, &s->my_x509.minimal, NULL, 0);
+ s->my_x509.vtable = &my_x509_vtable;
+ br_ssl_engine_set_x509(&s->sc.eng, &s->my_x509.vtable);
+ }
+
+ br_ssl_engine_set_buffer(&s->sc.eng, s->iobuf, sizeof(s->iobuf), 1);
+ br_ssl_client_reset(&s->sc, host, 0);
+ br_sslio_init(&s->ioc, &s->sc.eng, sock_read, &s->fd, sock_write, &s->fd);
+
+ if (br_sslio_flush(&s->ioc) < 0) {
+ weprintf("TLS handshake failed with %s\n", host);
+ free(s);
+ return NULL;
+ }
+ }
+#else
+ weprintf("TLS not supported, compile with FEATURE_USE_LIBRESSL or FEATURE_USE_BEARSSL\n");
+ free(s);
+ return NULL;
+#endif
+
+ return s;
+}
+
+ssize_t
+tls_read(struct TlsSocket *s, void *buf, size_t len)
+{
+ if (!s->is_tls) {
+ for (;;) {
+ ssize_t r = read(s->fd, buf, len);
+ if (r < 0 && errno == EINTR)
+ continue;
+ return r;
+ }
+ }
+#if FEATURE_USE_LIBRESSL
+ for (;;) {
+ ssize_t r = tls_read(s->ctx, buf, len);
+ if (r == TLS_WANT_POLLIN || r == TLS_WANT_POLLOUT)
+ continue;
+ return r;
+ }
+#elif FEATURE_USE_BEARSSL
+ return br_sslio_read(&s->ioc, buf, len);
+#else
+ return -1;
+#endif
+}
+
+ssize_t
+tls_write(struct TlsSocket *s, const void *buf, size_t len)
+{
+ if (!s->is_tls) {
+ for (;;) {
+ ssize_t r = write(s->fd, buf, len);
+ if (r < 0 && errno == EINTR)
+ continue;
+ return r;
+ }
+ }
+#if FEATURE_USE_LIBRESSL
+ for (;;) {
+ ssize_t r = tls_write(s->ctx, buf, len);
+ if (r == TLS_WANT_POLLIN || r == TLS_WANT_POLLOUT)
+ continue;
+ return r;
+ }
+#elif FEATURE_USE_BEARSSL
+ {
+ int r = br_sslio_write_all(&s->ioc, buf, len);
+ if (r < 0)
+ return -1;
+ if (br_sslio_flush(&s->ioc) < 0)
+ return -1;
+ return len;
+ }
+#else
+ return -1;
+#endif
+}
+
+void
+tls_close(struct TlsSocket *s, int close_fd)
+{
+ if (s->is_tls) {
+#if FEATURE_USE_LIBRESSL
+ tls_close(s->ctx);
+ tls_free(s->ctx);
+#elif FEATURE_USE_BEARSSL
+ br_sslio_close(&s->ioc);
+#endif
+ }
+ if (close_fd)
+ close(s->fd);
+ free(s);
+}
diff --git a/shared/redline.h b/shared/redline.h
@@ -0,0 +1,24 @@
+/* see license file for copyright and license details */
+#ifndef REDLINE_H_
+#define REDLINE_H_
+
+#include <stddef.h>
+
+struct redlineCompletions {
+ size_t len;
+ char **cvec;
+};
+
+char *redline(const char *prompt);
+void redlineSetCompletionCallback(void (*cb)(const char *, struct redlineCompletions *));
+void redlineAddCompletion(struct redlineCompletions *lc, const char *str);
+void redlineHistoryAdd(const char *line);
+void redlineHistorySetMaxLen(int len);
+int redlineHistorySave(const char *filename);
+int redlineHistoryLoad(const char *filename);
+char *redlineHistoryGet(int idx);
+int redlineHistoryLen(void);
+void redlineSetMultiLine(int ml);
+void redlineClearScreen(void);
+
+#endif /* REDLINE_H_ */
diff --git a/shared/tls.h b/shared/tls.h
@@ -0,0 +1,21 @@
+/* see license file for copyright and license details */
+#ifndef TLS_H_
+#define TLS_H_
+
+#include <sys/types.h>
+
+struct TlsSocket;
+
+/* tls_connect takes an already connected socket fd and upgrades it to tls
+ if check_cert is 0 certificate validation is bypassed
+ returns a new tls socket or null on error */
+struct TlsSocket *tls_connect(int fd, const char *host, int check_cert, int is_tls);
+
+/* standard read and write wrapping either libressl bearssl or plain fallback */
+ssize_t tls_read(struct TlsSocket *s, void *buf, size_t len);
+ssize_t tls_write(struct TlsSocket *s, const void *buf, size_t len);
+
+/* closes the tls connection and optionally closes the socket fd */
+void tls_close(struct TlsSocket *s, int close_fd);
+
+#endif /* tls_h_ */
diff --git a/shared/util.h b/shared/util.h
@@ -106,3 +106,52 @@ void explicit_bzero(void *, size_t);
void recurse_dir(const char *, void (*)(const char *));
void devtotty(int, int *, int *);
int ttytostr(int, int, char *, size_t);
+
+#include <sys/socket.h>
+#include <netinet/in.h>
+
+#ifndef IFNAMSIZ
+#define IFNAMSIZ 16
+#endif
+
+struct NetStats {
+ unsigned long long rx_bytes;
+ unsigned long long rx_packets;
+ unsigned long long rx_errs;
+ unsigned long long rx_drop;
+ unsigned long long tx_bytes;
+ unsigned long long tx_packets;
+ unsigned long long tx_errs;
+ unsigned long long tx_drop;
+};
+
+struct NetInterface {
+ char name[IFNAMSIZ];
+ unsigned int flags;
+ int mtu;
+ int metric;
+ unsigned char mac[6];
+ int has_mac;
+
+ /* ipv4 addresses */
+ struct sockaddr_in ipv4_addr;
+ int has_ipv4;
+ struct sockaddr_in ipv4_mask;
+ struct sockaddr_in ipv4_brd;
+
+ /* ipv6 addresses */
+ struct sockaddr_in6 ipv6_addr;
+ int has_ipv6;
+ unsigned int ipv6_scope;
+ unsigned int ipv6_prefix;
+};
+
+struct MemInfo {
+ unsigned long long total;
+ unsigned long long free;
+ unsigned long long shared;
+ unsigned long long buffers;
+ unsigned long long cached;
+ unsigned long long totalswap;
+ unsigned long long freeswap;
+};