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)
101 size_t Write (
int fd,
const void *buf,
size_t count);
111 size_t Read (
int fd,
void *buf,
size_t count);
122 bool MakeDir (
const char *relOrAbsPath,
bool setHome2lGroup =
true);
132 bool UnlinkTree (
const char *relOrAbsPath,
const char *skipPattern = NULL);
179 typedef void FLogCbMessage (
const char *title,
const char *msg);
191 void LogToSyslog (
const char *instanceName = NULL);
193 bool LoggingToSyslog ();
199 static inline void LogClose () {}
200 static inline bool LoggingToSyslog () {
return true; }
205 void LogPara (
const char *_logHead,
const char* _logFile,
int _logLine);
206 void 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)
349 static 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);
357 static inline int VersionMajor (uint32_t ver) {
return (
int) (ver >> 24); }
359 static inline int VersionMinor (uint32_t ver) {
return (
int) ((ver >> 16) & 0xff); }
361 static inline int VersionRevision (uint32_t ver) {
return (
int) ((ver >> 1) & 0x7fff); }
363 static inline bool VersionDirty (uint32_t ver) {
return (ver & 1) == 1; }
401 #define USE_GNU_GETTEXT 0
403 #define USE_GNU_GETTEXT 0
414 const char *LangGetText (
const char *msgId);
416 #define gettext(STR) LangGetText (STR)
422 void 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 ())
514 bool IntFromString (
const char *str,
int *ret,
int radix = 0);
537 void StringSplit (
const char *str,
int *retArgc,
char ***retArgv,
int maxArgc = INT_MAX,
const char *sepChars = NULL,
char **retRef = NULL);
570 const char *
PathLeaf (
const char *str);
572 const char *
GetAbsPath (
class CString *ret,
const char *relOrAbsPath,
const char *defaultPath);
587 const 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); }
809 int Entries ()
const {
return argc; }
810 const char *
Get (
int idx)
const {
return argv[idx]; }
813 int GetOffset (
int argNo) {
return (argv && ref) ? argv[argNo] - ref : 0; }
815 int GetOffset (
const char *p) {
return ref ? (p - ref) : 0; }
838 CRegex () { reValid =
false; lastError = 0; }
839 ~
CRegex () {
if (reValid) regfree (&re); }
841 bool SetPattern (
const char *pattern,
int cflags = REG_EXTENDED);
850 bool Match (
const char *s,
int eflags = 0,
size_t maxMatches = 0, regmatch_t *retMatchList = NULL);
862 bool IsValid () {
return reValid; }
863 const char *ErrorStr ();
889 #define CONT_ALIGNMENT 4
890 #define CONT_ALIGN(X) (((X) + CONT_ALIGNMENT - 1) & ~(CONT_ALIGNMENT - 1))
898 template <
typename T>
const char *ToStr (
CString *ret, T *obj) {
return obj->ToStr (ret); }
901 template <>
const char *ToStr<int> (
CString *ret,
int *obj);
920 int Entries ()
const {
return entries; }
926 void Clear () { SetEntries (0); }
934 virtual void Dump (
const char *name);
940 virtual void RecInit (
void *p);
943 virtual void RecClear (
void *p);
946 virtual void ValueInit (
void *p) {}
948 virtual void ValueClear (
void *p) {}
950 virtual void ValueSet (
void *p,
void *orig) {}
954 virtual const char *ValueToStr (
CString *ret,
void *p);
958 void SetEntries (
int _entries);
960 uint8_t *GetRecAdr (
int idx)
const {
return idx < 0 ? NULL : data + recSize * idx; }
962 uint8_t *GetValueAdr (
int idx)
const {
return idx < 0 ? NULL : data + recSize * idx + tagSize; }
964 void *GetValuePtr (
int idx)
const {
return idx < 0 ? NULL : * (
void **) (GetValueAdr (idx)); }
967 void Copy (
int idxDst,
int idxSrc);
968 void Swap (
void *rec0,
void *rec1);
970 void SetRaw (
int idx,
void *value);
973 void InsertRaw (
int idx,
void *value);
976 void *DisownRaw (
int idx);
982 int recSize, tagSize, entries, allocEntries;
1003 T *Get (
int idx) {
return (T *) GetValuePtr (idx); }
1004 T *operator [] (
int idx) {
return Get (idx); }
1012 void Set (
int idx, T *value) { SetRaw (idx, value); }
1015 void Insert (
int idx, T *value) { InsertRaw (idx, value); }
1018 void Append (T *value) { InsertRaw (INT_MAX, value); }
1021 T *
Disown (
int idx) {
return (T *) DisownRaw (idx); }
1026 virtual void ValueInit (
void *p) { * (T **) p = NULL; }
1027 virtual void ValueClear (
void *p) {
if (* (T**) p) {
delete * (T **) p; * (T **) p = NULL; } }
1028 virtual void ValueSet (
void *p,
void *orig) { ValueClear (p); * (T**) p = (T*) orig; }
1029 virtual const char *ValueToStr (
CString *ret,
void *p) { return ::ToStr<T> (ret, * (T**) p); }
1057 T *Get (
int idx) {
return (T *) GetValueAdr (idx); }
1058 T *operator [] (
int idx) {
return Get (idx); }
1064 void Set (
int idx, T *value) { SetRaw (idx, value); }
1067 void Insert (
int idx, T *value) { InsertRaw (idx, value); }
1070 void Append (T *value) { InsertRaw (INT_MAX, value); }
1076 virtual void ValueInit (
void *p) { memcpy (p, &emptyObj,
sizeof (emptyObj)); }
1077 virtual void ValueClear (
void *p) { ValueSet (p, &emptyObj); }
1078 virtual void ValueSet (
void *p,
void *orig) { * (T *) p = * (T *) orig; }
1079 virtual const char *ValueToStr (
CString *ret,
void *p) { return ::ToStr<T> (ret, (T*) p); }
1092 virtual void ValueClear (
void *p) { * (T **) p = NULL; }
1093 virtual void ValueSet (
void *p,
void *orig) { * (T**) p = (T*) orig; }
1101 #define DICT_KEYSIZE CONT_ALIGN((int) sizeof (CString))
1111 CDictRaw (
int _valueSize):
CListRaw (_valueSize + DICT_KEYSIZE) { tagSize = DICT_KEYSIZE; }
1121 void Del (
const char *key) {
Del (
Find (key)); }
1127 const char *
GetKey (
int idx)
const {
return ((
CString *) GetRecAdr (idx))->Get (); }
1129 int Find (
const char *key,
int *retInsIdx = NULL);
1132 void PrefixSearch (
const char *key,
int *retIdx0,
int *retIdx1);
1141 virtual void Dump (
const char *name);
1145 virtual void RecInit (
void *p);
1146 virtual void RecClear (
void *p);
1148 void SetRaw (
int idx,
void *value) { CListRaw::SetRaw (idx, value); }
1149 int SetRaw (
const char *key,
void *value);
1171 T *Get (
int idx) {
return (T *) GetValuePtr (idx); }
1172 T *Get (
const char *key) {
return Get (
Find (key)); }
1173 T *operator [] (
int idx) {
return Get (idx); }
1174 T *operator [] (
const char *key) {
return Get (key); }
1182 int Set (
const char *key, T *value) {
return SetRaw (key, value); }
1185 void SetValue (
int idx, T *value) { SetRaw (idx, value); }
1191 T *
DisownValue (
int idx) {
return (T *) DisownRaw (idx); }
1206 virtual void ValueInit (
void *p) { * (T **) p = NULL; }
1207 virtual void ValueClear (
void *p) {
if (* (T**) p) {
delete * (T **) p; * (T **) p = NULL; } }
1208 virtual void ValueSet (
void *p,
void *orig) { ValueClear (p); * (T**) p = (T*) orig; }
1209 virtual const char *ValueToStr (
CString *ret,
void *p) { return ::ToStr<T> (ret, * (T**) p); }
1226 T *Get (
int idx) {
return (T *) GetValueAdr (idx); }
1227 T *Get (
const char *key) {
return Get (
Find (key)); }
1228 T *operator [] (
int idx) {
return Get (idx); }
1229 T *operator [] (
const char *key) {
return Get (key); }
1234 int Set (
const char *key, T *value) {
return SetRaw (key, value); }
1237 void SetValue (
int idx, T *value) { SetRaw (idx, value); }
1250 virtual void ValueInit (
void *p) { memcpy (p, (
void *) &emptyObj,
sizeof (emptyObj)); }
1251 virtual void ValueClear (
void *p) { ValueSet (p, (
void *) &emptyObj); }
1252 virtual void ValueSet (
void *p,
void *orig) { * (T *) p = * (T *) orig; }
1253 virtual const char *ValueToStr (
CString *ret,
void *p) { return ::ToStr<T> (ret, (T*) p); }
1266 virtual void ValueClear (
void *p) { * (T **) p = NULL; }
1267 virtual void ValueSet (
void *p,
void *orig) { * (T**) p = (T*) orig; }
1282 const char *operator [] (
int idx) {
return GetKey (idx); }
1287 int Set (
const char *key) {
return SetRaw (key, NULL); }
1299 virtual void Dump (
const char *name);
1351 #define ASAP ((TTicks) 0)
1353 #define NEVER ((TTicks) INT64_MIN)
1418 void TicksToStructTimeval (
TTicks t,
struct timeval *retTv);
1420 #define TICKS_FROM_SECONDS(S) (((TTicks) (S)) * 1000)
1421 #define SECONDS_FROM_TICKS(T) (((TTicks) (T) + 500) / 1000)
1422 #define TICKS_FROM_MILLIS(MS) ((TTicks) (MS))
1423 #define MILLIS_FROM_TICKS(T) ((int) (T))
1433 #define DATE_OF(Y,M,D) ((TDate) (((Y) << 9) | ((M) << 5) | (D)))
1434 #define YEAR_OF(DT) ((int) (DT) >> 9)
1435 #define MONTH_OF(DT) (((int) (DT) >> 5) & 0xf)
1436 #define DAY_OF(DT) ((int) (DT) & 0x1f)
1441 #define TIME_OF(H,M,S) ((TTime) ((H) * 3600 + (M) * 60 + (S)))
1442 #define HOURS_OF(T) ((int) (T) / 3600)
1443 #define MINUTES_OF(T) ((int) (T) / 60)
1444 #define HOUR_OF(T) HOURS_OF(T)
1445 #define MINUTE_OF(T) (MINUTES_OF(T) % 60)
1446 #define SECOND_OF(T) ((int) (T) % 60)
1453 TTicks TicksOfDate (
int dy,
int dm,
int dd);
1454 TTicks TicksOfDate (TDate d);
1455 TTicks TicksOfTime (
int th,
int tm,
int ts);
1456 TTicks TicksOfTime (TTime t);
1458 TDate DateOfTicks (
TTicks t);
1459 TTime TimeOfTicks (
TTicks t);
1461 TTicks DateTimeToTicks (TDate d, TTime t,
struct tm *retTm = NULL);
1463 TTicks DateTimeToTicksUTC (TDate d, TTime t,
struct tm *retTm = NULL);
1465 void TicksToDateTime (
TTicks t, TDate *retDate, TTime *retTime,
struct tm *retTm = NULL);
1466 void TicksToDateTimeUTC (
TTicks t, TDate *retDate, TTime *retTime,
struct tm *retTm = NULL);
1472 static inline void DateTimeNow (TDate *d, TTime *t) { TicksToDateTime (
TicksNow (), d, t, NULL); }
1481 TDate DateIncByDays (TDate date,
int dDays);
1482 int DateDiffByDays (TDate d1, TDate d0);
1484 TDate DateIncByMonths (TDate date,
int dMon);
1486 static inline TDate DateFirstOfMonth (TDate date) {
return (date & ~0x1f) + 1; }
1488 int GetWeekDay (TDate date);
1489 int GetCalWeek (TDate date);
1579 void *GetCreator () {
return creator; }
1581 bool Pending () {
return isLinked; }
1589 virtual void OnTime () {
if (func) func (
this, data); }
1595 friend void TimerRun ();
1596 friend void *TimerThreadRoutine (
void *);
1598 static bool ClassIterateAL ();
1599 static TTicks GetDelayTimeAL ();
1608 TTicks nextTicks, interval;
1627 int TimerRun (
bool catchSignals =
true);
1671 CThread () { running =
false; }
1682 friend void *CThreadRoutine (
void *);
1684 virtual void *
Run () {
return NULL; }
1704 pthread_mutex_t mutex;
1737 pthread_cond_t cond;
1785 bool GetCmd (
void *retCmdRec);
1804 fd_set fdSetRead, fdSetWrite;
1805 int maxFd, cmdRecSize;
1844 CShell () { exitCode = -1; }
1849 virtual bool Start (
const char *cmd,
bool readStdErr =
false) = 0;
1862 virtual bool StartRestricted (
const char *name,
const char *args = NULL);
1873 virtual void Wait () = 0;
1879 int ExitCode () {
return exitCode; }
1885 int Run (
const char *cmd,
const char *input = NULL,
CString *output = NULL);
1896 virtual void CheckIO (
bool *canWrite,
bool *canRead,
TTicks maxTime = -1) = 0;
1928 virtual void WriteLine (
const char *line) = 0;
1961 CShellBare () { host = NULL; newProcessGroup =
false; fdToScript = fdFromScript = childPid = -1; }
1967 virtual bool Start (
const char *cmd,
bool readStdErr =
false);
1970 virtual void Wait ();
1971 virtual void Kill (
int sig = SIGTERM);
1976 virtual void CheckIO (
bool *canWrite,
bool *canRead,
TTicks maxTime = -1);
1979 virtual void WriteLine (
const char *line);
1983 virtual bool ReadClosed () {
return fdFromScript < 0 && !readBufMayContainLine; }
1993 int ReadFd () {
return fdFromScript; }
1994 int WriteFd () {
return fdToScript; }
2001 const char *Host () {
return host; }
2010 bool newProcessGroup;
2012 bool readBufMayContainLine;
2013 int fdToScript, fdFromScript;
2014 int childPid, killSig;
2016 bool DoWaitPid (
int options);
2040 const char *Host () {
return session.Host (); }
2045 virtual bool Start (
const char *cmd,
bool readStdErr =
false);
2046 virtual void Wait ();
2051 virtual void CheckIO (
bool *canWrite,
bool *canRead,
TTicks maxTime = -1);
2057 virtual bool ReadClosed () {
return !readOpen; }
2065 bool writeOpen, readOpen;
2108 CServiceKeeper () { isOpen = shouldBeOpen =
false; tDShort = tDLong = tShortToLong = 0; }
2110 { isOpen = shouldBeOpen =
false;
Setup (_tDShort, _tDLong, _tShortToLong); }
2127 void Close () { shouldBeOpen =
false; }
2142 bool IsOpen () {
return isOpen; }
2153 virtual void DoOpen () {}
2188 bool isOpen, shouldBeOpen;
2191 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).
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...
T * DisownValue(int idx)
Disown a value and clear it in the dictionary.
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)...
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.
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,...
const char * Get(int idx) const
Get one string.
void Clear()
Clear the object (only necessary if another string is to be split)
Dynamically allocated string.
char * Get() const
Get the C string. Unless explicitely set by 'SetC', this will never return NULL or an invalid pointer...
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 ("")
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.
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)....
char * Disown()
Return current string as a dynamic object and clear 'this'.
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 * Join()
Join with the background thread.
void Start()
Run the virtual method Run() in the background.
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 * MonthNameShort(int dm)
Get textual shortname. 1 = "Jan", ..., 12 = "Dec".
const char * DayNameShort(int wd)
Get textual name. 0 = "Mon", ..., 6 = "Sun".
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.
bool TicksFromString(const char *str, TTicks *ret, bool absolute)
Convert a string to a relative or absolute ticks value.
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)
const char * DayName(int wd)
Get textual name. 0 = "Monday", ..., 6 = "Sunday".
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.
#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 * TicksRelToString(CString *ret, TTicks ticks)
Get a string of the form "<integer>[<unit>]" for a relative time.
const char * MonthName(int dm)
Get textual name. 1 = "January", ..., 12 = "December".
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.
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.
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.
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....
const char * GetAbsPath(class CString *ret, const char *relOrAbsPath, const char *defaultPath)
Get absolute path.
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 * StringF(class CString *ret, const char *fmt,...)
Return 'ret->Get ()'.
const char * PathLeaf(const char *str)
Get leaf component of a path.
bool FloatFromString(const char *str, float *ret)
Convert a string to a floating-point value using 'strtof'. On success, '*ret' is set accordingly and ...
#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.
class CString * GetThreadTempString()
Get the thread-local temporary string (TTS) of the calling thread.
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 * ToIso8859(class CString *ret, const char *str)
Transcode an ISO8859-coded string to UTF-8. Result is valid until next call of this function.
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...
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...
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 const char * VersionGetOwnAsStr()
Get my own build version as a string.
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...
uint32_t VersionGetOwn()
Get my own build version.
static int VersionMajor(uint32_t ver)
Get the major component of the version.