Compare commits

..
309 Commits
Author SHA1 Message Date
Joachim Nilsson 6daebf4ea4 Bump version for v1.9.3 release
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2017-10-24 15:56:30 +02:00
Joachim Nilsson 4d6e3e060e Update ChangeLog(s) for v1.9.3
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2017-10-24 15:56:17 +02:00
Joachim Nilsson 86eef8e38d tree(): Increase internal buffer size, result may be truncated
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2017-10-24 08:42:55 +02:00
Joachim Nilsson d5d3dafc78 Slight ABI bump due to changes in initscr()
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2017-10-24 08:38:10 +02:00
Joachim Nilsson 2534c398ea initscr(): Use stdout, not stderr, just like other conio.h macros
A program's stderr may have been redirected by the operator.  We want to
query the size of stdout, even though it is buffered, so add fflush() to
handle that.

Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2017-10-24 08:33:02 +02:00
Joachim Nilsson 3691044007 conio.h: initscr() requires termios.h as well
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2017-10-24 08:32:30 +02:00
Joachim Nilsson 6770dad0cc conio.h: Minor, whitespace only
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2017-10-24 08:32:18 +02:00
Joachim Nilsson ef0db5e766 initscr(): Check if stdin and stdout are TTYs first
Programs that may be called in the background or with the stdin/stdout
redirected are not proper TTYs and we should not try to perform any
tricks on them.  This patch checks isatty() and returns standard term
sizes as a fallback.

Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2017-10-24 08:31:43 +02:00
Joachim Nilsson 485463c70e Update tree() test, use /usr/sbin instead of /sbin
Seems Debian finally went through with their move to symlink /bin and
/sbin to /usr/bin and /usr/sbin, respectively.

Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2017-09-30 11:13:23 +02:00
Joachim Nilsson 4b77eb1423 Update ChangeLog diff URLs
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2017-09-22 16:27:08 +02:00
Joachim Nilsson 0b54dc6015 Update Debian packaging, v1.9.2-1
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2017-08-15 08:15:30 +02:00
Joachim Nilsson 9d6df87d0d Update ChangeLog and bump version for v1.9.2 release
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2017-07-09 15:52:29 +02:00
Joachim Nilsson 5b2eee6aff conio.h: Minor refactor, cleanup
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2017-07-09 15:46:49 +02:00
Joachim Nilsson 6904f6e0fe conio.h: Add initscr(), probes terminal rows + cols
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2017-07-07 13:19:53 +02:00
Joachim Nilsson 877ba02d13 conio.h: Revert 018e607, fails unit tests
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2017-07-07 13:19:23 +02:00
Joachim Nilsson 25dfded835 conio.h: Update copyright years
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2017-07-07 12:51:43 +02:00
Joachim Nilsson 1323a88e94 conio.h: Convert printheader() to static inline function
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2017-07-07 12:51:25 +02:00
Joachim Nilsson 018e607290 conio.h: Use stderr instead of stdout because it's non-buffered
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2017-07-07 11:58:48 +02:00
Joachim Nilsson e48c9c5589 Bump version and update ChangeLog for v1.9.1, minor fix release
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2017-07-03 12:57:52 +02:00
Joachim Nilsson 2c875afe06 which: Allow which("ps aux"), which skips any arguments to command
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2017-07-03 12:48:02 +02:00
Joachim Nilsson 10e4a1d057 Update which() unit test, check for /bin/which and /bin/ps aux
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2017-07-03 12:45:33 +02:00
Joachim Nilsson 3dde2922c3 Add whichp() predicate function to which()
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2017-07-03 12:34:05 +02:00
Joachim Nilsson 4dd9459f65 Update debian/changelog for v1.9.0-1
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2017-07-02 19:23:49 +02:00
Joachim Nilsson 7172f487d5 Bump version for v1.9.0 GA release
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2017-07-02 19:18:55 +02:00
Joachim Nilsson 4c0967405d Bump ABI version, removed UNUSED() added which(), fixed touch()
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2017-07-02 19:18:55 +02:00
Joachim Nilsson fd65af31db Update HACKING document, mostly wrt library versioning
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2017-07-02 19:18:55 +02:00
Joachim Nilsson e55976d137 Update ChangeLog for v1.9 release
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2017-07-02 19:18:55 +02:00
Joachim Nilsson 1b1ffb33f1 Bump version to v1.9 due to new functionality, which()
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2017-07-02 16:51:21 +02:00
Joachim Nilsson d018a5215f which.c: C implementation of UNIX which(1)
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2017-07-02 16:50:58 +02:00
Joachim Nilsson 0d70c116d7 Update .gitignore files
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2017-07-02 16:33:00 +02:00
Joachim Nilsson 32c774deef tree(): Refactor, flatten tree
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2017-07-02 16:32:04 +02:00
Joachim Nilsson 441d5f58d7 Add simple ocular unit test for printheader()
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2017-06-30 20:28:31 +02:00
Joachim Nilsson 2a59289d53 conio.h: Add top-like heading macro, printheader()
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2017-06-30 20:27:59 +02:00
Joachim Nilsson f89c3c88de Clear build warnings for unit tests
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2017-06-30 17:43:11 +02:00
Joachim Nilsson 705b402344 Remove UNUSED() macro, just use -Wno-unused instead
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2017-06-30 17:36:10 +02:00
Joachim Nilsson fe82ab953c Fix non-writable tempfile(), "rw" --> "w+", found by Westermo
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2017-06-18 18:18:08 +02:00
Joachim Nilsson 6ec2a31042 Update tempfile() unit test to detect failed write + read
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2017-06-18 18:14:39 +02:00
Joachim Nilsson 9f5e852084 Bump version in preparation for 1.8.4 bug-fix release
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2017-05-20 09:29:26 +02:00
Joachim Nilsson 628c5597b9 Fix issue #6: touch does not update mtime if file exists
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2017-05-19 17:50:44 +02:00
Joachim Nilsson b7b635a3f4 Add unit test for touch to replicate issue #6
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2017-05-19 17:50:22 +02:00
Joachim Nilsson dd53c3ae9e Minor refactor of unit tests
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2017-05-19 17:50:07 +02:00
Joachim Nilsson 16a30a293c Add support for make package to build .deb files
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2017-03-12 17:43:53 +01:00
Joachim Nilsson 325fcbe149 lite.h: Add whitespace to compat macros, for readability
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2017-03-12 17:43:31 +01:00
Joachim Nilsson cbb1604ea0 New release for .deb package, 1.8.3-1
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2017-01-08 15:22:42 +01:00
Joachim Nilsson 8587971fb9 Update ChangeLog and bump version for v1.8.3 release
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2017-01-08 15:17:17 +01:00
Joachim Nilsson 6545ac8fd4 Bump ABI revision 3:0:0 --> 3:1:0
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2017-01-08 15:16:36 +01:00
Joachim Nilsson 9105e8d3d8 Update pidfile() documentation
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2017-01-08 15:16:00 +01:00
Joachim Nilsson 3555af6a6a Update ChangeLog and bump version for upcoming v1.8.3 release
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2017-01-07 13:58:59 +01:00
Joachim Nilsson 42715eab8a ChangeLog: Add missing link to v1.8.2 release
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2017-01-07 13:57:57 +01:00
Joachim Nilsson 497d58dbf0 ChangeLog: Minor Markdown fixes
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2017-01-07 13:57:21 +01:00
Joachim Nilsson 9ab70ebbcd Build all unit tests static, for easier debugging
- Add -static to LDFLAGS
- Remove CFLAGS override, respect input from configure script

Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2017-01-07 13:00:08 +01:00
Joachim Nilsson bad363883d Fix leaky makepath() unit test
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2017-01-07 12:59:27 +01:00
Joachim Nilsson 7f3215b3e6 Update pidfile unit test to cover new use-case
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2017-01-07 12:59:02 +01:00
Joachim Nilsson 729cc5307f pidfile: Add support for absolute path
The OpenBSD version of pidfile() makes sure to place all PID files in
the same, canonical, location: _PATH_VARRUN.  On Linux, however, some
disitributions prefer to place PID files in a sub-directory under the
canonical location: _PATH_VARRUN + __progname/ ...

This patch adds support for creating PID files in any location. If the
PID file name argument starts with a '/', the function assumes the rest
of the string is the full PATH to the PID file.

Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2017-01-07 12:55:26 +01:00
Joachim Nilsson 66290d132f pidfile: Re-create file on consequetive calls if it doesn't exist
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2017-01-07 08:15:49 +01:00
Joachim Nilsson 59f7a78441 pidfile: Always initialize global variables
Always initialize global variables, even though they cannot be used in
current code paths without being initialized at runtime.

Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2017-01-07 08:15:42 +01:00
Joachim Nilsson b716776863 tests/pidfile: Cleanup test files from /tmp
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2017-01-07 06:53:21 +01:00
Joachim Nilsson 018ecaca15 debian/source/format: Change to native mode to allow building from GIT
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2017-01-07 04:10:21 +01:00
Joachim Nilsson a293c37777 debian/: Support for building .deb packages
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2016-11-29 08:32:06 +01:00
Joachim Nilsson a4937a93e2 Add reminder about umask()
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2016-10-02 12:13:43 +02:00
Joachim Nilsson 94d547c9ec Unit test: fix search path for library header
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2016-09-05 00:19:52 +02:00
Joachim Nilsson 68cf8b6576 Update ChangeLog and bump version for v1.8.2 release
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2016-09-05 00:13:03 +02:00
Joachim Nilsson b6a55fcc46 Add err.h include to tests
lite.h no longer includes err.h it has to be included in each test.

Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2016-09-05 00:07:24 +02:00
Joachim Nilsson 5f29ef6413 Convert touch() et al to inline functions
The touch(), makedir(), makefifo(), and erase() macros print warnings to
stderr, which mess up the logging in Finit.  This patch refactors these
macros into inline functions and in the process removes the warn() use.

Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2016-09-04 23:58:32 +02:00
Joachim Nilsson 627c47caff Bump version for v1.8.2 devel
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2016-08-22 01:33:12 +02:00
Joachim Nilsson 7c2ed556b9 Replace \e GNUism w/ ISO \033 for escape sequences
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2016-08-22 01:31:49 +02:00
Joachim Nilsson 6dec4e3858 Extend lfile test with fstab parser
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2016-08-02 00:29:52 +02:00
Joachim Nilsson dff92356b3 Remove sys/cdefs.h include, does not exist in musl libc
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2016-07-19 15:39:57 +02:00
Joachim Nilsson 883c90112d Update modification date
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2016-07-04 12:46:44 +02:00
Joachim Nilsson a2c8dddaad Free pidfile_path atexit()
To prevent warnings from tools like Valgrind, or handle issues
with RAM leaks on non-MMU systems like uClinux, we must free
the memory allocated by pidfile().

Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2016-07-04 12:42:22 +02:00
Joachim Nilsson 14f547b638 Add ldconfig to build instructions, thanks rooth!
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2016-06-30 18:53:59 +02:00
Joachim Nilsson 6f2a03bba7 Update ChangeLog & bump version for v1.8.1 release
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2016-06-25 12:50:21 +02:00
Joachim Nilsson cdfffa312b Update ChangeLog for upcoming v1.8.1 fix release
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2016-06-08 07:18:30 +02:00
Joachim Nilsson 50cb72018f pidfile: Portability fix, utimensat() in sys/time.h
For building libite on NetBSD, and probably other BSD's as well.

Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2016-06-08 06:25:02 +02:00
Joachim Nilsson e8a3117158 fparseln: Portability fix _DIAGASSERT()
Only define _DIAGASSERT() if it's not already defined.
For building libite on NetBSD.

Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2016-06-08 06:23:34 +02:00
Joachim Nilsson 7cf2a3786c Bump version and ABI for v1.8.0 release
- Change from v1.7.1 to v1.8.0 due to amount of changes
  including ABI bump
- Update ChangeLog
- Bump library ABI version due to change in API semantics

Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2016-06-06 19:05:26 +02:00
Joachim Nilsson 1c1d5c94e3 Clarify ABI versioning and encourage more unit tests
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2016-06-06 19:00:14 +02:00
Joachim Nilsson 23703c75da tests/dir.c: Remove nested checker function
Move nested check function is_startup_config() outside main().

Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2016-06-06 18:15:47 +02:00
Joachim Nilsson efae15416c Bump version to -rc1, many changes since last release
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2016-06-06 18:11:03 +02:00
Joachim Nilsson 661b4b4d0b Remove last remnants of old build/unit test framework
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2016-06-06 18:09:59 +02:00
Joachim Nilsson 682b662bd5 Add unit test for chomp()
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2016-06-06 18:09:29 +02:00
Joachim Nilsson 75d4edb424 check.h: Add stdlib.h for exit()
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2016-06-06 18:08:54 +02:00
Joachim Nilsson 141d4f6936 Add unit test for copyfile()/fcopyfile()
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2016-06-06 17:59:52 +02:00
Joachim Nilsson 63aa6c5d07 Add unit test for dir()
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2016-06-06 17:56:13 +02:00
Joachim Nilsson 1d698418c7 dir(): Do not assert(), return -1 and errno
The dir() function, although useless compared to glob(), called assert()
and perror() instead of returning an error code.

Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2016-06-06 17:56:13 +02:00
Joachim Nilsson 92d81280a9 Add unit test for fexist()
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2016-06-06 17:45:19 +02:00
Joachim Nilsson 267465f3d2 Add unit test for fisdir()
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2016-06-06 17:42:31 +02:00
Joachim Nilsson c22a6e64d9 Add unit test for progress bars
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2016-06-06 17:39:31 +02:00
Joachim Nilsson 16ae343df2 Add missing progress bar API's
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2016-06-06 17:39:31 +02:00
Joachim Nilsson 6e558e98f0 Add unit test for rsync
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2016-06-06 17:28:41 +02:00
Joachim Nilsson 69291d3e74 Add unit test for fsendfile()
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2016-06-06 17:20:58 +02:00
Joachim Nilsson 6fdffeb355 fsendfile(): Change return type size_t --> ssize_t
Most send/recv/read/write API's return -1 on error and today use the
agreed upon type ssize_t for this purpose.

Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2016-06-06 17:19:54 +02:00
Joachim Nilsson b2f6721813 Clarify LITE file API in README
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2016-06-06 17:12:42 +02:00
Joachim Nilsson 3c350b8862 Add unit test for LITE file API
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2016-06-06 17:11:22 +02:00
Joachim Nilsson 5b786ce221 Add unit test for tempfile()
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2016-06-06 17:07:14 +02:00
Joachim Nilsson 86b883e2af strdupa.h: Unify header guards with other headers
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2016-06-06 15:32:35 +02:00
Joachim Nilsson 2d6e8850a2 Add unit test for tree
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2016-06-06 15:32:35 +02:00
Joachim Nilsson d8cb477861 Ignore *.log and *.trs files in unit test dir
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2016-06-06 15:31:24 +02:00
Joachim Nilsson 27644677dd Clean *.trs and *.log files from unit test dir
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2016-06-06 15:31:24 +02:00
Joachim Nilsson 3588c9b01f Rename unit tests, drop _func suffix
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2016-06-06 15:31:24 +02:00
Joachim Nilsson ca3ea5ae92 Add unit test for mkpath() and makepath() funcs
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2016-06-06 15:31:23 +02:00
Joachim Nilsson 188d968f89 Remove previous pidfilefn() unit test makefile
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2016-06-06 15:03:56 +02:00
Joachim Nilsson 8e2c58501c Build all unit tests with -W -Wall -Wextra
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2016-06-06 14:02:36 +02:00
Joachim Nilsson 1da317ce1e Add missing signal.h include
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2016-06-06 14:02:27 +02:00
Joachim Nilsson fe39284d50 Travis-CI: Verify installation and run unit tests
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2016-06-06 12:42:33 +02:00
Joachim Nilsson c3c23b9aef Update ChangeLog for upcoming v1.7.1 fix release
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2016-06-06 12:39:50 +02:00
Joachim Nilsson d45f2bad5b Update pidfile() description with hidden features
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2016-06-06 12:35:01 +02:00
Joachim Nilsson 61fb7aeca2 New unit test framework, first test pidfile funcs
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2016-06-06 12:30:35 +02:00
Joachim Nilsson dedcaf92d5 Minor style fix, to keep with pidfile.c style
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2016-06-06 12:16:14 +02:00
Joachim Nilsson c009c49a92 Expose __pidfile_path to override _PATH_VARRUN
This patch makes it possible to override the default pidfile() path used
for PID files, _PATH_VARRUN, with a custom path, e.g. _PATH_TMP.

This change does not affect the ABI of pidfile()

Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2016-06-06 12:14:26 +02:00
Joachim Nilsson 12f619a320 Fix minor build error in new strndupa() header
Wrong path to local strnlen.h file.

Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2016-06-06 11:04:17 +02:00
Joachim Nilsson c1b3b76ea3 Update ChangeLog and bump version for v1.7.0 release
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2016-06-05 00:36:43 +02:00
Joachim Nilsson 8108b8ec14 Add HACKING.md for release policy ABI versioning etc.
Most of the text shamelessly stolen from the libConfuse project :)

Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2016-06-04 19:01:18 +02:00
Joachim Nilsson 0e2d365eb9 Update ChangeLog with fixes and new features
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2016-06-04 18:56:07 +02:00
Joachim Nilsson 8b499aa9cd Add compat strnlen() implementation for non-GLIBC systems
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2016-06-04 18:51:25 +02:00
Joachim Nilsson f4fa44fe60 Add strndupa.h to distribution and update README
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2016-06-04 15:13:16 +02:00
Joachim Nilsson be08bcd09d strndupa.h: #error if building with non-GCC on non-GNU systems
At the moment only GCC is supported on non-GNU systems, unfortunately.
GNU systems usually have GLIBC, or another library with strndupa().
This strndupa() implementation requires GCC for the builtin alloca API.

Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2016-06-04 15:12:02 +02:00
Joachim Nilsson 1495a3f858 Add compat strndupa() implementation from libnostd
This patch adds compat support, to *BSD and other UNIX, for the GLIBC
strndupa() function.  The implementation is taken from libnostd written
by William Ahern.

http://www.25thandclement.com/~william/projects/libnostd.html

Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2016-06-04 15:07:17 +02:00
Joachim Nilsson 5eb816b4c0 Update ChangeLog and README with new strdupa()
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2016-06-03 23:12:50 +02:00
Valery Frolov 456c58d52d Add new headers, for strdupa(), to distribution
Signed-off-by: Valery Frolov <fvgenn@gmail.com>
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2016-06-03 23:08:08 +02:00
Joachim Nilsson 59869b876e strdupa.h: #error if building with non-GCC on non-GNU systems
At the moment only GCC is supported on non-GNU systems, unfortunately.
GNU systems usually have GLIBC, or another library with strdupa().  This
strdupa() implementation requires GCC for the builtin alloca API.

Followup to pull-request #4

Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2016-06-02 19:51:43 +02:00
Joachim Nilsson 113c3487bd Add info on building directly from GIT
Followup to pullrequest #4

Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2016-06-02 19:44:49 +02:00
Joachim Nilsson de73e268d3 Merge branch 'abs0-master'
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2016-05-30 22:32:43 +02:00
Joachim Nilsson b57c257f09 Cleanup of old shared rules.mk file, now only used by unit tests.
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2016-05-30 22:31:59 +02:00
Joachim Nilsson 94d42b3df7 Add compat strdupa() implementation from libnostd
This patch adds compat support, to *BSD and other UNIX, for GLIBC
strdupa() function, used in mkpath().  The implementation is taken
from http://www.25thandclement.com/~william/projects/libnostd.html
by William Ahern.

Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2016-05-30 22:29:30 +02:00
Joachim Nilsson 94ad65a121 Factor out string functions to lite/strlite.h
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2016-05-30 22:27:41 +02:00
David Brownlee f3f6947604 Handle old Linux/(G)LIBC and UNIX systems the same
Linux systems pre Linux 3.11, and UNIX do not have the O_TMPFILE flag,
so let's treat them the same, by wrapping tmpfile().

Signed-off-by: David Brownlee <abs@absd.org>
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2016-05-30 21:05:21 +02:00
Joachim Nilsson 613d397161 Fix mkpath() to handle relative dirs
After input from both StackOverflow and Valery Frolov.

Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2016-05-23 09:15:50 +02:00
Joachim Nilsson 7df1b75fa0 Bump version for v1.6.0 release
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2016-05-13 07:22:25 +02:00
Joachim Nilsson 9b1b7ca4cf ChangeLog: Fix Markdown links in v1.6.0 release
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2016-05-13 07:21:45 +02:00
Joachim Nilsson 1e064b8b4d Update ChangeLog for v1.6.0 release
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2016-05-12 21:13:10 +02:00
Joachim Nilsson 18dde87f0a Add NetBSD fparseln(3) v1.10
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2016-05-09 19:14:05 +02:00
Joachim Nilsson fcb38c9cc5 Constify fisdir() argument
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2016-05-09 19:10:05 +02:00
Joachim Nilsson ab69ae8374 Add OpenBSD reallocarray(3) v1.2
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2016-05-09 00:37:05 +02:00
Joachim Nilsson 95f7a91a8a Bump version for v1.6.0 release cycle
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2016-05-09 00:33:16 +02:00
Joachim Nilsson aab5a1145c Remove Emacs version-control handling
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2016-05-07 22:35:49 +02:00
Joachim Nilsson fe1a3a731d Update ChangeLog and bump version for v1.5.1 release
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2016-04-17 16:27:02 +02:00
Joachim Nilsson cd073f5221 fcopyfile: Westermo fixes and code simplification
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2016-04-17 16:17:00 +02:00
Joachim Nilsson 1a9d3bd91b Spellcheck
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2016-04-17 01:25:46 +02:00
Joachim Nilsson 8cc267f259 Markdown formatting
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2016-04-17 01:03:53 +02:00
Joachim Nilsson 35d396ec27 Is --> Are, a --> an ...
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2016-04-17 01:02:09 +02:00
Joachim Nilsson 7e91307138 Add Table of Contents
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2016-04-17 00:54:22 +02:00
Joachim Nilsson 2b8f54fbc7 Update build & install instructions
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2016-04-17 00:53:57 +02:00
Joachim Nilsson 2e58dd3203 Simplify configure script
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2016-04-17 00:47:21 +02:00
Joachim Nilsson 41392f7e85 Remove bogus autoconf version requirement
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2016-04-17 00:46:58 +02:00
Joachim Nilsson e4329d6c25 Add some integration tips when using GNU autotools
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2016-04-17 00:46:14 +02:00
Joachim Nilsson 7113b3d1d8 Add basic TODO file to keep track of stuff
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2016-04-11 01:24:53 +02:00
Joachim Nilsson 9b6ef1f053 pidfile(): Activate use of utimensat() to update atime+mtime
Due to problems with the unit tests the use of utimensat() in pidfile()
was disabled, and forgotten.  This patch enables it, but beware, this
thing is QUICK on any system with a L2 cache or better.

Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2016-04-11 01:18:57 +02:00
Joachim Nilsson efc70e3a75 Update ChangeLog and bump version for v1.5.0 release
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2016-03-20 02:24:26 +01:00
Joachim Nilsson 147df0c6da ABI revision bump
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2016-03-20 02:21:33 +01:00
Joachim Nilsson 7f89000c6c pidfilefn.c: Update unittests, add mtime test and prettyfy output
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2016-03-20 02:15:35 +01:00
Joachim Nilsson 7607148d46 Build unit tests with -g -O0 for debugging
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2016-03-20 02:14:55 +01:00
Joachim Nilsson 979f76aea7 pidfile(): Use utimensat() to update atime+mtime
This patch update the `-lite` patch to OpenBSD `pidfile()` by changing
the update atime+mtime patch from writing the PID again to instead use
utimensat(). Less overhead and nanosecond resolution.

Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2016-03-20 02:14:30 +01:00
Joachim Nilsson ac41fa70aa Update ChangeLog and bump version to v1.5.0-dev
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2016-03-13 01:59:41 +01:00
Joachim Nilsson 5f820b17b6 Change namespace for header files libite/lite.h --> lite/lite.h
The `libite/` namespace for header files has been the same since the
first public release in v1.0.0.  This patch surprisingly changes it to
the less surprising `lite/`.  Hopefully there aren't that many users of
this library out there yet, apart from myself.

Apologies if you are affected!

Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2016-03-13 01:58:56 +01:00
Joachim Nilsson 53b715c094 Remove surprise from pkg-config output
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2016-03-13 00:38:53 +01:00
Joachim Nilsson 1b4cd7b20b Update ChangeLog and bump version for v1.4.4 release
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2016-02-23 14:23:12 +01:00
Joachim Nilsson 8e379ca358 Update ChangeLog
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2016-02-22 19:11:29 +01:00
Joachim Nilsson 12241dcdfe libite.pc.in: Remove spurious @LTLIBINTL@ after copy-paste from libConfuse
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2016-02-20 22:26:24 +01:00
Joachim Nilsson 0ce1b3bf44 Add pkg-config support
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2016-02-20 22:03:25 +01:00
Joachim Nilsson 38ff0af61a Update ChangeLog with details on issue #3
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2016-02-15 18:20:25 +01:00
Joachim Nilsson 00737a5b74 Merge pull request #3 from askerin/tempfile-archfix
Tempfile() is dependent on $ARCH

Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2016-02-12 16:15:53 +01:00
Joachim Nilsson 1b8b164ed4 Test build with both GCC and Clang (LLVM)
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2016-02-12 16:15:15 +01:00
Joachim Nilsson 9f279c0fec Disable sudo for build while auto-tests are reintegrated
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2016-02-12 16:14:59 +01:00
Johan Askerin 4d7e6d4f78 In tempfile(): O_DIRECTORY is dependent on $ARCH, don't hardcore O_TMPFILE
Signed-off-by: Johan Askerin <johan.askerin@gmail.com>
2016-02-12 15:17:25 +01:00
Joachim Nilsson 0a57f2128f Update ChangeLog and bump version for v1.4.3 release
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2016-02-02 09:37:40 +01:00
Joachim Nilsson e254db48a8 Remove AUTHORS file from distribution, doesn't exist
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2016-02-02 08:40:14 +01:00
Joachim Nilsson 0fe429dcbe Update ChangeLog in preparation for v1.4.3 release
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2016-02-02 08:25:16 +01:00
Joachim Nilsson f1a2e01775 Makefile.am: Update to install and distribute README.md, LICENSE, etc.
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2016-02-02 08:24:15 +01:00
Joachim Nilsson e5eef2ae59 Remove confusing symlinks, it's a brave Markdown world
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2016-02-02 08:22:13 +01:00
Joachim Nilsson f9caffc9b7 Update ChangeLog and bump version for v1.4.2 release
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2016-01-23 11:29:50 +01:00
Joachim Nilsson 604b503b84 Fix issue #2: GCC6 -Wmisleading-indentation causing FTBFS in pimd
- Add function comment
- Fix misleading indentaion
- Fix coding sttle

Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2016-01-23 11:16:53 +01:00
Joachim Nilsson 5fc248522c Update ChangeLog and bump version for v1.4.1 release
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2016-01-22 01:07:35 +01:00
Joachim Nilsson c0b8bab164 Use pkginclude_HEADERS for libite include files
The v1.4.0 release installs the header files in $(prefix)/include, this
patch installs them in the proper $(prefix)/include/$(PACKAGE) dir.

Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2016-01-22 01:03:19 +01:00
Joachim Nilsson c0e9c0431a Bump version for 1.4.1-dev cycle
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2016-01-22 01:01:22 +01:00
Joachim Nilsson efdd61648a Update ChangeLog and bump version for release v1.4.0
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2016-01-22 00:05:01 +01:00
Joachim Nilsson 2e8e64fd2a Step ABI version 2:0:0 --> 2:1:0
Slight change in how `pidfile()` behaves, now exporting __pidfile_name.

Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2016-01-22 00:01:19 +01:00
Joachim Nilsson c4109e7e74 Add Niels Provos' famous splay and red-black tree implementation
This is the OpenBSD sys/tree.h r1.14

Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2016-01-21 23:51:40 +01:00
Joachim Nilsson 5d07594709 Update pidfile() documentation and add unit test for __pidfile_name
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2016-01-21 23:30:08 +01:00
Joachim Nilsson 253460b4b8 Make pidfile() name accessible (read-only) to daemon as __pidfile_name
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2016-01-21 23:28:59 +01:00
Joachim Nilsson acc59e0c1f Remove AM_MAINTAINER_MODE from configure script, not recommended anymore
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2016-01-21 22:32:23 +01:00
Joachim Nilsson 90374fc237 README: Add a Build & Install section
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2016-01-18 20:11:19 +01:00
Joachim Nilsson 7f375b6e9d Remove -Werror due to O_TMPFILE is missing on older kernels
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2016-01-14 21:49:49 +01:00
Joachim Nilsson e4236db2bd Ignore all generated files from build system
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2016-01-14 21:43:02 +01:00
Joachim Nilsson 42a5a906fc ChangeLog: Prepare for upcoming v1.4.0 release
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2016-01-14 21:28:08 +01:00
Joachim Nilsson 10b28127f5 Update .gitignore, add bogus m4/.gitignore to make Travis-CI happy
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2016-01-14 21:27:04 +01:00
Joachim Nilsson d265a05422 Update build script for Travis-CI with GNU configure and build system
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2016-01-14 18:56:01 +01:00
Joachim Nilsson f07c05138d Initial conversion to the GNU configure and build system
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2016-01-14 17:40:26 +01:00
Joachim Nilsson e1f8224666 Update ChangeLog and bump version for release v1.3.0
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2016-01-07 02:58:06 +01:00
Joachim Nilsson 84650d8836 Update include file boiler plate
We're not in Kansas anymore, Toto.

Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2016-01-07 02:58:06 +01:00
Joachim Nilsson b4fbd54a8c Update copyright years
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2016-01-07 02:58:06 +01:00
Joachim Nilsson c14c6a1e62 pidfile.c: Add LITE #ifdef pidfile and comment LITE mtime extension
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2016-01-07 02:58:06 +01:00
Joachim Nilsson 8aecba2b7a strtonum.c: Update to OpenBSD v1.7, style tweaks
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2016-01-07 02:58:06 +01:00
Joachim Nilsson 74dcaddc55 strlcat.c: Update to OpenBSD v1.14, readability fixes
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2016-01-07 02:57:59 +01:00
Joachim Nilsson c5a36ff7bd strlcpy.c: Update to OpenBSD v1.12, readability fixes
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2016-01-07 02:57:51 +01:00
Joachim Nilsson 3371e42035 queue.h: Update to OpenBSD v1.43 -- NOTE: Removes CIRCLEQ support!
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2016-01-07 02:03:10 +01:00
Joachim Nilsson 4e57a78255 README: Update section on OpenBSD Functions as well
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2016-01-06 13:35:35 +01:00
Joachim Nilsson ce3bd4ec8a README: Update documentation for pidfile() fn
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2016-01-06 13:31:32 +01:00
Joachim Nilsson 805571a7ef ChangeLog: Fix missing README link
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2016-01-05 13:34:41 +01:00
Joachim Nilsson 36435997bf ChangeLog: Fix Markdown links
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2016-01-05 13:33:34 +01:00
Joachim Nilsson f961889724 Add documentation for new macros and prepare ChangeLog for v1.3.0
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2016-01-05 13:27:40 +01:00
Tobias Waldekranz 6605fb9771 Makefile: Make sure queue.h and conio.h also are installed
This patch adds the BSD queue.h and the Borland inspired conio.h to the
install-dev Makefile target.

Signed-off-by: Tobias Waldekranz <tobias@waldekranz.com>
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2016-01-05 13:17:16 +01:00
Tobias Waldekranz 61254279b9 lite.h: Add min() and max() macros
These macros take care to avoid double evaluation.

Signed-off-by: Tobias Waldekranz <tobias@waldekranz.com>
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2016-01-05 13:16:34 +01:00
Joachim Nilsson e42aca8856 Makefile: Split install-dev taget into install-dev and install-data
This makes it possible to skip installing any unnecessary cruft.
Useful for embedded targets.

Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2016-01-05 13:14:37 +01:00
Joachim Nilsson 16611f3e5f Add ChangeLog to project and bump version for new release cycle
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2016-01-05 13:13:26 +01:00
Joachim Nilsson 975df87d6b Update unit test for pidfile()
Add ocular verification step for mtime update when pidfile() is
called more than once.

Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2015-12-17 00:15:18 +01:00
Joachim Nilsson 148027674a pidfile: Only update mtime i called multiple times
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2015-12-16 18:40:34 +01:00
Joachim Nilsson 12ed342d55 Bump version for v1.2.0 release
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2015-11-23 00:32:56 +01:00
Joachim Nilsson 23badc990d lfile: Improve unittest/example with /etc/group + passwd
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2015-10-26 00:50:18 +01:00
Joachim Nilsson ca53e097c3 lfile: Initialize strtok_r() save pointer
Must initialize the save pointer in the parser context, otherwise
strtok_r() will fail on statically built embedded targets.

Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2015-10-26 00:16:36 +01:00
Joachim Nilsson a7b5c240c1 Add UNIX lfile_t parser API to lite.h
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2015-10-25 23:25:17 +01:00
Joachim Nilsson c4eb5cb124 Add simple parser for UNIX configuration files.
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2015-10-25 22:50:10 +01:00
Joachim Nilsson db08b20f23 Make sure we don't inherit LDFLAGS from environment.
To pass custom LDFLAGS to libite, use EXTRA_LDFLAGS.

Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2015-10-22 18:35:35 +02:00
Joachim Nilsson 8779f54125 Do not allow VERSION to be overloaded by build system.
When integrating libite as a component in another piece of software,
that build system may set VERSION as an environment variable.  We do
not want that version to be set as the version of libite.

Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2015-10-03 09:13:37 +02:00
Joachim Nilsson bd9a618ea3 Bump version for v1.1.1 patch release.
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2015-09-27 00:59:54 +02:00
Joachim Nilsson 3f89fafe24 Fix macro definitions for compat APIs
Seems cpp is a bit uptight about spaces.

Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2015-09-27 00:56:20 +02:00
Joachim Nilsson ebec48d671 Silence annoying warnings from GNU ar
In (very) modern versions of binutils, for instance v2.25.1 shipped in
Ubuntu 15.10, ar complains about the VERY common `crus` argument.  This
patch silences this noise:

    $ make -j5
      ARCHIVE libite.a
    ar: `u' modifier ignored since `D' is the default (see `U')

Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2015-09-27 00:55:26 +02:00
Joachim Nilsson 4d6c32f81a Bump version to v1.1.0 and drop default optimization.
User of library will likely want to have better control over the default
optimization level.  Either way, defaulting to -Os is a lot more "risky"
than, say -O2.

Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2015-09-16 17:25:43 +02:00
Joachim Nilsson 25c725c240 Bump SONAME to libite.so.2 so for upcoming Finit v2.0
We need to lock down the ABI and do a new release on behalf of
Finit.  Finit will have support for using an externally built
libite and libuev, so Finit must lock down to a known ABI.

Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2015-09-16 17:23:49 +02:00
Joachim Nilsson 039a92b292 progress.c: Merge in latest changes from troglobit/toolbox@d845e67
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2015-08-24 23:52:26 +02:00
Joachim Nilsson 5ae5bfb767 Bump version to indicate new feature status, v1.1.0-beta1
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2015-08-23 19:37:08 +02:00
Joachim Nilsson a00e765789 Update README with info on progress() and tree()
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2015-08-23 19:36:21 +02:00
Joachim Nilsson aff5812c46 Minor whitespace fixes, use Linux KNF
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2015-08-23 13:15:18 +02:00
Joachim Nilsson 3809b109c6 Add autotest for progress()
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2015-08-23 13:11:20 +02:00
Joachim Nilsson 1909dd475c progress(): Very simple ASCII progress bar from troglobit/toolbox@f98c5d0
This patch adds a very simple progress bar I wrote once.  It's revision
f98c5d0 from https://github.com/troglobit/toolbox

Also included in this patch is conio.h, a neat little set of macros for
manipulating your terminal using ANSI escape seequences.

Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2015-08-23 13:07:03 +02:00
Joachim Nilsson a157fe4162 tree: Minor cleanup, also does not need sudo for tests.
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2015-08-23 05:23:54 +02:00
Joachim Nilsson 42b6a03317 rsync.test: Use homegrown tree, instead of out-of-tree tree ...
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2015-08-23 05:19:11 +02:00
Joachim Nilsson 1f1e88a640 New function: tree(), simple /bin/tree replacement.
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2015-08-23 05:12:38 +02:00
Joachim Nilsson bb67fb749d rsync.c: Refactor unit tests to work on Travis as well.
Travis does not have `/bin/tree` installed, and since we do not
output intermediate results from `make test`, there is no need
to call `/bin/tree` unless `-v` is supplied to the test.

Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2015-08-23 02:33:33 +02:00
Joachim Nilsson 3e337c7078 rules.mk: When V=1 is used, add -v to autotests.
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2015-08-23 02:32:29 +02:00
Joachim Nilsson 407e954f02 tempfile(): Handle kernels older than 3.11 by wrapping tmpfile()
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2015-08-23 02:17:45 +02:00
Joachim Nilsson 8978cb9bff Try sudo: true for sake of tests, skip Docker for now.
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2015-08-23 01:39:08 +02:00
Joachim Nilsson 9c90ec56a6 Attempt to activate autotests in Travis-CI.
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2015-08-23 01:33:24 +02:00
Joachim Nilsson 44e787c966 Add generic support for running tests as root.
By setting `ASROOT=1` in a unit test makefile a test will now run as
root, using `sudo -n`.

This patch allows us to simplify the pidfilefn() test.

Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2015-08-23 01:30:29 +02:00
Joachim Nilsson e8ff38ad6a Add autotest for fisdir()
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2015-08-22 23:26:41 +02:00
Joachim Nilsson 1138822d19 Add autotest for fexist()
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2015-08-22 23:22:38 +02:00
Joachim Nilsson de8f2b087c Add autotest for tempfile()
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2015-08-22 23:08:22 +02:00
Joachim Nilsson 87d6fe822c Make sure to start the makepath() tests clean.
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2015-08-22 23:07:56 +02:00
Joachim Nilsson 57c49bfe0c Add autotest for mkpath() and makepath()
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2015-08-22 23:01:15 +02:00
Joachim Nilsson b59249714b Add autotest for fsendfile()
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2015-08-22 22:49:48 +02:00
Joachim Nilsson 36da3aa35e Add autotest for dir
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2015-08-22 22:46:42 +02:00
Joachim Nilsson ab2b0f00fa Add autotest for pidfilefn et al.
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2015-08-22 22:41:34 +02:00
Joachim Nilsson bd69aad13a Add autotest for copyfile et al.
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2015-08-22 22:22:14 +02:00
Joachim Nilsson ebe2ad4a4c Add autotest for chomp
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2015-08-22 22:08:25 +02:00
Joachim Nilsson 2ea2357b62 Lay foundation for unit test build framework.
GNU Make double colon rules, rule ;-)

Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2015-08-22 21:59:52 +02:00
Joachim Nilsson b7a8042c87 Add Travis-CI status icon
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2015-08-22 16:11:31 +02:00
Joachim Nilsson 7d1423b5b1 Add dockerized Travis-CI autobuilder support.
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2015-08-22 16:09:54 +02:00
Joachim Nilsson 117ec58a90 Add some very useful helper macros: NELEMS() and bitops.
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2015-08-21 09:42:43 +02:00
Joachim Nilsson a4cbc7a10e pidfile.c: Upgrade to OpenBSD r1.11, asprintf() fixes.
Do not assume that asprintf() clears the pointer on failure, which
   is non-portable.  Also add missing asprintf() return value checks.
   Signed-off-by: millert@
   Signed-off-by: deraadt@ guenther@ doug@

Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2015-07-22 11:53:44 +02:00
Joachim Nilsson 3eb1fbb31d lite.h: Minor coding style cleanup.
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2015-07-22 11:52:41 +02:00
Joachim Nilsson f5355ecf7b lite.h: Convert from error.h to the more BSD friendly err.h
OpenBSD, and possibly the other BSD's, do not have error.h so we replace
it with err.h, which exists almost everywhere.

This means the macros in lite.h that used error() now instead use
warn(),  with the same semantics as before.

Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2015-07-18 15:36:06 +02:00
Joachim Nilsson 61b1b5b457 Add support for 'make distdir' used by GNU configure and build.
This patch adds support for being called with "make distdir" from a GNU
configure and build based project.  This was a requirement to get the
Inadyn v1.99.14 release out.

Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2015-07-14 17:26:32 +02:00
Joachim Nilsson 83f83466b5 Fix indentation of description to some API's.
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2015-07-12 13:13:21 +02:00
Joachim Nilsson 6d2717726f Shorten README title heading.
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2015-07-12 12:50:01 +02:00
Joachim Nilsson 2675426845 Update README for release.
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2015-07-12 12:44:39 +02:00
Joachim Nilsson 51c73030e0 Minor change.
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2015-07-12 12:43:57 +02:00
Joachim Nilsson a9d11d0498 ifconfig.c: Fix possible NULL pointer deref.
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2015-07-10 19:27:02 +02:00
Joachim Nilsson 1147e547dc Followup to atonum(), missing include file and const.
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2015-07-10 19:06:17 +02:00
Joachim Nilsson 41c9caff17 Add atonum() - Convert string to natural number, returns -1 on error.
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2015-07-10 19:00:11 +02:00
Joachim Nilsson 4005dd5e2c Add simple IPv4 only ifconfig() function from Finit
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2015-07-10 18:28:57 +02:00
Joachim Nilsson 614c8cbe47 Update documentation of OpenBSD derived functions with pointers to man pages.
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2015-07-10 18:27:46 +02:00
Joachim Nilsson 8db314623a Followup to pidfilefn.c, add system include file for usleep()
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2015-07-09 03:22:53 +02:00
Joachim Nilsson e731d83881 Add pidfile_poll() from Finit, waits max 5 sec for pidfile.
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2015-07-09 03:19:56 +02:00
Joachim Nilsson c2d0ed0d12 Fix minor issues in pidfile_read() and pidfile_signal(), caught by Coverity
- Simplify pidfile_read(), no need to call access() when fopen() is more
  than capable of failing on its own if we do not have READ access.
- The remove() syscall requires that you check the return value, but we
  don't care about that when having signalled a TERM signal to a process.

Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2015-07-09 01:59:10 +02:00
Joachim Nilsson 5a50a6add1 Add client side pidfile functions: pidfile_read(), pidfile_signal().
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2015-07-09 01:36:58 +02:00
Joachim Nilsson 9ed00baa94 Add pidfile() from NetBSD/OpenBSD, missing in GLIBC.
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2015-07-09 01:25:19 +02:00
Joachim Nilsson 1561e7567e Add recursive mkpath() and makepath(), works like mkdir -p
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2015-07-09 01:25:19 +02:00
Joachim Nilsson c5366a33da fsendfile(): Break ABI by switching src and dst to match rest of API.
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2015-07-06 02:04:28 +02:00
Joachim Nilsson af39ae5fa9 Refactor copyfile(), and copy_filep() --> fcopyfile() to use same backend.
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2015-07-06 02:03:28 +02:00
Tobias Waldekranz 1423edc044 Factor out fsendfile() to reduce overall size when linking.
Signed-off-by: Tobias Waldekranz <tobias@waldekranz.com>
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2015-07-05 15:21:55 +02:00
Joachim Nilsson c48ce14739 Default to silent build, use V=1 to get verbose mode.
Use kernel standard silent mode instead, and adopt kernel nomenclature
for enabling verbose mode.

Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2015-07-05 11:46:48 +02:00
Joachim Nilsson 6f19d1407a Default to verbose style build, use SILENT=1 to get silent mode.
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2015-07-05 11:28:03 +02:00
Joachim Nilsson 436a07ee06 Remove STATIC ifdef, always build .a and .so files
Using libite as a GIT submodule in a autoconf/automake based project it
is non-trivial to set a separate environment variable when descending
into the libite subdirectory.

It is better to instead simplify the build process and always build both
.a and .so files.

Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2015-07-05 11:06:33 +02:00
Joachim Nilsson e37aad9530 Update on tmpfile() requirements.
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2015-07-03 01:50:15 +02:00
Joachim Nilsson 32827cdea9 Add OpenBSD version of the extremely useful sys/queue.h API
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2015-07-03 01:47:22 +02:00
Joachim Nilsson e4c5a0e77e copyfile(): Fix potentially dangerous time of check-time of use bug.
Coverity reports a potenatially TOCTOU bug, CWE-367, in copyfile().
Turns out we tried to fall back to copy when readlink() failed, in
the case when the user requested to copy symlinks.

It's better to fail hard if stat() reports symlink and readlink()
right after fails to read the symlink ...

Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2015-06-22 22:39:59 +02:00
Joachim Nilsson 35b43c5c56 Handle missing O_TMPFILE gracefully and document tempfile() in README
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2015-06-22 22:02:39 +02:00
Joachim Nilsson c5434a4bc0 Add tempfile() - a secure tmpfile() replacement using O_TMPFILE.
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2015-06-22 21:42:38 +02:00
Joachim Nilsson 84c3667eba Default to -fPIC, bloats archives slightly, but works for everyone.
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2015-06-18 02:24:17 +02:00
Joachim Nilsson 262f8b8936 Cleanup: Fix install/uninstall of both static and dynamic builds.
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2015-06-18 02:14:55 +02:00
Joachim Nilsson c045bc7264 Add small clarification on licenses used in libite (-lite)
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2015-06-18 01:06:05 +02:00
Joachim Nilsson 82ca189a52 Fix buggy chomp() -- Chop off only trailing newlines, all of them.
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2015-06-17 23:45:39 +02:00
Joachim Nilsson 1b4dd15614 Document helper macros.
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2015-06-17 23:10:50 +02:00
Tobias Waldekranz 121e8ee888 Add Westermo chomp() function, slightly improved from Finit original.
Signed-off-by: Tobias Waldekranz <tobias@waldekranz.com>
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2015-06-17 22:07:10 +02:00
Joachim Nilsson 745256909e Shorten title.
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2015-06-17 21:57:29 +02:00
Joachim Nilsson 552f917b9b Update README slightly.
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2015-06-17 21:56:03 +02:00
Joachim Nilsson 08ce3d503e Add basic README.
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2015-06-17 21:26:58 +02:00
Joachim Nilsson 22a79ee947 Make libite standalone
Add basic .gitignore, cleanup inherited Makefile from Finit
and add a small rules.mk from libuEv.

Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2015-06-17 21:13:02 +02:00
Joachim Nilsson 1758f9a847 rsync.c: Use makedir() from lite.h
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2015-06-17 20:57:05 +02:00
Joachim Nilsson 9f0979daea Add some helper macros and wrappers for C library functions.
- touch()    - Create a file, or update mtime.  Errors on stderr
- makedir()  - Create directory, like mkdir().  Errors on stderr
- makefifo() - Create a FIFO, like mkfifo().  Errors on stderr
- erase()    - Erase file/directory with remove().  Errors on stderr
- chardev()  - Create character device
- blkdev()   - Create block device
- S_ISEXEC() - Mysteriously missing from GLIBC
- UNUSED()   - Shorter and more readable version of __attribute__ ((unused))

Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2015-06-17 20:56:07 +02:00
Joachim Nilsson 95922a9536 Add standard MIT/X11 license, from Finit.
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2015-06-17 16:14:14 +02:00
Joachim Nilsson f35f64f06f Fix last part of issue #8: Libite install problem with --enable-static
Skip install of .so libs when user has configured with --enable-static

Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2015-03-10 22:12:26 +01:00
Joachim Nilsson 8b7eb36d2a Overhaul build system and add support for disabling inetd support.
This patch adds support for a configure script and with it
support for disabling inetd support.  See the output from

    ./configure --help

* Add configure script
* Sprinkle #ifdef fairy dust on svc.c when inetd support is disabled
* Use GCC built-in autodep calculator (-MMD -MP)
* Fix name space issue with include files, use relative paths
* Disable username/group name to uid/gid functions in static builds
* Bug out (error) if a user tries to build the bootmisc plugin static

Possibly fixes GitHub issue #5 and issue #6.

NOTE: The static build has not received any testing at all!

Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2015-03-10 10:25:46 +01:00
Joachim Nilsson 5e31d05110 Initial support for building Finit statically (incomplete)
This patch adresses issue #5.  However, there still remains a few issues
to work around before Finit can be built completely standalone.

    $ make clean all STATIC=1
    LINK    finit
    helpers.o: In function `getgroup':
    helpers.c:(.text+0x10a7): warning: Using 'getgrnam' in statically linked applications requires at runtime the shared libraries from the glibc version used for linking
    helpers.o: In function `getuser':
    helpers.c:(.text+0x108e): warning: Using 'getpwnam' in statically linked applications requires at runtime the shared libraries from the glibc version used for linking
    inetd.o: In function `getent':
    inetd.c:(.text+0x127): warning: Using 'getprotobyname' in statically linked applications requires at runtime the shared libraries from the glibc version used for linking
    inetd.c:(.text+0xce): warning: Using 'getservbyname' in statically linked applications requires at runtime the shared libraries from the glibc version used for linking

The problem is the NSS plugins and similar issues that prevent static
linking when using the above functions.  See issue #5 for more on this.

Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2015-03-06 21:58:56 +01:00
Joachim Nilsson 5d184794b4 Fix various problems with unchecked return values from syscalls.
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2014-11-27 00:12:07 +01:00
Joachim Nilsson 0701b688fd libite/rsync.c: Fix build regression from previous commit.
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2014-11-26 23:37:04 +01:00
Joachim Nilsson e0c84e25a7 Fix problem with unchecked return value of mkdir(), wrap in makedir() macro.
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2014-11-26 23:27:15 +01:00
Joachim Nilsson e540ea8735 libite:rsync.c - Break out nested function.
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2014-10-31 14:56:51 +01:00
Joachim Nilsson 949d0a020f Bump version for release and update copyright years.
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2014-04-21 16:03:54 +02:00
Joachim Nilsson 36d24ce366 lite.h: Add some helper string comparison methods.
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2014-04-21 15:45:23 +02:00
Joachim Nilsson 80c2a132cd libite: Fix cppcheck warnings in rsync unit test
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2014-04-12 16:34:57 +02:00
Joachim Nilsson 5eb4f640b1 libite: Minor style cleanup of fsendfile()
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2014-04-12 16:21:41 +02:00
Joachim Nilsson 6b64189d14 libite: Simplify and fix another memleak in copyfile()
- Simplify: reduce indentation depth
- Always check for error condition first, cleaner code
- Make sure buffer is always freed, use same exit everyhere
- Use readable, but still short, local variable names

Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2014-04-12 16:11:59 +02:00
Joachim Nilsson bf9d1ec012 libite: Copy utility fixes and new functionality
- Add support for symlinks to copyfile()
- Fix memory leak in copy_filep()
- New function, fsendfile(), copy data between FILE streams

Also, minor whitespace and coding style cleanup.

Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2014-04-12 15:08:56 +02:00
Joachim Nilsson 499f4d45d3 libite: Add strtonum() from OpenBSD
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2013-05-21 19:55:41 +02:00
Mattias Walström cd63f8a73d libite: Fix memory leak in dir()
Signed-off-by: Mattias Walström <lazzer@gmail.com>
Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2013-05-19 19:01:44 +02:00
Joachim Nilsson ddf5ecc907 libite: Improve error handling for copyfile() and rsync()
When using the simple rsync() or copyfile() functions of libite some
error codes should not be interpreted as error.  I.e., if a file or
directory already exists when attempting to create it.

Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2013-05-19 18:00:31 +02:00
Mattias Walström 77971a31b2 libite: Add strlcat and strlcpy.
These function only exist on uClibc and BSD, so if they
not already defined in string.h, define them here.
2013-01-29 13:29:45 +01:00
Joachim Nilsson 7627b5848a Fix incorrect use of variable arguments in run_parts() and simplify code
The run_parts() implementation used variable arguments in a bad way,
resulting in it not working properly.  Replaced va_*() code with a
simple cmd argument that's passed to each script called.

Also, the opendir()/readdir() code has been replaced with scandir()
using regular alphasort(). This simplifies the code somewhat as well.

Otherwise, minor cleanups.

Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
2012-10-06 15:45:42 +02:00
75 changed files with 5785 additions and 550 deletions

No files matched your search

+25
View File
@@ -0,0 +1,25 @@
*~
*.d
*.o
*.so
*.so.*
*.a
.deps
.libs
tmp/
compile
config.*
configure
depcomp
install-sh
libtool
ltmain.sh
missing
stamp-h1
Makefile
Makefile.in
aclocal.m4
ar-lib
autom4te.cache
libite*
test-driver
+20
View File
@@ -0,0 +1,20 @@
# Travis CI integration -- https://travis-ci.org/troglobit/libite
# Defaults to GNU GCC and autotools: ./configure && make && make test
language: c
# Use docker for quicker builds, it now allows https://docs.travis-ci.com/user/apt/
sudo: false
# Test build with both GCC and Clang (LLVM)
compiler:
- gcc
- clang
script:
- ./autogen.sh
- ./configure --prefix=/tmp --disable-silent-rules
- make clean
- make -j5
- make install-strip
- ls -lR /tmp
- make check
+309
View File
@@ -0,0 +1,309 @@
Change Log
==========
All notable changes to the project are documented in this file.
[v1.9.3][] - 2017-10-24
-----------------------
### Changes
- `initscr()`, use stdout, not stderr, like the rest of the
`conio.h` macros. Also, stderr may be redirected by user
- `tree()`, update unit test, use standard directries
### Fixes
- `initscr()`, verify that both stdin and stdout are real TTYs
before messing up output or blocking on input for the user
- `tree()`, increase internal buffer slightly, output may be
truncated otherwise. Found by GCC 7.2
[v1.9.2][] - 2017-07-09
-----------------------
### Changes
- Add `initscr()` function to query screen size
- Convert `printheader()` to a static inline function
[v1.9.1][] - 2017-07-03
-----------------------
### Changes
- Add missing `whichp()` predicate function to accompany `which()`
- Allow `which("ps aux")`, which skips any arguments to command
[v1.9.0][] - 2017-07-02
-----------------------
### Changes
- Add `which()`, a C implementation of UNIX which(1)
- Add `printheader()`, prints a top-like table heading for client tools
- Remove `UNUSED()` macro, recommended to disable GCC warning instead
### Fixes
- Fix issue #6: `touch()` does not update mtime if file exists
- Fix non-writable `tempfile()`, now with proper unit test
[v1.8.3][] - 2017-01-08
-----------------------
### Changes
- Support absolute path in `pidfile()`. Needed by, e.g. Inadyn
- Add initial `debian/` packaging
- Update README with note on remembering to set `umask()`
### Fixes
- In use-cases when `pidfile()` is called consecutively, e.g. on
`SIGHUP`, recreate PID file if it no longer exists
[v1.8.2][] - 2016-09-05
-----------------------
### Changes
- Updated build instructions in README.
- Converted `touch()`, `makedir()`, `makefifo()`, and `erase()` from
macros to inline functions. Also removed implicit logging to stderr
on error.
### Fixes
- Fix small memory leak in `pidfile()` ... at exit.
- Fixes for building on musl libc
[v1.8.1][] - 2016-06-25
-----------------------
### Fixes
- `fparseln()`, portability fix for NetBSD
- `pidfile()`, portability fix for NetBSD and OpenBSD
[v1.8.0][] - 2016-06-06
-----------------------
### Changes
- Change return type of `fsendfile()` from `size_t` to `ssize_t`
- Change `dir()` semantics: do not assert and always return error
without calling `perror()` or similar.
- The OpenBSD `pidfile()` function's prefix path `_PATH_VARRUN`
can now be overridden by setting the hidden `__pidfile_path`
variable. E.g., to `_PATH_TMP`. Make sure read the docs!
- Add new unit test framework `make check`.
### Fixes
- Fix bad path in new `strndupa()` header file.
- Add missing progress bar API's to `lite.h`
[v1.7.0][] - 2016-06-05
-----------------------
### Changes
- Add support for GNU `strdupa()`, for [Inadyn][] on NetBSD.
- Add support for GNU `strndupa()` and `strnlen()`
### Fixes
- Fix `mkpath()` to handle creating relative directories.
[v1.6.0][] - 2016-05-13
-----------------------
### Changes
- Add support for NetBSD `fparaseln()` for the benefit of [Mg][]
- Add support for OpenBSD `reallocarray()` for the benefit of [Mg][]
- Constify `fisdir()` argument
[v1.5.1][] - 2016-04-17
-----------------------
Minor fix release.
### Changes
- Update README.md, add help when libite is used in autotools projects.
Spell checking and minor cleanup.
### Fixes
- Activate use of `utimensat()` when `pidfile()` is called multiple
times. This reduces the overhead of calling open+write+close to
simply updating the mtime of the PID file.
- Westermo fixes for `fcopyfile()`: nothing copied on embedded PPC
system when using `tmpfile()` as source.
[v1.5.0][] - 2016-03-20
-----------------------
This release changes the header file namespace. Apologies for any
problems this may cause!
### Changes
- Change namespace for header files: `libite/` to `lite/`, e.g. using
`pkg-config` your C program must now `#include <lite/lite.h>`
- Update `pidfile()` to use `utimensat()` to update atime+mtime instead
of opening and writing PID again. Less overhead and nanonsecond res.
[v1.4.4][] - 2016-02-23
-----------------------
### Changes
- Add `ibite.pc.in` for `pkg-config` support.
### Fixes
- Fix issue #3: `tempfile()` fails with bad `O_TMPFILE` on some embedded
targets, in particular PowerPC. On systems with older GLIBC but with
a sufficiently new kernel `O_TMPFILE` is missing and the local libite
definition was wrong, hard coded for x86. Fixed by Johan Askerin.
[v1.4.3][] - 2016-02-02
-----------------------
### Fixes
- Remove symlinks to Markdown files from GIT
- Distribute and install Markdown files: README.md, etc.
[v1.4.2][] - 2016-01-23
-----------------------
### Fixes
- Fix issue #2: GCC6 `-Wmisleading-indentation` causing FTBFS in pimd,
which enables `-Werror`
[v1.4.1][] - 2016-01-22
-----------------------
### Fixes
- Fix install path for include files, regression in v1.4.0 With the
introduction of GNU autotools include file namespace was unfortunately
lost. All include files were therefore installed in $(prefix)/include
instead of $(prefix)/include/libite.
[v1.4.0][] - 2016-01-22
-----------------------
### Changes
- Change to GNU configure and build system
- Add Niels Provos' splay and red-black tree implementation from OpenBSD
`sys/tree.h`, r1.14
- Make `pidfile()` file name accessible as `__pidfile_name`
- Step ABI revision to 2.1, with help from http://250bpm.com/blog:41
[v1.3.0][] - 2016-01-07
-----------------------
### Changes
- Add highly useful typeless `min()`/`max()` macros to `lite.h`,
courtesy of Tobias Waldekranz
- Add BSD `queue.h` and Borland inspired `conio.h` to `install-dev`
target. Needed by [Finit][].
- Note, this release update `queue.h` to OpenBSD v1.43, which removes
support for circular queues (CIRCLEQ).
- Update `strlcpy.c` to OpenBSD v1.12, readability fixes.
- Update `strlcat.c` to OpenBSD v1.14, readability fixes.
- Update `strtonum.c` to OpenBSD v1.7, tiniest of style tweaks.
### Fixes
- Only update mtime if `pidfile()` is called more than once, do not
install multiple `atexit()` handlers.
- Add `#ifndef pidfile`, as for other BSD functions, in case the user
already have a local copy, or a C library with one.
[v1.2.0][] - 2015-11-23
-----------------------
### Changes
- Add simple parser for UNIX configuration files, e.g. `/etc/group`,
`/etc/passwd`, and `/etc/protocols`:
- `lfopen()`
- `lfclose()`
- `lftok()`
- `lfgetkey()`
- `lfgetint()`
- `fgetint()`
### Fixes
- Do not allow `VERSION` to be overloaded by build system.
- Make sure we don't inherit `LDFLAGS` from environment.
[v1.1.1][] - 2015-09-27
-----------------------
### Fixes
* Silence annoying warnings from GNU ar
* Fix macro definitions for compat APIs
[v1.1.0][] - 2015-09-16
-----------------------
### Changes
- Support for `make distdir` used by automake based projects
- `lite.h` move from `error.h` to more BSD friendly `err.h`
- Add highly useful `NELEMS()` and bitmanip macros
- Lots of autotests added
- Add support for running autotests from Travis
- Add `progress()` simple progress bar
- Add `tree()` simple command line tree replacement
- Bump `SONAME` to `libite.so.2` on behalf of [Finit][]
### Fixes
- `pidfile()` upgrade to OpenBSD r1.11
- Lots of README updates, fixes and additions
[v1.0.0][] - 2015-07-12
-----------------------
Initial extraction of frog DNA from [Finit][]. See [README][] for API details.
[UNRELEASED]: https://github.com/troglobit/libite/compare/v1.9.2...HEAD
[v1.9.2]: https://github.com/troglobit/libite/compare/v1.9.1...v1.9.2
[v1.9.1]: https://github.com/troglobit/libite/compare/v1.9.0...v1.9.1
[v1.9.0]: https://github.com/troglobit/libite/compare/v1.8.3...v1.9.0
[v1.8.3]: https://github.com/troglobit/libite/compare/v1.8.2...v1.8.3
[v1.8.2]: https://github.com/troglobit/libite/compare/v1.8.1...v1.8.2
[v1.8.1]: https://github.com/troglobit/libite/compare/v1.8.0...v1.8.1
[v1.8.0]: https://github.com/troglobit/libite/compare/v1.7.0...v1.8.0
[v1.7.0]: https://github.com/troglobit/libite/compare/v1.6.0...v1.7.0
[v1.6.0]: https://github.com/troglobit/libite/compare/v1.5.1...v1.6.0
[v1.5.1]: https://github.com/troglobit/libite/compare/v1.5.0...v1.5.1
[v1.5.0]: https://github.com/troglobit/libite/compare/v1.4.4...v1.5.0
[v1.4.4]: https://github.com/troglobit/libite/compare/v1.4.3...v1.4.4
[v1.4.3]: https://github.com/troglobit/libite/compare/v1.4.2...v1.4.3
[v1.4.2]: https://github.com/troglobit/libite/compare/v1.4.1...v1.4.2
[v1.4.1]: https://github.com/troglobit/libite/compare/v1.4.0...v1.4.1
[v1.4.0]: https://github.com/troglobit/libite/compare/v1.3.0...v1.4.0
[v1.3.0]: https://github.com/troglobit/libite/compare/v1.2.0...v1.3.0
[v1.2.0]: https://github.com/troglobit/libite/compare/v1.1.1...v1.2.0
[v1.1.1]: https://github.com/troglobit/libite/compare/v1.1.0...v1.1.1
[v1.1.0]: https://github.com/troglobit/libite/compare/v1.0.0...v1.1.0
[v1.0.0]: https://github.com/troglobit/libite/compare/TAIL...v1.0.0
[Finit]: https://github.com/troglobit/finit/
[Inadyn]: https://github.com/troglobit/inadyn/
[Mg]: https://github.com/troglobit/mg
[README]: https://github.com/troglobit/libite/blob/v1.0.0/README.md
<!--
-- Local Variables:
-- mode: markdown
-- End:
-->
+104
View File
@@ -0,0 +1,104 @@
Maintenance and Release Checklist
=================================
Maintenance
-----------
* Encourage contributors to write tests, in particular for new features
* Run tests regularly, use Travis-CI to do this automatically
* Leverage GitHub issues for milestone planning
* Reference issues from GitHub pull requests to alert issue subscribers
* Bump library ABI version just before release!
Release Checklist
-----------------
* Update ChangeLog, follow http://keepachangelog.com/ loosely
- Inform users in a plain language of changes and bug fixes
- Do *not* copy-paste GIT commit logs!
- Order entrys according to importance, most relevant first
* Run unit tests: `make check`
* Do we need to bump the ABI version? (Probably, see below)
* Tag
* Push last commit(s) *and* tags to GitHub
* Make release
make distclean
./autogen.sh
./configure
make release
* Create new release in GitHub releases page
* Copy and paste ChangeLog entry, check any stale links!
* Upload release tarball and MD5 files
Library Versioning
------------------
Libite (-lite) relies on GNU Libtool for building the library. For a
user of the library it is important to maintain a clear ABI versioning
scheme. This is not the same as the library version, but rather the
library "compatibility level".
The ABI version is specified in `src/Makefile.am` and looks like this:
libite_la_LDFLAGS = -version-info 0:0:0
\ \ `-- age
\ `--- revision
`---- current
It must be updated according to the [GNU Libtool recommendations][1]:
1. Start with version information of `0:0:0` for each libtool library.
2. Update the version information only immediately before a public
release of your software. More frequent updates are unnecessary, and
only guarantee that the current interface number gets larger faster.
3. If the library *source code has changed at all* since the last update,
then increment revision (`c:r:a` becomes `c:r+1:a`).
4. If any *interfaces have been added, removed, or changed* since the
last update, increment current, and set revision to 0.
5. If any *interfaces have been added* since the last public release,
then increment age.
6. If any *interfaces have been removed or changed* since the last
public release, then set age to 0.
The libtool ABI versioning logic is very confusing but works if you just
disable your brain and follow the rules, one by one.
**Example #1:** a new function has been added, none of the existing ones
have changed. The initial version is 1:0:0, we follow the rules above to
the letter: increase revision, increase current and set revision to zero,
and finally increase age. This, rather confusingly, gives us 2:0:1 which
libtool then translates to `libconfuse.so.1.1.0`.
**Example #2:** some existing functions are changed, they now return an
`int` instead of `void`. The initial version is 0:0:0, and we follow the
rules again: increment revision, increment current and set revision to
zero, set age to zero. This gives us 1:0:0, which is then translated to
`libconfuse.so.1.0.0`.
### Note
Usually, non-developers have no interest in running development versions
(releases are frequent enough), and developers are expected to know how
to juggle versions. In such an ideal world, it is good enough to bump
the library version just prior to a release, point 2.
However, if releases are few and far between, distributors may start to
use snapshots. When a distributor uses a snapshot, the distributor has
to handle the library version manually. Things can get ugly when the
distributor has released an intermediate version with a bumped library
version, and when the official release is bumped to that version, the
distributor will then have to bump the library version for the official
release, and it can be confusing if someone reports bugs on versions
that you didn't even know existed.
The problem with bumping the version with every change is that if your
interface is not finished, the version number might run away, and it
looks pretty bad if a library is at version 262. It kind of tells the
user that the library interface is volatile, which is not good for
business.
[1]: https://www.gnu.org/software/libtool/manual/html_node/Updating-version-info.html
+25
View File
@@ -0,0 +1,25 @@
Much of the code in libite (-lite) is written by Claudio Matsuoka for Finit
and released under the MIT/X11 license. Joachim Nilsson later improved on
the Finit code base and included pieces of software released under the ISC
and BSD licenses. See each respective file for license details.
Copyright (c) 2008-2010 Claudio Matsuoka <cmatsuoka@gmail.com>
Copyright (c) 2008-2016 Joachim Nilsson <troglobit@gmail.com>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
-79
View File
@@ -1,79 +0,0 @@
# Finit libite -- Light-weight utility functions and C-library extensions
#
# Copyright (c) 2008-2012 Joachim Nilsson <troglobit@gmail.com>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
.EXPORT_ALL_VARIABLES:
.PHONY: all install clean
include ../common.mk
CFLAGS += -fPIC
HEADERS = lite.h
OBJS := copyfile.o dir.o fexist.o fisdir.o fmode.o rsync.o
DEPS := $(addprefix ., $(OBJS:.o=.d))
VER = 0
LIBNAME = libite
TARGET = $(LIBNAME).so
VERLIB = $(TARGET).$(VER)
STATICLIB = $(LIBNAME).a
CHECK_FLAGS = $(CFLAGS) $(CPPFLAGS)
all: $(TARGET)
$(OBJS): Makefile
$(TARGET): $(OBJS)
@printf " LINK %s\n" $@
# @$(AR) $(ARFLAGS) $(STATICLIB) $(OBJS)
@$(CC) $(LDFLAGS) -shared $(OBJS) -lrt -lcrypt -Wl,-soname,$@ -o $@
@ln -sf $@ $(VERLIB)
install-exec: all
@install -d $(DESTDIR)$(libdir)
@echo " INSTALL $(DESTDIR)$(libdir)/$(TARGET)"
@$(STRIPINST) $(TARGET) $(DESTDIR)$(libdir)/$(TARGET)
@ln -sf $(TARGET) $(DESTDIR)$(libdir)/$(VERLIB)
install-dev:
@for file in $(HEADERS); do \
printf " INSTALL $(DESTDIR)$(incdir)/$$file\n"; \
$(INSTALL) -m 0644 $$file $(DESTDIR)$(incdir)/$$file; \
done
install: install-dev install-exec
uninstall:
-@$(RM) $(DESTDIR)$(libdir)/$(VERLIB)
-@$(RM) $(DESTDIR)$(libdir)/$(TARGET)
clean: uninstall
-@$(RM) $(OBJS) $(DEPS) $(TARGET) $(VERLIB) $(STATICLIB)
distclean: clean
-@$(RM) $(JUNK) unittest *.o .*.d *.unittest
ifneq ($(MAKECMDGOALS),clean)
ifneq ($(MAKECMDGOALS),distclean)
-include $(DEPS)
endif
endif
+56
View File
@@ -0,0 +1,56 @@
ACLOCAL_AMFLAGS = -I m4
lib_LTLIBRARIES = libite.la
pkgincludedir = $(includedir)/lite
pkginclude_HEADERS = lite.h queue.h conio.h tree.h strlite.h strdupa.h strndupa.h strnlen.h
libite_la_SOURCES = chomp.c copyfile.c dir.c fexist.c fisdir.c fmode.c fparseln.c \
fsendfile.c ifconfig.c lfile.c makepath.c pidfile.c pidfilefn.c \
progress.c reallocarray.c rsync.c strlcpy.c strlcat.c strtonum.c \
tempfile.c tree.c which.c
libite_la_CPPFLAGS = -D_GNU_SOURCE
libite_la_CFLAGS = -W -Wall -Wextra
libite_la_LDFLAGS = $(AM_LDFLAGS) -version-info 4:1:0
pkgconfigdir = $(libdir)/pkgconfig
pkgconfig_DATA = libite.pc
doc_DATA = README.md LICENSE
EXTRA_DIST = README.md LICENSE ChangeLog.md
SUBDIRS = tests
## Generate .deb package
package:
@dpkg-buildpackage -uc -us -B
## Generate MD5 checksum file
MD5 = md5sum
md5-dist:
@for file in $(DIST_ARCHIVES); do \
$(MD5) $$file > $$file.md5; \
done
## Check if tagged in git
release-hook:
if [ ! `git tag | grep $(PACKAGE_VERSION)` ]; then \
echo; \
printf "\033[1m\033[41mCannot find release tag $(PACKAGE_VERSION)\033[0m\n"; \
printf "\033[1m\033[5mDo release anyway?\033[0m "; read yorn; \
if [ "$$yorn" != "y" -a "$$yorn" != "Y" ]; then \
printf "OK, aborting release.\n"; \
exit 1; \
fi; \
echo; \
else \
echo; \
printf "\033[1m\033[42mFound GIT release tag $(PACKAGE_VERSION)\033[0m\n"; \
printf "\033[1m\033[44m>>Remember to push tags!\033[0m\n"; \
echo; \
fi
## Target to run when building a release
release: dist release-hook md5-dist
@for file in $(DIST_ARCHIVES); do \
printf "$$file \tDistribution tarball\n"; \
printf "$$file.md5\t"; cat $$file.md5 | cut -f1 -d' '; \
mv $$file* ../; \
done
+412
View File
@@ -0,0 +1,412 @@
-lite | Frog DNA, basically
===========================
[![Travis Status][]][Travis]
Table of Contents
-----------------
* [Introduction](#introduction)
* [Using -lite](#using--lite)
* [Helper Macros](#helper-macros)
* [Generic Functions](#generic-functions)
* [OpenBSD Functions](#openbsd-functions)
* [Build & Install](#origin--references)
* [TODO](#todo)
Introduction
------------
Libite is a lightweight library of *frog DNA*. It can be used to fill
the gaps in any dinosaur project. It holds useful functions and macros
developed by both [Finit][1] and the [OpenBSD][2] project. Most notably
the string functions: [strlcpy(3)][3], [strlcat(3)][3] and the highly
useful *BSD [sys/queue.h][4] and [sys/tree.h][7] API's.
Libite is the frog DNA missing in GNU libc. However, -lite does not aim
to become another [GLIB][5]! One noticeable gap in GLIBC is the missing
`_SAFE` macros in the BSD `sys/queue.h` API &mdash; highly recommended
when traversing lists to delete/free nodes.
The code is open sourced under a mix of the [MIT/X11 license][MIT], the
[ISC license][ISC] used by OpenBSD, and [BSD licenses][BSD], all of them
are extremely liberal and can be used freely in proprietary software if
needed.
For an introduction to why Libite happened, and how you can use it, see
[this blog post][6].
Using -lite
-----------
Libite is by default installed as a library and a set of include files.
To prevent clashing with include files of the same name `-lite` employs
an include file namespace `lite/`, which is strongly recommended to use
in your applications:
#include <lite/lite.h>
#include <lite/conio.h>
#include <lite/queue.h>
#include <lite/tree.h>
The output from the `pkg-config` tool holds no surprises in this regard:
$ pkg-config --libs --static --cflags libite
-I/usr/local/include -L/usr/local/lib -lite
The prefix path `/usr/local/` shown here is only the default. Use the
`configure` script to select a different prefix when installing libite.
For GNU autotools based projects, use the following in `configure.ac`:
# Check for required libraries
PKG_CHECK_MODULES([lite], [libite >= 1.5.0])
and in your `Makefile.am`:
proggy_CFLAGS = $(lite_CFLAGS)
proggy_LDADD = $(lite_LIBS)
Important Note
--------------
When using functions like `mkpath()`, `makepath()`, and `makefifo()`,
make sure your `umask()` is correct so you do not accidentally create
files and directories accessible to other users than intended.
Helper Macros
-------------
- `atonum(str)`
Convert string to natural number, works for 32-bit non-negative
integers. Returns -1 on error. (Uses `strtonum()` internally.)
- `blkdev(dev)`
Create block device
- `chardev(dev)`
Create character device
- `erase(path)`
Erase file/directory with `remove()`. Errors on `stderr`
- `makedir(path)`
Create directory, like `mkdir()`. Errors on `stderr`
- `makefifo(path)`
Create a FIFO, like `mkfifo()`. Errors on `stderr`
- `min(a,b)`/`max(a,b)`
These macros take care to avoid double evaluation.
- `touch(path)`
Create a file, or update mtime. Errors on `stderr`
- `S_ISEXEC(mode_t m)`
Mysteriously missing from GLIBC
- `ISCLR(word,bit)`
Is bit in (integer) word cleared?
- `ISSET(word,bit)`
Is bit in (integer) word set?
- `ISOTHER(word,bit)`
Are any other bits, except bit, in (integer) word set?
- `SETBIT(word,bit)`
Set bit in (integer) word.
- `CLRBIT(word,bit)`
Clear bit in (integer) word.
- `NELEMS(array)`
Returns the number of elements in an array. From the great book, The
Practice of Programming, by Kernighan and Pike.
Generic Functions
-----------------
- `chomp(str)`
Perl like chomp function, chop off last char if newline.
- `copyfile(src, dst, len, symlink)`
Like the shell `cp(1)` and `dd(1),` can also create symlinks.
- `dir(dir, ext, filter, list, strip)`
Wrapper for `scandir()` with optional filter. Returns a list of
names: files and directories that must be freed after use. See
the unit test for an example, or take a look at `glob(3)`, it's
probably what you want anyway.
- `fcopyfile(src, dst)`
Like `copyfile()` but uses already open `FILE *` pointers. Copies
from current file positions to current file positions until EOF.
- `fexist(file)`
Check for the existence of a file, returns True(1) or False(0).
- `fisdir(path)`
Check for the existence of a directory, returns True(1) or False(0).
- `fmode(file)`
Returns the `mode_t` bits of a file or directory.
- `fsendfile(src, dst, len)`
Copy data between file streams, very similar to `fcopyfile()`, but
`dst` is allowed to be `NULL` to be able to read and discard `len`
bytes from `src`.
- `ifconfig(ifname, addr, mask, up)`
Basic ifconfig like operations on an interface. Only supports IPv4
addresses. Note that mask is not CIDR notation.
- `lfopen(file, sep)`, `lfclose(lf)`
LITE file API for parsing UNIX style configuration files like
`/etc/protocols` and `/etc/services`.
- `lftok(lf)`
Read tokens, delimited by `sep`, from file opened with `lfopen()`.
- `lfgetkey(lf, key)`
Find `key` in file opened with `lfopen()`, return value/argument.
- `lfgetint(lf, key)`
Wrapper for `lfgetkey()`, returns positive integer value to `key`,
or `-1` if `key` is not found.
- `fgetint(file, sep, key)`
Wrapper for `lfopen()`, `lfgetint()`, and `lfclose()`. Useful for
when only reading a single `key` from a file.
- `makepath(dir)`
Create all components of the specified directory.
- `mkpath(dir, mode)`
Like `makepath()`, but also takes a `mode_t` permission mode argument.
- `movefile(src, dst)`
Like `copyfile()`, but renames `src` to `dst`, or recreates symlink
with the `dst` name. On successful operation the source is removed
and the function returns POSIX OK (0).
- `pidfile(name)`
Create a daemon PID file using either the `name` as a full path, if
`name` starts with `/`, or in `_PATH_VARRUN` using `name` as the
basename of the application. If `name` is `NULL`, then `__progname`
is used as the basename. The resulting file name is available to the
user as a read-only pointer:
extern char *__pidfile_name;
Use this function to create a PID file for your daemon when it is
ready to receive signals. A client application may poll for the
existence of this file, so make sure to have your signal handlers
properly setup before calling this function.
The PID file is removed when the program exits, using an `atexit()`
handler. However, depending on how the program terminates the file
may still exist even though the program is no longer running.
Calling this function multiple times updates the mtime of the file.
Only one `atexit()` handler is created, regardless of the amount of
times the function is called. If the file is removed, subsequent
calls to this function will recreate the file.
See below for a link to OpenBSD man page.
- `pidfile_read(pidfile)`
Read PID from pid file created by `pidfile()`.
- `pidfile_signal(pidfile, signal)`
Send signal to PID found in pid file created by `pidfile()`.
- `progress(percent, max_width)`
Simple ASCII progress bar with a spinner. Start it with `percent=0`
and set the `max_width=chars` to indicate width of the progress bar.
Called multiple times with the same percentage value cause spinner to
spin.
- `rsync(src, dst, delete, *filter())`
Very simple `rsync()` to copy files files and directories
recursively.
- `tempfile()`
Secure replacement for `tmpfile()`. Creates an invisible temporary
file in `/tmp` that is removed when the returned `FILE` pointer is
closed.
**Note:** Requires Linux v3.11, or later, will fall back to the old
and unsafe `tmpfile()` on older systems.
- `tree(path, show_perms)`
Very simple `/bin/tree` replacement. Draw ASCII tree of `path`, with
optional listing of file and directory permissions if `show_perms` is
set. The `path` argument should be a directory.
- `which(cmd)`, `whichp(cmd)`
C implementation of UNIX which(1). Returns a malloc'ed string with the
full path to `cmd` on success, otherwise `NULL`.
`whichp()` is a predicate function, returns `TRUE` or `FALSE`.
**Note:** `which("/bin/ps aux")` will return `/bin/ps`, or `TRUE`,
provided of course `/bin/ps` exists.
GNU Functions
-------------
The following are useful GNU functions, that do not exist on *BSD, and
some other platforms.
- `strdupa(str)`
http://man7.org/linux/man-pages/man3/strdupa.3.html
- `strndupa(str)`
http://man7.org/linux/man-pages/man3/strndupa.3.html
- `strnlen(str, lim)`
http://man7.org/linux/man-pages/man3/strnlen.3.html
OpenBSD/NetBSD/FreeBSD Functions
--------------------------------
The following are popular functions and highly useful macros from the
*BSD world of UNIX that are sadly missing on Linux.
- `fparseln(fp, *len, *lineno, delim, flags)`
http://man.openbsd.org/OpenBSD-current/man3/fparseln.3
- `pidfile(basename)`
http://www.openbsd.org/cgi-bin/man.cgi/OpenBSD-current/man3/pidfile.3
**Note:** the version of `pidfile()` in -lite has been extended to
handle it being called multiple times, i.e. to not create multiple
`atexit()` handlers, and also to export a few internal paths:
- `__pidfile_path`: prefix path, default `_PATH_VARRUN`. Notice the
trailing slash requirement if you want to override it!
- `__pidfile_name`: full path to PID file , similar to `__progname`.
See previous section for details.
- `reallocarray(ptr, nmemb, size)`
http://man.openbsd.org/OpenBSD-current/man3/reallocarray.3
- `strlcpy(dst, src, len)`
http://www.openbsd.org/cgi-bin/man.cgi/OpenBSD-current/man3/strlcpy.3
- `strlcat(dst, src, len)`
http://www.openbsd.org/cgi-bin/man.cgi/OpenBSD-current/man3/strlcat.3
- `strtonum()`
http://www.openbsd.org/cgi-bin/man.cgi/OpenBSD-current/man3/strtonum.3
- `sys/queue.h` API
http://www.openbsd.org/cgi-bin/man.cgi/OpenBSD-current/man3/LIST_EMPTY.3
- `sys/tree.h` API
Niels Provos' famous splay and red-black tree implementation.
http://www.openbsd.org/cgi-bin/man.cgi/OpenBSD-current/man3/SPLAY_FOREACH.3
Build & Install
---------------
This library was initially built for and developed on GNU/Linux systems
as a light weight utility library, these days NetBSD should also work.
Libite (LITE) employs the de facto standard GNU configure and build
system:
./configure
make -j5
sudo make install-strip
sudo ldconfig
**Note:** When checking code from GitHub, use <kbd>./autogen.sh</kbd> to
generate a `configure` script. It is a generated file and otherwise only
included in released tarballs.
TODO
----
- Improve documentation, possibly use kdoc or gdoc2 to generate docs from API.
- Continuously, update OpenBSD functions/macros.
[1]: https://github.com/troglobit/finit
[2]: http://www.openbsd.org/
[3]: http://www.openbsd.org/cgi-bin/man.cgi?query=strlcpy
[4]: http://www.openbsd.org/cgi-bin/man.cgi/OpenBSD-current/man3/LIST_EMPTY.3
[5]: https://developer.gnome.org/glib/
[6]: http://troglobit.com/blog/2015/07/02/howto-using-lite-with-a-git-based-application/
[7]: http://www.openbsd.org/cgi-bin/man.cgi/OpenBSD-current/man3/SPLAY_FOREACH.3
[MIT]: https://en.wikipedia.org/wiki/MIT_License
[ISC]: https://en.wikipedia.org/wiki/ISC_license
[BSD]: https://en.wikipedia.org/wiki/BSD_licenses
[Travis]: https://travis-ci.org/troglobit/libite
[Travis Status]: https://travis-ci.org/troglobit/libite.png?branch=master
<!--
-- Local Variables:
-- mode: markdown
-- End:
-->
+7
View File
@@ -0,0 +1,7 @@
TODO ... in no particular order
===============================
* Investigate adding FreeBSD pidfile_open() et al
* Investigate FreeBSD libutil library, could be useful for porting between unices
Executable
+3
View File
@@ -0,0 +1,3 @@
#!/bin/sh
autoreconf -W portability -visfm
+53
View File
@@ -0,0 +1,53 @@
/* Perl inspired chomp() implementation.
*
* Copyright (c) 2014-2015 Joachim Nilsson <troglobit@gmail.com>
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include <errno.h>
#include <string.h>
/**
* chomp - Perl like chomp function, chop off last char(s) if newline.
* @str: String to chomp
*
* This function is like Perl chomp, but it's set to chop of all
* trailing newlines.
*
* Returns:
* If @str is a valid pointer this function returns @str, otherwise
* @errno is set to %EINVAL and this function returns %NULL.
*/
char *chomp(char *str)
{
char *p;
if (!str || strlen(str) < 1) {
errno = EINVAL;
return NULL;
}
p = str + strlen(str) - 1;
while (*p == '\n')
*p-- = 0;
return str;
}
/**
* Local Variables:
* indent-tabs-mode: t
* c-file-style: "linux"
* End:
*/
+14
View File
@@ -0,0 +1,14 @@
AC_INIT(libite, 1.9.3, https://github.com/troglobit/libite/issues)
AM_INIT_AUTOMAKE([1.11 foreign no-dist-gzip dist-xz])
AM_SILENT_RULES([yes])
AC_CONFIG_SRCDIR(lite.h)
AM_CONFIG_HEADER(config.h)
AC_CONFIG_FILES([Makefile tests/Makefile libite.pc])
AC_CONFIG_MACRO_DIR([m4])
AC_PROG_CC
AM_PROG_AR
LT_INIT
AC_OUTPUT
+152
View File
@@ -0,0 +1,152 @@
/* A conio.h like implementation for VTANSI displays.
*
* Copyright (c) 2009-2017 Joachim Nilsson <troglobit@gmail.com>
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#ifndef CONIO_H_
#define CONIO_H_
#include <stdio.h>
#include <termios.h>
#include <unistd.h>
/* Attributes */
#define RESETATTR 0
#define BRIGHT 1
#define DIM 2
#define UNDERSCORE 4
#define BLINK 5 /* May not work on all displays. */
#define REVERSE 7
#define HIDDEN 8
/* Colors for text and background */
#define BLACK 0x0
#define RED 0x1
#define GREEN 0x2
#define BROWN 0x3
#define BLUE 0x4
#define MAGENTA 0x5
#define CYAN 0x6
#define LIGHTGREY 0x7
#define DARKGREY 0x10
#define LIGHTRED 0x11
#define LIGHTGREEN 0x12
#define YELLOW 0x13
#define LIGHTBLUE 0x14
#define LIGHTMAGENTA 0x15
#define LIGHTCYAN 0x16
#define WHITE 0x17
#ifndef SCREEN_WIDTH
#define SCREEN_WIDTH 80 /* Override using, e.g. #define SCREEN_WIDTH tty_width() */
#endif
/* Esc[2JEsc[1;1H - Clear screen and move cursor to 1,1 (upper left) pos. */
#define clrscr() fputs("\033[2J\033[1;1H", stdout)
/* Esc[K - Erases from the current cursor position to the end of the current line. */
#define clreol() fputs("\033[K", stdout)
/* Esc[2K - Erases the entire current line. */
#define delline() fputs("\033[2K", stdout)
/* Esc[Line;ColumnH - Moves the cursor to the specified position (coordinates) */
#define gotoxy(x,y) fprintf(stdout, "\033[%d;%dH", y, x)
/* Esc[?25l (lower case L) - Hide Cursor */
#define hidecursor() fputs("\033[?25l", stdout)
/* Esc[?25h (lower case H) - Show Cursor */
#define showcursor() fputs("\033[?25h", stdout)
/* Esc[Value;...;Valuem - Set Graphics Mode (attr, color, val) */
#define __set_gm(a,c,v) \
if (!c) \
fprintf(stdout, "\033[%dm", a); \
else \
fprintf(stdout, "\033[%d;%dm", c & 0x10 ? 1 : 0, (c & 0xF) + v)
#define textattr(attr) __set_gm(attr, 0, 0)
#define textcolor(color) __set_gm(RESETATTR, color, 30)
#define textbackground(color) __set_gm(RESETATTR, color, 40)
/* Print table heading @line to @fp, with optional leading newline */
static inline void printheader(FILE *fp, const char *line, int nl)
{
fprintf(fp ?: stdout,
"%s\033[7m%s%*s\033[0m\n",
nl ? "\n" : "",
line, SCREEN_WIDTH - (int)strlen(line), "");
}
/* Requries: #inlude <termios.h> and #include <poll.h> */
static inline void initscr(int *row, int *col)
{
if (!row || !col)
return;
#if defined(TCSANOW) && defined(POLLIN)
struct termios tc, saved;
struct pollfd fd = { STDIN_FILENO, POLLIN, 0 };
if (!isatty(STDIN_FILENO) || !isatty(STDOUT_FILENO)) {
*row = 24;
*col = 80;
return;
}
/* Disable echo to terminal while probing */
tcgetattr(STDOUT_FILENO, &tc);
saved = tc;
tc.c_cflag |= (CLOCAL | CREAD);
tc.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG);
tcsetattr(STDOUT_FILENO, TCSANOW, &tc);
/*
* Save cursor pos+attr
* Diable top+bottom margins
* Set cursor at the far bottom,right pos
* Query term for resulting pos
*/
fprintf(stdout, "\e7" "\e[r" "\e[999;999H" "\e[6n");
fflush(stdout);
/*
* Wait here for terminal to echo back \e[row,lineR ...
*/
if (poll(&fd, 1, 300) <= 0 || scanf("\e[%d;%dR", row, col) != 2) {
*row = 24;
*col = 80;
}
/*
* Restore above saved cursor pos+attr
*/
fprintf(stdout, "\e8");
fflush(stdout);
/* Restore terminal */
tcsetattr(STDOUT_FILENO, TCSANOW, &saved);
return;
#else
*row = 24;
*col = 80;
#endif
}
#endif /* CONIO_H_ */
/**
* Local Variables:
* indent-tabs-mode: t
* c-file-style: "linux"
* End:
*/
+128 -185
View File
@@ -23,89 +23,153 @@
#include <errno.h>
#include <fcntl.h>
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/param.h> /* MAX(), isset(), setbit(), TRUE, FALSE, et consortes. :-) */
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include "lite.h"
static int __isdir_and_append_filename(char *src, char **dst);
/* Tests if dst is a directory, if so, reallocates dst and appends src filename returning 1 */
static int adjust_target(char *src, char **dst)
{
int isdir = 0;
if (fisdir(*dst)) {
int slash = 0;
char *tmp, *ptr = strrchr(src, '/');
if (!ptr)
ptr = src;
else
ptr++;
tmp = malloc(strlen(*dst) + strlen(ptr) + 2);
if (!tmp) {
errno = EISDIR;
return 0;
}
isdir = 1; /* Free dst before exit! */
slash = fisslashdir(*dst);
sprintf(tmp, "%s%s%s", *dst, slash ? "" : "/", ptr);
*dst = tmp;
}
return isdir;
}
/* Actual copy loop, used by both copyfile() and fcopyfile()
* breaks loop on error and EOF */
static ssize_t do_copy(int in, int out, size_t num, char *buffer, size_t len)
{
ssize_t ret = 0, size = 0;
do {
size_t count = num > len ? len : num;
ret = read(in, buffer, count);
if (ret <= 0) {
if (ret == -1 && EINTR == errno)
continue;
break;
}
if (ret > 0)
size += write(out, buffer, ret);
num -= count;
} while (num > 0);
return size;
}
/**
* copyfile - Copy a file to another.
* @src: Source file.
* @dst: Target file.
* @src: Full path name to source file.
* @dst: Full path name to target file.
* @len: Number of bytes to copy, zero (0) for entire file.
* @sym: Should symlinks be recreated (1) or followed (0)
*
* This is a C implementation of the command line cp(1) utility. It is one
* of the classic missing links in the UNIX C library. This version is from
* the finit project, http://helllabs.org/finit/, which is a reimplementation
* of fastinit for the Asus EeePC.
*
* Only some small changes to save stack space have been introduced.
*
* Returns:
* The number of bytes copied, zero may be error (check errno!), but it
* may also indicate that @src was empty. If @src is a directory errno
* may also indicate that @src was empty. If @src is a directory @errno
* will be set to %EISDIR since copyfile() is not recursive.
*/
ssize_t copyfile(char *src, char *dst, int len)
ssize_t copyfile(char *src, char *dst, int len, int sym)
{
char *buffer;
int s, d, n, isdir = 0, saved_errno = 0;
int in, out, isdir = 0, saved_errno = 0;
size_t num;
ssize_t size = 0;
struct stat st;
errno = 0; /* Reset before leaving this function. */
// fprintf (stderr, "%s() src: %s, dst: %s, len: %d\n", __func__, src, dst, len);
errno = 0;
buffer = malloc(BUFSIZ);
if (!buffer)
return 0;
if (fisdir(src)) {
errno = EISDIR; /* Error: source is a directory */
return 0;
saved_errno = EISDIR; /* Error: source is a directory */
goto exit;
}
/* Check if target is a directory, then append the src base filename. */
isdir = __isdir_and_append_filename(src, &dst);
/* Check if target is a directory, then append src filename. */
isdir = adjust_target(src, &dst);
/* Len == 0 means copy entire file */
if (len == 0) {
/* XXX: This feels a bit unsafe, but 2047 MiB may be sufficient for us.
* --Jocke 2008-08-11 */
len = INT_MAX;
/* Check if the source file is a symlink ... */
if (stat(src, &st)) {
size = -1;
goto exit;
}
if ((s = open(src, O_RDONLY)) >= 0) {
if ((d =
open(dst, O_WRONLY | O_CREAT | O_TRUNC,
fmode(src))) >= 0) {
do {
int clen = len > BUFSIZ ? BUFSIZ : len;
if ((n = read(s, buffer, clen)) > 0) {
size += write(d, buffer, n);
}
len -= clen;
/* ... only try readlink() if symlink and @sym is set. */
if (sym && (st.st_mode & S_IFMT) == S_IFLNK) {
size = readlink(src, buffer, BUFSIZ);
if (size > 0) {
if (size >= (ssize_t)BUFSIZ) {
saved_errno = ENOBUFS;
size = -1;
} else {
buffer[size] = 0;
size = !symlink(buffer, dst);
}
while (len > 0 && n == BUFSIZ);
close(d);
} else {
saved_errno = errno;
}
close(s);
} else {
saved_errno = errno;
/* Don't fall back to copy, that is a potentially
* dangerous race condition, see CWE-367. */
goto exit;
}
/* 0: copy entire file */
if (len == 0)
num = st.st_size;
else
num = (size_t)len;
in = open(src, O_RDONLY);
if (in < 0) {
saved_errno = errno;
goto exit;
}
out = open(dst, O_WRONLY | O_CREAT | O_TRUNC, fmode(src));
if (out < 0) {
close(in);
saved_errno = errno;
goto exit;
}
size = do_copy(in, out, num, buffer, BUFSIZ);
if (!size && errno)
saved_errno = errno;
close(out);
close(in);
exit:
free(buffer);
if (isdir)
free(dst);
@@ -135,12 +199,12 @@ int movefile(char *src, char *dst)
int isdir, result = 0;
/* Check if target is a directory, then append the src base filename. */
isdir = __isdir_and_append_filename(src, &dst);
isdir = adjust_target(src, &dst);
if (rename(src, dst)) {
if (errno == EXDEV) {
errno = 0;
copyfile(src, dst, 0);
copyfile(src, dst, 0, 1);
if (errno)
result = 1;
else
@@ -157,161 +221,40 @@ int movefile(char *src, char *dst)
}
/**
* copy_filep - Copy between FILE *fp.
* fcopyfile - Copy between FILE *fp.
* @src: Source FILE.
* @dst: Destination FILE.
*
* Function takes signals into account and will restart the syscalls as long
* as error is %EINTR.
* Function takes signals into account and will restart the syscalls as
* long as error is %EINTR.
*
* Returns:
* POSIX OK(0), or non-zero with errno set on error.
*/
int copy_filep(FILE *src, FILE *dst)
int fcopyfile(FILE *src, FILE *dst)
{
int result = 0;
char *buf = (char *)malloc(BUFSIZ);
char *buf;
if (!src || !dst)
return EINVAL;
if (!src || !dst) {
errno = EINVAL;
return -1;
}
buf = malloc(BUFSIZ);
if (!buf)
return errno;
return -1;
while (1) {
if (!fgets(buf, BUFSIZ, src)) {
if (errno == EINTR) {
clearerr(src);
continue;
}
if (feof(src))
break;
result = errno;
goto exit;
}
while (EOF == fputs(buf, dst)) {
if (errno == EINTR) {
clearerr(dst);
continue;
}
result = errno;
goto exit;
}
}
exit:
while (fgets(buf, BUFSIZ, src))
fputs(buf, dst);
free(buf);
return errno = result;
}
/* Tests if dst is a directory, if so, reallocates dst and appends src filename returning 1 */
static int __isdir_and_append_filename(char *src, char **dst)
{
int isdir = 0;
if (fisdir(*dst)) {
int slash = 0;
char *tmp, *ptr = strrchr(src, '/');
if (!ptr)
ptr = src;
else
ptr++;
// fprintf (stderr, "Yes %s is a dir --> add %s\n", *dst, ptr);
tmp = malloc(strlen(*dst) + strlen(ptr) + 2);
if (!tmp) {
errno = EISDIR;
return 0;
}
isdir = 1; /* Free dst before exit! */
slash = fisslashdir(*dst);
sprintf(tmp, "%s%s%s", *dst, slash ? "" : "/", ptr);
*dst = tmp;
// fprintf (stderr, "NEW DST:%s\n", *dst);
}
return isdir;
}
#ifdef UNITTEST
#include <stdio.h>
/* XXX: Make a real set of unit tests ... */
#if 0
int main(int argc, char *argv[])
{
if (argc < 3) {
fprintf(stderr,
"Usage: %s <src> <dst>\nCopies the <src> file to the <dst> file.\n",
argv[0]);
return 1;
}
printf("Copying file %s to %s\n", argv[1], argv[2]);
return copyfile(argv[1], argv[2], 0);
}
#else
int main(void)
{
int i = 0;
char *files[] = {
"/etc/passwd", "/tmp/tok", "/tmp/tok",
"/etc/passwd", "/tmp/", "/tmp/passwd",
"/etc/passwd", "/tmp", "/tmp/passwd",
NULL
};
FILE *src, *dst;
fprintf(stderr, "\n=>Start testing copy_filep()\n");
while (files[i]) {
fprintf(stderr, "copy_filep(%s, %s)\t", files[i],
files[i + 1]);
src = fopen(files[i], "r");
dst = fopen(files[i + 1], "w");
if (copy_filep(src, dst))
perror("Failed");
if (src)
fclose(src);
if (dst)
fclose(dst);
if (fexist(files[i + 2]))
fprintf(stderr, "OK => %s\n", files[i + 2]);
remove(files[i + 2]);
i += 3;
}
printf("\n\n=>Start testing copyfile()\n");
i = 0;
while (files[i]) {
fprintf(stderr, "copyfile(%s, %s)\t", files[i], files[i + 1]);
if (!copyfile(files[i], files[i + 1], 0))
perror("Failed");
if (fexist(files[i + 2]))
fprintf(stderr, "OK => %s\n", files[i + 2]);
remove(files[i + 2]);
i += 3;
}
return 0;
}
#endif
#endif /* UNITTEST */
/**
* Local Variables:
* compile-command: "gcc -g -I../include -o unittest -DUNITTEST copyfile.c && ./unittest"
* version-control: t
* kept-new-versions: 2
* c-file-style: "ellemtel"
* indent-tabs-mode: t
* c-file-style: "linux"
* End:
*/
+8
View File
@@ -0,0 +1,8 @@
tmp/*
libuev/*
libuev*
autoreconf*
debhelper*
files
!*.dirs
!*.install
+35
View File
@@ -0,0 +1,35 @@
libite (1.9.3-1) unstable; urgency=low
* New upstream release, v1.9.3, fixes to conio.h, initscr() and tree().
-- Joachim Nilsson <troglobit@gmail.com> Tue, 24 Oct 2017 08:49:54 +0200
libite (1.9.2-1) unstable; urgency=low
* New upstream reelase, v1.9.2, see upstream ChangeLog for details.
-- Joachim Nilsson <troglobit@gmail.com> Tue, 15 Aug 2017 08:15:14 +0200
libite (1.9.1-1) unstable; urgency=low
* New upstream reelase, v1.9.1.
-- Joachim Nilsson <troglobit@gmail.com> Sun, 02 Jul 2017 19:23:00 +0100
libite (1.9.0-1) unstable; urgency=low
* New upstream reelase.
-- Joachim Nilsson <troglobit@gmail.com> Sun, 02 Jul 2017 19:23:00 +0100
libite (1.8.3-1) unstable; urgency=low
* New upstream reelase.
-- Joachim Nilsson <troglobit@gmail.com> Sun, 08 Jan 2017 15:22:26 +0100
libite (1.8.2-1) unstable; urgency=low
* Initial release.
-- Joachim Nilsson <troglobit@gmail.com> Tue, 29 Nov 2016 08:23:35 +0100
+1
View File
@@ -0,0 +1 @@
config.log
+1
View File
@@ -0,0 +1 @@
9
+51
View File
@@ -0,0 +1,51 @@
Source: libite
Priority: optional
Maintainer: Joachim Nilsson <troglobit@gmail.com>
Build-Depends: dpkg-dev (>= 1.14.9), debhelper (>= 9), dh-autoreconf
Standards-Version: 3.9.6
Section: libs
Homepage: https://github.com/troglobit/libite/
Vcs-Git: https://github.com/troglobit/libite.git
Vcs-Browser: https://github.com/troglobit/libite/
Package: libite-dev
Priority: extra
Section: libdevel
Architecture: any
Depends: ${misc:Depends}, libite (= ${binary:Version})
Description: static library, header files, and docs for libite
Static library, header files, and documentation for libite.
.
Libite is a lightweight library of frog DNA. It can be used to fill the
gaps in any dinosaur project. It holds useful functions and macros
developed by both Finit and the OpenBSD project. Most notably the
string functions: strlcpy(3), strlcat(3) and the highly useful *BSD
sys/queue.h and sys/tree.h API's.
.
Libite is the frog DNA missing in GNU libc. However, -lite does not aim
to become another GLIB! One noticeable gap in GLIBC is the missing
_SAFE macros in the BSD sys/queue.h API — highly recommended when
traversing lists to delete/free nodes.
.
The code is open sourced under a mix of the MIT/X11 license, the ISC
license used by OpenBSD, and BSD licenses, all of them are extremely
liberal and can be used freely in proprietary software if needed.
Package: libite
Architecture: any
Depends: ${misc:Depends}, ${shlibs:Depends}
Description: That missing frog DNA you've been looking for. MIT/X11/ISC/BSD License.
Libite is a lightweight library of frog DNA. It can be used to fill the
gaps in any dinosaur project. It holds useful functions and macros
developed by both Finit and the OpenBSD project. Most notably the
string functions: strlcpy(3), strlcat(3) and the highly useful *BSD
sys/queue.h and sys/tree.h API's.
.
Libite is the frog DNA missing in GNU libc. However, -lite does not aim
to become another GLIB! One noticeable gap in GLIBC is the missing
_SAFE macros in the BSD sys/queue.h API — highly recommended when
traversing lists to delete/free nodes.
.
The code is open sourced under a mix of the MIT/X11 license, the ISC
license used by OpenBSD, and BSD licenses, all of them are extremely
liberal and can be used freely in proprietary software if needed.
+84
View File
@@ -0,0 +1,84 @@
Format: http://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
Source: https.//github.com/troglobit/libite/
Files: *
Copyright:
2008-2010 Claudio Matsuoka <cmatsuoka@gmail.com>
2008-2016 Joachim Nilsson <troglobit@gmail.com>
License: MIT
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
Files: chomp.c
Copyright: 2014-2015 Joachim Nilsson <troglobit@gmail.com>
License: ISC
Files: conio.h
Copyright: 2009-2013 Joachim Nilsson <troglobit@gmail.com>
License: ISC
Files: dir.c
Copyright: 2008-2016 Joachim Nilsson <troglobit@gmail.com>
License: ISC
Files: lfile.c
Copyright: 2015-2016 Joachim Nilsson <troglobit@gmail.com>
License: ISC
Files: pidfile.c
Copyright: 1999 The NetBSD Foundation, Inc.
License: BSD-2-clause
Files: queue.h
Copyright: 1991, 1993 The Regents of the University of California.
License: BSD-3-clause
Files: reallocarray.c
Copyright: 2008 Otto Moerbeek <otto@drijf.net>
License: ISC
Files: rsync.c
Copyright: 2011, 2012 Joachim Nilsson <troglobit@gmail.com>
License: ISC
Files: strdupa.h strndupa.h
Copyright: 2009 William Ahern
License: MIT
Files: strlcat.c strlcpy.c
Copyright: 998, 2015 Todd C. Miller <Todd.Miller@courtesan.com>
License: MIT
Files: strnlen.c
Copyright: 2016 Joachim Nilsson <troglobit@gmail.com>
License: ISC
Files: strtonum.c
Copyright: 2004 Ted Unangst and Todd Miller
License: ISC
Files: tempfile.c
Copyright: 2015-2016 Joachim Nilsson <troglobit@gmail.com>
License: ISC
Files: tree.c
Copyright: 2015 Joachim Nilsson <troglobit@gmail.com>
License: ISC
Files: tests/*.c
License: public-domain
Vendored
+1
View File
@@ -0,0 +1 @@
README.md
+2
View File
@@ -0,0 +1,2 @@
usr/lib
usr/include
+4
View File
@@ -0,0 +1,4 @@
usr/include/lite/*.h
usr/lib/*/lib*.a
usr/lib/*/lib*.so
usr/lib/*/pkgconfig/lib*.pc
+1
View File
@@ -0,0 +1 @@
usr/lib
+1
View File
@@ -0,0 +1 @@
usr/lib/*/lib*.so.*
Vendored Executable
+8
View File
@@ -0,0 +1,8 @@
#!/usr/bin/make -f
# Uncomment this to turn on verbose mode.
#export DH_VERBOSE=1
%:
dh $@ --with autoreconf
+1
View File
@@ -0,0 +1 @@
3.0 (native)
+17 -113
View File
@@ -1,6 +1,6 @@
/* Functions for operating on files in directories.
*
* Copyright (c) 2008-2012 Joachim Nilsson <troglobit@gmail.com>
* Copyright (c) 2008-2016 Joachim Nilsson <troglobit@gmail.com>
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
@@ -15,14 +15,14 @@
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include <assert.h>
#include <errno.h>
#include <dirent.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
static const char *matcher_type = NULL;
static int (*matcher_filter) (const char *file) = NULL;
static int matcher(const struct dirent *entry)
{
char *pos = strrchr(entry->d_name, '.');
@@ -72,7 +72,8 @@ static int matcher(const struct dirent *entry)
* would be returned as "config0".
*
* Returns:
* Number of files in @list, zero if no matching files of @type.
* Number of files in @list, zero if no matching files of @type, or
* non-zero on error with @errno set.
*/
int dir(const char *dir, const char *type, int (*filter) (const char *file), char ***list, int strip)
{
@@ -80,7 +81,10 @@ int dir(const char *dir, const char *type, int (*filter) (const char *file), cha
char **files;
struct dirent **namelist;
assert(list);
if (!list) {
errno = EINVAL;
return -1;
}
if (!dir)
/* Assuming current directory */
@@ -92,9 +96,10 @@ int dir(const char *dir, const char *type, int (*filter) (const char *file), cha
matcher_type = type;
matcher_filter = filter;
n = scandir(dir, &namelist, matcher, alphasort);
if (n < 0) {
perror("scandir");
} else {
if (n < 0)
return -1;
if (n > 0) {
files = (char **)malloc(n * sizeof(char *));
for (i = 0; i < n; i++) {
if (files) {
@@ -109,119 +114,18 @@ int dir(const char *dir, const char *type, int (*filter) (const char *file), cha
}
free(namelist[i]);
}
free(namelist);
if (num)
*list = files;
}
if (num)
*list = files;
if (namelist)
free(namelist);
return num;
}
#ifdef UNITTEST
#include <errno.h>
#include <sys/stat.h>
#include <fcntl.h>
#include "otn/c.h"
#define DIR_TYPE_IMAGE ".img"
#define DIR_TYPE_SYSLOG ""
#define DIR_TYPE_CONFIG ".cfg"
#define STARTUP_CONFIG "startup-config.cfg"
int simulate_files(int creat)
{
int i;
char *files[] =
{ "config0.cfg", "config1.cfg", "config2.cfg", "config3.cfg",
"rr109.img", "rx100.img", "rx107.img", "rm957.img", "messages"
};
for (i = 0; i < ARRAY_ELEMENTS(files); i++) {
if (creat)
touch(files[i]);
else
remove(files[i]);
}
if (creat)
symlink("config2.cfg", STARTUP_CONFIG);
else
remove(STARTUP_CONFIG);
return 0;
}
static int cfg_dir_filter(const char *file)
{
/* Skip the STARTUP_CONFIG file, it is a symbolic link to the
* current startup configuration. */
return ! !strcmp(file, STARTUP_CONFIG);
}
int main(int argc, char *argv[])
{
int i, num;
char *type = DIR_TYPE_CONFIG;
char **files;
int once = 1;
int is_startup_config(const char *entry) {
static char file[80];
if (once) {
int len = readlink(STARTUP_CONFIG, file, sizeof(file));
if (len == -1)
return 0;
file[len] = 0;
once = 0; /* Only once per call to dir() */
}
//printf ("Comparing link %s with entry %s\n", file, entry);
return !strcmp(file, entry);
}
simulate_files(1);
if (argc >= 2) {
if (!strcasecmp("CONFIG", argv[1])) {
type = DIR_TYPE_CONFIG;
system("ls -l *" DIR_TYPE_CONFIG);
}
if (!strcasecmp("IMAGE", argv[1])) {
type = DIR_TYPE_IMAGE;
system("ls -l *" DIR_TYPE_IMAGE);
}
if (!strcasecmp("SYSLOG", argv[1])) {
type = DIR_TYPE_SYSLOG;
system("ls -l *");
}
}
num = dir(NULL, type, cfg_dir_filter, &files, 0);
if (num) {
for (i = 0; i < num; i++) {
printf("%s", files[i]);
if (is_startup_config(files[i]))
printf(" --> startup-config");
printf("\n");
free(files[i]);
}
free(files);
}
simulate_files(0);
return 0;
}
#endif /* UNITTEST */
/**
* Local Variables:
* compile-command: "gcc -g -DUNITTEST -o unittest dir.c"
* version-control: t
* indent-tabs-mode: t
* c-file-style: "linux"
* End:
-1
View File
@@ -46,7 +46,6 @@ int fexist(char *file)
/**
* Local Variables:
* version-control: t
* indent-tabs-mode: t
* c-file-style: "linux"
* End:
+1 -3
View File
@@ -21,7 +21,6 @@
* THE SOFTWARE.
*/
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
@@ -32,7 +31,7 @@
* Returns:
* %TRUE(1) if the file exists and is a directory, otherwise %FALSE(0).
*/
int fisdir(char *file)
int fisdir(const char *file)
{
struct stat sb;
@@ -44,7 +43,6 @@ int fisdir(char *file)
/**
* Local Variables:
* version-control: t
* indent-tabs-mode: t
* c-file-style: "linux"
* End:
+1 -2
View File
@@ -39,7 +39,7 @@ mode_t fmode(char *file)
if (!file) {
errno = EINVAL;
return 0; /* Doesn't exist ... */
return 0;
}
if (!stat(file, &sb))
@@ -50,7 +50,6 @@ mode_t fmode(char *file)
/**
* Local Variables:
* version-control: t
* indent-tabs-mode: t
* c-file-style: "linux"
* End:
+199
View File
@@ -0,0 +1,199 @@
/* $NetBSD: fparseln.c,v 1.10 2009/10/21 01:07:45 snj Exp $ */
/*
* Copyright (c) 1997 Christos Zoulas. All rights reserved.
*
* 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.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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.
*/
#include <assert.h>
#include <errno.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "lite.h"
#ifndef _DIAGASSERT
#define _DIAGASSERT(t)
#endif
static int isescaped(const char *, const char *, int);
/* isescaped():
* Return true if the character in *p that belongs to a string
* that starts in *sp, is escaped by the escape character esc.
*/
static int
isescaped(const char *sp, const char *p, int esc)
{
const char *cp;
size_t ne;
_DIAGASSERT(sp != NULL);
_DIAGASSERT(p != NULL);
/* No escape character */
if (esc == '\0')
return 0;
/* Count the number of escape characters that precede ours */
for (ne = 0, cp = p; --cp >= sp && *cp == esc; ne++)
continue;
/* Return true if odd number of escape characters */
return (ne & 1) != 0;
}
/* fparseln():
* Read a line from a file parsing continuations ending in \
* and eliminating trailing newlines, or comments starting with
* the comment char.
*/
char *
fparseln(FILE *fp, size_t *size, size_t *lineno, const char str[3], int flags)
{
static const char dstr[3] = { '\\', '\\', '#' };
ssize_t s;
size_t len, ptrlen;
char *buf;
char *ptr, *cp;
int cnt;
char esc, con, nl, com;
_DIAGASSERT(fp != NULL);
len = 0;
buf = NULL;
ptrlen = 0;
ptr = NULL;
cnt = 1;
if (str == NULL)
str = dstr;
esc = str[0];
con = str[1];
com = str[2];
/*
* XXX: it would be cool to be able to specify the newline character,
* getdelim(3) does let us, but supporting it would diverge from BSDs.
*/
nl = '\n';
flockfile(fp);
while (cnt) {
cnt = 0;
if (lineno)
(*lineno)++;
s = getline(&ptr, &ptrlen, fp);
if (s < 0)
break;
if (s && com) { /* Check and eliminate comments */
for (cp = ptr; cp < ptr + s; cp++)
if (*cp == com && !isescaped(ptr, cp, esc)) {
s = cp - ptr;
cnt = s == 0 && buf == NULL;
break;
}
}
if (s && nl) { /* Check and eliminate newlines */
cp = &ptr[s - 1];
if (*cp == nl)
s--; /* forget newline */
}
if (s && con) { /* Check and eliminate continuations */
cp = &ptr[s - 1];
if (*cp == con && !isescaped(ptr, cp, esc)) {
s--; /* forget continuation char */
cnt = 1;
}
}
if (s == 0) {
/*
* nothing to add, skip realloc except in case
* we need a minimal buf to return an empty line
*/
if (cnt || buf != NULL)
continue;
}
if ((cp = realloc(buf, len + s + 1)) == NULL) {
funlockfile(fp);
free(buf);
free(ptr);
return NULL;
}
buf = cp;
(void) memcpy(buf + len, ptr, s);
len += s;
buf[len] = '\0';
}
funlockfile(fp);
free(ptr);
if ((flags & FPARSELN_UNESCALL) != 0 && esc && buf != NULL &&
strchr(buf, esc) != NULL) {
ptr = cp = buf;
while (cp[0] != '\0') {
int skipesc;
while (cp[0] != '\0' && cp[0] != esc)
*ptr++ = *cp++;
if (cp[0] == '\0' || cp[1] == '\0')
break;
skipesc = 0;
if (cp[1] == com)
skipesc += (flags & FPARSELN_UNESCCOMM);
if (cp[1] == con)
skipesc += (flags & FPARSELN_UNESCCONT);
if (cp[1] == esc)
skipesc += (flags & FPARSELN_UNESCESC);
if (cp[1] != com && cp[1] != con && cp[1] != esc)
skipesc = (flags & FPARSELN_UNESCREST);
if (skipesc)
cp++;
else
*ptr++ = *cp++;
*ptr++ = *cp++;
}
*ptr = '\0';
len = strlen(buf);
}
if (size)
*size = len;
return buf;
}
+85
View File
@@ -0,0 +1,85 @@
/* Copy data between file streams
*
* Copyright (c) 2013 Tobias Waldekranz <tobias@waldekranz.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
/**
* fsendfile - copy data between file streams
* @src: Source stream
* @dst: Destination stream
* @len: Number of bytes to copy
*
* @dst may be %NULL, in which case @len bytes are read and discarded
* from @src. This can be useful for streams where seeking is not
* permitted. Additionally, @len may be the special value zero (0), in
* which case fsendfile() will copy until %EOF is seen on @src.
*
* Returns:
* The number of bytes copied. If an error is detected -1 is returned
* and @errno will be set accordingly.
*/
ssize_t fsendfile(FILE *src, FILE *dst, size_t len)
{
char *buf;
size_t tot = 0;
ssize_t blk = BUFSIZ, num = 0;
if (!src) {
errno = EINVAL;
return -1;
}
buf = (char *)malloc(BUFSIZ);
if (!buf)
return -1;
while (!len || tot < len) {
if (len && ((len - tot) < BUFSIZ))
blk = len - tot;
num = fread(buf, 1, blk, src);
if (num == 0)
break;
if (dst && (fwrite(buf, num, 1, dst) != 1)) {
num = -1;
break;
}
tot += num;
}
free(buf);
return (num == -1) ? -1 : (ssize_t)tot;
}
/**
* Local Variables:
* indent-tabs-mode: t
* c-file-style: "linux"
* End:
*/
+91
View File
@@ -0,0 +1,91 @@
/* Fastinit (finit) ifconfig() implementation.
*
* Copyright (c) 2008 Claudio Matsuoka <http://helllabs.org/finit/>
* Copyright (C) 2009-2014 Joachim Nilsson <joachim.nilsson@westermo.se>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include <arpa/inet.h>
#include <errno.h>
#include <net/if.h>
#include <netinet/in.h>
#include <string.h>
#include <sys/ioctl.h>
#include <sys/socket.h>
#include <unistd.h>
extern size_t strlcpy(char *dst, const char *src, size_t siz);
/**
* ifconfig - Basic ifconfig like operations on an interface
* @ifname: Name of interface to operate on
* @addr: If @up then set this optional IPv4 address
* @mask: If @up and @addr, and @addr is not INADDR_ANY, then set netmask
* @up: Control %IFF_UP flag on interface
*
* Returns:
* POSIX OK(0) on success, or non-zero on error.
*/
int ifconfig(char *ifname, char *addr, char *mask, int up)
{
int sd, ret = -1;
struct ifreq ifr;
struct sockaddr_in *sin = (struct sockaddr_in *)&ifr.ifr_addr;
if ((sd = socket(PF_INET, SOCK_DGRAM, IPPROTO_IP)) < 0)
return -1;
memset(&ifr, 0, sizeof (ifr));
strlcpy(ifr.ifr_name, ifname, IFNAMSIZ);
ifr.ifr_addr.sa_family = AF_INET;
if (up) {
if (addr) {
if (inet_pton(AF_INET, addr, &sin->sin_addr) == 1)
ret = ioctl(sd, SIOCSIFADDR, &ifr);
}
/* Non-zero IP address */
if (mask && addr && strcmp(addr, "0.0.0.0")) {
if (inet_pton(AF_INET, mask, &sin->sin_addr) == -1)
ret = ioctl(sd, SIOCSIFNETMASK, &ifr);
}
}
if (!ioctl(sd, SIOCGIFFLAGS, &ifr)) {
if (up)
ifr.ifr_flags |= IFF_UP;
else
ifr.ifr_flags &= ~IFF_UP;
ret = ioctl(sd, SIOCSIFFLAGS, &ifr);
}
close(sd);
return ret;
}
/**
* Local Variables:
* indent-tabs-mode: t
* c-file-style: "linux"
* End:
*/
+195
View File
@@ -0,0 +1,195 @@
/* Parse UNIX /etc configuration files like /etc/protocols and /etc/services
*
* Copyright (c) 2015-2016 Joachim Nilsson <troglobit@gmail.com>
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include <errno.h>
#include <stdio.h> /* FILE */
#include <stdlib.h> /* atoi() */
#include <string.h> /* strlen(), strncmp(), strtok_r() */
#include <sys/param.h> /* MAX() */
typedef struct lfile {
FILE *fp;
char buf[256];
char *sep, *save;
} lfile_t;
/**
* lfopen - Open file and return parsing context
* @file: File to parse
* @sep: Separator(s) to use in lftok()
*
* Returns:
* Pointer to a &lftile_t parser context, or %NULL on error.
*/
lfile_t *lfopen(char *file, char *sep)
{
lfile_t *lf;
if (!file || !sep) {
errno = EINVAL;
return NULL;
}
/* Use calloc for clearing buf on behalf of lftok() */
lf = calloc(sizeof(*lf), sizeof(char));
if (lf) {
lf->fp = fopen(file, "r");
lf->sep = sep;
lf->save = lf->buf;
if (!lf->fp) {
free(lf);
return NULL;
}
}
return lf;
}
/**
* lfclose - Close a parser context
* @lf: Pointer to &lfile_t context from lfopen()
*/
void lfclose(lfile_t *lf)
{
if (!lf)
return;
if (lf->fp)
fclose(lf->fp);
free(lf);
}
/**
* lftok - Get next token in file
* @lf: Pointer to &lfile_t context from lfopen()
*
* Returns:
* Next token, read from file previously opened with lfopen(),
* or %NULL if EOF.
*/
char *lftok(lfile_t *lf)
{
char *token;
if (!lf || !lf->fp || !lf->sep) {
errno = EINVAL;
return NULL;
}
token = strtok_r(NULL, lf->sep, &lf->save);
if (!token) {
while (fgets(lf->buf, sizeof(lf->buf), lf->fp)) {
if (lf->buf[0] == '#')
continue;
token = strtok_r(lf->buf, lf->sep, &lf->save);
if (!token)
continue;
return token;
}
errno = ENOENT;
return NULL;
}
return token;
}
/**
* lfgetkey - Find key in file
* @lf: Pointer to &lfile_t context from lfopen()
* @key: Key to look for
*
* Locate @key from the current position in the file parser context
* returned from lfopen(). Please note, the search for @key does not
* start from the beginning of the file, it searches from the current
* position. To restart search from the beginning use rewind() on the
* lf->fp.
*
* Returns:
* The value to @key, or %NULL if not found.
*/
char *lfgetkey(lfile_t *lf, char *key)
{
char *token;
while ((token = lftok(lf))) {
if (token[0] == '#')
continue;
if (!strncmp(token, key, MAX(strlen(token), strlen(key))))
return lftok(lf);
}
return NULL;
}
/**
* lfgetint - Same as lfgetkey() but returns an integer
* @lf: Pointer to &lfile_t context from lfopen()
* @key: Key to look for
*
* This function is the same as lfgetkey() but returns the positive
* integer value for the matching @key, if found.
*
* Returns:
* The positive integer value for @key, or -1 if not found.
*/
int lfgetint(lfile_t *lf, char *key)
{
char *token = lfgetkey(lf, key);
if (token)
return atoi(token);
return -1;
}
/**
* fgetint - Find the integer value for key in a file
* @file: File to search for @key
* @sep: Separator for tokens in @file
* @key: Key to look for in @file
*
* This is a convenience wrapper for lfopen(), lfgetint(), and
* lfclose().
*
* Returns:
* The positive integer value for @key, or -1 if not found.
*/
int fgetint(char *file, char *sep, char *key)
{
int val = -1;
lfile_t *lf;
lf = lfopen(file, sep);
if (lf) {
val = lfgetint(lf, key);
lfclose(lf);
}
return val;
}
/**
* Local Variables:
* indent-tabs-mode: t
* c-file-style: "linux"
* End:
*/
+12
View File
@@ -0,0 +1,12 @@
prefix=@prefix@
exec_prefix=@exec_prefix@
libdir=@libdir@
includedir=@includedir@
Name: @PACKAGE@
Description: Frog DNA, basically
Version: @VERSION@
Requires:
Libs: -L${libdir} -lite
Cflags: -I${includedir}
+140 -14
View File
@@ -1,7 +1,7 @@
/* Collection of utility funcs and C library extensions for finit & its plugins
/* Collection of frog DNA
*
* Copyright (c) 2008-2010 Claudio Matsuoka <cmatsuoka@gmail.com>
* Copyright (c) 2008-2012 Joachim Nilsson <troglobit@gmail.com>
* Copyright (c) 2008-2016 Joachim Nilsson <troglobit@gmail.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
@@ -22,38 +22,164 @@
* THE SOFTWARE.
*/
#ifndef FINIT_LITE_H_
#define FINIT_LITE_H_
#ifndef LITE_H_
#define LITE_H_
#include <errno.h>
#include <stdio.h>
#include <string.h>
#include <stdint.h> /* uint8_t, uint16_t, uint32_t, INT32_MAX, etc. */
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/param.h> /* MAX(), isset(), setbit(), TRUE, FALSE, et consortes. :-) */
#include <unistd.h>
#include "strlite.h"
/*
* fparseln() specific operation flags.
*/
#define FPARSELN_UNESCESC 0x01
#define FPARSELN_UNESCCONT 0x02
#define FPARSELN_UNESCCOMM 0x04
#define FPARSELN_UNESCREST 0x08
#define FPARSELN_UNESCALL 0x0f
typedef struct lfile lfile_t;
char *chomp (char *str);
char *fparseln (FILE *, size_t *, size_t *, const char[3], int);
int fexist (char *file);
int fisdir (char *file);
int fisdir (const char *file);
mode_t fmode (char *file);
ssize_t copyfile (char *src, char *dst, int len);
FILE *tempfile (void);
ssize_t copyfile (char *src, char *dst, int len, int sym);
int movefile (char *src, char *dst);
int copy_filep (FILE *src, FILE *dst);
int fcopyfile (FILE *src, FILE *dst);
ssize_t fsendfile (FILE *src, FILE *dst, size_t len);
int ifconfig (char *ifname, char *addr, char *mask, int up);
lfile_t*lfopen (char *file, char *sep);
void lfclose (lfile_t *lf);
char *lftok (lfile_t *lf);
char *lfgetkey (lfile_t *lf, char *key);
int lfgetint (lfile_t *lf, char *key);
int fgetint (char *file, char *sep, char *key);
int mkpath (char *dir, mode_t mode);
int makepath (char *dir);
int dir (const char *dir, const char *type, int (*filter) (const char *file), char ***list, int strip);
int rsync (char *src, char *dst, int delete, int (*filter) (const char *file));
int rsync (char *src, char *dst, int delete, int (*filter) (const char *file));
int pidfile (const char *basename);
int pidfile_signal(const char *pidfile, int signal);
pid_t pidfile_read (const char *pidfile);
pid_t pidfile_poll (const char *pidfile);
void *reallocarray(void *optr, size_t nmemb, size_t size);
int tree(char *path, int show_perms);
void progress (int percent, int max_width);
void progress_simple(int percent);
char *which (const char *cmd);
int whichp (const char *cmd);
#ifndef touch
#include <sys/stat.h> /* utimensat() */
#include <sys/time.h> /* utimensat() on *BSD */
static inline int touch(const char *path)
{
if (mknod((path), S_IFREG|0644, 0)) {
if (errno == EEXIST)
return utimensat(0, path, NULL, 0);
return -1;
}
return 0;
}
#endif
#ifndef makedir
static inline int makedir(const char *path, mode_t mode)
{
if (mkdir(path, mode) && errno != EEXIST)
return -1;
return 0;
}
#endif
#ifndef makefifo
static inline int makefifo(const char *path, mode_t mode)
{
if (mkfifo(path, mode) && errno != EEXIST)
return -1;
return 0;
}
#endif
#ifndef erase
static inline int erase(const char *path)
{
if (remove(path) && errno != ENOENT)
return -1;
return 0;
}
#endif
#ifndef chardev
# define chardev(x,m,maj,min) mknod((x), S_IFCHR|(m), makedev((maj),(min)))
#endif
#ifndef blkdev
# define blkdev(x,m,maj,min) mknod((x), S_IFBLK|(m), makedev((maj),(min)))
#endif
#ifndef S_ISEXEC
# define S_ISEXEC(m) (((m) & S_IXUSR) == S_IXUSR)
#endif
/* Unline isset(), setbit() et al, these work with integers/shorts/longwords/etc. */
#ifndef ISCLR
#define ISCLR(word,bit) ((word & (1 << (bit)) ? 0 : 1))
#endif
#ifndef ISSET
#define ISSET(word,bit) ((word & (1 << (bit)) ? 1 : 0))
#endif
#ifndef ISOTHER
#define ISOTHER(word,bit) ((word & ~(1 << (bit)) ? 1 : 0)) /* Is any other bit set? */
#endif
#ifndef SETBIT
#define SETBIT(word,bit) (word |= (1 << (bit)))
#endif
#ifndef CLRBIT
#define CLRBIT(word,bit) (word &= ~(1 << (bit)))
#endif
/* From The Practice of Programming, by Kernighan and Pike */
#ifndef NELEMS
#define NELEMS(array) (sizeof(array) / sizeof(array[0]))
#endif
/* Does directory end with a slash? */
static inline int fisslashdir(char *dir)
{
if (!dir) return 0;
if (strlen (dir) > 0) return dir[strlen (dir) - 1] == '/';
return 0;
if (!dir)
return 0;
if (strlen(dir) > 0)
return dir[strlen(dir) - 1] == '/';
return 0;
}
#endif /* FINIT_LITE_H_ */
/* Compat */
#define copy_filep(src, dst) fcopyfile(src, dst)
#define pidfile_read_pid(file) pifile_read(file)
#define signal_pidfile(file, signo) pidfile_signal(file, signo)
#endif /* LITE_H_ */
/**
* Local Variables:
* version-control: t
* indent-tabs-mode: t
* c-file-style: "linux"
* End:
+1
View File
@@ -0,0 +1 @@
*.m4
+69
View File
@@ -0,0 +1,69 @@
/* mkpath() -- Create all components leading up to a given directory
*
* Copyright (c) 2013-2016 Joachim Nilsson <troglobit@gmail.com>
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include <errno.h>
#include <libgen.h>
#include <sys/stat.h>
#include <sys/types.h>
#include "lite.h"
/**
* mkpath - Like makepath() but takes a mode_t argument
* @dir: Directory to created, relative or absolute
* @mode: A &mode_t mode to create @dir with
*
* Returns:
* POSIX OK(0) on success, otherwise -1 with @errno set.
*/
int mkpath(char *dir, mode_t mode)
{
struct stat sb;
if (!dir) {
errno = EINVAL;
return 1;
}
if (!stat(dir, &sb))
return 0;
mkpath(dirname(strdupa(dir)), mode);
return mkdir(dir, mode);
}
/**
* makepath - Create all components of the specified directory.
* @dir: Directory to create.
*
* Returns:
* POSIX OK (0) on success, otherwise -1 and errno set appropriately.
* This function returns EINVAL on bad argument, or ENOMEM when it
* fails allocating temporary memory. For other error codes see the
* mkdir() syscall description.
*/
int makepath(char *dir)
{
return mkpath(dir, 0777);
}
/**
* Local Variables:
* indent-tabs-mode: t
* c-file-style: "linux"
* End:
*/
+136
View File
@@ -0,0 +1,136 @@
/* Updated by troglobit for libite/finit/uftpd projects 2016/07/04 */
/* $OpenBSD: pidfile.c,v 1.11 2015/06/03 02:24:36 millert Exp $ */
/* $NetBSD: pidfile.c,v 1.4 2001/02/19 22:43:42 cgd Exp $ */
/*-
* Copyright (c) 1999 The NetBSD Foundation, Inc.
* All rights reserved.
*
* This code is derived from software contributed to The NetBSD Foundation
* by Jason R. Thorpe.
*
* 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.
*
* THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. 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 FOUNDATION 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.
*/
#include <sys/stat.h> /* utimensat() */
#include <sys/time.h> /* utimensat() on *BSD */
#include <sys/types.h>
#include <errno.h>
#include <paths.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#ifndef pidfile
static char *pidfile_path = NULL;
static pid_t pidfile_pid = 0;
static void pidfile_cleanup(void);
const char *__pidfile_path = _PATH_VARRUN; /* Note: includes trailing slash '/' */
const char *__pidfile_name = NULL;
extern char *__progname;
int
pidfile(const char *basename)
{
int save_errno;
int atexit_already;
pid_t pid;
FILE *f;
if (basename == NULL)
basename = __progname;
pid = getpid();
atexit_already = 0;
if (pidfile_path != NULL) {
if (!access(pidfile_path, R_OK) && pid == pidfile_pid) {
utimensat(0, pidfile_path, NULL, 0);
return (0);
}
free(pidfile_path);
pidfile_path = NULL;
__pidfile_name = NULL;
atexit_already = 1;
}
if (basename[0] != '/') {
if (asprintf(&pidfile_path, "%s%s.pid", __pidfile_path, basename) == -1)
return (-1);
} else {
if (asprintf(&pidfile_path, "%s", basename) == -1)
return (-1);
}
if ((f = fopen(pidfile_path, "w")) == NULL) {
save_errno = errno;
free(pidfile_path);
pidfile_path = NULL;
errno = save_errno;
return (-1);
}
if (fprintf(f, "%ld\n", (long)pid) <= 0 || fflush(f) != 0) {
save_errno = errno;
(void) fclose(f);
(void) unlink(pidfile_path);
free(pidfile_path);
pidfile_path = NULL;
errno = save_errno;
return (-1);
}
(void) fclose(f);
__pidfile_name = pidfile_path;
/*
* LITE extension, no need to set up another atexit() handler
* if user only called us to update the mtime of the PID file
*/
if (atexit_already)
return (0);
pidfile_pid = pid;
if (atexit(pidfile_cleanup) < 0) {
save_errno = errno;
(void) unlink(pidfile_path);
free(pidfile_path);
pidfile_path = NULL;
pidfile_pid = 0;
errno = save_errno;
return (-1);
}
return (0);
}
static void
pidfile_cleanup(void)
{
if (pidfile_path != NULL && pidfile_pid == getpid()) {
(void) unlink(pidfile_path);
free(pidfile_path);
pidfile_path = NULL;
}
}
#endif
+126
View File
@@ -0,0 +1,126 @@
/* Functions for dealing with PID files (client side)
*
* Copyright (c) 2009-2015 Joachim Nilsson <troglobit@gmail.com>
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <unistd.h>
extern char *chomp(char *str);
/**
* pidfile_read - Reads a PID value from a pidfile.
* @pidfile: File containing PID, usually in /var/run/<PROC>.pid
*
* This function takes a @pidfile and returns the PID found therein.
*
* Returns:
* On invalid @pidfile -1 and errno set to %EINVAL, when @pidfile does not exist -1
* and errno set to %ENOENT. When the pidfile is empty or when its contents cannot
* be translated this function returns zero (0), on success this function returns
* a PID value greater than one. PID 1 is reserved for the system init process.
*/
pid_t pidfile_read(const char *pidfile)
{
int pid = 0;
char buf[16];
FILE *fp;
if (!pidfile) {
errno = EINVAL;
return -1;
}
fp = fopen(pidfile, "r");
if (!fp)
return -1;
if (fgets(buf, sizeof(buf), fp)) {
char *ptr = chomp(buf);
if (ptr) {
errno = 0;
pid = strtoul(ptr, NULL, 0);
if (errno)
pid = 0; /* Failed conversion. */
}
}
fclose(fp);
return pid;
}
/**
* pidfile_poll - Poll for the existence of a pidfile and return PID
* @pidfile: Path to pidfile to poll for
*
* This function polls for the pidfile at @pidfile for at most 5 seconds
* before timing out. If the file is created within that time span the
* file is read and its PID contents returned.
*
* Returns:
* The PID read from @pidfile, or zero on timeout.
*/
pid_t pidfile_poll(const char *pidfile)
{
pid_t pid = 0;
int tries = 0;
/* Timeout = 100 * 50ms = 5s */
while ((pid = pidfile_read(pidfile)) <= 0 && tries++ < 100)
usleep(50000); /* Wait 50ms between retries */
if (pid < 0)
pid = 0;
return pid;
}
/**
* pidfile_signal - Send signal to a PID and cleanup pidfile afterwards
* @pidfile: File containing PID, usually in /var/run/<PROC>.pid
* @signal: Signal to send to PID found in @pidfile.
*
* If @signal is any of %SIGTERM, %SIGKILL, or if kill() returns -1 the
* @pidfile is removed.
*
* Returns:
* POSIX OK(0) on success, non-zero otherwise.
*/
int pidfile_signal(const char *pidfile, int signal)
{
int pid = -1, ret = -1;
pid = pidfile_read(pidfile);
if (pid <= 0)
return 1;
ret = kill(pid, signal);
if ((ret == -1) || (signal == SIGTERM) || (signal == SIGKILL))
(void)remove(pidfile);
return 0;
}
/**
* Local Variables:
* compile-command: "make V=1 -f pidfilefn.mk"
* indent-tabs-mode: t
* c-file-style: "linux"
* End:
*/
+122
View File
@@ -0,0 +1,122 @@
/* Simple termios based progress bar
*
* Copyright (c) 2012-2015 Joachim Nilsson <troglobit@gmail.com>
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include <limits.h> /* INT_MAX */
#include <stdio.h>
#include <string.h>
#include "conio.h"
#define SPINNER_THROB ".oOo"
#define SPINNER_PULSAR ".oO°Oo."
#define SPINNER_ARROW "v<^>"
#define SPINNER_STAR ".oO@*"
#define SPINNER_DEFAULT "|/-\\"
static char spinner(char *style)
{
size_t num;
static unsigned int i = 0;
if (!style)
style = SPINNER_DEFAULT;
num = strlen(style);
return style[i++ % num]; /* % Number of states in style */
}
/**
* progress - Advanced ASCII progress bar with spinner
* @percent: Start first call with this set to 0, end with 100
* @max_width: Max width of progress bar, in total characters.
*
* This function draws an advanced ASCII progressbar at the current
* line. It always start from the first column.
*
* The progress bar will hide the cursor if started with @percent 0 and
* show it again at the end, when called with @percent 100.
*
* While being called with the same percentage the spinner will spin,
* to show the user the process hasn't frozen.
*
* If the output TTY cannot interpret control characters, like \r, it is
* advised to instead used the progress_simple() function.
*/
void progress(int percent, int max_width)
{
int i, bar;
/* Adjust for progress bar overhead */
max_width -= 10;
if (0 == percent)
hidecursor();
fprintf(stderr, "\r%3d%% %c [", percent, spinner(NULL));
bar = percent * max_width / 100;
for (i = 0; i < max_width; i++) {
if (i > bar)
fputc(' ', stderr);
else if (i == bar)
fputc('>', stderr);
else
fputc('=', stderr);
}
fprintf(stderr, "]");
if (100 == percent) {
showcursor();
fputc('\n', stderr);
}
}
void progress_simple(int percent)
{
static int last = 1;
int ratio, numout;
if (!percent && last) {
last = 0;
fputs("0% 25% 50% 75% 100%\n"
"|---------+---------+---------+---------|\n"
"|", stderr);
return;
}
ratio = 40 * percent / 100;
numout = ratio - last;
if (ratio <= last)
return;
last = ratio;
while (numout--) {
if (ratio != 40 || numout)
putc('=', stderr);
else
putc('|', stderr);
}
}
/**
* Local Variables:
* indent-tabs-mode: t
* c-file-style: "linux"
* End:
*/
+533
View File
@@ -0,0 +1,533 @@
/* $OpenBSD: queue.h,v 1.43 2015/12/28 19:38:40 millert Exp $ */
/* $NetBSD: queue.h,v 1.11 1996/05/16 05:17:14 mycroft Exp $ */
/*
* Copyright (c) 1991, 1993
* The Regents of the University of California. All rights reserved.
*
* 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.
*
* @(#)queue.h 8.5 (Berkeley) 8/20/94
*/
#ifndef _SYS_QUEUE_H_
#define _SYS_QUEUE_H_
/*
* This file defines five types of data structures: singly-linked lists,
* lists, simple queues, tail queues and XOR simple queues.
*
*
* A singly-linked list is headed by a single forward pointer. The elements
* are singly linked for minimum space and pointer manipulation overhead at
* the expense of O(n) removal for arbitrary elements. New elements can be
* added to the list after an existing element or at the head of the list.
* Elements being removed from the head of the list should use the explicit
* macro for this purpose for optimum efficiency. A singly-linked list may
* only be traversed in the forward direction. Singly-linked lists are ideal
* for applications with large datasets and few or no removals or for
* implementing a LIFO queue.
*
* A list is headed by a single forward pointer (or an array of forward
* pointers for a hash table header). The elements are doubly linked
* so that an arbitrary element can be removed without a need to
* traverse the list. New elements can be added to the list before
* or after an existing element or at the head of the list. A list
* may only be traversed in the forward direction.
*
* A simple queue is headed by a pair of pointers, one to the head of the
* list and the other to the tail of the list. The elements are singly
* linked to save space, so elements can only be removed from the
* head of the list. New elements can be added to the list before or after
* an existing element, at the head of the list, or at the end of the
* list. A simple queue may only be traversed in the forward direction.
*
* A tail queue is headed by a pair of pointers, one to the head of the
* list and the other to the tail of the list. The elements are doubly
* linked so that an arbitrary element can be removed without a need to
* traverse the list. New elements can be added to the list before or
* after an existing element, at the head of the list, or at the end of
* the list. A tail queue may be traversed in either direction.
*
* An XOR simple queue is used in the same way as a regular simple queue.
* The difference is that the head structure also includes a "cookie" that
* is XOR'd with the queue pointer (first, last or next) to generate the
* real pointer value.
*
* For details on the use of these macros, see the queue(3) manual page.
*/
#if defined(QUEUE_MACRO_DEBUG) || (defined(_KERNEL) && defined(DIAGNOSTIC))
#define _Q_INVALIDATE(a) (a) = ((void *)-1)
#else
#define _Q_INVALIDATE(a)
#endif
/*
* Singly-linked List definitions.
*/
#define SLIST_HEAD(name, type) \
struct name { \
struct type *slh_first; /* first element */ \
}
#define SLIST_HEAD_INITIALIZER(head) \
{ NULL }
#define SLIST_ENTRY(type) \
struct { \
struct type *sle_next; /* next element */ \
}
/*
* Singly-linked List access methods.
*/
#define SLIST_FIRST(head) ((head)->slh_first)
#define SLIST_END(head) NULL
#define SLIST_EMPTY(head) (SLIST_FIRST(head) == SLIST_END(head))
#define SLIST_NEXT(elm, field) ((elm)->field.sle_next)
#define SLIST_FOREACH(var, head, field) \
for((var) = SLIST_FIRST(head); \
(var) != SLIST_END(head); \
(var) = SLIST_NEXT(var, field))
#define SLIST_FOREACH_SAFE(var, head, field, tvar) \
for ((var) = SLIST_FIRST(head); \
(var) && ((tvar) = SLIST_NEXT(var, field), 1); \
(var) = (tvar))
/*
* Singly-linked List functions.
*/
#define SLIST_INIT(head) { \
SLIST_FIRST(head) = SLIST_END(head); \
}
#define SLIST_INSERT_AFTER(slistelm, elm, field) do { \
(elm)->field.sle_next = (slistelm)->field.sle_next; \
(slistelm)->field.sle_next = (elm); \
} while (0)
#define SLIST_INSERT_HEAD(head, elm, field) do { \
(elm)->field.sle_next = (head)->slh_first; \
(head)->slh_first = (elm); \
} while (0)
#define SLIST_REMOVE_AFTER(elm, field) do { \
(elm)->field.sle_next = (elm)->field.sle_next->field.sle_next; \
} while (0)
#define SLIST_REMOVE_HEAD(head, field) do { \
(head)->slh_first = (head)->slh_first->field.sle_next; \
} while (0)
#define SLIST_REMOVE(head, elm, type, field) do { \
if ((head)->slh_first == (elm)) { \
SLIST_REMOVE_HEAD((head), field); \
} else { \
struct type *curelm = (head)->slh_first; \
\
while (curelm->field.sle_next != (elm)) \
curelm = curelm->field.sle_next; \
curelm->field.sle_next = \
curelm->field.sle_next->field.sle_next; \
} \
_Q_INVALIDATE((elm)->field.sle_next); \
} while (0)
/*
* List definitions.
*/
#define LIST_HEAD(name, type) \
struct name { \
struct type *lh_first; /* first element */ \
}
#define LIST_HEAD_INITIALIZER(head) \
{ NULL }
#define LIST_ENTRY(type) \
struct { \
struct type *le_next; /* next element */ \
struct type **le_prev; /* address of previous next element */ \
}
/*
* List access methods.
*/
#define LIST_FIRST(head) ((head)->lh_first)
#define LIST_END(head) NULL
#define LIST_EMPTY(head) (LIST_FIRST(head) == LIST_END(head))
#define LIST_NEXT(elm, field) ((elm)->field.le_next)
#define LIST_FOREACH(var, head, field) \
for((var) = LIST_FIRST(head); \
(var)!= LIST_END(head); \
(var) = LIST_NEXT(var, field))
#define LIST_FOREACH_SAFE(var, head, field, tvar) \
for ((var) = LIST_FIRST(head); \
(var) && ((tvar) = LIST_NEXT(var, field), 1); \
(var) = (tvar))
/*
* List functions.
*/
#define LIST_INIT(head) do { \
LIST_FIRST(head) = LIST_END(head); \
} while (0)
#define LIST_INSERT_AFTER(listelm, elm, field) do { \
if (((elm)->field.le_next = (listelm)->field.le_next) != NULL) \
(listelm)->field.le_next->field.le_prev = \
&(elm)->field.le_next; \
(listelm)->field.le_next = (elm); \
(elm)->field.le_prev = &(listelm)->field.le_next; \
} while (0)
#define LIST_INSERT_BEFORE(listelm, elm, field) do { \
(elm)->field.le_prev = (listelm)->field.le_prev; \
(elm)->field.le_next = (listelm); \
*(listelm)->field.le_prev = (elm); \
(listelm)->field.le_prev = &(elm)->field.le_next; \
} while (0)
#define LIST_INSERT_HEAD(head, elm, field) do { \
if (((elm)->field.le_next = (head)->lh_first) != NULL) \
(head)->lh_first->field.le_prev = &(elm)->field.le_next;\
(head)->lh_first = (elm); \
(elm)->field.le_prev = &(head)->lh_first; \
} while (0)
#define LIST_REMOVE(elm, field) do { \
if ((elm)->field.le_next != NULL) \
(elm)->field.le_next->field.le_prev = \
(elm)->field.le_prev; \
*(elm)->field.le_prev = (elm)->field.le_next; \
_Q_INVALIDATE((elm)->field.le_prev); \
_Q_INVALIDATE((elm)->field.le_next); \
} while (0)
#define LIST_REPLACE(elm, elm2, field) do { \
if (((elm2)->field.le_next = (elm)->field.le_next) != NULL) \
(elm2)->field.le_next->field.le_prev = \
&(elm2)->field.le_next; \
(elm2)->field.le_prev = (elm)->field.le_prev; \
*(elm2)->field.le_prev = (elm2); \
_Q_INVALIDATE((elm)->field.le_prev); \
_Q_INVALIDATE((elm)->field.le_next); \
} while (0)
/*
* Simple queue definitions.
*/
#define SIMPLEQ_HEAD(name, type) \
struct name { \
struct type *sqh_first; /* first element */ \
struct type **sqh_last; /* addr of last next element */ \
}
#define SIMPLEQ_HEAD_INITIALIZER(head) \
{ NULL, &(head).sqh_first }
#define SIMPLEQ_ENTRY(type) \
struct { \
struct type *sqe_next; /* next element */ \
}
/*
* Simple queue access methods.
*/
#define SIMPLEQ_FIRST(head) ((head)->sqh_first)
#define SIMPLEQ_END(head) NULL
#define SIMPLEQ_EMPTY(head) (SIMPLEQ_FIRST(head) == SIMPLEQ_END(head))
#define SIMPLEQ_NEXT(elm, field) ((elm)->field.sqe_next)
#define SIMPLEQ_FOREACH(var, head, field) \
for((var) = SIMPLEQ_FIRST(head); \
(var) != SIMPLEQ_END(head); \
(var) = SIMPLEQ_NEXT(var, field))
#define SIMPLEQ_FOREACH_SAFE(var, head, field, tvar) \
for ((var) = SIMPLEQ_FIRST(head); \
(var) && ((tvar) = SIMPLEQ_NEXT(var, field), 1); \
(var) = (tvar))
/*
* Simple queue functions.
*/
#define SIMPLEQ_INIT(head) do { \
(head)->sqh_first = NULL; \
(head)->sqh_last = &(head)->sqh_first; \
} while (0)
#define SIMPLEQ_INSERT_HEAD(head, elm, field) do { \
if (((elm)->field.sqe_next = (head)->sqh_first) == NULL) \
(head)->sqh_last = &(elm)->field.sqe_next; \
(head)->sqh_first = (elm); \
} while (0)
#define SIMPLEQ_INSERT_TAIL(head, elm, field) do { \
(elm)->field.sqe_next = NULL; \
*(head)->sqh_last = (elm); \
(head)->sqh_last = &(elm)->field.sqe_next; \
} while (0)
#define SIMPLEQ_INSERT_AFTER(head, listelm, elm, field) do { \
if (((elm)->field.sqe_next = (listelm)->field.sqe_next) == NULL)\
(head)->sqh_last = &(elm)->field.sqe_next; \
(listelm)->field.sqe_next = (elm); \
} while (0)
#define SIMPLEQ_REMOVE_HEAD(head, field) do { \
if (((head)->sqh_first = (head)->sqh_first->field.sqe_next) == NULL) \
(head)->sqh_last = &(head)->sqh_first; \
} while (0)
#define SIMPLEQ_REMOVE_AFTER(head, elm, field) do { \
if (((elm)->field.sqe_next = (elm)->field.sqe_next->field.sqe_next) \
== NULL) \
(head)->sqh_last = &(elm)->field.sqe_next; \
} while (0)
#define SIMPLEQ_CONCAT(head1, head2) do { \
if (!SIMPLEQ_EMPTY((head2))) { \
*(head1)->sqh_last = (head2)->sqh_first; \
(head1)->sqh_last = (head2)->sqh_last; \
SIMPLEQ_INIT((head2)); \
} \
} while (0)
/*
* XOR Simple queue definitions.
*/
#define XSIMPLEQ_HEAD(name, type) \
struct name { \
struct type *sqx_first; /* first element */ \
struct type **sqx_last; /* addr of last next element */ \
unsigned long sqx_cookie; \
}
#define XSIMPLEQ_ENTRY(type) \
struct { \
struct type *sqx_next; /* next element */ \
}
/*
* XOR Simple queue access methods.
*/
#define XSIMPLEQ_XOR(head, ptr) ((__typeof(ptr))((head)->sqx_cookie ^ \
(unsigned long)(ptr)))
#define XSIMPLEQ_FIRST(head) XSIMPLEQ_XOR(head, ((head)->sqx_first))
#define XSIMPLEQ_END(head) NULL
#define XSIMPLEQ_EMPTY(head) (XSIMPLEQ_FIRST(head) == XSIMPLEQ_END(head))
#define XSIMPLEQ_NEXT(head, elm, field) XSIMPLEQ_XOR(head, ((elm)->field.sqx_next))
#define XSIMPLEQ_FOREACH(var, head, field) \
for ((var) = XSIMPLEQ_FIRST(head); \
(var) != XSIMPLEQ_END(head); \
(var) = XSIMPLEQ_NEXT(head, var, field))
#define XSIMPLEQ_FOREACH_SAFE(var, head, field, tvar) \
for ((var) = XSIMPLEQ_FIRST(head); \
(var) && ((tvar) = XSIMPLEQ_NEXT(head, var, field), 1); \
(var) = (tvar))
/*
* XOR Simple queue functions.
*/
#define XSIMPLEQ_INIT(head) do { \
arc4random_buf(&(head)->sqx_cookie, sizeof((head)->sqx_cookie)); \
(head)->sqx_first = XSIMPLEQ_XOR(head, NULL); \
(head)->sqx_last = XSIMPLEQ_XOR(head, &(head)->sqx_first); \
} while (0)
#define XSIMPLEQ_INSERT_HEAD(head, elm, field) do { \
if (((elm)->field.sqx_next = (head)->sqx_first) == \
XSIMPLEQ_XOR(head, NULL)) \
(head)->sqx_last = XSIMPLEQ_XOR(head, &(elm)->field.sqx_next); \
(head)->sqx_first = XSIMPLEQ_XOR(head, (elm)); \
} while (0)
#define XSIMPLEQ_INSERT_TAIL(head, elm, field) do { \
(elm)->field.sqx_next = XSIMPLEQ_XOR(head, NULL); \
*(XSIMPLEQ_XOR(head, (head)->sqx_last)) = XSIMPLEQ_XOR(head, (elm)); \
(head)->sqx_last = XSIMPLEQ_XOR(head, &(elm)->field.sqx_next); \
} while (0)
#define XSIMPLEQ_INSERT_AFTER(head, listelm, elm, field) do { \
if (((elm)->field.sqx_next = (listelm)->field.sqx_next) == \
XSIMPLEQ_XOR(head, NULL)) \
(head)->sqx_last = XSIMPLEQ_XOR(head, &(elm)->field.sqx_next); \
(listelm)->field.sqx_next = XSIMPLEQ_XOR(head, (elm)); \
} while (0)
#define XSIMPLEQ_REMOVE_HEAD(head, field) do { \
if (((head)->sqx_first = XSIMPLEQ_XOR(head, \
(head)->sqx_first)->field.sqx_next) == XSIMPLEQ_XOR(head, NULL)) \
(head)->sqx_last = XSIMPLEQ_XOR(head, &(head)->sqx_first); \
} while (0)
#define XSIMPLEQ_REMOVE_AFTER(head, elm, field) do { \
if (((elm)->field.sqx_next = XSIMPLEQ_XOR(head, \
(elm)->field.sqx_next)->field.sqx_next) \
== XSIMPLEQ_XOR(head, NULL)) \
(head)->sqx_last = \
XSIMPLEQ_XOR(head, &(elm)->field.sqx_next); \
} while (0)
/*
* Tail queue definitions.
*/
#define TAILQ_HEAD(name, type) \
struct name { \
struct type *tqh_first; /* first element */ \
struct type **tqh_last; /* addr of last next element */ \
}
#define TAILQ_HEAD_INITIALIZER(head) \
{ NULL, &(head).tqh_first }
#define TAILQ_ENTRY(type) \
struct { \
struct type *tqe_next; /* next element */ \
struct type **tqe_prev; /* address of previous next element */ \
}
/*
* Tail queue access methods.
*/
#define TAILQ_FIRST(head) ((head)->tqh_first)
#define TAILQ_END(head) NULL
#define TAILQ_NEXT(elm, field) ((elm)->field.tqe_next)
#define TAILQ_LAST(head, headname) \
(*(((struct headname *)((head)->tqh_last))->tqh_last))
/* XXX */
#define TAILQ_PREV(elm, headname, field) \
(*(((struct headname *)((elm)->field.tqe_prev))->tqh_last))
#define TAILQ_EMPTY(head) \
(TAILQ_FIRST(head) == TAILQ_END(head))
#define TAILQ_FOREACH(var, head, field) \
for((var) = TAILQ_FIRST(head); \
(var) != TAILQ_END(head); \
(var) = TAILQ_NEXT(var, field))
#define TAILQ_FOREACH_SAFE(var, head, field, tvar) \
for ((var) = TAILQ_FIRST(head); \
(var) != TAILQ_END(head) && \
((tvar) = TAILQ_NEXT(var, field), 1); \
(var) = (tvar))
#define TAILQ_FOREACH_REVERSE(var, head, headname, field) \
for((var) = TAILQ_LAST(head, headname); \
(var) != TAILQ_END(head); \
(var) = TAILQ_PREV(var, headname, field))
#define TAILQ_FOREACH_REVERSE_SAFE(var, head, headname, field, tvar) \
for ((var) = TAILQ_LAST(head, headname); \
(var) != TAILQ_END(head) && \
((tvar) = TAILQ_PREV(var, headname, field), 1); \
(var) = (tvar))
/*
* Tail queue functions.
*/
#define TAILQ_INIT(head) do { \
(head)->tqh_first = NULL; \
(head)->tqh_last = &(head)->tqh_first; \
} while (0)
#define TAILQ_INSERT_HEAD(head, elm, field) do { \
if (((elm)->field.tqe_next = (head)->tqh_first) != NULL) \
(head)->tqh_first->field.tqe_prev = \
&(elm)->field.tqe_next; \
else \
(head)->tqh_last = &(elm)->field.tqe_next; \
(head)->tqh_first = (elm); \
(elm)->field.tqe_prev = &(head)->tqh_first; \
} while (0)
#define TAILQ_INSERT_TAIL(head, elm, field) do { \
(elm)->field.tqe_next = NULL; \
(elm)->field.tqe_prev = (head)->tqh_last; \
*(head)->tqh_last = (elm); \
(head)->tqh_last = &(elm)->field.tqe_next; \
} while (0)
#define TAILQ_INSERT_AFTER(head, listelm, elm, field) do { \
if (((elm)->field.tqe_next = (listelm)->field.tqe_next) != NULL)\
(elm)->field.tqe_next->field.tqe_prev = \
&(elm)->field.tqe_next; \
else \
(head)->tqh_last = &(elm)->field.tqe_next; \
(listelm)->field.tqe_next = (elm); \
(elm)->field.tqe_prev = &(listelm)->field.tqe_next; \
} while (0)
#define TAILQ_INSERT_BEFORE(listelm, elm, field) do { \
(elm)->field.tqe_prev = (listelm)->field.tqe_prev; \
(elm)->field.tqe_next = (listelm); \
*(listelm)->field.tqe_prev = (elm); \
(listelm)->field.tqe_prev = &(elm)->field.tqe_next; \
} while (0)
#define TAILQ_REMOVE(head, elm, field) do { \
if (((elm)->field.tqe_next) != NULL) \
(elm)->field.tqe_next->field.tqe_prev = \
(elm)->field.tqe_prev; \
else \
(head)->tqh_last = (elm)->field.tqe_prev; \
*(elm)->field.tqe_prev = (elm)->field.tqe_next; \
_Q_INVALIDATE((elm)->field.tqe_prev); \
_Q_INVALIDATE((elm)->field.tqe_next); \
} while (0)
#define TAILQ_REPLACE(head, elm, elm2, field) do { \
if (((elm2)->field.tqe_next = (elm)->field.tqe_next) != NULL) \
(elm2)->field.tqe_next->field.tqe_prev = \
&(elm2)->field.tqe_next; \
else \
(head)->tqh_last = &(elm2)->field.tqe_next; \
(elm2)->field.tqe_prev = (elm)->field.tqe_prev; \
*(elm2)->field.tqe_prev = (elm2); \
_Q_INVALIDATE((elm)->field.tqe_prev); \
_Q_INVALIDATE((elm)->field.tqe_next); \
} while (0)
#define TAILQ_CONCAT(head1, head2, field) do { \
if (!TAILQ_EMPTY(head2)) { \
*(head1)->tqh_last = (head2)->tqh_first; \
(head2)->tqh_first->field.tqe_prev = (head1)->tqh_last; \
(head1)->tqh_last = (head2)->tqh_last; \
TAILQ_INIT((head2)); \
} \
} while (0)
#endif /* !_SYS_QUEUE_H_ */
+38
View File
@@ -0,0 +1,38 @@
/* $OpenBSD: reallocarray.c,v 1.2 2014/12/08 03:45:00 bcook Exp $ */
/*
* Copyright (c) 2008 Otto Moerbeek <otto@drijf.net>
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include <sys/types.h>
#include <errno.h>
#include <stdint.h>
#include <stdlib.h>
/*
* This is sqrt(SIZE_MAX+1), as s1*s2 <= SIZE_MAX
* if both s1 < MUL_NO_OVERFLOW and s2 < MUL_NO_OVERFLOW
*/
#define MUL_NO_OVERFLOW ((size_t)1 << (sizeof(size_t) * 4))
void *
reallocarray(void *optr, size_t nmemb, size_t size)
{
if ((nmemb >= MUL_NO_OVERFLOW || size >= MUL_NO_OVERFLOW) &&
nmemb > 0 && SIZE_MAX / nmemb < size) {
errno = ENOMEM;
return NULL;
}
return realloc(optr, size * nmemb);
}
+52 -131
View File
@@ -25,9 +25,9 @@
#include <sys/types.h>
#include "lite.h"
#include "../helpers.h"
static int makedir(char *buf, size_t buf_len, char *dir, char *name, mode_t mode);
static int copy(char *src, char *dst);
static int mdir(char *buf, size_t buf_len, char *dir, char *name, mode_t mode);
static int prune(char *dst, char **new_files, int new_num);
@@ -58,21 +58,16 @@ int rsync(char *src, char *dst, int delete, int (*filter) (const char *file))
int i = 0, num = 0, result = 0;
char **files; /* Array of file names. */
void copy(char *src, char *dst)
{
errno = 0;
copyfile(src, dst, 0);
if (errno) result++;
}
if (!fisdir(dst))
mkdir(dst, 0755);
makedir(dst, 0755);
if (!fisdir(src)) {
if (!fexist(src))
return 1;
copy(src, dst);
if (copy(src, dst))
result++;
return errno;
}
@@ -85,7 +80,7 @@ int rsync(char *src, char *dst, int delete, int (*filter) (const char *file))
else
ptr++;
if (makedir(dest, sizeof(dest), dst, ptr, fmode(src)))
if (mdir(dest, sizeof(dest), dst, ptr, fmode(src)))
return 1;
dst = dest;
}
@@ -98,7 +93,7 @@ int rsync(char *src, char *dst, int delete, int (*filter) (const char *file))
char dst2[256];
strcat(source, "/");
if (makedir (dst2, sizeof(dst2), dst, files[i], fmode(source))) {
if (mdir (dst2, sizeof(dst2), dst, files[i], fmode(source))) {
result++;
continue;
}
@@ -106,7 +101,9 @@ int rsync(char *src, char *dst, int delete, int (*filter) (const char *file))
rsync(source, dst2, delete, filter);
continue; /* Next file/dir in @src to copy... */
}
copy(source, dst);
if (copy(source, dst))
result++;
}
/* We ignore any errors from the pruning, that phase albeit useful is only
@@ -123,36 +120,60 @@ int rsync(char *src, char *dst, int delete, int (*filter) (const char *file))
return result;
}
/* Creates dir/name @mode ... skipping / if dir already ends so. */
static int makedir(char *buf, size_t buf_len, char *dir, char *name, mode_t mode)
static int copy(char *src, char *dst)
{
snprintf(buf, buf_len, "%s%s%s/", dir, fisslashdir(dir) ? "" : "/", name);
if (mkdir(buf, mode))
return 1;
errno = 0;
copyfile(src, dst, 0, 1);
if (errno) {
if (errno != EEXIST)
return 1;
errno = 0;
}
return 0;
}
/* Creates dir/name @mode ... skipping / if dir already ends so. */
static int mdir(char *buf, size_t buf_len, char *dir, char *name, mode_t mode)
{
snprintf(buf, buf_len, "%s%s%s/", dir, fisslashdir(dir) ? "" : "/", name);
if (mkdir(buf, mode)) {
if (EEXIST != errno)
return 1;
errno = 0;
}
return 0;
}
static int find(char *file, char **files, int num)
{
int n;
for (n = 0; n < num; n++)
if (!strncmp (files[n], file, MAX(strlen(files[n]), strlen(file))))
return 1;
return 0;
}
/* Prune old files, no longer existing on source, from destination directory. */
static int prune(char *dst, char **new_files, int new_num)
{
int i, num, result = 0;
int num, result = 0;
char **files;
int find(char *file) {
int n;
for (n = 0; n < new_num; n++)
if (!strncmp (new_files[n], file, MAX(strlen(new_files[n]), strlen(file))))
return 1;
return 0;
}
num = dir(dst, "", NULL, &files, 0);
if (num) {
int i;
for (i = 0; i < num; i++) {
if (!find(files[i])) {
if (!find(files[i], new_files, new_num)) {
char *name;
size_t len = strlen(files[i]) + 2 + strlen(dst);
@@ -172,108 +193,8 @@ static int prune(char *dst, char **new_files, int new_num)
return result;
}
#ifdef UNITTEST
#define BASE "/tmp/.unittest/"
#define SRC BASE "src/"
#define DST BASE "dst/"
char *files[] = {
SRC "sub1/1.tst",
SRC "sub1/2.tst",
SRC "sub1/3.tst",
SRC "sub2/4.tst",
SRC "sub2/5.tst",
SRC "sub2/6.tst",
SRC "sub3/7.tst",
SRC "sub3/8.tst",
SRC "sub3/9.tst",
NULL
};
void cleanup_test(void)
{
system("rm -rf " BASE);
}
void setup_test(void)
{
int i;
char cmd[256];
mode_t dir_modes[] = { 755, 700 };
mode_t file_modes[] = { 644, 600 };
cleanup_test();
mkdir(BASE, 0755);
mkdir(SRC, 0755);
mkdir(DST, 0755);
for (i = 0; files[i]; i++) {
snprintf(cmd, sizeof(cmd), "mkdir -m %d -p `dirname %s`",
dir_modes[i % 2], files[i]);
system(cmd);
snprintf(cmd, sizeof(cmd), "touch %s; chmod %d %s", files[i],
file_modes[i % 2], files[i]);
system(cmd);
}
}
int run_test()
{
#if 0
setup_test();
puts("Before:");
system("tree -np " BASE);
rsync(SRC, DST, 0, NULL);
puts("After:");
system("tree -np " BASE);
cleanup_test();
#endif
setup_test();
rsync(BASE "src", DST, 0, NULL);
puts("Only partial rsync of src <-- No slash!");
system("tree -np " BASE);
#if 0
cleanup_test();
setup_test();
rsync(BASE "src/sub1", BASE "dst", 0, NULL);
puts("Only partial rsync of src/sub1 <-- No slashes!!");
system("tree -np " BASE);
cleanup_test();
setup_test();
rsync(BASE "src/sub1/", DST, 0, NULL);
puts("Only partial rsync of src/sub1/");
system("tree -np " BASE);
cleanup_test();
setup_test();
rsync(BASE "src/sub1", DST, 0, NULL);
puts("Only partial rsync of src/sub1 <-- No slash!");
system("tree -np " BASE);
rsync("/etc", "/var/tmp", 0, NULL);
puts("Real life test:");
system("tree -np /var/tmp");
#endif
return 0;
}
int main(int argc, char *argv[])
{
atexit(cleanup_test);
return run_test();
}
#endif /* UNITTEST */
/**
* Local Variables:
* compile-command: "make -f rsync.mk"
* version-control: t
* indent-tabs-mode: t
* c-file-style: "linux"
* End:
-22
View File
@@ -1,22 +0,0 @@
# Unittest makefile for rsync.c
.PHONY: clean
SRC = rsync.c
OBJS = dir.o copyfile.o fexist.o fisdir.o fmode.o
UNIT = rsync.unittest
#CPPFLAGS = -DDEBUG -I../../.. -I../../include
all: build run
clean:
@rm -f $(OBJS) $(UNIT)
# This rule also forces a cleanup of built objects to not leave any object files
# lingering in the tree to interfere with cross builds.
build: clean $(OBJS)
$(CC) $(CFLAGS) $(CPPFLAGS) -o $(UNIT) -DUNITTEST $(SRC) $(OBJS)
@rm -f $(OBJS)
run:
@./$(UNIT)
+52
View File
@@ -0,0 +1,52 @@
/* ==========================================================================
* strdupa.h - Re-implementation of glibc strdupa.
* --------------------------------------------------------------------------
* Copyright (c) 2009 William Ahern
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to permit
* persons to whom the Software is furnished to do so, subject to the
* following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
* NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
* OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
* USE OR OTHER DEALINGS IN THE SOFTWARE.
* ==========================================================================
*/
#ifndef LITE_STRDUPA_H
#define LITE_STRDUPA_H
#if !defined(HAVE_STRDUPA)
#if defined(strdupa)
#define HAVE_STRDUPA 1
#endif
#endif
#if !HAVE_STRDUPA
#if defined(__GNUC__)
#include <stddef.h> /* size_t */
#include <string.h> /* memcpy(3) strlen(3) */
#define strdupa(src) (__extension__ ({ \
size_t len_ = strlen(src); \
char *dst_ = __builtin_alloca(len_ + 1); \
dst_[len_] = '\0'; \
(char *)memcpy(dst_, src, len_); \
}))
#else /* If not GCC, e.g. Clang */
#error strdupa() may use an unsupported GNU C API, please forward any fix to maintainer, cheers!
#endif /* __GNUC__ */
#endif /* !HAVE_STRDUPA */
#endif /* LITE_STRDUPA_H */
+57
View File
@@ -0,0 +1,57 @@
/* $OpenBSD: strlcat.c,v 1.15 2015/03/02 21:41:08 millert Exp $ */
/*
* Copyright (c) 1998, 2015 Todd C. Miller <Todd.Miller@courtesan.com>
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include <sys/types.h>
#include <string.h>
#ifndef strlcat
/*
* Appends src to string dst of size dsize (unlike strncat, dsize is the
* full size of dst, not space left). At most dsize-1 characters
* will be copied. Always NUL terminates (unless dsize <= strlen(dst)).
* Returns strlen(src) + MIN(dsize, strlen(initial dst)).
* If retval >= dsize, truncation occurred.
*/
size_t
strlcat(char *dst, const char *src, size_t dsize)
{
const char *odst = dst;
const char *osrc = src;
size_t n = dsize;
size_t dlen;
/* Find the end of dst and adjust bytes left but don't go past end. */
while (n-- != 0 && *dst != '\0')
dst++;
dlen = dst - odst;
n = dsize - dlen;
if (n-- == 0)
return(dlen + strlen(src));
while (*src != '\0') {
if (n != 0) {
*dst++ = *src;
n--;
}
src++;
}
*dst = '\0';
return(dlen + (src - osrc)); /* count does not include NUL */
}
#endif
+52
View File
@@ -0,0 +1,52 @@
/* $OpenBSD: strlcpy.c,v 1.12 2015/01/15 03:54:12 millert Exp $ */
/*
* Copyright (c) 1998, 2015 Todd C. Miller <Todd.Miller@courtesan.com>
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include <sys/types.h>
#include <string.h>
#ifndef strlcpy
/*
* Copy string src to buffer dst of size dsize. At most dsize-1
* chars will be copied. Always NUL terminates (unless dsize == 0).
* Returns strlen(src); if retval >= dsize, truncation occurred.
*/
size_t
strlcpy(char *dst, const char *src, size_t dsize)
{
const char *osrc = src;
size_t nleft = dsize;
/* Copy as many bytes as will fit. */
if (nleft != 0) {
while (--nleft != 0) {
if ((*dst++ = *src++) == '\0')
break;
}
}
/* Not enough room in dst, add NUL and traverse rest of src. */
if (nleft == 0) {
if (dsize != 0)
*dst = '\0'; /* NUL-terminate dst */
while (*src++)
;
}
return(src - osrc - 1); /* count does not include NUL */
}
#endif
+100
View File
@@ -0,0 +1,100 @@
/* Collection of frog DNA
*
* Copyright (c) 2008-2016 Joachim Nilsson <troglobit@gmail.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#ifndef LITE_STRING_H_
#define LITE_STRING_H_
#include <string.h>
#include "strdupa.h"
#include "strndupa.h"
#include "strnlen.h"
#ifndef strlcpy
size_t strlcpy (char *dst, const char *src, size_t siz);
#endif
#ifndef strlcat
size_t strlcat (char *dst, const char *src, size_t siz);
#endif
#ifndef strtonum
long long strtonum (const char *numstr, long long minval, long long maxval, const char **errstrp);
#endif
/* Convert string to natural number (0-2147483647), returns -1 on error. */
static inline int atonum(const char *str)
{
int val = -1;
const char *errstr;
if (str) {
val = strtonum(str, 0, INT32_MAX, &errstr);
if (errstr)
return -1;
}
return val;
}
/* Validate string, non NULL and not zero length */
static inline int string_valid(const char *s)
{
return s && strlen(s);
}
/* Relaxed comparison, e.g., sys_string_match("small", "smaller") => TRUE */
static inline int string_match(const char *a, const char *b)
{
size_t min = MIN(strlen(a), strlen(b));
return !strncasecmp(a, b, min);
}
/* Strict comparison, e.g., sys_string_match("small", "smaller") => FALSE */
static inline int string_compare(const char *a, const char *b)
{
return strlen(a) == strlen(b) && !strcmp(a, b);
}
/* Strict comparison, like sys_string_compare(), but case insensitive,
* e.g., sys_string_match("small", "SmAlL") => TRUE
*/
static inline int string_case_compare(const char *a, const char *b)
{
return strlen (a) == strlen (b) && !strcasecmp (a, b);
}
#define min(a,b) \
({ \
__typeof__ (a) _a = (a); \
__typeof__ (b) _b = (b); \
_a < _b ? _a : _b; \
})
#define max(a,b) \
({ \
__typeof__ (a) _a = (a); \
__typeof__ (b) _b = (b); \
_a > _b ? _a : _b; \
})
#endif /* LITE_STRING_H_ */
+53
View File
@@ -0,0 +1,53 @@
/* ==========================================================================
* strndupa.h - Re-implementation of glibc strndupa.
* --------------------------------------------------------------------------
* Copyright (c) 2009 William Ahern
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to permit
* persons to whom the Software is furnished to do so, subject to the
* following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
* NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
* OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
* USE OR OTHER DEALINGS IN THE SOFTWARE.
* ==========================================================================
*/
#ifndef LITE_STRNDUPA_H_
#define LITE_STRNDUPA_H_
#if !defined(HAVE_STRNDUPA)
#if defined(strndupa)
#define HAVE_STRNDUPA 1
#endif
#endif
#if !HAVE_STRNDUPA
#if defined(__GNUC__)
#include <stddef.h> /* size_t */
#include <string.h> /* memcpy(3) */
#include "strnlen.h"
#define strndupa(src, lim) (__extension__ ({ \
size_t len_ = strnlen(src, lim); \
char *dst_ = __builtin_alloca(len_ + 1); \
dst_[len_] = '\0'; \
(char *)memcpy(dst_, src, len_); \
}))
#else /* If not GCC, e.g. Clang */
+#error strndupa() may use an unsupported GNU C API, please forward any fix to maintainer, cheers!
#endif /* __GNUC__ */
#endif /* !HAVE_STRNDUPA */
#endif /* GNU_STRING_STRNDUPA_H */
+43
View File
@@ -0,0 +1,43 @@
/* strnlen.h - Re-implementation of GLIBC strnlen()
*
* Copyright (c) 2016 Joachim Nilsson <troglobit@gmail.com>
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#ifndef LITE_STRNLEN_H_
#define LITE_STRNLEN_H_
#if !defined(HAVE_STRNLEN)
#if defined(strnlen)
#define HAVE_STRNLEN 1
#endif
#endif
#if !HAVE_STRNLEN
#include <stddef.h> /* size_t */
#define strnlen(str, lim) xstrnlen(str, lim)
static inline size_t xstrnlen(const char *str, size_t lim)
{
size_t i = 0;
while (str[i] && i < lim)
i++;
return i;
}
#endif
#endif /* LITE_STRNLEN_H_ */
+67
View File
@@ -0,0 +1,67 @@
/* $OpenBSD: strtonum.c,v 1.7 2013/04/17 18:40:58 tedu Exp $ */
/*
* Copyright (c) 2004 Ted Unangst and Todd Miller
* All rights reserved.
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include <errno.h>
#include <limits.h>
#include <stdlib.h>
#ifndef strtonum
#define INVALID 1
#define TOOSMALL 2
#define TOOLARGE 3
long long
strtonum(const char *numstr, long long minval, long long maxval,
const char **errstrp)
{
long long ll = 0;
int error = 0;
char *ep;
struct errval {
const char *errstr;
int err;
} ev[4] = {
{ NULL, 0 },
{ "invalid", EINVAL },
{ "too small", ERANGE },
{ "too large", ERANGE },
};
ev[0].err = errno;
errno = 0;
if (minval > maxval) {
error = INVALID;
} else {
ll = strtoll(numstr, &ep, 10);
if (numstr == ep || *ep != '\0')
error = INVALID;
else if ((ll == LLONG_MIN && errno == ERANGE) || ll < minval)
error = TOOSMALL;
else if ((ll == LLONG_MAX && errno == ERANGE) || ll > maxval)
error = TOOLARGE;
}
if (errstrp != NULL)
*errstrp = ev[error].errstr;
errno = ev[error].err;
if (error)
ll = 0;
return (ll);
}
#endif
+59
View File
@@ -0,0 +1,59 @@
/* A secure tmpfile() replacement.
*
* Copyright (c) 2015-2016 Joachim Nilsson <troglobit@gmail.com>
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include <paths.h>
#include <fcntl.h> /* O_TMPFILE requires -D_GNU_SOURCE */
#include <stdio.h> /* fdopen() */
#include <sys/stat.h> /* umask() */
/**
* tempfile - A secure tmpfile() replacement
*
* This is the secure replacement for tmpfile() that does not exist in
* GLIBC. The function uses the Linux specific %O_TMPFILE and %O_EXCL
* for security. When the %FILE is fclose()'ed the file contents is
* lost. The file is hidden in the %_PATH_TMP directory on the system.
*
* This function requires Linux 3.11, or later, due to %O_TMPFILE.
*
* Returns:
* An open %FILE pointer, or %NULL on error.
*/
FILE *tempfile(void)
{
#ifdef O_TMPFILE /* Only on Linux, with fairly recent (G)LIBC */
int fd;
mode_t oldmask;
oldmask = umask(0077);
fd = open(_PATH_TMP, O_TMPFILE | O_RDWR | O_EXCL | O_CLOEXEC, S_IRUSR | S_IWUSR);
umask(oldmask);
if (-1 == fd)
return NULL;
return fdopen(fd, "w+");
#else
return tmpfile(); /* Fallback on older GLIBC/Linux and actual UNIX systems */
#endif
}
/**
* Local Variables:
* indent-tabs-mode: t
* c-file-style: "linux"
* End:
*/
+17
View File
@@ -0,0 +1,17 @@
*.log
*.trs
chomp
copyfile
dir
fexist
fisdir
fsendfile
lfile
makepath
pidfile
progress
rsync
tempfile
touch
tree
which
+27
View File
@@ -0,0 +1,27 @@
EXTRA_DIST = check.h
CLEANFILES = *~ *.trs *.log
TESTS =
TESTS += chomp
TESTS += copyfile
TESTS += dir
TESTS += fexist
TESTS += fisdir
TESTS += fsendfile
TESTS += lfile
TESTS += makepath
TESTS += pidfile
TESTS += touch
TESTS += progress
TESTS += rsync
TESTS += tempfile
TESTS += tree
TESTS += which
check_PROGRAMS = $(TESTS)
# Ignore warnings about unused result, in e.g. write()
CFLAGS += -Wno-unused-result
CPPFLAGS += -D_GNU_SOURCE
LDADD = -L../ ../libite.la
LDFLAGS += -static
+81
View File
@@ -0,0 +1,81 @@
#ifndef LITE_TESTS_CHECK_H_
#define LITE_TESTS_CHECK_H_
#include <stdarg.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include "../conio.h"
#include "../lite.h"
#define PRINT(args...) if (verbose) printf(args)
#define fail_unless(test) \
do { \
if (!(test)) { \
fprintf(stderr, \
"----------------------------------------------\n" \
"%s:%d: test FAILED:\nFailed test: %s\n" \
"----------------------------------------------\n", \
__FILE__, __LINE__, #test); \
exit(1); \
} \
} while (0)
static inline int test(int result, const char *fmt, ...)
{
char buf[80];
size_t len;
va_list ap;
const char success[] = " \033[1m[ OK ]\033[0m\n";
const char failure[] = " \033[7m[FAIL]\033[0m\n";
const char dots[] = " .....................................................................";
va_start(ap, fmt);
len = vsnprintf(buf, sizeof(buf), fmt, ap);
va_end(ap);
write(STDERR_FILENO, buf, len);
write(STDERR_FILENO, dots, 60 - len); /* pad with dots. */
if (!result)
write(STDERR_FILENO, success, strlen(success));
else
write(STDERR_FILENO, failure, strlen(failure));
return result;
}
static inline int timespec_newer(const struct timespec *a, const struct timespec *b)
{
if (a->tv_sec != b->tv_sec)
return a->tv_sec > b->tv_sec;
return a->tv_nsec > b->tv_nsec;
}
static inline char *timespec2str(struct timespec *ts, char *buf, size_t len)
{
size_t ret, pos;
struct tm t;
memset(buf, 0, len);
tzset();
if (localtime_r(&(ts->tv_sec), &t) == NULL)
return buf;
ret = strftime(buf, len, "%F %T", &t);
if (ret == 0)
return buf;
len -= ret - 1;
pos = strlen(buf);
len -= pos;
snprintf(&buf[pos], len, ".%09ld", ts->tv_nsec);
return buf;
}
#endif /* LITE_TESTS_CHECK_H_ */
+24
View File
@@ -0,0 +1,24 @@
#include "check.h"
int main(void)
{
size_t i;
char t[][16] = {
"hej\ndej",
"Slime\n\n\\n",
"Tripple\n\n\n"
};
for (i = 0; i < NELEMS(t); i++) {
char *str = t[i];
size_t len;
chomp(str);
len = strlen(str);
printf("[%02zd]: '%s'\n", i, str);
fail_unless(str[len] != '\n');
}
return 0;
}
+55
View File
@@ -0,0 +1,55 @@
#include <err.h>
#include <errno.h>
#include "check.h"
int main(void)
{
int i = 0;
char *files[] = {
"/etc/passwd", "/tmp/mypwd", "/tmp/mypwd",
"/etc/passwd", "/tmp/", "/tmp/passwd",
"/etc/passwd", "/tmp", "/tmp/passwd",
NULL
};
FILE *src, *dst;
printf("=>Start testing fcopyfile()\n");
while (files[i]) {
printf("fcopyfile(%s, %s)\t", files[i], files[i + 1]);
src = fopen(files[i], "r");
dst = fopen(files[i + 1], "w");
if (fcopyfile(src, dst)) {
if (!fisdir(files[i + 1]))
err(1, "Failed fcopyfile(%s, %s)", files[i], files[i + 1]);
}
if (src)
fclose(src);
if (dst)
fclose(dst);
if (fexist(files[i + 2]))
printf("OK => %s", files[i + 2]);
printf("\n");
erase(files[i + 2]);
i += 3;
}
printf("\n=>Start testing copyfile()\n");
i = 0;
while (files[i]) {
printf("copyfile(%s, %s)\t", files[i], files[i + 1]);
if (!copyfile(files[i], files[i + 1], 0, 0))
err(1, "Failed copyfile(%s, %s)", files[i], files[i + 1]);
if (fexist(files[i + 2]))
printf("OK => %s", files[i + 2]);
printf("\n");
erase(files[i + 2]);
i += 3;
}
return 0;
}
+99
View File
@@ -0,0 +1,99 @@
#include <errno.h>
#include <fcntl.h>
#include <stdlib.h>
#include <sys/stat.h>
#include "check.h"
#define DIR_TYPE_IMAGE ".img"
#define DIR_TYPE_SYSLOG ""
#define DIR_TYPE_CONFIG ".cfg"
#define STARTUP_CONFIG "startup-config.cfg"
int simulate_files(int creat)
{
size_t i;
char *files[] =
{ "config0.cfg", "config1.cfg", "config2.cfg", "config3.cfg",
"rr109.img", "rx100.img", "rx107.img", "rm957.img", "messages"
};
for (i = 0; i < NELEMS(files); i++) {
if (creat)
touch(files[i]);
else
erase(files[i]);
}
if (creat)
symlink("config2.cfg", STARTUP_CONFIG);
else
erase(STARTUP_CONFIG);
return 0;
}
static int cfg_dir_filter(const char *file)
{
/* Skip the STARTUP_CONFIG file, it is a symbolic link to the
* current startup configuration. */
return ! !strcmp(file, STARTUP_CONFIG);
}
static int is_startup_config(const char *entry)
{
static int once = 1;
static char file[80];
if (once) {
int len = readlink(STARTUP_CONFIG, file, sizeof(file));
if (len == -1)
return 0;
file[len] = 0;
once = 0; /* Only once per call to dir() */
}
//printf ("Comparing link %s with entry %s\n", file, entry);
return !strcmp(file, entry);
}
int main(int argc, char *argv[])
{
int i, num;
char *type = DIR_TYPE_CONFIG;
char **files;
simulate_files(1);
if (argc >= 2) {
if (!strcasecmp("CONFIG", argv[1])) {
type = DIR_TYPE_CONFIG;
system("ls -l *" DIR_TYPE_CONFIG);
}
if (!strcasecmp("IMAGE", argv[1])) {
type = DIR_TYPE_IMAGE;
system("ls -l *" DIR_TYPE_IMAGE);
}
if (!strcasecmp("SYSLOG", argv[1])) {
type = DIR_TYPE_SYSLOG;
system("ls -l *");
}
}
num = dir(NULL, type, cfg_dir_filter, &files, 0);
if (num) {
for (i = 0; i < num; i++) {
printf("%s", files[i]);
if (is_startup_config(files[i]))
printf(" --> startup-config");
printf("\n");
free(files[i]);
}
free(files);
}
simulate_files(0);
return 0;
}
+24
View File
@@ -0,0 +1,24 @@
#include <err.h>
#include "check.h"
int main(void)
{
size_t i = 0;
struct { char *file; int exist; } arr[] = {
{ "/etc/passwd", 1 },
{ "/etc/kalle", 0 },
{ "/sbin/init", 1 },
{ "/dev/null", 1 },
{ NULL, 0 },
};
for (i = 0; i < NELEMS(arr); i++) {
if (fexist(arr[i].file) != arr[i].exist)
err(1, "Failed fexist(%s)", arr[i].file ?: "NULL");
else
printf("File %-11s %-14s => OK!\n", arr[i].file ?: "NULL",
arr[i].exist ? "does exist" : "does not exist");
}
return 0;
}
+25
View File
@@ -0,0 +1,25 @@
#include <err.h>
#include "check.h"
int main(void)
{
size_t i = 0;
struct { char *file; int exist; } arr[] = {
{ "/etc/passwd", 0 },
{ "/etc/", 1 },
{ "/sbin/init", 0 },
{ "/dev/null", 0 },
{ "/dev/", 1 },
{ NULL, 0 },
};
for (i = 0; i < NELEMS(arr); i++) {
if (fisdir(arr[i].file) != arr[i].exist)
err(1, "Failed fisdir(%s)", arr[i].file ?: "NULL");
else
printf("fisdir() %-11s %-18s => OK!\n", arr[i].file ?: "NULL",
arr[i].exist ? "is a directory" : "is NOT a directory");
}
return 0;
}
+31
View File
@@ -0,0 +1,31 @@
#include <err.h>
#include <unistd.h>
#include "check.h"
int main(void)
{
int i = 0;
char *files[] = {
"/etc/passwd", "/tmp/tok",
"/etc/passwd", "/tmp/passwd",
"/etc/passwd", "/tmp/passwd",
NULL
};
FILE *src, *dst;
while (files[i]) {
src = fopen(files[i], "r");
dst = fopen(files[i + 1], "w");
printf("fsendfile(%s, %s, 512)\t", files[i], files[i + 1]);
if (-1 == fsendfile(src, dst, 512))
err(1, "Failed fsendfile(%s, %s)", files[i], files[i + 1]);
if (!access(files[i + 1], F_OK))
printf("OK => %s\n", files[i + 1]);
remove(files[i + 1]);
i += 2;
}
return 0;
}
+74
View File
@@ -0,0 +1,74 @@
#include <stdio.h>
#include "check.h"
#define FSTAB "/etc/fstab"
static int fstab(void)
{
int field = 1;
char *token;
lfile_t *lf;
lf = lfopen(FSTAB, " \t\n");
if (!lf) {
perror("Failed opening " FSTAB);
return 1;
}
printheader(NULL, "FILE SYSTEM MOUNT OPTIONS D P", 0);
while ((token = lftok(lf))) {
if (field == 1)
printf("%-41s ", token);
if (field == 2)
printf("%-9s ", token);
if (field == 4)
printf("%-17s ", token);
if (field == 5)
printf("%d ", atoi(token));
if (field == 6) {
field = 0;
printf("%d\n", atoi(token));
}
field++;
}
lfclose(lf);
return 0;
}
int main(void)
{
int val;
val = fgetint("/etc/protocols", " \n\t", "udp");
if (val == -1) {
perror("Failed locating 'udp' protocol");
return 1;
}
printf("udp has proto %d\n", val);
val = fgetint("/etc/services", " /\n\t", "ftp");
if (val == -1) {
perror("Failed locating 'ftp' service");
return 1;
}
printf("ftp is inet port %d\n", val);
val = fgetint("/etc/group", "x:\n", "utmp");
if (val == -1) {
perror("Failed locating group 'utmp'");
return 1;
}
printf("utmp is gid %d\n", val);
val = fgetint("/etc/passwd", "x:\n", "nobody");
if (val == -1) {
perror("Failed locating user 'nobody'");
return 1;
}
printf("nobody is uid %d\n", val);
return fstab();
}
+67
View File
@@ -0,0 +1,67 @@
#include <errno.h>
#include <errno.h>
#include <libgen.h>
#include <stdlib.h>
#include "check.h"
int checkpath(char *dir)
{
char tmp[256];
struct stat sb;
snprintf(tmp, sizeof(tmp), "ls -ld %s", dir);
if (system(tmp))
perror("system");
if (!stat(dir, &sb) && S_ISDIR(sb.st_mode))
return 0;
errno = ENOTDIR;
return 1;
}
int test_makepath(char *dir)
{
int ret = makepath(dir);
if (!ret)
ret = checkpath(dir);
if (ret)
perror("Failed");
return ret;
}
int main(void)
{
int i, ret = 0;
char *list[] = {
"/tmp/libite-test/tok/",
"/tmp/libite-test/tok2",
"/tmp/libite-test/ab",
"/tmp/libite-test/b",
"/tmp/libite-test/a/",
"/tmp/libite-test/a/b",
"/tmp/libite-test/a/c/",
NULL
};
printf("Testing makepath() ...\n");
mkdir("/tmp/libite-test", 0755);
for (i = 0; list[i] && !ret; i++)
ret |= test_makepath(list[i]);
printf("\nCleaning up ...\n");
system("rm -rf /tmp/libite-test");
return ret;
}
/**
* Local Variables:
* indent-tabs-mode: t
* c-file-style: "linux"
* compile-command: "make makepath && ./makepath"
* End:
*/
+129
View File
@@ -0,0 +1,129 @@
#include <err.h>
#include <paths.h>
#include <signal.h>
#include <stdarg.h>
#include <time.h>
#include "check.h"
extern char *__pidfile_name;
extern char *__pidfile_path;
static char *ident;
static char *pidfile_arg;
static char PIDFILE[42];
static int verbose = 0;
static struct stat before, after;
static void sigterm_handler(int signo)
{
PRINT("Exiting ...\n");
remove(PIDFILE);
}
static void sigalrm_handler(int signo)
{
PRINT("Calling pidfile(%s)\n", pidfile_arg ?: "NULL");
if (pidfile(pidfile_arg))
err(1, "failed creating1 %s", pidfile_arg);
if (!fexist(PIDFILE))
err(1, "failed creating2 %s, created %s", PIDFILE, __pidfile_name);
stat(PIDFILE, &before);
}
static int mtime()
{
int ret;
char buf[80];
/* Must sleep a while here otherwise we execute too fast => no mtime change :-( */
usleep(10000);
PRINT("Calling pidfile() again to update mtime ...\n");
if (pidfile(pidfile_arg))
err(1, "failed creating3 %s", pidfile_arg);
stat(PIDFILE, &after);
ret = timespec_newer(&after.st_mtim, &before.st_mtim);
PRINT("Before: %s\n", timespec2str(&before.st_mtim, buf, sizeof(buf)));
PRINT("After : %s\n", timespec2str(&after.st_mtim, buf, sizeof(buf)));
return !ret;
}
int test_pidfile(char *arg0)
{
/* pidfile() argument */
pidfile_arg = arg0;
/* Expected PID file name */
if (!arg0)
snprintf(PIDFILE, sizeof(PIDFILE), "%s%s.pid", __pidfile_path, ident);
else if (arg0[0] != '/')
snprintf(PIDFILE, sizeof(PIDFILE), "%s%s.pid", __pidfile_path, arg0);
else
snprintf(PIDFILE, sizeof(PIDFILE), "%s", arg0);
PRINT("Verifying pidfile(%s) ... PID: %d\n", PIDFILE, getpid());
/* Remove any lingering files from previous test runs */
remove(PIDFILE);
signal(SIGTERM, sigterm_handler);
signal(SIGALRM, sigalrm_handler);
/* For signalling test */
alarm(1);
return test(pidfile_poll(PIDFILE) != getpid(), "Testing pidfile_poll()")
|| test(strcmp(__pidfile_name, PIDFILE), "Testing __pidfile_name vs guessed PID filename")
|| test(mtime(), "Testing mtime update of followup pidfile() call")
|| test(pidfile_signal(PIDFILE, SIGTERM), "Testing signalling ourselves")
;
}
static char *progname(char *arg0)
{
char *nm;
nm = strrchr(arg0, '/');
if (nm)
nm++;
else
nm = arg0;
return nm;
}
int main(int argc, char *argv[])
{
int ret = 0;
size_t i;
char *pidfiles[] = {
NULL,
"pidfile_test1",
"/var/tmp/pidfile_test2.pid",
};
if (argc > 1 && !strcmp(argv[1], "-v"))
verbose = 1;
/* Override default _PATH_VARRUN in pidfile() */
__pidfile_path = _PATH_TMP;
/* Find __progname, not all C libraries support this */
ident = progname(argv[0]);
for (i = 0; i < NELEMS(pidfiles); i++)
ret += test_pidfile(pidfiles[i]);
return ret;
}
/**
* Local Variables:
* indent-tabs-mode: t
* c-file-style: "linux"
* compile-command: "make pidfile && ./pidfile -v"
* End:
*/
+51
View File
@@ -0,0 +1,51 @@
#include <stdlib.h> /* atexit() */
#include <unistd.h> /* usleep() */
#include "check.h"
#include "../conio.h"
#define MAX_WIDTH 80
#define msleep(msec) usleep(msec * 1000)
static void bye(void)
{
showcursor();
}
static void testit(int fn, int percent)
{
if (fn)
progress(percent, MAX_WIDTH);
else
progress_simple(percent);
}
static void run_test(int fn)
{
int i, percent, block = 0, num = 85;
while (block < num) {
percent = block * 100 / num;
for (i = 0; i < 10; i++) {
testit(fn, percent);
msleep(1);
}
block++;
msleep(1);
}
testit(fn, 100);
}
int main(void)
{
atexit(bye);
hidecursor();
printf("\nAdvanced:\n");
run_test(1);
printf("\nSimple:\n");
run_test(0);
printf("\n");
return 0;
}
+108
View File
@@ -0,0 +1,108 @@
#include <stdlib.h>
#include "check.h"
#define BASE "/tmp/.unittest/"
#define SRC BASE "src/"
#define DST BASE "dst/"
static int verbose = 0;
static char *files[] = {
SRC "sub1/1.tst",
SRC "sub1/2.tst",
SRC "sub1/3.tst",
SRC "sub2/4.tst",
SRC "sub2/5.tst",
SRC "sub2/6.tst",
SRC "sub3/7.tst",
SRC "sub3/8.tst",
SRC "sub3/9.tst",
NULL
};
void cleanup_test(void)
{
system("rm -rf " BASE);
}
void setup_test(void)
{
int i;
char cmd[256];
mode_t dir_modes[] = { 755, 700 };
mode_t file_modes[] = { 644, 600 };
cleanup_test();
mkdir(BASE, 0755);
mkdir(SRC, 0755);
mkdir(DST, 0755);
for (i = 0; files[i]; i++) {
snprintf(cmd, sizeof(cmd), "mkdir -m %d -p `dirname %s`",
dir_modes[i % 2], files[i]);
system(cmd);
snprintf(cmd, sizeof(cmd), "touch %s; chmod %d %s", files[i],
file_modes[i % 2], files[i]);
system(cmd);
}
}
static void check_tree(char *heading, char *dir)
{
if (verbose) {
if (heading)
puts(heading);
tree(dir, 1);
}
}
int run_test(void)
{
int result = 0;
#if 0
setup_test();
check_tree("Before:", BASE);
result += rsync(SRC, DST, 0, NULL);
check_tree("After:", BASE);
cleanup_test();
#endif
setup_test();
result += rsync(BASE "src", DST, 0, NULL);
check_tree("Only partial rsync of src <-- No slash!", BASE);
#if 0
cleanup_test();
setup_test();
result += rsync(BASE "src/sub1", BASE "dst", 0, NULL);
check_tree("Only partial rsync of src/sub1 <-- No slashes!!", BASE);
cleanup_test();
setup_test();
result += rsync(BASE "src/sub1/", DST, 0, NULL);
check_tree("Only partial rsync of src/sub1/", BASE);
cleanup_test();
setup_test();
result += rsync(BASE "src/sub1", DST, 0, NULL);
check_tree("Only partial rsync of src/sub1 <-- No slash!", BASE);
result += rsync("/etc", "/var/tmp", 0, NULL);
check_tree("Real life test:", "/var/tmp");
#endif
return result;
}
int main(int argc, char *argv[])
{
if (argc > 1)
verbose = !strncmp("-v", argv[1], 2);
atexit(cleanup_test);
return run_test();
}
+36
View File
@@ -0,0 +1,36 @@
#include <fcntl.h> /* O_TMPFILE requires -D_GNU_SOURCE */
#include <paths.h>
#include <stdio.h>
#include <stdlib.h>
#include "check.h"
#ifndef O_TMPFILE
#warning O_TMPFILE is missing, either too old GLIBC, Linux, or non-Linux system
#endif
#define READBACK "Reality is frequently inaccurate.\n"
int main(void)
{
int ret;
FILE *fp;
char buf[80] = "";
printf("Before tempfile():\n");
ret = system("ls -lrt " _PATH_TMP " | tail -3");
fp = tempfile();
fail_unless(fp != NULL);
ret = fputs(READBACK, fp);
rewind(fp);
if (fgets(buf, sizeof(buf), fp))
fprintf(stderr, "\nRead-back from tempfile: %s", buf);
fail_unless(!strcmp(buf, READBACK));
printf("\nAfter tempfile(), should be same list:\n");
ret = system("ls -lrt " _PATH_TMP " | tail -3");
return fclose(fp);
}
+61
View File
@@ -0,0 +1,61 @@
#include <err.h>
#include <paths.h>
#include <signal.h>
#include <stdarg.h>
#include <time.h>
#include "check.h"
int verbose = 0;
static int mtime(char *file)
{
int ret;
char buf[80];
struct stat before, after;
PRINT("Calling touch() to create file ...\n");
touch(file);
stat(file, &before);
/* Must sleep a while here otherwise we execute too fast => no mtime change :-( */
usleep(10000);
PRINT("Calling touch() again to update mtime ...\n");
if (touch(file)) {
erase(file);
err(1, "Failed creating %s", file);
}
stat(file, &after);
ret = timespec_newer(&after.st_mtim, &before.st_mtim);
PRINT("Before: %s\n", timespec2str(&before.st_mtim, buf, sizeof(buf)));
PRINT("After : %s\n", timespec2str(&after.st_mtim, buf, sizeof(buf)));
return !ret;
}
int main(int argc, char *argv[])
{
int fd;
char file[42] = "/tmp/touch_test.XXXXXX";
if (argc > 1 && !strcmp(argv[1], "-v"))
verbose = 1;
fd = mkstemp(file);
if (fd < 0)
err(1, "Failed creating tempfile, %s", file);
close(fd);
return mtime(file);
}
/**
* Local Variables:
* indent-tabs-mode: t
* c-file-style: "linux"
* compile-command: "make pidfile && ./pidfile -v"
* End:
*/
+19
View File
@@ -0,0 +1,19 @@
#include "check.h"
int main(void)
{
int result = 0;
size_t i;
struct { char *path; int fail; } arr[] = {
{ "/etc/passwd", -1 },
{ "/dev", 0 },
{ "/usr/sbin", 0 },
};
for (i = 0; i < NELEMS(arr); i++) {
if (tree(arr[i].path, 1) != arr[i].fail)
result++;
}
return result;
}
+49
View File
@@ -0,0 +1,49 @@
#include "check.h"
struct tc {
char *cmd;
int exp;
int res;
};
int main(void)
{
int result = 0;
size_t i;
struct tc test[] = {
{ "ls", 1 },
{ "free", 1 },
{ "modinfo", 1 },
{ "useradd", 1 },
{ "/bin/which", 1 },
{ "/bin/ps aux", 1 },
{ "/etc/passwd", 0 },
{ NULL, 0 }
};
for (i = 0; test[i].cmd; i++) {
char *path;
path = which(test[i].cmd);
if (!path) {
test[i].res = 0;
fprintf(stderr, "%20s : Not hot dog\n", test[i].cmd);
} else {
test[i].res = 1;
fprintf(stderr, "%20s : hot dog --> %s\n", test[i].cmd, path);
free(path);
}
}
for (i = 0; test[i].cmd; i++)
result += test[i].exp != test[i].res;
return result;
}
/**
* Local Variables:
* indent-tabs-mode: t
* c-file-style: "linux"
* End:
*/
+126
View File
@@ -0,0 +1,126 @@
/* Simple /bin/tree replacement
*
* Copyright (c) 2015 Joachim Nilsson <troglobit@gmail.com>
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include <errno.h>
#include <dirent.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
static int all = 0;
static int filter(const struct dirent *entry)
{
/* Skip current dir ".", and prev dir "..", from list of files */
if ((1 == strlen(entry->d_name) && entry->d_name[0] == '.') ||
(2 == strlen(entry->d_name) && !strcmp(entry->d_name, "..")))
return 0;
if (!all && entry->d_name[0] == '.')
return 0;
return 1;
}
static void get_perms(struct stat *st, char *buf, size_t len)
{
mode_t m = st->st_mode;
snprintf(buf, len, "[%c%c%c%c%c%c%c%c%c%c] ",
S_ISCHR(m) ? 'c' : S_ISBLK(m) ? 'b' : S_ISFIFO(m) ? 'p' : S_ISLNK(m) ? 'l' : S_ISSOCK(m) ? 's' : '-',
(m & S_IRUSR) ? 'r' : '-',
(m & S_IWUSR) ? 'w' : '-',
(m & S_ISUID ) ? 's' : (m & S_IXUSR) ? 'x' : '-',
(m & S_IRGRP) ? 'r' : '-',
(m & S_IWGRP) ? 'w' : '-',
(m & S_ISGID) ? 's' : (m & S_IXGRP) ? 'x' : '-',
(m & S_IROTH) ? 'r' : '-',
(m & S_IWOTH) ? 'w' : '-',
(m & S_IXOTH) ? 'x' : '-'
);
}
static int descend(char *path, int show_perms, char *pfx)
{
int i, n, result = 0;
struct stat st;
struct dirent **namelist = NULL;
if (-1 == lstat(path, &st))
return 1;
if ((st.st_mode & S_IFMT) != S_IFDIR) {
errno = ENOTDIR;
return -1;
}
n = scandir(path, &namelist, filter, alphasort);
if (n) {
for (i = 0; i < n; i++) {
char t = ' ', p[14] = "", s[256] = "";
char buf[512];
char dir[80];
if (i + 1 == n) {
printf("%s `- ", pfx);
snprintf(dir, sizeof(dir), "%s ", pfx);
} else {
printf("%s|-- ", pfx);
snprintf(dir, sizeof(dir), "%s| ", pfx);
}
snprintf(buf, sizeof(buf), "%s/%s", path, namelist[i]->d_name);
if (!lstat(buf, &st)) {
if (show_perms)
get_perms(&st, p, sizeof(p));
if ((st.st_mode & S_IFMT) == S_IFDIR)
t = '/';
if (S_ISLNK(st.st_mode)) {
snprintf(s, sizeof(s), "-> ");
if (-1 == readlink(buf, &s[3], sizeof(s) - 3))
s[0] = 0;
}
}
printf("%s%s%c%s\n", p, namelist[i]->d_name, t, s);
if (t == '/')
result += descend(buf, show_perms, dir);
free(namelist[i]);
}
free(namelist);
}
return result;
}
int tree(char *path, int show_perms)
{
printf("[%s]\n", path);
return descend(path, show_perms, "");
}
/**
* Local Variables:
* indent-tabs-mode: t
* c-file-style: "linux"
* End:
*/
+748
View File
@@ -0,0 +1,748 @@
/* $OpenBSD: tree.h,v 1.14 2015/05/25 03:07:49 deraadt Exp $ */
/*
* Copyright 2002 Niels Provos <provos@citi.umich.edu>
* All rights reserved.
*
* 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.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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.
*/
#ifndef _SYS_TREE_H_
#define _SYS_TREE_H_
/*
* This file defines data structures for different types of trees:
* splay trees and red-black trees.
*
* A splay tree is a self-organizing data structure. Every operation
* on the tree causes a splay to happen. The splay moves the requested
* node to the root of the tree and partly rebalances it.
*
* This has the benefit that request locality causes faster lookups as
* the requested nodes move to the top of the tree. On the other hand,
* every lookup causes memory writes.
*
* The Balance Theorem bounds the total access time for m operations
* and n inserts on an initially empty tree as O((m + n)lg n). The
* amortized cost for a sequence of m accesses to a splay tree is O(lg n);
*
* A red-black tree is a binary search tree with the node color as an
* extra attribute. It fulfills a set of conditions:
* - every search path from the root to a leaf consists of the
* same number of black nodes,
* - each red node (except for the root) has a black parent,
* - each leaf node is black.
*
* Every operation on a red-black tree is bounded as O(lg n).
* The maximum height of a red-black tree is 2lg (n+1).
*/
#define SPLAY_HEAD(name, type) \
struct name { \
struct type *sph_root; /* root of the tree */ \
}
#define SPLAY_INITIALIZER(root) \
{ NULL }
#define SPLAY_INIT(root) do { \
(root)->sph_root = NULL; \
} while (0)
#define SPLAY_ENTRY(type) \
struct { \
struct type *spe_left; /* left element */ \
struct type *spe_right; /* right element */ \
}
#define SPLAY_LEFT(elm, field) (elm)->field.spe_left
#define SPLAY_RIGHT(elm, field) (elm)->field.spe_right
#define SPLAY_ROOT(head) (head)->sph_root
#define SPLAY_EMPTY(head) (SPLAY_ROOT(head) == NULL)
/* SPLAY_ROTATE_{LEFT,RIGHT} expect that tmp hold SPLAY_{RIGHT,LEFT} */
#define SPLAY_ROTATE_RIGHT(head, tmp, field) do { \
SPLAY_LEFT((head)->sph_root, field) = SPLAY_RIGHT(tmp, field); \
SPLAY_RIGHT(tmp, field) = (head)->sph_root; \
(head)->sph_root = tmp; \
} while (0)
#define SPLAY_ROTATE_LEFT(head, tmp, field) do { \
SPLAY_RIGHT((head)->sph_root, field) = SPLAY_LEFT(tmp, field); \
SPLAY_LEFT(tmp, field) = (head)->sph_root; \
(head)->sph_root = tmp; \
} while (0)
#define SPLAY_LINKLEFT(head, tmp, field) do { \
SPLAY_LEFT(tmp, field) = (head)->sph_root; \
tmp = (head)->sph_root; \
(head)->sph_root = SPLAY_LEFT((head)->sph_root, field); \
} while (0)
#define SPLAY_LINKRIGHT(head, tmp, field) do { \
SPLAY_RIGHT(tmp, field) = (head)->sph_root; \
tmp = (head)->sph_root; \
(head)->sph_root = SPLAY_RIGHT((head)->sph_root, field); \
} while (0)
#define SPLAY_ASSEMBLE(head, node, left, right, field) do { \
SPLAY_RIGHT(left, field) = SPLAY_LEFT((head)->sph_root, field); \
SPLAY_LEFT(right, field) = SPLAY_RIGHT((head)->sph_root, field);\
SPLAY_LEFT((head)->sph_root, field) = SPLAY_RIGHT(node, field); \
SPLAY_RIGHT((head)->sph_root, field) = SPLAY_LEFT(node, field); \
} while (0)
/* Generates prototypes and inline functions */
#define SPLAY_PROTOTYPE(name, type, field, cmp) \
void name##_SPLAY(struct name *, struct type *); \
void name##_SPLAY_MINMAX(struct name *, int); \
struct type *name##_SPLAY_INSERT(struct name *, struct type *); \
struct type *name##_SPLAY_REMOVE(struct name *, struct type *); \
\
/* Finds the node with the same key as elm */ \
static __inline struct type * \
name##_SPLAY_FIND(struct name *head, struct type *elm) \
{ \
if (SPLAY_EMPTY(head)) \
return(NULL); \
name##_SPLAY(head, elm); \
if ((cmp)(elm, (head)->sph_root) == 0) \
return (head->sph_root); \
return (NULL); \
} \
\
static __inline struct type * \
name##_SPLAY_NEXT(struct name *head, struct type *elm) \
{ \
name##_SPLAY(head, elm); \
if (SPLAY_RIGHT(elm, field) != NULL) { \
elm = SPLAY_RIGHT(elm, field); \
while (SPLAY_LEFT(elm, field) != NULL) { \
elm = SPLAY_LEFT(elm, field); \
} \
} else \
elm = NULL; \
return (elm); \
} \
\
static __inline struct type * \
name##_SPLAY_MIN_MAX(struct name *head, int val) \
{ \
name##_SPLAY_MINMAX(head, val); \
return (SPLAY_ROOT(head)); \
}
/* Main splay operation.
* Moves node close to the key of elm to top
*/
#define SPLAY_GENERATE(name, type, field, cmp) \
struct type * \
name##_SPLAY_INSERT(struct name *head, struct type *elm) \
{ \
if (SPLAY_EMPTY(head)) { \
SPLAY_LEFT(elm, field) = SPLAY_RIGHT(elm, field) = NULL; \
} else { \
int __comp; \
name##_SPLAY(head, elm); \
__comp = (cmp)(elm, (head)->sph_root); \
if(__comp < 0) { \
SPLAY_LEFT(elm, field) = SPLAY_LEFT((head)->sph_root, field);\
SPLAY_RIGHT(elm, field) = (head)->sph_root; \
SPLAY_LEFT((head)->sph_root, field) = NULL; \
} else if (__comp > 0) { \
SPLAY_RIGHT(elm, field) = SPLAY_RIGHT((head)->sph_root, field);\
SPLAY_LEFT(elm, field) = (head)->sph_root; \
SPLAY_RIGHT((head)->sph_root, field) = NULL; \
} else \
return ((head)->sph_root); \
} \
(head)->sph_root = (elm); \
return (NULL); \
} \
\
struct type * \
name##_SPLAY_REMOVE(struct name *head, struct type *elm) \
{ \
struct type *__tmp; \
if (SPLAY_EMPTY(head)) \
return (NULL); \
name##_SPLAY(head, elm); \
if ((cmp)(elm, (head)->sph_root) == 0) { \
if (SPLAY_LEFT((head)->sph_root, field) == NULL) { \
(head)->sph_root = SPLAY_RIGHT((head)->sph_root, field);\
} else { \
__tmp = SPLAY_RIGHT((head)->sph_root, field); \
(head)->sph_root = SPLAY_LEFT((head)->sph_root, field);\
name##_SPLAY(head, elm); \
SPLAY_RIGHT((head)->sph_root, field) = __tmp; \
} \
return (elm); \
} \
return (NULL); \
} \
\
void \
name##_SPLAY(struct name *head, struct type *elm) \
{ \
struct type __node, *__left, *__right, *__tmp; \
int __comp; \
\
SPLAY_LEFT(&__node, field) = SPLAY_RIGHT(&__node, field) = NULL;\
__left = __right = &__node; \
\
while ((__comp = (cmp)(elm, (head)->sph_root))) { \
if (__comp < 0) { \
__tmp = SPLAY_LEFT((head)->sph_root, field); \
if (__tmp == NULL) \
break; \
if ((cmp)(elm, __tmp) < 0){ \
SPLAY_ROTATE_RIGHT(head, __tmp, field); \
if (SPLAY_LEFT((head)->sph_root, field) == NULL)\
break; \
} \
SPLAY_LINKLEFT(head, __right, field); \
} else if (__comp > 0) { \
__tmp = SPLAY_RIGHT((head)->sph_root, field); \
if (__tmp == NULL) \
break; \
if ((cmp)(elm, __tmp) > 0){ \
SPLAY_ROTATE_LEFT(head, __tmp, field); \
if (SPLAY_RIGHT((head)->sph_root, field) == NULL)\
break; \
} \
SPLAY_LINKRIGHT(head, __left, field); \
} \
} \
SPLAY_ASSEMBLE(head, &__node, __left, __right, field); \
} \
\
/* Splay with either the minimum or the maximum element \
* Used to find minimum or maximum element in tree. \
*/ \
void name##_SPLAY_MINMAX(struct name *head, int __comp) \
{ \
struct type __node, *__left, *__right, *__tmp; \
\
SPLAY_LEFT(&__node, field) = SPLAY_RIGHT(&__node, field) = NULL;\
__left = __right = &__node; \
\
while (1) { \
if (__comp < 0) { \
__tmp = SPLAY_LEFT((head)->sph_root, field); \
if (__tmp == NULL) \
break; \
if (__comp < 0){ \
SPLAY_ROTATE_RIGHT(head, __tmp, field); \
if (SPLAY_LEFT((head)->sph_root, field) == NULL)\
break; \
} \
SPLAY_LINKLEFT(head, __right, field); \
} else if (__comp > 0) { \
__tmp = SPLAY_RIGHT((head)->sph_root, field); \
if (__tmp == NULL) \
break; \
if (__comp > 0) { \
SPLAY_ROTATE_LEFT(head, __tmp, field); \
if (SPLAY_RIGHT((head)->sph_root, field) == NULL)\
break; \
} \
SPLAY_LINKRIGHT(head, __left, field); \
} \
} \
SPLAY_ASSEMBLE(head, &__node, __left, __right, field); \
}
#define SPLAY_NEGINF -1
#define SPLAY_INF 1
#define SPLAY_INSERT(name, x, y) name##_SPLAY_INSERT(x, y)
#define SPLAY_REMOVE(name, x, y) name##_SPLAY_REMOVE(x, y)
#define SPLAY_FIND(name, x, y) name##_SPLAY_FIND(x, y)
#define SPLAY_NEXT(name, x, y) name##_SPLAY_NEXT(x, y)
#define SPLAY_MIN(name, x) (SPLAY_EMPTY(x) ? NULL \
: name##_SPLAY_MIN_MAX(x, SPLAY_NEGINF))
#define SPLAY_MAX(name, x) (SPLAY_EMPTY(x) ? NULL \
: name##_SPLAY_MIN_MAX(x, SPLAY_INF))
#define SPLAY_FOREACH(x, name, head) \
for ((x) = SPLAY_MIN(name, head); \
(x) != NULL; \
(x) = SPLAY_NEXT(name, head, x))
/* Macros that define a red-black tree */
#define RB_HEAD(name, type) \
struct name { \
struct type *rbh_root; /* root of the tree */ \
}
#define RB_INITIALIZER(root) \
{ NULL }
#define RB_INIT(root) do { \
(root)->rbh_root = NULL; \
} while (0)
#define RB_BLACK 0
#define RB_RED 1
#define RB_ENTRY(type) \
struct { \
struct type *rbe_left; /* left element */ \
struct type *rbe_right; /* right element */ \
struct type *rbe_parent; /* parent element */ \
int rbe_color; /* node color */ \
}
#define RB_LEFT(elm, field) (elm)->field.rbe_left
#define RB_RIGHT(elm, field) (elm)->field.rbe_right
#define RB_PARENT(elm, field) (elm)->field.rbe_parent
#define RB_COLOR(elm, field) (elm)->field.rbe_color
#define RB_ROOT(head) (head)->rbh_root
#define RB_EMPTY(head) (RB_ROOT(head) == NULL)
#define RB_SET(elm, parent, field) do { \
RB_PARENT(elm, field) = parent; \
RB_LEFT(elm, field) = RB_RIGHT(elm, field) = NULL; \
RB_COLOR(elm, field) = RB_RED; \
} while (0)
#define RB_SET_BLACKRED(black, red, field) do { \
RB_COLOR(black, field) = RB_BLACK; \
RB_COLOR(red, field) = RB_RED; \
} while (0)
#ifndef RB_AUGMENT
#define RB_AUGMENT(x) do {} while (0)
#endif
#define RB_ROTATE_LEFT(head, elm, tmp, field) do { \
(tmp) = RB_RIGHT(elm, field); \
if ((RB_RIGHT(elm, field) = RB_LEFT(tmp, field))) { \
RB_PARENT(RB_LEFT(tmp, field), field) = (elm); \
} \
RB_AUGMENT(elm); \
if ((RB_PARENT(tmp, field) = RB_PARENT(elm, field))) { \
if ((elm) == RB_LEFT(RB_PARENT(elm, field), field)) \
RB_LEFT(RB_PARENT(elm, field), field) = (tmp); \
else \
RB_RIGHT(RB_PARENT(elm, field), field) = (tmp); \
} else \
(head)->rbh_root = (tmp); \
RB_LEFT(tmp, field) = (elm); \
RB_PARENT(elm, field) = (tmp); \
RB_AUGMENT(tmp); \
if ((RB_PARENT(tmp, field))) \
RB_AUGMENT(RB_PARENT(tmp, field)); \
} while (0)
#define RB_ROTATE_RIGHT(head, elm, tmp, field) do { \
(tmp) = RB_LEFT(elm, field); \
if ((RB_LEFT(elm, field) = RB_RIGHT(tmp, field))) { \
RB_PARENT(RB_RIGHT(tmp, field), field) = (elm); \
} \
RB_AUGMENT(elm); \
if ((RB_PARENT(tmp, field) = RB_PARENT(elm, field))) { \
if ((elm) == RB_LEFT(RB_PARENT(elm, field), field)) \
RB_LEFT(RB_PARENT(elm, field), field) = (tmp); \
else \
RB_RIGHT(RB_PARENT(elm, field), field) = (tmp); \
} else \
(head)->rbh_root = (tmp); \
RB_RIGHT(tmp, field) = (elm); \
RB_PARENT(elm, field) = (tmp); \
RB_AUGMENT(tmp); \
if ((RB_PARENT(tmp, field))) \
RB_AUGMENT(RB_PARENT(tmp, field)); \
} while (0)
/* Generates prototypes and inline functions */
#define RB_PROTOTYPE(name, type, field, cmp) \
RB_PROTOTYPE_INTERNAL(name, type, field, cmp,)
#define RB_PROTOTYPE_STATIC(name, type, field, cmp) \
RB_PROTOTYPE_INTERNAL(name, type, field, cmp, __attribute__((__unused__)) static)
#define RB_PROTOTYPE_INTERNAL(name, type, field, cmp, attr) \
attr void name##_RB_INSERT_COLOR(struct name *, struct type *); \
attr void name##_RB_REMOVE_COLOR(struct name *, struct type *, struct type *);\
attr struct type *name##_RB_REMOVE(struct name *, struct type *); \
attr struct type *name##_RB_INSERT(struct name *, struct type *); \
attr struct type *name##_RB_FIND(struct name *, struct type *); \
attr struct type *name##_RB_NFIND(struct name *, struct type *); \
attr struct type *name##_RB_NEXT(struct type *); \
attr struct type *name##_RB_PREV(struct type *); \
attr struct type *name##_RB_MINMAX(struct name *, int); \
\
/* Main rb operation.
* Moves node close to the key of elm to top
*/
#define RB_GENERATE(name, type, field, cmp) \
RB_GENERATE_INTERNAL(name, type, field, cmp,)
#define RB_GENERATE_STATIC(name, type, field, cmp) \
RB_GENERATE_INTERNAL(name, type, field, cmp, __attribute__((__unused__)) static)
#define RB_GENERATE_INTERNAL(name, type, field, cmp, attr) \
attr void \
name##_RB_INSERT_COLOR(struct name *head, struct type *elm) \
{ \
struct type *parent, *gparent, *tmp; \
while ((parent = RB_PARENT(elm, field)) && \
RB_COLOR(parent, field) == RB_RED) { \
gparent = RB_PARENT(parent, field); \
if (parent == RB_LEFT(gparent, field)) { \
tmp = RB_RIGHT(gparent, field); \
if (tmp && RB_COLOR(tmp, field) == RB_RED) { \
RB_COLOR(tmp, field) = RB_BLACK; \
RB_SET_BLACKRED(parent, gparent, field);\
elm = gparent; \
continue; \
} \
if (RB_RIGHT(parent, field) == elm) { \
RB_ROTATE_LEFT(head, parent, tmp, field);\
tmp = parent; \
parent = elm; \
elm = tmp; \
} \
RB_SET_BLACKRED(parent, gparent, field); \
RB_ROTATE_RIGHT(head, gparent, tmp, field); \
} else { \
tmp = RB_LEFT(gparent, field); \
if (tmp && RB_COLOR(tmp, field) == RB_RED) { \
RB_COLOR(tmp, field) = RB_BLACK; \
RB_SET_BLACKRED(parent, gparent, field);\
elm = gparent; \
continue; \
} \
if (RB_LEFT(parent, field) == elm) { \
RB_ROTATE_RIGHT(head, parent, tmp, field);\
tmp = parent; \
parent = elm; \
elm = tmp; \
} \
RB_SET_BLACKRED(parent, gparent, field); \
RB_ROTATE_LEFT(head, gparent, tmp, field); \
} \
} \
RB_COLOR(head->rbh_root, field) = RB_BLACK; \
} \
\
attr void \
name##_RB_REMOVE_COLOR(struct name *head, struct type *parent, struct type *elm) \
{ \
struct type *tmp; \
while ((elm == NULL || RB_COLOR(elm, field) == RB_BLACK) && \
elm != RB_ROOT(head)) { \
if (RB_LEFT(parent, field) == elm) { \
tmp = RB_RIGHT(parent, field); \
if (RB_COLOR(tmp, field) == RB_RED) { \
RB_SET_BLACKRED(tmp, parent, field); \
RB_ROTATE_LEFT(head, parent, tmp, field);\
tmp = RB_RIGHT(parent, field); \
} \
if ((RB_LEFT(tmp, field) == NULL || \
RB_COLOR(RB_LEFT(tmp, field), field) == RB_BLACK) &&\
(RB_RIGHT(tmp, field) == NULL || \
RB_COLOR(RB_RIGHT(tmp, field), field) == RB_BLACK)) {\
RB_COLOR(tmp, field) = RB_RED; \
elm = parent; \
parent = RB_PARENT(elm, field); \
} else { \
if (RB_RIGHT(tmp, field) == NULL || \
RB_COLOR(RB_RIGHT(tmp, field), field) == RB_BLACK) {\
struct type *oleft; \
if ((oleft = RB_LEFT(tmp, field)))\
RB_COLOR(oleft, field) = RB_BLACK;\
RB_COLOR(tmp, field) = RB_RED; \
RB_ROTATE_RIGHT(head, tmp, oleft, field);\
tmp = RB_RIGHT(parent, field); \
} \
RB_COLOR(tmp, field) = RB_COLOR(parent, field);\
RB_COLOR(parent, field) = RB_BLACK; \
if (RB_RIGHT(tmp, field)) \
RB_COLOR(RB_RIGHT(tmp, field), field) = RB_BLACK;\
RB_ROTATE_LEFT(head, parent, tmp, field);\
elm = RB_ROOT(head); \
break; \
} \
} else { \
tmp = RB_LEFT(parent, field); \
if (RB_COLOR(tmp, field) == RB_RED) { \
RB_SET_BLACKRED(tmp, parent, field); \
RB_ROTATE_RIGHT(head, parent, tmp, field);\
tmp = RB_LEFT(parent, field); \
} \
if ((RB_LEFT(tmp, field) == NULL || \
RB_COLOR(RB_LEFT(tmp, field), field) == RB_BLACK) &&\
(RB_RIGHT(tmp, field) == NULL || \
RB_COLOR(RB_RIGHT(tmp, field), field) == RB_BLACK)) {\
RB_COLOR(tmp, field) = RB_RED; \
elm = parent; \
parent = RB_PARENT(elm, field); \
} else { \
if (RB_LEFT(tmp, field) == NULL || \
RB_COLOR(RB_LEFT(tmp, field), field) == RB_BLACK) {\
struct type *oright; \
if ((oright = RB_RIGHT(tmp, field)))\
RB_COLOR(oright, field) = RB_BLACK;\
RB_COLOR(tmp, field) = RB_RED; \
RB_ROTATE_LEFT(head, tmp, oright, field);\
tmp = RB_LEFT(parent, field); \
} \
RB_COLOR(tmp, field) = RB_COLOR(parent, field);\
RB_COLOR(parent, field) = RB_BLACK; \
if (RB_LEFT(tmp, field)) \
RB_COLOR(RB_LEFT(tmp, field), field) = RB_BLACK;\
RB_ROTATE_RIGHT(head, parent, tmp, field);\
elm = RB_ROOT(head); \
break; \
} \
} \
} \
if (elm) \
RB_COLOR(elm, field) = RB_BLACK; \
} \
\
attr struct type * \
name##_RB_REMOVE(struct name *head, struct type *elm) \
{ \
struct type *child, *parent, *old = elm; \
int color; \
if (RB_LEFT(elm, field) == NULL) \
child = RB_RIGHT(elm, field); \
else if (RB_RIGHT(elm, field) == NULL) \
child = RB_LEFT(elm, field); \
else { \
struct type *left; \
elm = RB_RIGHT(elm, field); \
while ((left = RB_LEFT(elm, field))) \
elm = left; \
child = RB_RIGHT(elm, field); \
parent = RB_PARENT(elm, field); \
color = RB_COLOR(elm, field); \
if (child) \
RB_PARENT(child, field) = parent; \
if (parent) { \
if (RB_LEFT(parent, field) == elm) \
RB_LEFT(parent, field) = child; \
else \
RB_RIGHT(parent, field) = child; \
RB_AUGMENT(parent); \
} else \
RB_ROOT(head) = child; \
if (RB_PARENT(elm, field) == old) \
parent = elm; \
(elm)->field = (old)->field; \
if (RB_PARENT(old, field)) { \
if (RB_LEFT(RB_PARENT(old, field), field) == old)\
RB_LEFT(RB_PARENT(old, field), field) = elm;\
else \
RB_RIGHT(RB_PARENT(old, field), field) = elm;\
RB_AUGMENT(RB_PARENT(old, field)); \
} else \
RB_ROOT(head) = elm; \
RB_PARENT(RB_LEFT(old, field), field) = elm; \
if (RB_RIGHT(old, field)) \
RB_PARENT(RB_RIGHT(old, field), field) = elm; \
if (parent) { \
left = parent; \
do { \
RB_AUGMENT(left); \
} while ((left = RB_PARENT(left, field))); \
} \
goto color; \
} \
parent = RB_PARENT(elm, field); \
color = RB_COLOR(elm, field); \
if (child) \
RB_PARENT(child, field) = parent; \
if (parent) { \
if (RB_LEFT(parent, field) == elm) \
RB_LEFT(parent, field) = child; \
else \
RB_RIGHT(parent, field) = child; \
RB_AUGMENT(parent); \
} else \
RB_ROOT(head) = child; \
color: \
if (color == RB_BLACK) \
name##_RB_REMOVE_COLOR(head, parent, child); \
return (old); \
} \
\
/* Inserts a node into the RB tree */ \
attr struct type * \
name##_RB_INSERT(struct name *head, struct type *elm) \
{ \
struct type *tmp; \
struct type *parent = NULL; \
int comp = 0; \
tmp = RB_ROOT(head); \
while (tmp) { \
parent = tmp; \
comp = (cmp)(elm, parent); \
if (comp < 0) \
tmp = RB_LEFT(tmp, field); \
else if (comp > 0) \
tmp = RB_RIGHT(tmp, field); \
else \
return (tmp); \
} \
RB_SET(elm, parent, field); \
if (parent != NULL) { \
if (comp < 0) \
RB_LEFT(parent, field) = elm; \
else \
RB_RIGHT(parent, field) = elm; \
RB_AUGMENT(parent); \
} else \
RB_ROOT(head) = elm; \
name##_RB_INSERT_COLOR(head, elm); \
return (NULL); \
} \
\
/* Finds the node with the same key as elm */ \
attr struct type * \
name##_RB_FIND(struct name *head, struct type *elm) \
{ \
struct type *tmp = RB_ROOT(head); \
int comp; \
while (tmp) { \
comp = cmp(elm, tmp); \
if (comp < 0) \
tmp = RB_LEFT(tmp, field); \
else if (comp > 0) \
tmp = RB_RIGHT(tmp, field); \
else \
return (tmp); \
} \
return (NULL); \
} \
\
/* Finds the first node greater than or equal to the search key */ \
attr struct type * \
name##_RB_NFIND(struct name *head, struct type *elm) \
{ \
struct type *tmp = RB_ROOT(head); \
struct type *res = NULL; \
int comp; \
while (tmp) { \
comp = cmp(elm, tmp); \
if (comp < 0) { \
res = tmp; \
tmp = RB_LEFT(tmp, field); \
} \
else if (comp > 0) \
tmp = RB_RIGHT(tmp, field); \
else \
return (tmp); \
} \
return (res); \
} \
\
/* ARGSUSED */ \
attr struct type * \
name##_RB_NEXT(struct type *elm) \
{ \
if (RB_RIGHT(elm, field)) { \
elm = RB_RIGHT(elm, field); \
while (RB_LEFT(elm, field)) \
elm = RB_LEFT(elm, field); \
} else { \
if (RB_PARENT(elm, field) && \
(elm == RB_LEFT(RB_PARENT(elm, field), field))) \
elm = RB_PARENT(elm, field); \
else { \
while (RB_PARENT(elm, field) && \
(elm == RB_RIGHT(RB_PARENT(elm, field), field)))\
elm = RB_PARENT(elm, field); \
elm = RB_PARENT(elm, field); \
} \
} \
return (elm); \
} \
\
/* ARGSUSED */ \
attr struct type * \
name##_RB_PREV(struct type *elm) \
{ \
if (RB_LEFT(elm, field)) { \
elm = RB_LEFT(elm, field); \
while (RB_RIGHT(elm, field)) \
elm = RB_RIGHT(elm, field); \
} else { \
if (RB_PARENT(elm, field) && \
(elm == RB_RIGHT(RB_PARENT(elm, field), field))) \
elm = RB_PARENT(elm, field); \
else { \
while (RB_PARENT(elm, field) && \
(elm == RB_LEFT(RB_PARENT(elm, field), field)))\
elm = RB_PARENT(elm, field); \
elm = RB_PARENT(elm, field); \
} \
} \
return (elm); \
} \
\
attr struct type * \
name##_RB_MINMAX(struct name *head, int val) \
{ \
struct type *tmp = RB_ROOT(head); \
struct type *parent = NULL; \
while (tmp) { \
parent = tmp; \
if (val < 0) \
tmp = RB_LEFT(tmp, field); \
else \
tmp = RB_RIGHT(tmp, field); \
} \
return (parent); \
}
#define RB_NEGINF -1
#define RB_INF 1
#define RB_INSERT(name, x, y) name##_RB_INSERT(x, y)
#define RB_REMOVE(name, x, y) name##_RB_REMOVE(x, y)
#define RB_FIND(name, x, y) name##_RB_FIND(x, y)
#define RB_NFIND(name, x, y) name##_RB_NFIND(x, y)
#define RB_NEXT(name, x, y) name##_RB_NEXT(y)
#define RB_PREV(name, x, y) name##_RB_PREV(y)
#define RB_MIN(name, x) name##_RB_MINMAX(x, RB_NEGINF)
#define RB_MAX(name, x) name##_RB_MINMAX(x, RB_INF)
#define RB_FOREACH(x, name, head) \
for ((x) = RB_MIN(name, head); \
(x) != NULL; \
(x) = name##_RB_NEXT(x))
#define RB_FOREACH_SAFE(x, name, head, y) \
for ((x) = RB_MIN(name, head); \
((x) != NULL) && ((y) = name##_RB_NEXT(x), 1); \
(x) = (y))
#define RB_FOREACH_REVERSE(x, name, head) \
for ((x) = RB_MAX(name, head); \
(x) != NULL; \
(x) = name##_RB_PREV(x))
#define RB_FOREACH_REVERSE_SAFE(x, name, head, y) \
for ((x) = RB_MAX(name, head); \
((x) != NULL) && ((y) = name##_RB_PREV(x), 1); \
(x) = (y))
#endif /* _SYS_TREE_H_ */
+127
View File
@@ -0,0 +1,127 @@
/* C implementation of UNIX which(1)
*
* Copyright (c) 2017 Joachim Nilsson <troglobit@gmail.com>
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include <ctype.h>
#include <errno.h>
#include <stdio.h> /* snprintf() */
#include <stdlib.h> /* realloc(), free() */
#include <string.h> /* strtok_r() */
#include <unistd.h> /* access() */
/* Strip any arguments in "/path/to/bin --some args", modifies input string */
static char *strip_args(char *path)
{
size_t i = 0;
if (!path)
return NULL;
/* Find first whitespace (space/tab/etc.) */
while (path[i] && !isspace(path[i]))
i++;
path[i] = 0;
return path;
}
/*
* Like which(1), returns a malloc'ed path to cmd on success, or NULL
*/
char *which(const char *cmd)
{
size_t pathlen = 0;
char *ptr, *tok, *env, *path = NULL;
if (!cmd) {
errno = EINVAL;
return NULL;
}
if (cmd[0] == '/') {
path = strip_args(strdup(cmd));
if (!path)
return NULL;
if (!access(path, X_OK))
return path;
if (path)
free(path);
return NULL;
}
ptr = getenv("PATH");
if (!ptr)
return NULL;
env = strdup(ptr);
if (!env)
return NULL;
tok = strtok_r(env, ":", &ptr);
while (tok) {
size_t len = strlen(tok) + strlen(cmd) + 2;
if (pathlen < len) {
path = realloc(path, len);
if (!path) {
free(env);
return NULL;
}
pathlen = len;
}
snprintf(path, pathlen, "%s/%s", tok, cmd);
path = strip_args(path);
if (!path || !access(path, X_OK)) {
free(env);
return path;
}
tok = strtok_r(NULL, ":", &ptr);
}
if (path)
free(path);
free(env);
return NULL;
}
/*
* Like which(), above, but only answers TRUE(1)/FALSE(0)
*/
int whichp(const char *cmd)
{
char *path;
path = which(cmd);
if (path) {
free(path);
return 1;
}
return 0;
}
/**
* Local Variables:
* indent-tabs-mode: t
* c-file-style: "linux"
* End:
*/