libite
|
Collection of frog DNA. More...
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdarg.h>
#include <stdint.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/param.h>
#include <unistd.h>
#include "strlite.h"
#include <sys/time.h>
Go to the source code of this file.
Macros | |
#define | LIBITE_LITE_H_ |
#define | FPARSELN_UNESCESC 0x01 |
Remove escape preceding an escaped comment. More... | |
#define | FPARSELN_UNESCCONT 0x02 |
Remove escape preceding an escaped continuation. More... | |
#define | FPARSELN_UNESCCOMM 0x04 |
Remove escape preceding an escaped escape. More... | |
#define | FPARSELN_UNESCREST 0x08 |
Remove escape preceding any other character. More... | |
#define | FPARSELN_UNESCALL 0x0f |
All of the above. More... | |
#define | LITE_FOPT_RSYNC_DELETE 0x01 |
Prune files from destination that are not in source. | |
#define | LITE_FOPT_COPYFILE_SYM 0x01 |
Recreate symlink or follow to copy target. | |
#define | LITE_FOPT_KEEP_MTIME 0x02 |
Preserve modification time. | |
#define | chardev(x, m, maj, min) mknod((x), S_IFCHR|(m), makedev((maj),(min))) |
#define | blkdev(x, m, maj, min) mknod((x), S_IFBLK|(m), makedev((maj),(min))) |
#define | S_ISEXEC(m) (((m) & S_IXUSR) == S_IXUSR) |
#define | ISCLR(word, bit) ((word & (1 << (bit)) ? 0 : 1)) |
Is bit cleared in word? | |
#define | ISSET(word, bit) ((word & (1 << (bit)) ? 1 : 0)) |
Is bit set in word? | |
#define | ISOTHER(word, bit) ((word & ~(1 << (bit)) ? 1 : 0)) |
Is any other bit set? | |
#define | SETBIT(word, bit) (word |= (1 << (bit))) |
Set bit in word. More... | |
#define | CLRBIT(word, bit) (word &= ~(1 << (bit))) |
Clear bit in word. More... | |
#define | NELEMS(array) (sizeof(array) / sizeof(array[0])) |
Number of elements in array. More... | |
#define | copy_filep(src, dst) fcopyfile(src, dst) |
#define | pidfile_read_pid(file) pidfile_read(file) |
#define | signal_pidfile(file, signo) pidfile_signal(file, signo) |
Typedefs | |
typedef struct lfile | lfile_t |
Opqaue context struct for lfile APIs. | |
typedef struct sdbuf | sdbuf_t |
Opqaue context struct for telnet APIs. | |
Functions | |
char * | chomp (char *str) |
Perl like chomp function, chop off last char(s) if newline. More... | |
int | erasef (const char *fmt,...) __attribute__((format(printf |
int char * | fparseln (FILE *, size_t *, size_t *, const char[3], int) |
Read a line from a file parsing continuations and trailing newlines. More... | |
int | fexist (const char *file) |
Check if a file exists in the file system. More... | |
int | fexistf (const char *fmt,...) __attribute__((format(printf |
int int | fisdir (const char *path) |
Check if a path exists and is a directory. More... | |
FILE * | vfopenf (const char *mode, const char *fmt, va_list ap) |
Similar to fopenf() except it takes a va_list argument. More... | |
FILE * | fopenf (const char *mode, const char *fmt,...) __attribute__((format(printf |
FILE int | fremove (const char *fmt,...) __attribute__((format(printf |
FILE int FILE * | tempfile (void) |
A secure tmpfile() replacement. More... | |
ssize_t | copyfile (const char *src, const char *dst, int len, int opt) |
Copy a file to another. More... | |
int | movefile (const char *src, const char *dst) |
Move a file to another location. More... | |
int | fcopyfile (FILE *src, FILE *dst) |
Copy between FILE *fp. More... | |
ssize_t | fsendfile (FILE *src, FILE *dst, size_t len) |
Copy data between file streams. More... | |
int | truncatef (off_t length, const char *fmt,...) __attribute__((format(printf |
int char * | vreadsnf (char *line, size_t len, const char *fmt, va_list ap) |
Similar to readsnf() except it takes a va_list argument. More... | |
char * | readsnf (char *line, size_t len, const char *fmt,...) |
Read first line from a file composed from fmt and optional args. More... | |
int | writesf (const char *str, const char *mode, const char *fmt,...) |
Write a string buffer to a file composed from fmt and optional args. More... | |
int | vreadllf (long long *value, const char *fmt, va_list ap) |
Same as readllf() except it takes a va_list argument. | |
int | readllf (long long *value, const char *fmt,...) |
Read 64-bit integer value from a file composed from fmt and optional args. More... | |
int | readdf (int *value, const char *fmt,...) |
Read integer value from a file composed from fmt and optional args. More... | |
int | writellf (long long value, const char *mode, const char *fmt,...) |
Write 64-bit integer value to a file composed from fmt and optional args. More... | |
int | writedf (int value, const char *mode, const char *fmt,...) |
Write integer value to a file composed from fmt and optional args. More... | |
int | ifconfig (const char *ifname, const char *addr, const char *mask, int up) |
Basic ifconfig like operations on an interface. More... | |
lfile_t * | lfopen (const char *file, const char *sep) |
Open file and return parsing context. More... | |
void | lfclose (lfile_t *lf) |
Close a parser context. More... | |
char * | lftok (lfile_t *lf) |
Get next token in file. More... | |
char * | lfgetkey (lfile_t *lf, const char *key) |
Find key in file. More... | |
int | lfgetint (lfile_t *lf, const char *key) |
Same as lfgetkey() but returns an integer. More... | |
int | fgetint (const char *file, const char *sep, const char *key) |
Find the integer value for key in a file. More... | |
int | fmkpath (mode_t mode, const char *fmt,...) __attribute__((format(printf |
int int | mkpath (const char *dir, mode_t mode) |
makepath() but takes a mode_t argument. More... | |
int | makepath (const char *dir) |
Create all components of the specified directory. More... | |
int | dir (const char *dir, const char *type, int(*filter)(const char *file), char ***list, int strip) |
List all files of a certain type in the given directory. More... | |
int | rsync (char *src, char *dst, int opt, int(*filter)(const char *file)) |
Synchronize contents and optionally remove non-existing backups. More... | |
FILE * | popenf (const char *type, const char *fmt,...) __attribute__((format(printf |
FILE int | pidfile (const char *basename) |
Create or update mtime of process PID file. More... | |
int | pidfile_signal (const char *pidfile, int signal) |
Send signal to a PID and cleanup pidfile afterwards. More... | |
pid_t | pidfile_read (const char *pidfile) |
Reads a PID value from a pidfile. More... | |
pid_t | pidfile_poll (const char *pidfile) |
Poll for the existence of a pidfile and return PID. More... | |
void * | reallocarray (void *optr, size_t nmemb, size_t size) |
Similar to realloc() but for an array of items, like calloc() More... | |
void | progress (int percent, int max_width) |
Advanced ASCII progress bar with spinner. More... | |
void | progress_simple (int percent) |
Alternative progress bar on systems where progress() doesn't work. More... | |
int | runbg (char *const cmd[], int delay) |
Run command in the background. More... | |
int | systemf (const char *fmt,...) __attribute__((format(printf |
int sdbuf_t * | telnet_open (int addr, short port) |
Open telnet connection to addr:port and connect. More... | |
int | telnet_close (sdbuf_t *ctx) |
Close a telnet session previously opened with telnet_open() More... | |
int | telnet_expect (sdbuf_t *ctx, char *script[], FILE *output) |
Poor man's telnet expect. More... | |
int | telnet_session (int addr, short port, char *script[], FILE *output) |
Very simple expect-like implementation for telnet. More... | |
int | touchf (const char *fmt,...) __attribute__((format(printf |
int int | yorn (const char *fmt,...) __attribute__((format(printf |
int int char * | which (const char *cmd) |
Like which(1), or command -v foo More... | |
int | whichp (const char *cmd) |
Predicate variant of which() More... | |
Collection of frog DNA.
The latest version of this manual and the libite (-lite) software library are available at https://github.com/troglobit/libite/
#define CLRBIT | ( | word, | |
bit | |||
) | (word &= ~(1 << (bit))) |
Clear bit in word.
#define FPARSELN_UNESCALL 0x0f |
All of the above.
#define FPARSELN_UNESCCOMM 0x04 |
Remove escape preceding an escaped escape.
#define FPARSELN_UNESCCONT 0x02 |
Remove escape preceding an escaped continuation.
#define FPARSELN_UNESCESC 0x01 |
Remove escape preceding an escaped comment.
#define FPARSELN_UNESCREST 0x08 |
Remove escape preceding any other character.
#define NELEMS | ( | array | ) | (sizeof(array) / sizeof(array[0])) |
Number of elements in array.
#define SETBIT | ( | word, | |
bit | |||
) | (word |= (1 << (bit))) |
Set bit in word.
char* chomp | ( | char * | str | ) |
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. Useful in combination with fgets().
NULL
with errno set, if str is not a valid pointer. EINVAL | if the input argument is not a valid pointer. |
ssize_t copyfile | ( | const char * | src, |
const char * | dst, | ||
int | len, | ||
int | opt | ||
) |
Copy a file to another.
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. |
opt | An option mask of LITE_FOPT_COPYFILE_SYM, LITE_FOPT_KEEP_MTIME |
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.
The opt field replaces the sym argument in previous releases and works as follows. To maintain backwards compatibility with sym the LITE_FOPT_COPYFILE_SYM has a value of 1
. Supported option flags are:
EISDIR | if src is a directory, since copyfile() is not recursive. |
int dir | ( | const char * | dir, |
const char * | type, | ||
int(*)(const char *file) | filter, | ||
char *** | list, | ||
int | strip | ||
) |
List all files of a certain type in the given directory.
dir | Base directory for dir operation. |
type | File type suffix, e.g. ".cfg". |
filter | Optional file name filter. |
list | Pointer to an array of file names. |
strip | Flag, if set dir() strips the file type. |
This function returns a list of files, matching the type suffix, in the given directory dir.
The list argument is a pointer to where to store the dynamically allocated list of file names. This list should be free'd by first calling free() on each file name and then on the list itself.
If filter is not NULL
it will be called for each file found. If filter returns non-zero the file argument is included in the resulting list. If filter returns zero for given file it is discarded. If the strip flag is set the resulting list of files has their file type stripped, including the dot. So a match "config0.cfg" would be returned as "config0".
int fcopyfile | ( | FILE * | src, |
FILE * | dst | ||
) |
Copy between FILE *fp.
src | Source FILE. |
dst | Destination FILE. |
int fexist | ( | const char * | file | ) |
Check if a file exists in the file system.
file | File to look for, with full path. |
TRUE(1)
if the file exists, otherwise FALSE(0)
. int fgetint | ( | const char * | file, |
const char * | sep, | ||
const char * | key | ||
) |
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().
int int fisdir | ( | const char * | path | ) |
Check if a path exists and is a directory.
path | Path to file or directory |
TRUE(1)
if path
exists and is a directory, otherwise FALSE(0)
. int char* fparseln | ( | FILE * | fp, |
size_t * | size, | ||
size_t * | lineno, | ||
const char | str[3], | ||
int | flags | ||
) |
Read a line from a file parsing continuations and trailing newlines.
fp | FILE pointer to read from |
size | The resulting length of the string, unused if NULL |
lineno | Incremented with number of lines read, unused if NULL |
str | Characters to look for, escape character, continuation, and comment |
flags | FPARSELN_UNESCCOMM, FPARSELN_UNESCCONT, FPARSELN_UNESCESC, FPARSELN_UNESCREST, FPARSELN_UNESCALL |
This function reads a line from a file, parsing continuations ending in '\' and eliminating trailing newlines, or comments starting with the comment char '#'.
If size is not NULL
, the resulting length of the returned string is stored in size.
If lineno is not NULL
, it is incremented for each actual line read from fp.
NULL
on EOF or error. ssize_t fsendfile | ( | FILE * | src, |
FILE * | dst, | ||
size_t | len | ||
) |
Copy data between file streams.
src | Source stream |
dst | Destination stream |
len | Number of bytes to copy |
The dst
argument 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() copies until EOF
is seen on src.
int ifconfig | ( | const char * | ifname, |
const char * | addr, | ||
const char * | mask, | ||
int | up | ||
) |
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 |
void lfclose | ( | lfile_t * | lf | ) |
Close a parser context.
lf | Pointer to lfile_t parser context from lfopen() |
int lfgetint | ( | lfile_t * | lf, |
const char * | key | ||
) |
Same as lfgetkey() but returns an integer.
lf | Pointer to lfile_t parser 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.
char* lfgetkey | ( | lfile_t * | lf, |
const char * | key | ||
) |
Find key in file.
lf | Pointer to lfile_t parser 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.
NULL
if not found. lfile_t* lfopen | ( | const char * | file, |
const char * | sep | ||
) |
Open file and return parsing context.
file | File to parse |
sep | Separator(s) to use in lftok() |
NULL
on error. char* lftok | ( | lfile_t * | lf | ) |
int makepath | ( | const char * | dir | ) |
Create all components of the specified directory.
dir | Directory to create. |
EINVAL | on bad argument, or |
ENOMEM | when it fails allocating temporary memory. |
For other error codes see the mkdir(2) syscall description.
int int mkpath | ( | const char * | dir, |
mode_t | mode | ||
) |
makepath() but takes a mode_t argument.
dir | Directory to created, relative or absolute |
mode | A &mode_t mode to create dir with |
int movefile | ( | const char * | src, |
const char * | dst | ||
) |
Move a file to another location.
src | Source file. |
dst | Target file, or location. |
This is a C implementation of the command line mv(1) utility. Usually the rename() API is sufficient, but not when moving across file system boundaries.
The src
argument must include the full path to the source file, whereas the dst
argument may only be a directory, in which case the same file name from src
is used.
FILE int pidfile | ( | const char * | basename | ) |
Create or update mtime of process PID file.
basename | Program name, or NULL , may start with '/' |
This function is intended to be used by UNIX daemons to save the PID of the main process responsible for handling signals. If basename
is NULL
the implicit __progname variable from the C-library is used. The basename
may also start with '/', in which case it is interpreted as the absolute path to the PID file.
pid_t pidfile_poll | ( | const char * | pidfile | ) |
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.
pidfile
, or zero on timeout. pid_t pidfile_read | ( | const char * | pidfile | ) |
Reads a PID value from a pidfile.
pidfile | File containing PID, usually in /var/run/PROCNAME .pid |
This function takes a pidfile
and returns the PID found therein.
pidfile
, -1 with errno set. If 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.EINVAL | on invalid pidfile , or |
ENOENT | when pidfile does not exist. |
int pidfile_signal | ( | const char * | pidfile, |
int | signal | ||
) |
Send signal to a PID and cleanup pidfile afterwards.
pidfile | File containing PID, usually in /var/run/PROCNAME .pid |
signal | Signal to send to PID found in pidfile . |
If signal
is any of SIGTERM
or SIGKILL
, or if kill(2) returns -1, the pidfile
is removed.
void progress | ( | int | percent, |
int | max_width | ||
) |
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_simple | ( | int | percent | ) |
Alternative progress bar on systems where progress() doesn't work.
percent | Start first call with this set to 0, end with 100 |
int readdf | ( | int * | value, |
const char * | fmt, | ||
... | |||
) |
Read integer value from a file composed from fmt and optional args.
value | Pointer to where to store read integer value. |
mode | An fopen() mode string, e.g. "w+". |
fmt | Formatted string to be composed into a pathname. |
int readllf | ( | long long * | value, |
const char * | fmt, | ||
... | |||
) |
Read 64-bit integer value from a file composed from fmt and optional args.
value | Pointer to where to store read 64-bit integer value. |
mode | An fopen() mode string, e.g. "w+". |
fmt | Formatted string to be composed into a pathname. |
char* readsnf | ( | char * | line, |
size_t | len, | ||
const char * | fmt, | ||
... | |||
) |
Read first line from a file composed from fmt and optional args.
line | Pointer to line buffer. |
len | Size of line buffer. |
fmt | Formatted string to be composed into a pathname. |
line
read from the file, with any trailing 'NULL
. void* reallocarray | ( | void * | optr, |
size_t | nmemb, | ||
size_t | size | ||
) |
Similar to realloc() but for an array of items, like calloc()
optr | Pointer to old (current) array |
nmemb | Number of elements |
size | Size of each element, in bytes |
NULL
on error. int rsync | ( | char * | src, |
char * | dst, | ||
int | opt, | ||
int(*)(const char *file) | filter | ||
) |
Synchronize contents and optionally remove non-existing backups.
src | Source directory |
dst | Destination directory |
opt | An option mask of LITE_FOPT_RSYNC_DELETE, LITE_FOPT_KEEP_MTIME |
filter | Optional filtering function for source directory. |
This is a miniature implementation of the famous rsync for local use only. In fact, it is not even a true rsync since it copies all files from src
to dst
. The LITE_FOPT_RSYNC_DELETE opt
flag is useful for creating backups, when set all files removed from src since last backup are pruned from the destination (backup) directory.
The opt
parameter to rsync() is an option mask for the most common rsync(1) options. Previously this argument was called delete
and to maintain backwards compatibility the value 1 is reserved:
LITE_FOPT_RSYNC_DELETE: Prune files from dst
that no longer exist in src
. LITE_FOPT_KEEP_MTIME: Preserve modification time
The filter callback, filter
, if provided, is used to determine what files to include from the source directory when backing up. If a file is to be skipped the callback should simply return zero.
Returns: POSIX OK(0), or non-zero with errno set on error.
int runbg | ( | char *const | cmd[], |
int | delay | ||
) |
Run command in the background.
cmd | NULL terminated list of command and optional arguments |
delay | Microseconds after fork() to wait before calling cmd |
This function forks to run the given command cmd
in the background. To ensure there are no lingering zombies the function actuall forks twice, and also calls setsid(), before it calls usleep() with the delay
argument. The command cmd
is handed over to execvp().
Since it runs in the background it is not possible to get the return code of the command.
int telnet_close | ( | sdbuf_t * | ctx | ) |
Close a telnet session previously opened with telnet_open()
ctx | An sdbuf_t socket buffer context |
int telnet_expect | ( | sdbuf_t * | ctx, |
char * | script[], | ||
FILE * | output | ||
) |
Poor man's telnet expect.
ctx | Telnet session context from telnet_open() |
script | NULL terminated list of expect and response strings |
output | Optional output from session |
Issues script
sequence on telnet session specified in ctx
, with optional output
from session.
The script
consists of strings of expect and response pairs. For example, expect "ogin: " followed by response "root\n", expect "assword: "with response "secret\n", concluded by NULL
.
int sdbuf_t* telnet_open | ( | int | addr, |
short | port | ||
) |
Open telnet connection to addr:port and connect.
addr | Integer encoded IPv4 address in network byte order |
port | Internet port number in network byte order |
int telnet_session | ( | int | addr, |
short | port, | ||
char * | script[], | ||
FILE * | output | ||
) |
Very simple expect-like implementation for telnet.
addr | Integer encoded IPv4 address, in network byte order, use htonl(). |
port | Internet port to connect to, in network byte order, use htons(). |
script | Expect like script of paired 'expect', 'response' strings. |
output | A FILE pointer to a tempfile() for output from the last command. |
This is a very simple expect-like implementation for querying and operating daemons remotely over telnet.
The script
is a query-response type of list of strings leading up to a final command, which output is then written to the given output
file.
FILE int FILE* tempfile | ( | void | ) |
A secure tmpfile() replacement.
This is the secure replacement for tmpfile() that does not exist in GLIBC. It uses the Linux specific O_TMPFILE
and O_EXCL
to hide the filename. When the FILE
is fclose()'ed, the file contents is lost. The file is hidden in the _PATH_TMP
("/tmp") directory in the system.
This function requires Linux 3.11, or later, due to O_TMPFILE
. Not all file systems support hidden inodes, in which case this function defaults to call tmpfile() as a fallback.
FILE
pointer, or NULL
on error. FILE* vfopenf | ( | const char * | mode, |
const char * | fmt, | ||
va_list | ap | ||
) |
int char* vreadsnf | ( | char * | line, |
size_t | len, | ||
const char * | fmt, | ||
va_list | ap | ||
) |
int int char* which | ( | const char * | cmd | ) |
Like which(1), or command -v foo
cmd | Command to look for in $PATH |
NULL
. int whichp | ( | const char * | cmd | ) |
Predicate variant of which()
cmd | Command to look for in $PATH |
TRUE(1)
or FALSE(0)
if cmd
exists in $PATH. int writedf | ( | int | value, |
const char * | mode, | ||
const char * | fmt, | ||
... | |||
) |
Write integer value to a file composed from fmt and optional args.
value | Integer value to write. |
mode | An fopen() mode string, e.g. "w+". |
fmt | Formatted string to be composed into a pathname. |
int writellf | ( | long long | value, |
const char * | mode, | ||
const char * | fmt, | ||
... | |||
) |
Write 64-bit integer value to a file composed from fmt and optional args.
value | 64-bit integer value to write. |
mode | An fopen() mode string, e.g. "w+". |
fmt | Formatted string to be composed into a pathname. |
int writesf | ( | const char * | str, |
const char * | mode, | ||
const char * | fmt, | ||
... | |||
) |
Write a string buffer to a file composed from fmt and optional args.
str | Pointer to string buffer, may be multiple lines. |
mode | An fopen() mode string, e.g. "w+". |
fmt | Formatted string to be composed into a pathname. |