Home2L - C/C++ API  v1.2-2-ga4fe (2023-04-15)
Smart Tools for a Private Home
Classes | Macros | Typedefs | Functions | Variables
base.H File Reference
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include <limits.h>
#include <unistd.h>
#include <signal.h>
#include <pthread.h>
#include <regex.h>
#include <stdarg.h>
#include <config.H>
Include dependency graph for base.H:
This graph shows which files directly or indirectly include this file:

Go to the source code of this file.

Classes

class  CString
 Dynamically allocated string. More...
 
class  CSplitString
 Factory class to split a string into substrings. More...
 
class  CRegex
 Factory class for regular expression matching. More...
 
class  CListRaw
 Raw list (base class for other list variants). More...
 
class  CList< T >
 Dynamic list. More...
 
class  CListCompact< T >
 Compact list. More...
 
class  CListRef< T >
 Reference list. More...
 
class  CDictRaw
 Raw dictionary (base class for other dictionary variants). More...
 
class  CDict< T >
 Dictionary. More...
 
class  CDictCompact< T >
 Compact dictionary. More...
 
class  CDictRef< T >
 Dictionary of references. More...
 
class  CKeySet
 Set of strings (keys). More...
 
class  CTimer
 Timer class. More...
 
class  CThread
 Class to wrap (POSIX) threads. More...
 
class  CMutex
 Class to wrap (POSIX) mutex objects. More...
 
class  CCond
 Class to wrap (POSIX) condition variables. More...
 
class  CSleeper
 Class allowing to sleep until one out of multiple i/o operations becomes possible. More...
 
class  CShell
 Abstract base class for shells that can execute system commands. More...
 
class  CShellBare
 Normal shell: Commands are executed individually. More...
 
class  CShellSession
 Session shell: Multiple commands are executed through one shell. More...
 
class  CServiceKeeper
 Service keeper: Helper class to keep an unreliable service running. More...
 

Macros

#define MIN(A, B)   ((A) < (B) ? (A) : (B))
 Typeless min-operator.
 
#define MAX(A, B)   ((A) > (B) ? (A) : (B))
 Typeless max-operator.
 
#define STR(X)   #X
 Stringify macro.
 
#define OFFSET(type, field)   ((unsigned) &(((type *) 0)->field))
 Byte offset of a field in struct or class.
 
#define ENTRIES(ARRAY)   ((int) (sizeof (ARRAY) / sizeof (ARRAY[0])))
 Number of entries of a statically declared constant array.
 
#define CLEAR(X)   bzero (&(X), sizeof (X))
 Set variable/object 'X' to all-zero.
 
#define DEBUG(LEVEL, MSG)   do { if (envDebug >= LEVEL) { LogPara ("DEBUG-" #LEVEL, __FILE__, __LINE__); LogPrintf (MSG); } } while (0)
 Print a debug message. This is only effective if the tool was compiled with WITH_DEBUG == 1 and the configuration parameter 'debug' is set to a value > 0. More...
 
#define DEBUGF(LEVEL, FMT)   do { if (envDebug >= LEVEL) { LogPara ("DEBUG-" #LEVEL, __FILE__, __LINE__); LogPrintf FMT; } } while (0)
 Print a formatted debug message. The argument must contain a parantheses with arguments, which will then be passed to a printf() function variant. For example: DEBUGF(("Current value is %i", my_value))
 
#define INFO(MSG)   do { LogPara ("INFO", __FILE__, __LINE__); LogPrintf (MSG); } while (0)
 Print a debug message to the console.
 
#define INFOF(FMT)   do { LogPara ("INFO", __FILE__, __LINE__); LogPrintf FMT; } while (0)
 Print a formatted info message.
 
#define WARNING(MSG)   do { LogPara ("WARNING", __FILE__, __LINE__); LogPrintf (MSG); } while (0)
 Print a warning message to the console.
 
#define WARNINGF(FMT)   do { LogPara ("WARNING", __FILE__, __LINE__); LogPrintf FMT; } while (0)
 Print a formatted warning message.
 
#define SECURITY(MSG)   do { LogPara ("SECURITY", __FILE__, __LINE__); LogPrintf (MSG); } while (0)
 Print a security-related warning to the console. These are warnings an adminstrator should regularly check out for, since they may be caused by an attack.
 
#define SECURITYF(FMT)   do { LogPara ("SECURITY", __FILE__, __LINE__); LogPrintf FMT; } while (0)
 Print a formatted security-related warning.
 
#define ERROR(MSG)   do { LogPara ("ERROR", __FILE__, __LINE__); LogPrintf (MSG); _exit (3); } while (0)
 Print an error message to the console and quit the application.
 
#define ERRORF(FMT)   do { LogPara ("ERROR", __FILE__, __LINE__); LogPrintf FMT; _exit (3); } while (0)
 Print a formatted error message to the console and quit the application.
 
#define ABORT(MSG)   do { LogPara ("ERROR", __FILE__, __LINE__); LogPrintf (MSG); abort (); } while (0)
 Print an error message to the console and abort the application. Unlike ERROR, this uses the abort() system call, which may generate a core dump to be used for debugging.
 
#define ABORTF(FMT)   do { LogPara ("ERROR", __FILE__, __LINE__); LogPrintf FMT; abort (); } while (0)
 Print a formatted error message to the console and abort the application.
 
#define ASSERT(COND)   do { if (!(COND)) { LogPara ("ERROR", __FILE__, __LINE__); LogPrintf ("Assertion failed"); LogStack (); abort (); } } while (0)
 Check a condition and abort the application if not true.
 
#define ASSERTM(COND, MSG)   do { if (!(COND)) { LogPara ("ERROR", __FILE__, __LINE__); LogPrintf ("Assertion failed: %s", MSG); LogStack (); abort (); } } while (0)
 Check a condition and, if not true, abort the application with a message.
 
#define ASSERTF(COND, FMT)   do { if (!(COND)) { LogPara ("ERROR", __FILE__, __LINE__); LogPrintf ("Assertion failed - explanation follows."); LogPrintf FMT; abort (); LogStack (); abort (); } } while (0)
 Check a condition and, if not true, abort the application with a message.
 
#define ASSERT_WARN(COND)   do { if (!(COND)) WARNING("Weak assertion failed"); } while (0)
 Check a condition and emit a warning if not true.
 
#define _(STR)   gettext(STR)
 GNU gettext-compliant macro for translating strings.
 
#define N_(STR)   gettext_noop(STR)
 GNU gettext-compliant macro for translating strings.
 
#define WHITESPACE   " \t\n\r\v"
 white space characters according to 'man 3 isspace'
 
#define TTS   (GetThreadTempString ())
 Get the thread-local temporary string (TTS) of the calling thread (short version).
 
Atomic read and write operations ...

(presently GCC-specific)

#define ATOMIC_READ(OBJ)   __atomic_load_n (&(OBJ), __ATOMIC_RELAXED)
 
#define ATOMIC_WRITE(OBJ, VAL)   __atomic_store_n (&(OBJ), VAL, __ATOMIC_RELAXED)
 
#define ATOMIC_INC(OBJ, N)   __atomic_exchange_n (&(OBJ), (OBJ) + (N), __ATOMIC_RELAXED)
 
C-style Allocation ...
#define MALLOC(T, N)   (T*) malloc (sizeof (T) * (N))
 Allocate an array of N objects of type T (type-safe)
 
#define REALLOC(T, P, N)   (T*) realloc (P, sizeof (T) * (N))
 Reallocate an array of N objects of type T (type-safe)
 
#define SETP(P, X)   { if (P) free (P); P = (X); }
 Replace P with a new object/array, eventually free'ing the old one.
 
#define FREEP(P)   SETP(P, NULL)
 Free object/array P and set P = NULL, but only if P was != NULL.
 
C++-style Allocation ...
#define SETO(O, X)   { if (O) delete O; O = (X); }
 Replace O with a new object, eventually deleting the old one.
 
#define FREEO(O)   SETO(O, NULL)
 Free object O, but only if O != NULL
 
#define SETA(A, X)   { if (A) delete [] A; A = (X); }
 Replace A with a new array, eventually deleting the old one.
 
#define FREEA(A)   SETA(A, NULL)
 Free array A, but only if A != NULL
 

Typedefs

typedef void FLogCbMessage(const char *title, const char *msg)
 Callback to display a message box using OS mechanisms. This is mainly used if the program is aborted using an ERROR... or ABORT... macro and presently only supported on Android.
 
typedef void FLogCbToast(const char *msg, bool showLonger)
 Callback to display a short info popup using OS mechanisms. This is used if for messages printed using an INFO... macro, where the message is preceeded by "-t- " (short toast) or "-T- " (long toast). Toasts are presently only supported on Android.
 
typedef void FTimerCallback(class CTimer *timer, void *data)
 Function type for timer callbacks. More...
 
typedef void * FThreadRoutine(void *data)
 Function type for thread routines. More...
 

Functions

void LogToSyslog (const char *instanceName=NULL)
 Redirect logging to syslog from now; instance name must be passed if this is called before EnvInit()
 
void LogStack ()
 Log a stack trace (requires linker flag '-rdynamic' to print function names)
 
static uint32_t VersionCompose (uint8_t major, uint8_t minor, uint16_t revision, bool dirty=false)
 
static int VersionMajor (uint32_t ver)
 Get the major component of the version.
 
static int VersionMinor (uint32_t ver)
 Get the minor component of the version.
 
static int VersionRevision (uint32_t ver)
 Get the revision component of the version.
 
static bool VersionDirty (uint32_t ver)
 Get the "dirty" component of the version.
 
uint32_t VersionFromStr (const char *str)
 Get a numeric representation of the version string. On syntax error, a warning is logged and 0 is returned.
 
const char * VersionToStr (class CString *ret, uint32_t ver)
 Get a string representation of the version. This may be shorter than an eventual original string passed to VersionFromStr(), i.e. an eventual git ID is missing.
 
static const char * VersionGetOwnAsStr ()
 Get my own build version as a string.
 
uint32_t VersionGetOwn ()
 Get my own build version.
 
void LangTranslateNumber (char *str)
 Adapt numeric string by replacing all '.' by the locale's decimal point.
 
class CStringGetThreadTempString ()
 Get the thread-local temporary string (TTS) of the calling thread. More...
 
const char * StringF (class CString *ret, const char *fmt,...)
 Return 'ret->Get ()'.
 
bool BoolFromString (const char *str, bool *ret)
 Convert a string to a Boolean value. On success, '*ret' is set accordingly and 'true' is returned. On failure, 'false' is returned and '*ret' remains unchanged.
 
bool ValidBoolFromString (const char *str, bool defaultVal)
 Convert a string to a Boolean value. On failure, 'defaultVal' is returned.
 
bool IntFromString (const char *str, int *ret, int radix=0)
 Convert a string to an integer using 'strtol'. On success, '*ret' is set accordingly and 'true' is returned. On failure, 'false' is returned and '*ret' remains unchanged. If 'radix == 0', it is auto-detected from the string (16 with a preceeding "0x", 10 otherwise).
 
int ValidIntFromString (const char *str, int defaultVal, int radix=0)
 Convert a string to an integer. On failure, 'defaultVal' is returned.
 
bool UnsignedFromString (const char *str, unsigned *ret, int radix=0)
 Convert a string to an unsigned integer using 'strtoul'. On success, '*ret' is set accordingly and 'true' is returned. On failure, 'false' is returned and '*ret' remains unchanged. If 'radix == 0', it is auto-detected from the string (16 with a preceeding "0x", 10 otherwise).
 
unsigned ValidUnsignedFromString (const char *str, unsigned defaultVal, int radix=0)
 Convert a string to an unsigned integer. On failure, 'defaultVal' is returned.
 
bool FloatFromString (const char *str, float *ret)
 Convert a string to a floating-point value using 'strtof'. On success, '*ret' is set accordingly and 'true' is returned. On failure, 'false' is returned and '*ret' remains unchanged.
 
float ValidFloatFromString (const char *str, float defaultVal)
 Convert a string to a float value. On failure, 'defaultVal' is returned.
 
void StringStrip (char *str, const char *sepChars=WHITESPACE)
 Remove seperator (whitespace) characters at the beginning and end of the string.
 
void StringTruncate (char *str, const char *sepChars=WHITESPACE, bool after=false)
 Cut away anything from or after the first occurence of any of the given seperator characters.
 
void StringSplit (const char *str, int *retArgc, char ***retArgv, int maxArgc=INT_MAX, const char *sepChars=NULL, char **retRef=NULL)
 Split a string into (whitespace-)separated arguments. More...
 
void StringSplitFree (char ***argv)
 Free memory allocated by StringSplit(). More...
 
bool CharIsWhiteSpace (char c)
 Indicate whether the given character is white space (see WHITSPACE).
 
void Sleep (TTicks mSecs)
 Suspend for mSecs milliseconds using nanosleep().
 
Enhanced file and directory operations ...
size_t Write (int fd, const void *buf, size_t count)
 Similar to POSIX write(), but writes all 'count' bytes as possible. More...
 
size_t Read (int fd, void *buf, size_t count)
 Similar to POSIX read(), but reads all 'count' bytes as possible. More...
 
bool MakeDir (const char *relOrAbsPath, bool setHome2lGroup=true)
 Create a directory (and all its parents as necessary). More...
 
bool UnlinkTree (const char *relOrAbsPath, const char *skipPattern=NULL)
 Unlink (remove) a directory with all its decendants. More...
 
bool ReadDir (const char *relOrAbsPath, class CKeySet *ret)
 Read a directory into a CKeySet object. More...
 
Path handling ...
void PathNormalize (char *str)
 Treat string as a (full) pathname and normalize it.
 
void PathRemoveTrailingSlashes (char *str)
 Treat string as a (full) pathname and remove trailing slash(es)
 
const char * PathLeaf (const char *str)
 Get leaf component of a path.
 
const char * GetAbsPath (class CString *ret, const char *relOrAbsPath, const char *defaultPath)
 Get absolute path. More...
 
Transcoding ...
const char * ToUtf8 (class CString *ret, const char *iso8859str)
 Transcode an ISO8859-coded string to UTF-8. Result is valid until next call of this function.
 
const char * ToIso8859 (class CString *ret, const char *str)
 Transcode an ISO8859-coded string to UTF-8. Result is valid until next call of this function.
 
Conversion between ticks and date/time ...
TTicks TicksOfDate (int dy, int dm, int dd)
 
TTicks TicksOfDate (TDate d)
 
TTicks TicksOfTime (int th, int tm, int ts)
 
TTicks TicksOfTime (TTime t)
 
TDate DateOfTicks (TTicks t)
 
TTime TimeOfTicks (TTicks t)
 
TTicks DateTimeToTicks (TDate d, TTime t, struct tm *retTm=NULL)
 
TTicks DateTimeToTicksUTC (TDate d, TTime t, struct tm *retTm=NULL)
 
void TicksToDateTime (TTicks t, TDate *retDate, TTime *retTime, struct tm *retTm=NULL)
 
void TicksToDateTimeUTC (TTicks t, TDate *retDate, TTime *retTime, struct tm *retTm=NULL)
 
Date/time: Current time...
static void DateTimeNow (TDate *d, TTime *t)
 Retrieve current date and time (both pointers may be NULL)
 
TDate Today ()
 
TTicks TicksToday ()
 
Date/time: Arithmetics...
TDate DateIncByDays (TDate date, int dDays)
 
int DateDiffByDays (TDate d1, TDate d0)
 
TDate DateIncByMonths (TDate date, int dMon)
 
static TDate DateFirstOfMonth (TDate date)
 
int GetWeekDay (TDate date)
 
int GetCalWeek (TDate date)
 
Date/time: Written month and weekday names ...
const char * MonthName (int dm)
 Get textual name. 1 = "January", ..., 12 = "December".
 
const char * MonthNameShort (int dm)
 Get textual shortname. 1 = "Jan", ..., 12 = "Dec".
 
const char * DayName (int wd)
 Get textual name. 0 = "Monday", ..., 6 = "Sunday".
 
const char * DayNameShort (int wd)
 Get textual name. 0 = "Mon", ..., 6 = "Sun".
 
Control functions (for the main program) ...
bool TimerIterate ()
 Returns false if nothing was done.
 
TTicks TimerGetDelay ()
 Returns number of milliseconds until next call to TimerIterate() is necessary, or -1 if no timer is pending.
 
void TimerStart ()
 Start TimerRun() in a background thread, which is to be stopped using TimerStop(). All timer functions are then run from the same, namely that background thread.
 
int TimerRun (bool catchSignals=true)
 Perform an endless loop calling timers until TimerStop() is called. More...
 
void TimerStop ()
 Request TimerRun() to return at next occasion (can be called from any thread). If a dedicated timer thread was started, this is joined, too.
 

Variables

int envDebug
 Debug level (read-only; may also be mapped to a constant macro).
 

Ticks ...

#define ASAP   ((TTicks) 0)
 Special value that may represent "as soon as possible" for absolute or monotonic times.
 
#define NEVER   ((TTicks) INT64_MIN)
 Special value that may represent "never" for absolute or monotonic times. Other application-specific special values may be defined as (NEVER + 1), (NEVER + 2), ... . The actual value is and will always be < 0.
 
#define TICKS_FROM_SECONDS(S)   (((TTicks) (S)) * 1000)
 Convert seconds (integer!) to ticks.
 
#define SECONDS_FROM_TICKS(T)   (((TTicks) (T) + 500) / 1000)
 Convert ticks to seconds.
 
#define TICKS_FROM_MILLIS(MS)   ((TTicks) (MS))
 Convert milliseconds (integer!) to ticks.
 
#define MILLIS_FROM_TICKS(T)   ((int) (T))
 Convert ticks to milliseconds.
 
typedef int64_t TTicks
 Time value (relative, absolute, or monotonic).
 
TTicks TicksNow ()
 Get the current absolute time in milliseconds. This function never returns 0 or a negative value.
 
TTicks TicksNowMonotonic ()
 Get the current monotonic time in milliseconds. This function never returns 0 or a negative value.
 
TTicks TicksAbsFromMonotic (TTicks tm)
 Get the approximated absolute (real) time for a monotonic time. Arguments <= 0 are returned unmodified.
 
TTicks TicksMonotonicFromAbs (TTicks ta)
 Get the approximated monotonic time for an absolute time . Arguments <= 0 are returned unmodified.
 
const char * TicksAbsToString (CString *ret, TTicks ticks, int fracDigits=INT_MAX, bool precise=false)
 Get a string of the form "YYYY-MM-DD-hhmmss[.<millis>]" in local time. More...
 
const char * TicksRelToString (CString *ret, TTicks ticks)
 Get a string of the form "<integer>[<unit>]" for a relative time. More...
 
bool TicksFromString (const char *str, TTicks *ret, bool absolute)
 Convert a string to a relative or absolute ticks value. More...
 
static bool TicksAbsFromString (const char *str, TTicks *ret)
 Convert a string to an absolute ticks value. See TicksFromString() for supported string formats.
 
static bool TicksRelFromString (const char *str, TTicks *ret)
 Convert a string to a relative ticks value. See TicksFromString() for supported string formats.
 
void TicksToStructTimeval (TTicks t, struct timeval *retTv)
 

Date/time: Types ...

#define DATE_OF(Y, M, D)   ((TDate) (((Y) << 9) | ((M) << 5) | (D)))
 
#define YEAR_OF(DT)   ((int) (DT) >> 9)
 
#define MONTH_OF(DT)   (((int) (DT) >> 5) & 0xf)
 
#define DAY_OF(DT)   ((int) (DT) & 0x1f)
 
#define TIME_OF(H, M, S)   ((TTime) ((H) * 3600 + (M) * 60 + (S)))
 
#define HOURS_OF(T)   ((int) (T) / 3600)
 
#define MINUTES_OF(T)   ((int) (T) / 60)
 
#define HOUR_OF(T)   HOURS_OF(T)
 
#define MINUTE_OF(T)   (MINUTES_OF(T) % 60)
 
#define SECOND_OF(T)   ((int) (T) % 60)
 
typedef int TDate
 
typedef int TTime