74#define MIN(A, B) ((A) < (B) ? (A) : (B))
75#define MAX(A, B) ((A) > (B) ? (A) : (B))
80#define OFFSET(type, field) ((unsigned) &(((type *) 0)->field))
83#define ENTRIES(ARRAY) ((int) (sizeof (ARRAY) / sizeof (ARRAY[0])))
86#define CLEAR(X) bzero (&(X), sizeof (X))
93#define ATOMIC_READ(OBJ) __atomic_load_n (&(OBJ), __ATOMIC_RELAXED)
94#define ATOMIC_WRITE(OBJ, VAL) __atomic_store_n (&(OBJ), VAL, __ATOMIC_RELAXED)
95#define ATOMIC_INC(OBJ, N) __atomic_exchange_n (&(OBJ), (OBJ) + (N), __ATOMIC_RELAXED)
101size_t Write (
int fd,
const void *buf,
size_t count);
111size_t Read (
int fd,
void *buf,
size_t count);
122bool MakeDir (
const char *relOrAbsPath,
bool setHome2lGroup =
true);
132bool UnlinkTree (
const char *relOrAbsPath,
const char *skipPattern = NULL);
179typedef void FLogCbMessage (
const char *title,
const char *msg);
193bool LoggingToSyslog ();
199static inline void LogClose () {}
200static inline bool LoggingToSyslog () {
return true; }
205void LogPara (
const char *_logHead,
const char* _logFile,
int _logLine);
206void LogPrintf (
const char *format, ...);
210#define DEBUG(LEVEL, MSG) do { if (envDebug >= LEVEL) { LogPara ("DEBUG-" #LEVEL, __FILE__, __LINE__); LogPrintf (MSG); } } while (0)
221#define DEBUGF(LEVEL, FMT) do { if (envDebug >= LEVEL) { LogPara ("DEBUG-" #LEVEL, __FILE__, __LINE__); LogPrintf FMT; } } while (0)
227#define DEBUG(LEVEL, MSG) do {} while (0)
228#define DEBUGF(LEVEL, FMT) do {} while (0)
231#define INFO(MSG) do { LogPara ("INFO", __FILE__, __LINE__); LogPrintf (MSG); } while (0)
233#define INFOF(FMT) do { LogPara ("INFO", __FILE__, __LINE__); LogPrintf FMT; } while (0)
236#define WARNING(MSG) do { LogPara ("WARNING", __FILE__, __LINE__); LogPrintf (MSG); } while (0)
238#define WARNINGF(FMT) do { LogPara ("WARNING", __FILE__, __LINE__); LogPrintf FMT; } while (0)
241#define SECURITY(MSG) do { LogPara ("SECURITY", __FILE__, __LINE__); LogPrintf (MSG); } while (0)
245#define SECURITYF(FMT) do { LogPara ("SECURITY", __FILE__, __LINE__); LogPrintf FMT; } while (0)
248#define ERROR(MSG) do { LogPara ("ERROR", __FILE__, __LINE__); LogPrintf (MSG); _exit (3); } while (0)
250#define ERRORF(FMT) do { LogPara ("ERROR", __FILE__, __LINE__); LogPrintf FMT; _exit (3); } while (0)
253#define ABORT(MSG) do { LogPara ("ERROR", __FILE__, __LINE__); LogPrintf (MSG); abort (); } while (0)
257#define ABORTF(FMT) do { LogPara ("ERROR", __FILE__, __LINE__); LogPrintf FMT; abort (); } while (0)
260#define ASSERT(COND) do { if (!(COND)) { LogPara ("ERROR", __FILE__, __LINE__); LogPrintf ("Assertion failed"); LogStack (); abort (); } } while (0)
262#define ASSERTM(COND,MSG) do { if (!(COND)) { LogPara ("ERROR", __FILE__, __LINE__); LogPrintf ("Assertion failed: %s", MSG); LogStack (); abort (); } } while (0)
264#define ASSERTF(COND,FMT) do { if (!(COND)) { LogPara ("ERROR", __FILE__, __LINE__); LogPrintf ("Assertion failed - explanation follows."); LogPrintf FMT; abort (); LogStack (); abort (); } } while (0)
267#define ASSERT_WARN(COND) do { if (!(COND)) WARNING("Weak assertion failed"); } while (0)
276#if __cplusplus >= 201103L
277#define STATIC_ASSERT(COND) static_assert (COND, "please check!")
282#define STATIC_ASSERT(COND) static inline void build_assert_##__LINE__() { (void) sizeof(char[(COND) - 1]); }
304#define MALLOC(T, N) (T*) malloc (sizeof (T) * (N))
306#define REALLOC(T, P, N) (T*) realloc (P, sizeof (T) * (N))
308#define SETP(P, X) { if (P) free (P); P = (X); }
310#define FREEP(P) SETP(P, NULL)
317#define SETO(O, X) { if (O) delete O; O = (X); }
319#define FREEO(O) SETO(O, NULL)
322#define SETA(A, X) { if (A) delete [] A; A = (X); }
324#define FREEA(A) SETA(A, NULL)
349static inline uint32_t
VersionCompose (uint8_t major, uint8_t minor, uint16_t revision,
bool dirty =
false) {
355 return (((uint32_t) major) << 24) + (((uint32_t) minor) << 16) + (((uint32_t) revision) << 1) + ((uint32_t) dirty);
357static inline int VersionMajor (uint32_t ver) {
return (
int) (ver >> 24); }
359static inline int VersionMinor (uint32_t ver) {
return (
int) ((ver >> 16) & 0xff); }
361static inline int VersionRevision (uint32_t ver) {
return (
int) ((ver >> 1) & 0x7fff); }
363static inline bool VersionDirty (uint32_t ver) {
return (ver & 1) == 1; }
401#define USE_GNU_GETTEXT 0
403#define USE_GNU_GETTEXT 0
414const char *LangGetText (
const char *msgId);
416#define gettext(STR) LangGetText (STR)
422void LangInit (
const char *localeDir,
const char *locale);
431#define _(STR) gettext(STR)
432#define gettext_noop(STR) STR
433#define N_(STR) gettext_noop(STR)
481#define WHITESPACE " \t\n\r\v"
502#define TTS (GetThreadTempString ())
514bool IntFromString (
const char *str,
int *ret,
int radix = 0);
537void StringSplit (
const char *str,
int *retArgc,
char ***retArgv,
int maxArgc = INT_MAX,
const char *sepChars = NULL,
char **retRef = NULL);
570const char *
PathLeaf (
const char *str);
572const char *
GetAbsPath (
class CString *ret,
const char *relOrAbsPath,
const char *defaultPath);
587const char *
ToUtf8 (
class CString *ret,
const char *iso8859str);
611 CString (
const char *str,
int maxLen = INT_MAX) { size = 0; Set (str, maxLen); }
612 ~CString () {
if (size) free (ptr); }
617 void Set (
char c) { Clear (); Insert (0, c); }
618 void Set (
const char *str,
int maxLen = INT_MAX);
620 void SetF (
const char *fmt, ...);
622 void SetFV (
const char *fmt, va_list ap);
625 void SetC (
const char *_ptr);
633 void SetO (
const char *_ptr);
659 char *
Get ()
const {
return ptr; }
660 int Len () {
return strlen (ptr); }
666 void Del (
int n0,
int dn = INT_MAX);
668 void Insert (
int n0,
int dn,
int *retInsPos = NULL);
669 void Insert (
int n0,
char c);
670 void Insert (
int n0,
const char *str,
int maxLen = INT_MAX);
671 void InsertF (
int n0,
const char *fmt, ...);
672 void InsertFV (
int n0,
const char *fmt, va_list ap);
674 void Append (
char c) { Insert (INT_MAX, c); }
675 void Append (
const char *str,
int maxLen = INT_MAX) { Insert (INT_MAX, str, maxLen); }
676 void AppendF (
const char *fmt, ...);
677 void AppendFV (
const char *fmt, va_list ap) { InsertFV (INT_MAX, fmt, ap); }
682 int Compare (
const char *str2);
684 void Strip (
const char *sepChars =
WHITESPACE);
685 void Truncate (
const char *sepChars =
WHITESPACE,
bool after =
false);
688 void Split (
int *retArgc,
char ***retArgv,
int maxArgc = INT_MAX,
const char *sepChars =
WHITESPACE) {
StringSplit (ptr, retArgc, retArgv, maxArgc, sepChars); }
696 void AppendEscaped (
const char *s,
const char *dontEscape = NULL);
724 void PathNormalize ();
725 void PathRemoveTrailingSlashes ();
727 void PathGo (
const char *where);
732 bool ReadFile (
const char *relOrAbsPath);
750 operator char * () {
return ptr; }
753 CString& operator = (
const char *str) { Set (str);
return *
this; }
754 char& operator [] (
int n) {
return n >= 0 ? ptr [n] : ptr [strlen (ptr) + n]; }
755 CString operator + (
const char *str);
756 CString& operator += (
char c) { Append (c);
return *
this; }
757 CString& operator += (
const char *str) { Append (str);
return *
this; }
759 bool operator < (
const char *str) {
return Compare (str) < 0; }
760 bool operator > (
const char *str) {
return Compare (str) > 0; }
761 bool operator <= (
const char *str) {
return Compare (str) <= 0; }
762 bool operator >= (
const char *str) {
return Compare (str) >= 0; }
763 bool operator == (
const char *str) {
return Compare (str) == 0; }
764 bool operator != (
const char *str) {
return Compare (str) != 0; }
771 void SetSize (
int _size);
772 void MakeWriteable () {
if (!size) SetSize (strlen (ptr) + 1); }
794 CSplitString (
const char *str,
int maxArgc = INT_MAX,
const char *sepChars = NULL) {
StringSplit (str, &argc, &argv, maxArgc, sepChars, &ref); }
801 void Set (
const char *str,
int maxArgc = INT_MAX,
const char *sepChars = NULL) {
Clear ();
StringSplit (str, &argc, &argv, maxArgc, sepChars, &ref); }
811 int Entries ()
const {
return argc; }
812 const char *
Get (
int idx)
const {
return argv[idx]; }
815 int GetOffset (
int argNo) {
return (argv && ref) ? argv[argNo] - ref : 0; }
817 int GetOffset (
const char *p) {
return ref ? (p - ref) : 0; }
840 CRegex () { reValid =
false; lastError = 0; }
843 bool SetPattern (
const char *pattern,
int cflags = REG_EXTENDED);
852 bool Match (
const char *s,
int eflags = 0,
size_t maxMatches = 0, regmatch_t *retMatchList = NULL);
864 bool IsValid () {
return reValid; }
865 const char *ErrorStr ();
891#define CONT_ALIGNMENT 4
892#define CONT_ALIGN(X) (((X) + CONT_ALIGNMENT - 1) & ~(CONT_ALIGNMENT - 1))
900template <
typename T>
const char *ToStr (
CString *ret, T *obj) {
return obj->ToStr (ret); }
903template <>
const char *ToStr<int> (
CString *ret,
int *obj);
922 int Entries ()
const {
return entries; }
928 void Clear () { SetEntries (0); }
936 virtual void Dump (
const char *name);
942 virtual void RecInit (
void *p);
945 virtual void RecClear (
void *p);
948 virtual void ValueInit (
void *p) {}
950 virtual void ValueClear (
void *p) {}
952 virtual void ValueSet (
void *p,
void *orig) {}
956 virtual const char *ValueToStr (
CString *ret,
void *p);
960 void SetEntries (
int _entries);
962 uint8_t *GetRecAdr (
int idx)
const {
return idx < 0 ? NULL : data + recSize * idx; }
964 uint8_t *GetValueAdr (
int idx)
const {
return idx < 0 ? NULL : data + recSize * idx + tagSize; }
966 void *GetValuePtr (
int idx)
const {
return idx < 0 ? NULL : * (
void **) (GetValueAdr (idx)); }
969 void Copy (
int idxDst,
int idxSrc);
970 void Swap (
void *rec0,
void *rec1);
972 void SetRaw (
int idx,
void *value);
975 void InsertRaw (
int idx,
void *value);
978 void *DisownRaw (
int idx);
984 int recSize, tagSize, entries, allocEntries;
1005 T *Get (
int idx) {
return (T *) GetValuePtr (idx); }
1006 T *operator [] (
int idx) {
return Get (idx); }
1014 void Set (
int idx, T *value) { SetRaw (idx, value); }
1017 void Insert (
int idx, T *value) { InsertRaw (idx, value); }
1020 void Append (T *value) { InsertRaw (INT_MAX, value); }
1023 T *
Disown (
int idx) {
return (T *) DisownRaw (idx); }
1028 virtual void ValueInit (
void *p) { * (T **) p = NULL; }
1029 virtual void ValueClear (
void *p) {
if (* (T**) p) {
delete * (T **) p; * (T **) p = NULL; } }
1030 virtual void ValueSet (
void *p,
void *orig) { ValueClear (p); * (T**) p = (T*) orig; }
1031 virtual const char *ValueToStr (
CString *ret,
void *p) { return ::ToStr<T> (ret, * (T**) p); }
1059 T *Get (
int idx) {
return (T *) GetValueAdr (idx); }
1060 T *operator [] (
int idx) {
return Get (idx); }
1066 void Set (
int idx, T *value) { SetRaw (idx, value); }
1069 void Insert (
int idx, T *value) { InsertRaw (idx, value); }
1072 void Append (T *value) { InsertRaw (INT_MAX, value); }
1078 virtual void ValueInit (
void *p) { memcpy (p, &emptyObj,
sizeof (emptyObj)); }
1079 virtual void ValueClear (
void *p) { ValueSet (p, &emptyObj); }
1080 virtual void ValueSet (
void *p,
void *orig) { * (T *) p = * (T *) orig; }
1081 virtual const char *ValueToStr (
CString *ret,
void *p) { return ::ToStr<T> (ret, (T*) p); }
1094 virtual void ValueClear (
void *p) { * (T **) p = NULL; }
1095 virtual void ValueSet (
void *p,
void *orig) { * (T**) p = (T*) orig; }
1103#define DICT_KEYSIZE CONT_ALIGN((int) sizeof (CString))
1113 CDictRaw (
int _valueSize):
CListRaw (_valueSize + DICT_KEYSIZE) { tagSize = DICT_KEYSIZE; }
1123 void Del (
const char *key) {
Del (
Find (key)); }
1129 const char *
GetKey (
int idx)
const {
return ((
CString *) GetRecAdr (idx))->Get (); }
1131 int Find (
const char *key,
int *retInsIdx = NULL);
1134 void PrefixSearch (
const char *key,
int *retIdx0,
int *retIdx1);
1143 virtual void Dump (
const char *name);
1147 virtual void RecInit (
void *p);
1148 virtual void RecClear (
void *p);
1150 void SetRaw (
int idx,
void *value) { CListRaw::SetRaw (idx, value); }
1151 int SetRaw (
const char *key,
void *value);
1173 T *Get (
int idx) {
return (T *) GetValuePtr (idx); }
1174 T *Get (
const char *key) {
return Get (
Find (key)); }
1175 T *operator [] (
int idx) {
return Get (idx); }
1176 T *operator [] (
const char *key) {
return Get (key); }
1184 int Set (
const char *key, T *value) {
return SetRaw (key, value); }
1187 void SetValue (
int idx, T *value) { SetRaw (idx, value); }
1193 T *
DisownValue (
int idx) {
return (T *) DisownRaw (idx); }
1208 virtual void ValueInit (
void *p) { * (T **) p = NULL; }
1209 virtual void ValueClear (
void *p) {
if (* (T**) p) {
delete * (T **) p; * (T **) p = NULL; } }
1210 virtual void ValueSet (
void *p,
void *orig) { ValueClear (p); * (T**) p = (T*) orig; }
1211 virtual const char *ValueToStr (
CString *ret,
void *p) { return ::ToStr<T> (ret, * (T**) p); }
1228 T *Get (
int idx) {
return (T *) GetValueAdr (idx); }
1229 T *Get (
const char *key) {
return Get (
Find (key)); }
1230 T *operator [] (
int idx) {
return Get (idx); }
1231 T *operator [] (
const char *key) {
return Get (key); }
1236 int Set (
const char *key, T *value) {
return SetRaw (key, value); }
1239 void SetValue (
int idx, T *value) { SetRaw (idx, value); }
1252 virtual void ValueInit (
void *p) { memcpy (p, (
void *) &emptyObj,
sizeof (emptyObj)); }
1253 virtual void ValueClear (
void *p) { ValueSet (p, (
void *) &emptyObj); }
1254 virtual void ValueSet (
void *p,
void *orig) { * (T *) p = * (T *) orig; }
1255 virtual const char *ValueToStr (
CString *ret,
void *p) { return ::ToStr<T> (ret, (T*) p); }
1268 virtual void ValueClear (
void *p) { * (T **) p = NULL; }
1269 virtual void ValueSet (
void *p,
void *orig) { * (T**) p = (T*) orig; }
1284 const char *operator [] (
int idx) {
return GetKey (idx); }
1289 int Set (
const char *key) {
return SetRaw (key, NULL); }
1301 virtual void Dump (
const char *name);
1353#define ASAP ((TTicks) 0)
1355#define NEVER ((TTicks) INT64_MIN)
1420void TicksToStructTimeval (
TTicks t,
struct timeval *retTv);
1422#define TICKS_FROM_SECONDS(S) (((TTicks) (S)) * 1000)
1423#define SECONDS_FROM_TICKS(T) (((TTicks) (T) + 500) / 1000)
1424#define TICKS_FROM_MILLIS(MS) ((TTicks) (MS))
1425#define MILLIS_FROM_TICKS(T) ((int) (T))
1435#define DATE_OF(Y,M,D) ((TDate) (((Y) << 9) | ((M) << 5) | (D)))
1436#define YEAR_OF(DT) ((int) (DT) >> 9)
1437#define MONTH_OF(DT) (((int) (DT) >> 5) & 0xf)
1438#define DAY_OF(DT) ((int) (DT) & 0x1f)
1443#define TIME_OF(H,M,S) ((TTime) ((H) * 3600 + (M) * 60 + (S)))
1444#define HOURS_OF(T) ((int) (T) / 3600)
1445#define MINUTES_OF(T) ((int) (T) / 60)
1446#define HOUR_OF(T) HOURS_OF(T)
1447#define MINUTE_OF(T) (MINUTES_OF(T) % 60)
1448#define SECOND_OF(T) ((int) (T) % 60)
1455TTicks TicksOfDate (
int dy,
int dm,
int dd);
1456TTicks TicksOfDate (TDate d);
1457TTicks TicksOfTime (
int th,
int tm,
int ts);
1458TTicks TicksOfTime (TTime t);
1460TDate DateOfTicks (
TTicks t);
1461TTime TimeOfTicks (
TTicks t);
1463TTicks DateTimeToTicks (TDate d, TTime t,
struct tm *retTm = NULL);
1465TTicks DateTimeToTicksUTC (TDate d, TTime t,
struct tm *retTm = NULL);
1467void TicksToDateTime (
TTicks t, TDate *retDate, TTime *retTime,
struct tm *retTm = NULL);
1468void TicksToDateTimeUTC (
TTicks t, TDate *retDate, TTime *retTime,
struct tm *retTm = NULL);
1474static inline void DateTimeNow (TDate *d, TTime *t) { TicksToDateTime (
TicksNow (), d, t, NULL); }
1483TDate DateIncByDays (TDate date,
int dDays);
1484int DateDiffByDays (TDate d1, TDate d0);
1486TDate DateIncByMonths (TDate date,
int dMon);
1488static inline TDate DateFirstOfMonth (TDate date) {
return (date & ~0x1f) + 1; }
1490int GetWeekDay (TDate date);
1491int GetCalWeek (TDate date);
1581 void *GetCreator () {
return creator; }
1583 bool Pending () {
return isLinked; }
1591 virtual void OnTime () {
if (func) func (
this, data); }
1597 friend void TimerRun ();
1598 friend void *TimerThreadRoutine (
void *);
1600 static bool ClassIterateAL ();
1601 static TTicks GetDelayTimeAL ();
1610 TTicks nextTicks, interval;
1629int TimerRun (
bool catchSignals =
true);
1673 CThread () { running =
false; }
1684 friend void *CThreadRoutine (
void *);
1686 virtual void *
Run () {
return NULL; }
1706 pthread_mutex_t mutex;
1739 pthread_cond_t cond;
1787 bool GetCmd (
void *retCmdRec);
1806 fd_set fdSetRead, fdSetWrite;
1807 int maxFd, cmdRecSize;
1846 CShell () { exitCode = -1; }
1851 virtual bool Start (
const char *cmd,
bool readStdErr =
false) = 0;
1864 virtual bool StartRestricted (
const char *name,
const char *args = NULL);
1875 virtual void Wait () = 0;
1881 int ExitCode () {
return exitCode; }
1887 int Run (
const char *cmd,
const char *input = NULL,
CString *output = NULL);
1898 virtual void CheckIO (
bool *canWrite,
bool *canRead,
TTicks maxTime = -1) = 0;
1930 virtual void WriteLine (
const char *line) = 0;
1963 CShellBare () { host = NULL; newProcessGroup =
false; fdToScript = fdFromScript = childPid = -1; }
1969 virtual bool Start (
const char *cmd,
bool readStdErr =
false);
1972 virtual void Wait ();
1973 virtual void Kill (
int sig = SIGTERM);
1978 virtual void CheckIO (
bool *canWrite,
bool *canRead,
TTicks maxTime = -1);
1981 virtual void WriteLine (
const char *line);
1985 virtual bool ReadClosed () {
return fdFromScript < 0 && !readBufMayContainLine; }
1995 int ReadFd () {
return fdFromScript; }
1996 int WriteFd () {
return fdToScript; }
2003 const char *Host () {
return host; }
2008 bool StartSession (
bool readStdErr =
false) {
return Start (NULL, readStdErr); }
2014 bool newProcessGroup;
2016 bool readBufMayContainLine;
2017 int fdToScript, fdFromScript;
2018 int childPid, killSig;
2020 bool DoWaitPid (
int options);
2044 const char *Host () {
return session.Host (); }
2045 bool HasHost () {
return session.
HasHost (); }
2050 virtual bool Start (
const char *cmd,
bool readStdErr =
false);
2051 virtual void Wait ();
2056 virtual void CheckIO (
bool *canWrite,
bool *canRead,
TTicks maxTime = -1);
2070 bool writeOpen, readOpen;
2113 CServiceKeeper () { isOpen = shouldBeOpen =
false; tDShort = tDLong = tShortToLong = 0; }
2115 { isOpen = shouldBeOpen =
false;
Setup (_tDShort, _tDLong, _tShortToLong); }
2132 void Close () { shouldBeOpen =
false; }
2147 bool IsOpen () {
return isOpen; }
2158 virtual void DoOpen () {}
2193 bool isOpen, shouldBeOpen;
2196 TTicks tDShort, tDLong, tShortToLong;
Class to wrap (POSIX) condition variables.
void Signal()
Wakeup ONE waiting thread.
void Wait(CMutex *mutex)
Wait until woken up. The supplied mutex must be locked and will be atomically unlocked while waiting.
void Broadcast()
Wakeup ALL waiting threads.
void Merge(CDictCompact< T > *dict2)
Merge another map into this one. Complexity is O(n_this + n_dict2). 'dict2' will be empty afterwards.
void SetValue(int idx, T *value)
Set (replace) a value. The entry must exist and 'idx' be valid. Complexity is O(1).
int Set(const char *key, T *value)
Add or replace the keyed entry. Complexity is O(n).
Raw dictionary (base class for other dictionary variants).
int Find(const char *key, int *retInsIdx=NULL)
Make binary search and return index of entry found or -1 if the key does not exist....
virtual void Dump(const char *name)
Dump contents by means of INFO logs (for debugging)
const char * GetKey(int idx) const
Get key by index.
void PrefixSearch(const char *key, int *retIdx0, int *retIdx1)
Determine all elements with keys starting with key.
void Del(int idx)
Delete entry; complexity is O(n).
Dictionary of references.
int Set(const char *key, T *value)
Add or replace the keyed entry. Complexity is O(n).
T * DisownValue(int idx)
Disown a value and clear it in the dictionary.
void SetValue(int idx, T *value)
Set (replace) a value.
void Merge(CDict< T > *dict2)
Merge another dictionary into this one. Complexity is O(n_this + n_dict2). 'dict2' will be empty afte...
virtual void Dump(const char *name)
Dump contents by means of INFO logs (for debugging)
void Merge(CKeySet *set2)
Merge another map into this one. Complexity is O(n_this + n_set2). 'set2' will be empty afterwards.
void Set(int idx, T *value)
Set (replace) a value. The entry must exist and 'idx' be valid. Complexity is O(1).
void Append(T *value)
Append a new value. Complexity is O(1) if no resizing is necessary, else O(1).
void Insert(int idx, T *value)
Insert a new value. Complexity is O(n).
Raw list (base class for other list variants).
void Clear()
Clear the list.
virtual void Dump(const char *name)
Dump contents by means of INFO logs (for debugging)
int Entries() const
Get number of entries.
void Del(int idx)
Delete entry; complexity is O(n).
void Append(T *value)
Append a new value. Complexity is O(1) if no resizing is necessary, else O(1).
T * Disown(int idx)
Disown a value and clear it in the array.
void Set(int idx, T *value)
Set (replace) a value. The entry must exist and 'idx' be valid. Complexity is O(1).
void Insert(int idx, T *value)
Insert a new value. Complexity is O(n).
Class to wrap (POSIX) mutex objects.
Factory class for regular expression matching.
bool SetPattern(const char *pattern, int cflags=REG_EXTENDED)
Set and compile a search pattern.
bool Match(const char *s, int eflags=0, size_t maxMatches=0, regmatch_t *retMatchList=NULL)
Perform a regular expression search.
Service keeper: Helper class to keep an unreliable service running.
void Close()
Request the service to close.
void ReportLost()
Report that the service is no longer running.
virtual void DoOpen()
Attempt to open the service in callback use. If this method is overloaded it must call ReportOpenAtte...
void Setup(TTicks _tDShort, TTicks _tDLong=NEVER, TTicks _tShortToLong=NEVER)
Setup the retry policy.
void ReportOpenAttempt(bool success)
Report an open attempt (either successful or not). This must be called from DoOpen() or after OpenAtt...
bool OpenAttemptNow()
Query if the connection should be (re-)opened now. After the attempt, ReportOpenAttempt() must be cal...
void Open()
Request the service to open.
void Iterate()
Iterate (callback use); perform all open/close actions as adequate. Not needed for polling use.
bool IsOpen()
check if the service is actually open.
bool CloseNow()
Query if the connection should be closed now. Closing must not fail.
bool ShouldBeOpen()
check if the service has been requested to be open.
void Refresh()
Force retry on next Iterate() and return to short retry intervals.
virtual void DoClose()
Actually close the service. If this method is overloaded it must call ReportClosed() to report that t...
void ReportClosed()
Report that the service was actually closed. This must be calld from DoClose() or after CloseNow() ha...
Normal shell: Commands are executed individually.
int ReadFd()
Get FD to allow select() by owner with multiple scripts.
virtual void Kill(int sig=SIGTERM)
(not tested in shell mode!)
virtual bool Start(const char *cmd, bool readStdErr=false)
Start new command, optionally on a remote host (see below).
virtual void Wait()
Wait until current command completes.
void SetNewProcessGroup(bool on=true)
Create a new process group and let this process become the leader (for daemon to support job control)...
bool HasHost()
Return whether this is a remote shell (including remote SSH to 'localhost').
virtual bool ReadClosed()
Close the read channel.
void SetHost(const char *_host)
Set host to run subsequent commands on; 'NULL' represents the local host.
virtual bool IsRunning()
Still running?
bool StartSession(bool readStdErr=false)
Start a commmand shell session.
int WriteFd()
Get FD to allow select() by owner with multiple scripts.
virtual void WriteClose()
Close the write channel.
virtual void WriteLine(const char *line)
Blocking write, execution is guaranteed. To avoid blocking, run Writable() or CheckI() first.
virtual void CheckIO(bool *canWrite, bool *canRead, TTicks maxTime=-1)
Use select() to check whether the i/o channels can take/deliver data.
virtual bool ReadLine(CString *str)
Non-Blocking read, returns 'true' on success. str can be NULL, in which case the line is ignored,...
Session shell: Multiple commands are executed through one shell.
virtual void CheckIO(bool *canWrite, bool *canRead, TTicks maxTime=-1)
Check whether the i/o channels can take/deliver data.
virtual bool ReadLine(CString *str)
Non-Blocking read, returns 'true' on success. str can be NULL, in which case the line is ignored,...
virtual bool Start(const char *cmd, bool readStdErr=false)
Start command.
virtual void WriteClose()
Close the write channel.
virtual void WriteLine(const char *line)
Blocking write, execution is guaranteed. To avoid blocking, run Writable() or CheckI() first.
void SetHost(const char *_host)
Define a remote host; must be called before first Start() call.
int WriteFd()
Get FD to allow select() by owner with multiple scripts.
virtual void Wait()
Wait until current command completes.
virtual bool ReadClosed()
Close the read channel.
int ReadFd()
Get FD to allow select() by owner with multiple scripts.
Abstract base class for shells that can execute system commands.
bool Writable()
Poll for writability (non-blocking).
virtual bool IsRunning()
Still running?
int ExitCode()
Get the exit code of last command.
virtual bool Start(const char *cmd, bool readStdErr=false)=0
Start command.
int Run(const char *cmd, const char *input=NULL, CString *output=NULL)
Run command 'cmd' synchronously and return its exit code.
virtual void WriteLine(const char *line)=0
Blocking write, execution is guaranteed. To avoid blocking, run Writable() or CheckI() first.
virtual void Wait()=0
Wait until current command completes.
virtual bool StartRestricted(const char *name, const char *args=NULL)
Same as 'Start', but fetch the command from the environment.
virtual void Kill(int sig=SIGTERM)
Kill the current command nicely. This may not work for all types of shells. A Wait() invocation is re...
bool Readable()
Poll for readability.
bool WaitUntilReadable(TTicks maxTime=-1)
Wait until output of the external command is readable. Be aware of potential deadlocks....
virtual bool ReadClosed()=0
Close the read channel.
bool WaitUntilWritable(TTicks maxTime=-1)
Wait until the external command can accept written input. Be aware of potential deadlocks....
virtual void WriteClose()=0
Close the write channel.
virtual bool ReadLine(CString *str)=0
Non-Blocking read, returns 'true' on success. str can be NULL, in which case the line is ignored,...
virtual void CheckIO(bool *canWrite, bool *canRead, TTicks maxTime=-1)=0
Check whether the i/o channels can take/deliver data.
Class allowing to sleep until one out of multiple i/o operations becomes possible.
void Prepare()
Prepare for sleeping, clear all file descriptors.
void AddWritable(int fd)
Add file descriptor fd to monitor for writability, descriptors < 0 are silently ignored.
void EnableCmds(int _cmdRecSize)
Enable sending commands by PutCmd(). To be called immediately after initialization and only if the co...
bool IsWritable(int fd)
Check if file descriptor is writable (flags are only updated in Sleep() ).
void AddReadable(int fd)
Add file descriptor fd to monitor for readability, descriptors < 0 are silently ignored.
void Sleep(TTicks maxTime=-1)
Sleep until one file descriptor is readable/writable or a new command was received.
bool GetCmd(void *retCmdRec)
Get and consume next command (non-blocking).
void PutCmd(const void *cmdRec, TTicks t=0, TTicks _interval=0)
Send message to sleeper.
void ClearTimedCmds()
Clear any scheduled commands which have not yet been put into the queue. Note: Respective commands ma...
bool IsReadable(int fd)
Check if file descriptor is readable (flags are only updated in Sleep() ).
Factory class to split a string into substrings.
int GetOffset(int argNo)
Get offset of argument number arg in the original string.
const char * Get(int idx) const
Get one string.
void Set(const char *str, int maxArgc=INT_MAX, const char *sepChars=NULL)
Set and split a string.
int Entries() const
Get number of string after splitting.
const char * operator[](int n) const
Get one string.
int GetIdx(int pos)
Get the argument number of character number pos of the original string. On error, -1 is returned,...
void Clear()
Clear the object (only necessary if another string is to be split)
Dynamically allocated string.
bool SetAsIso8859(const char *str)
'this' will be ISO-8859-encoded string, the source is expected to be (normal) UTF-8
bool ReadFile(const char *relOrAbsPath)
Read a complete text file into a string. The path may be absolute or relative to HOME2L_ROOT.
static const char *const emptyStr
Use this whenever you need an empty string ("")
char * Disown()
Return current string as a dynamic object and clear 'this'.
void SetFromIso8859(const char *iso8859str)
'this' will be a (normal) UTF-8 string, the source is expected to be ISO-8859
void AppendEscaped(const char *s, const char *dontEscape=NULL)
Same as 'Set...', but appending the result to the current srtring.
void SetFByLine(const char *fmt, const char *text)
Split 'text' into lines and reassembles the text by processing each line through sprintf and 'fmt'....
bool ReadLine(CString *ret)
Consume and optionally return the first line from 'this'. On success, 'true' is returned....
void SetEscaped(const char *s, const char *dontEscape=NULL)
Set and escape all non-alphanumerical characters by "\...".
void SetFV(const char *fmt, va_list ap)
Set using vprintf() formatting.
void SetF(const char *fmt,...)
Set using printf() formatting.
bool SetUnescaped(const char *s)
Set and revers escapes. On error, 'false' is returned and the string remains unchanged....
void SetO(const char *_ptr)
Set content and take ownership of '_ptr'. '_ptr' must have been dynamically allocated,...
bool AppendUnescaped(const char *s)
Same as 'Set...', but appending the result to the current srtring.
char * Get() const
Get the C string. Unless explicitely set by 'SetC', this will never return NULL or an invalid pointer...
void AppendFByLine(const char *fmt, const char *text)
Same as SetFByLine(), but appending the result to the current srtring.
void SetC(const char *_ptr)
Set without copying or taking ownership of '_ptr' (but "copy-on-write" semantics)....
bool AppendFromFile(int fd, const char *name=NULL)
Read as much as possible from 'fd' and append to buffer. If an end-of-file is encountered,...
bool IsEmpty()
Check, if empty.
Class to wrap (POSIX) threads.
virtual void * Run()
Main thread routine (to be overloaded)
void Start()
Run the virtual method Run() in the background.
void * Join()
Join with the background thread.
bool IsRunning()
(only for main thread)
void Clear()
Remove timer from the event list.
static void DelByCreator(void *_creator)
Remove all timers created by _creator from the event list.
void Reschedule(TTicks _time, TTicks _interval=0)
Change a timer (like 'Set'), but leave function and creator unchanged.
virtual void OnTime()
[T:timer] Virtual function called when the timer triggers.
friend TTicks TimerGetDelay()
Returns number of milliseconds until next call to TimerIterate() is necessary, or -1 if no timer is p...
void Set(FTimerCallback *_func, void *_data=NULL, void *_creator=NULL)
Setup timer without (re-)scheduling it.
friend bool TimerIterate()
Returns false if nothing was done.
bool Pending()
Indicate whether the timer is pending and may be executed in the future.
size_t Read(int fd, void *buf, size_t count)
Similar to POSIX read(), but reads all 'count' bytes as possible.
bool ReadDir(const char *relOrAbsPath, class CKeySet *ret)
Read a directory into a CKeySet object.
bool UnlinkTree(const char *relOrAbsPath, const char *skipPattern=NULL)
Unlink (remove) a directory with all its decendants.
size_t Write(int fd, const void *buf, size_t count)
Similar to POSIX write(), but writes all 'count' bytes as possible.
bool MakeDir(const char *relOrAbsPath, bool setHome2lGroup=true)
Create a directory (and all its parents as necessary).
const char * MonthName(int dm)
Get textual name. 1 = "January", ..., 12 = "December".
bool TicksFromString(const char *str, TTicks *ret, bool absolute)
Convert a string to a relative or absolute ticks value.
const char * DayName(int wd)
Get textual name. 0 = "Monday", ..., 6 = "Sunday".
static bool TicksAbsFromString(const char *str, TTicks *ret)
Convert a string to an absolute ticks value. See TicksFromString() for supported string formats.
static void DateTimeNow(TDate *d, TTime *t)
Retrieve current date and time (both pointers may be NULL)
TTicks TicksAbsFromMonotic(TTicks tm)
Get the approximated absolute (real) time for a monotonic time. Arguments <= 0 are returned unmodifie...
int64_t TTicks
Time value (relative, absolute, or monotonic).
static bool TicksRelFromString(const char *str, TTicks *ret)
Convert a string to a relative ticks value. See TicksFromString() for supported string formats.
TTicks TicksNowMonotonic()
Get the current monotonic time in milliseconds. This function never returns 0 or a negative value.
const char * TicksRelToString(CString *ret, TTicks ticks)
Get a string of the form "<integer>[<unit>]" for a relative time.
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.
#define NEVER
Special value that may represent "never" for absolute or monotonic times. Other application-specific ...
TTicks TicksMonotonicFromAbs(TTicks ta)
Get the approximated monotonic time for an absolute time . Arguments <= 0 are returned unmodified.
const char * DayNameShort(int wd)
Get textual name. 0 = "Mon", ..., 6 = "Sun".
const char * MonthNameShort(int dm)
Get textual shortname. 1 = "Jan", ..., 12 = "Dec".
TTicks TicksNow()
Get the current absolute time in milliseconds. This function never returns 0 or a negative value.
void LangTranslateNumber(char *str)
Adapt numeric string by replacing all '.' by the locale's decimal point.
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 ...
int envDebug
Debug level (read-only; may also be mapped to a constant macro).
void LogToSyslog(const char *instanceName=NULL)
Redirect logging to syslog from now; instance name must be passed if this is called before EnvInit()
void FLogCbToast(const char *msg, bool showLonger)
Callback to display a short info popup using OS mechanisms. This is used if for messages printed usin...
void LogStack()
Log a stack trace (requires linker flag '-rdynamic' to print function names)
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 't...
int ValidIntFromString(const char *str, int defaultVal, int radix=0)
Convert a string to an integer. On failure, 'defaultVal' is returned.
unsigned ValidUnsignedFromString(const char *str, unsigned defaultVal, int radix=0)
Convert a string to an unsigned integer. On failure, 'defaultVal' is returned.
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.
const char * GetAbsPath(class CString *ret, const char *relOrAbsPath, const char *defaultPath)
Get absolute path.
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.
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.
float ValidFloatFromString(const char *str, float defaultVal)
Convert a string to a float value. On failure, 'defaultVal' is returned.
bool BoolFromString(const char *str, bool *ret)
Convert a string to a Boolean value. On success, '*ret' is set accordingly and 'true' is returned....
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)
bool ValidBoolFromString(const char *str, bool defaultVal)
Convert a string to a Boolean value. On failure, 'defaultVal' is returned.
void StringSplitFree(char ***argv)
Free memory allocated by StringSplit().
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.
bool FloatFromString(const char *str, float *ret)
Convert a string to a floating-point value using 'strtof'. On success, '*ret' is set accordingly and ...
const char * StringF(class CString *ret, const char *fmt,...)
Return 'ret->Get ()'.
class CString * GetThreadTempString()
Get the thread-local temporary string (TTS) of the calling thread.
#define WHITESPACE
white space characters according to 'man 3 isspace'
bool CharIsWhiteSpace(char c)
Indicate whether the given character is white space (see WHITSPACE).
void StringStrip(char *str, const char *sepChars=WHITESPACE)
Remove seperator (whitespace) characters at the beginning and end of the string.
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 re...
const char * PathLeaf(const char *str)
Get leaf component of a path.
void * FThreadRoutine(void *data)
Function type for thread routines.
void Sleep(TTicks mSecs)
Suspend for mSecs milliseconds using nanosleep().
int TimerRun(bool catchSignals=true)
Perform an endless loop calling timers until TimerStop() is called.
TTicks TimerGetDelay()
Returns number of milliseconds until next call to TimerIterate() is necessary, or -1 if no timer is p...
void TimerStart()
Start TimerRun() in a background thread, which is to be stopped using TimerStop()....
bool TimerIterate()
Returns false if nothing was done.
void FTimerCallback(class CTimer *timer, void *data)
Function type for timer callbacks.
void TimerStop()
Request TimerRun() to return at next occasion (can be called from any thread). If a dedicated timer t...
static const char * VersionGetOwnAsStr()
Get my own build version as a string.
static bool VersionDirty(uint32_t ver)
Get the "dirty" component of the version.
static uint32_t VersionCompose(uint8_t major, uint8_t minor, uint16_t revision, bool dirty=false)
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.
uint32_t VersionFromStr(const char *str)
Get a numeric representation of the version string. On syntax error, a warning is logged and 0 is ret...
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 pass...
uint32_t VersionGetOwn()
Get my own build version.
static int VersionMajor(uint32_t ver)
Get the major component of the version.