vdr  2.4.6
tools.c
Go to the documentation of this file.
1 /*
2  * tools.c: Various tools
3  *
4  * See the main source file 'vdr.c' for copyright information and
5  * how to reach the author.
6  *
7  * $Id: tools.c 4.13 2020/11/22 13:32:05 kls Exp $
8  */
9 
10 #include "tools.h"
11 #include <ctype.h>
12 #include <dirent.h>
13 #include <errno.h>
14 extern "C" {
15 #ifdef boolean
16 #define HAVE_BOOLEAN
17 #endif
18 #include <jpeglib.h>
19 #undef boolean
20 }
21 #include <locale.h>
22 #include <stdlib.h>
23 #include <sys/time.h>
24 #include <sys/vfs.h>
25 #include <time.h>
26 #include <unistd.h>
27 #include <utime.h>
28 #include "i18n.h"
29 #include "thread.h"
30 
31 int SysLogLevel = 3;
32 
33 #define MAXSYSLOGBUF 256
34 
35 void syslog_with_tid(int priority, const char *format, ...)
36 {
37  va_list ap;
38  char fmt[MAXSYSLOGBUF];
39  snprintf(fmt, sizeof(fmt), "[%d] %s", cThread::ThreadId(), format);
40  va_start(ap, format);
41  vsyslog(priority, fmt, ap);
42  va_end(ap);
43 }
44 
45 int BCD2INT(int x)
46 {
47  return ((1000000 * BCDCHARTOINT((x >> 24) & 0xFF)) +
48  (10000 * BCDCHARTOINT((x >> 16) & 0xFF)) +
49  (100 * BCDCHARTOINT((x >> 8) & 0xFF)) +
50  BCDCHARTOINT( x & 0xFF));
51 }
52 
53 ssize_t safe_read(int filedes, void *buffer, size_t size)
54 {
55  for (;;) {
56  ssize_t p = read(filedes, buffer, size);
57  if (p < 0 && errno == EINTR) {
58  dsyslog("EINTR while reading from file handle %d - retrying", filedes);
59  continue;
60  }
61  return p;
62  }
63 }
64 
65 ssize_t safe_write(int filedes, const void *buffer, size_t size)
66 {
67  ssize_t p = 0;
68  ssize_t written = size;
69  const unsigned char *ptr = (const unsigned char *)buffer;
70  while (size > 0) {
71  p = write(filedes, ptr, size);
72  if (p < 0) {
73  if (errno == EINTR) {
74  dsyslog("EINTR while writing to file handle %d - retrying", filedes);
75  continue;
76  }
77  break;
78  }
79  ptr += p;
80  size -= p;
81  }
82  return p < 0 ? p : written;
83 }
84 
85 void writechar(int filedes, char c)
86 {
87  safe_write(filedes, &c, sizeof(c));
88 }
89 
90 int WriteAllOrNothing(int fd, const uchar *Data, int Length, int TimeoutMs, int RetryMs)
91 {
92  int written = 0;
93  while (Length > 0) {
94  int w = write(fd, Data + written, Length);
95  if (w > 0) {
96  Length -= w;
97  written += w;
98  }
99  else if (written > 0 && !FATALERRNO) {
100  // we've started writing, so we must finish it!
101  cTimeMs t;
102  cPoller Poller(fd, true);
103  Poller.Poll(RetryMs);
104  if (TimeoutMs > 0 && (TimeoutMs -= t.Elapsed()) <= 0)
105  break;
106  }
107  else
108  // nothing written yet (or fatal error), so we can just return the error code:
109  return w;
110  }
111  return written;
112 }
113 
114 char *strcpyrealloc(char *dest, const char *src)
115 {
116  if (src) {
117  int l = max(dest ? strlen(dest) : 0, strlen(src)) + 1; // don't let the block get smaller!
118  dest = (char *)realloc(dest, l);
119  if (dest)
120  strcpy(dest, src);
121  else
122  esyslog("ERROR: out of memory");
123  }
124  else {
125  free(dest);
126  dest = NULL;
127  }
128  return dest;
129 }
130 
131 char *strn0cpy(char *dest, const char *src, size_t n)
132 {
133  char *s = dest;
134  for ( ; --n && (*dest = *src) != 0; dest++, src++) ;
135  *dest = 0;
136  return s;
137 }
138 
139 char *strreplace(char *s, char c1, char c2)
140 {
141  if (s) {
142  char *p = s;
143  while (*p) {
144  if (*p == c1)
145  *p = c2;
146  p++;
147  }
148  }
149  return s;
150 }
151 
152 char *strreplace(char *s, const char *s1, const char *s2)
153 {
154  char *p = strstr(s, s1);
155  if (p) {
156  int of = p - s;
157  int l = strlen(s);
158  int l1 = strlen(s1);
159  int l2 = strlen(s2);
160  if (l2 > l1) {
161  if (char *NewBuffer = (char *)realloc(s, l + l2 - l1 + 1))
162  s = NewBuffer;
163  else {
164  esyslog("ERROR: out of memory");
165  return s;
166  }
167  }
168  char *sof = s + of;
169  if (l2 != l1)
170  memmove(sof + l2, sof + l1, l - of - l1 + 1);
171  strncpy(sof, s2, l2);
172  }
173  return s;
174 }
175 
176 const char *strchrn(const char *s, char c, size_t n)
177 {
178  if (n == 0)
179  return s;
180  if (s) {
181  for ( ; *s; s++) {
182  if (*s == c && --n == 0)
183  return s;
184  }
185  }
186  return NULL;
187 }
188 
189 int strcountchr(const char *s, char c)
190 {
191  int n = 0;
192  if (s && c) {
193  for ( ; *s; s++) {
194  if (*s == c)
195  n++;
196  }
197  }
198  return n;
199 }
200 
201 char *stripspace(char *s)
202 {
203  if (s && *s) {
204  for (char *p = s + strlen(s) - 1; p >= s; p--) {
205  if (!isspace(*p))
206  break;
207  *p = 0;
208  }
209  }
210  return s;
211 }
212 
213 char *compactspace(char *s)
214 {
215  if (s && *s) {
216  char *t = stripspace(skipspace(s));
217  char *p = t;
218  while (p && *p) {
219  char *q = skipspace(p);
220  if (q - p > 1)
221  memmove(p + 1, q, strlen(q) + 1);
222  p++;
223  }
224  if (t != s)
225  memmove(s, t, strlen(t) + 1);
226  }
227  return s;
228 }
229 
230 char *compactchars(char *s, char c)
231 {
232  if (s && *s && c) {
233  char *t = s;
234  char *p = s;
235  int n = 0;
236  while (*p) {
237  if (*p != c) {
238  *t++ = *p;
239  n = 0;
240  }
241  else if (t != s && n == 0) {
242  *t++ = *p;
243  n++;
244  }
245  p++;
246  }
247  if (n)
248  t--; // the last character was c
249  *t = 0;
250  }
251  return s;
252 }
253 
254 cString strescape(const char *s, const char *chars)
255 {
256  char *buffer;
257  const char *p = s;
258  char *t = NULL;
259  while (*p) {
260  if (strchr(chars, *p)) {
261  if (!t) {
262  buffer = MALLOC(char, 2 * strlen(s) + 1);
263  t = buffer + (p - s);
264  s = strcpy(buffer, s);
265  }
266  *t++ = '\\';
267  }
268  if (t)
269  *t++ = *p;
270  p++;
271  }
272  if (t)
273  *t = 0;
274  return cString(s, t != NULL);
275 }
276 
277 cString strgetval(const char *s, const char *name, char d)
278 {
279  if (s && name) {
280  int l = strlen(name);
281  const char *t = s;
282  while (const char *p = strstr(t, name)) {
283  t = skipspace(p + l);
284  if (p == s || *(p - 1) <= ' ') {
285  if (*t == d) {
286  t = skipspace(t + 1);
287  const char *v = t;
288  while (*t > ' ')
289  t++;
290  return cString(v, t);
291  break;
292  }
293  }
294  }
295  }
296  return NULL;
297 }
298 
299 char *strshift(char *s, int n)
300 {
301  if (s && n > 0) {
302  int l = strlen(s);
303  if (n < l)
304  memmove(s, s + n, l - n + 1); // we also copy the terminating 0!
305  else
306  *s = 0;
307  }
308  return s;
309 }
310 
311 bool startswith(const char *s, const char *p)
312 {
313  while (*p) {
314  if (*p++ != *s++)
315  return false;
316  }
317  return true;
318 }
319 
320 bool endswith(const char *s, const char *p)
321 {
322  const char *se = s + strlen(s) - 1;
323  const char *pe = p + strlen(p) - 1;
324  while (pe >= p) {
325  if (*pe-- != *se-- || (se < s && pe >= p))
326  return false;
327  }
328  return true;
329 }
330 
331 bool isempty(const char *s)
332 {
333  return !(s && *skipspace(s));
334 }
335 
336 int numdigits(int n)
337 {
338  int res = 1;
339  while (n >= 10) {
340  n /= 10;
341  res++;
342  }
343  return res;
344 }
345 
346 bool isnumber(const char *s)
347 {
348  if (!s || !*s)
349  return false;
350  do {
351  if (!isdigit(*s))
352  return false;
353  } while (*++s);
354  return true;
355 }
356 
357 int64_t StrToNum(const char *s)
358 {
359  char *t = NULL;
360  int64_t n = strtoll(s, &t, 10);
361  if (t) {
362  switch (*t) {
363  case 'T': n *= 1024;
364  case 'G': n *= 1024;
365  case 'M': n *= 1024;
366  case 'K': n *= 1024;
367  }
368  }
369  return n;
370 }
371 
372 bool StrInArray(const char *a[], const char *s)
373 {
374  if (a) {
375  while (*a) {
376  if (strcmp(*a, s) == 0)
377  return true;
378  a++;
379  }
380  }
381  return false;
382 }
383 
384 cString AddDirectory(const char *DirName, const char *FileName)
385 {
386  if (*FileName == '/')
387  FileName++;
388  return cString::sprintf("%s/%s", DirName && *DirName ? DirName : ".", FileName);
389 }
390 
391 #define DECIMAL_POINT_C '.'
392 
393 double atod(const char *s)
394 {
395  static lconv *loc = localeconv();
396  if (*loc->decimal_point != DECIMAL_POINT_C) {
397  char buf[strlen(s) + 1];
398  char *p = buf;
399  while (*s) {
400  if (*s == DECIMAL_POINT_C)
401  *p = *loc->decimal_point;
402  else
403  *p = *s;
404  p++;
405  s++;
406  }
407  *p = 0;
408  return atof(buf);
409  }
410  else
411  return atof(s);
412 }
413 
414 cString dtoa(double d, const char *Format)
415 {
416  static lconv *loc = localeconv();
417  char buf[16];
418  snprintf(buf, sizeof(buf), Format, d);
419  if (*loc->decimal_point != DECIMAL_POINT_C)
420  strreplace(buf, *loc->decimal_point, DECIMAL_POINT_C);
421  return buf;
422 }
423 
424 cString itoa(int n)
425 {
426  char buf[16];
427  snprintf(buf, sizeof(buf), "%d", n);
428  return buf;
429 }
430 
431 bool EntriesOnSameFileSystem(const char *File1, const char *File2)
432 {
433  struct stat st;
434  if (stat(File1, &st) == 0) {
435  dev_t dev1 = st.st_dev;
436  if (stat(File2, &st) == 0)
437  return st.st_dev == dev1;
438  else
439  LOG_ERROR_STR(File2);
440  }
441  else
442  LOG_ERROR_STR(File1);
443  return true; // we only return false if both files actually exist and are in different file systems!
444 }
445 
446 int FreeDiskSpaceMB(const char *Directory, int *UsedMB)
447 {
448  if (UsedMB)
449  *UsedMB = 0;
450  int Free = 0;
451  struct statfs statFs;
452  if (statfs(Directory, &statFs) == 0) {
453  double blocksPerMeg = 1024.0 * 1024.0 / statFs.f_bsize;
454  if (UsedMB)
455  *UsedMB = int((statFs.f_blocks - statFs.f_bfree) / blocksPerMeg);
456  Free = int(statFs.f_bavail / blocksPerMeg);
457  }
458  else
459  LOG_ERROR_STR(Directory);
460  return Free;
461 }
462 
463 bool DirectoryOk(const char *DirName, bool LogErrors)
464 {
465  struct stat ds;
466  if (stat(DirName, &ds) == 0) {
467  if (S_ISDIR(ds.st_mode)) {
468  if (access(DirName, R_OK | W_OK | X_OK) == 0)
469  return true;
470  else if (LogErrors)
471  esyslog("ERROR: can't access %s", DirName);
472  }
473  else if (LogErrors)
474  esyslog("ERROR: %s is not a directory", DirName);
475  }
476  else if (LogErrors)
477  LOG_ERROR_STR(DirName);
478  return false;
479 }
480 
481 bool MakeDirs(const char *FileName, bool IsDirectory)
482 {
483  bool result = true;
484  char *s = strdup(FileName);
485  char *p = s;
486  if (*p == '/')
487  p++;
488  while ((p = strchr(p, '/')) != NULL || IsDirectory) {
489  if (p)
490  *p = 0;
491  struct stat fs;
492  if (stat(s, &fs) != 0 || !S_ISDIR(fs.st_mode)) {
493  dsyslog("creating directory %s", s);
494  if (mkdir(s, ACCESSPERMS) == -1) {
495  LOG_ERROR_STR(s);
496  result = false;
497  break;
498  }
499  }
500  if (p)
501  *p++ = '/';
502  else
503  break;
504  }
505  free(s);
506  return result;
507 }
508 
509 bool RemoveFileOrDir(const char *FileName, bool FollowSymlinks)
510 {
511  struct stat st;
512  if (stat(FileName, &st) == 0) {
513  if (S_ISDIR(st.st_mode)) {
514  cReadDir d(FileName);
515  if (d.Ok()) {
516  struct dirent *e;
517  while ((e = d.Next()) != NULL) {
518  cString buffer = AddDirectory(FileName, e->d_name);
519  if (FollowSymlinks) {
520  struct stat st2;
521  if (lstat(buffer, &st2) == 0) {
522  if (S_ISLNK(st2.st_mode)) {
523  int size = st2.st_size + 1;
524  char *l = MALLOC(char, size);
525  int n = readlink(buffer, l, size - 1);
526  if (n < 0) {
527  if (errno != EINVAL)
528  LOG_ERROR_STR(*buffer);
529  }
530  else {
531  l[n] = 0;
532  dsyslog("removing %s", l);
533  if (remove(l) < 0)
534  LOG_ERROR_STR(l);
535  }
536  free(l);
537  }
538  }
539  else if (errno != ENOENT) {
540  LOG_ERROR_STR(FileName);
541  return false;
542  }
543  }
544  dsyslog("removing %s", *buffer);
545  if (remove(buffer) < 0)
546  LOG_ERROR_STR(*buffer);
547  }
548  }
549  else {
550  LOG_ERROR_STR(FileName);
551  return false;
552  }
553  }
554  dsyslog("removing %s", FileName);
555  if (remove(FileName) < 0) {
556  LOG_ERROR_STR(FileName);
557  return false;
558  }
559  }
560  else if (errno != ENOENT) {
561  LOG_ERROR_STR(FileName);
562  return false;
563  }
564  return true;
565 }
566 
567 bool RemoveEmptyDirectories(const char *DirName, bool RemoveThis, const char *IgnoreFiles[])
568 {
569  bool HasIgnoredFiles = false;
570  cReadDir d(DirName);
571  if (d.Ok()) {
572  bool empty = true;
573  struct dirent *e;
574  while ((e = d.Next()) != NULL) {
575  if (strcmp(e->d_name, "lost+found")) {
576  cString buffer = AddDirectory(DirName, e->d_name);
577  struct stat st;
578  if (stat(buffer, &st) == 0) {
579  if (S_ISDIR(st.st_mode)) {
580  if (!RemoveEmptyDirectories(buffer, true, IgnoreFiles))
581  empty = false;
582  }
583  else if (RemoveThis && IgnoreFiles && StrInArray(IgnoreFiles, e->d_name))
584  HasIgnoredFiles = true;
585  else
586  empty = false;
587  }
588  else {
589  LOG_ERROR_STR(*buffer);
590  empty = false;
591  }
592  }
593  }
594  if (RemoveThis && empty) {
595  if (HasIgnoredFiles) {
596  while (*IgnoreFiles) {
597  cString buffer = AddDirectory(DirName, *IgnoreFiles);
598  if (access(buffer, F_OK) == 0) {
599  dsyslog("removing %s", *buffer);
600  if (remove(buffer) < 0) {
601  LOG_ERROR_STR(*buffer);
602  return false;
603  }
604  }
605  IgnoreFiles++;
606  }
607  }
608  dsyslog("removing %s", DirName);
609  if (remove(DirName) < 0) {
610  LOG_ERROR_STR(DirName);
611  return false;
612  }
613  }
614  return empty;
615  }
616  else
617  LOG_ERROR_STR(DirName);
618  return false;
619 }
620 
621 int DirSizeMB(const char *DirName)
622 {
623  cReadDir d(DirName);
624  if (d.Ok()) {
625  int size = 0;
626  struct dirent *e;
627  while (size >= 0 && (e = d.Next()) != NULL) {
628  cString buffer = AddDirectory(DirName, e->d_name);
629  struct stat st;
630  if (stat(buffer, &st) == 0) {
631  if (S_ISDIR(st.st_mode)) {
632  int n = DirSizeMB(buffer);
633  if (n >= 0)
634  size += n;
635  else
636  size = -1;
637  }
638  else
639  size += st.st_size / MEGABYTE(1);
640  }
641  else {
642  LOG_ERROR_STR(*buffer);
643  size = -1;
644  }
645  }
646  return size;
647  }
648  else if (errno != ENOENT)
649  LOG_ERROR_STR(DirName);
650  return -1;
651 }
652 
653 char *ReadLink(const char *FileName)
654 {
655  if (!FileName)
656  return NULL;
657  char *TargetName = canonicalize_file_name(FileName);
658  if (!TargetName) {
659  if (errno == ENOENT) // file doesn't exist
660  TargetName = strdup(FileName);
661  else // some other error occurred
662  LOG_ERROR_STR(FileName);
663  }
664  return TargetName;
665 }
666 
667 bool SpinUpDisk(const char *FileName)
668 {
669  for (int n = 0; n < 10; n++) {
670  cString buf;
671  if (DirectoryOk(FileName))
672  buf = cString::sprintf("%s/vdr-%06d", *FileName ? FileName : ".", n);
673  else
674  buf = cString::sprintf("%s.vdr-%06d", FileName, n);
675  if (access(buf, F_OK) != 0) { // the file does not exist
676  timeval tp1, tp2;
677  gettimeofday(&tp1, NULL);
678  int f = open(buf, O_WRONLY | O_CREAT, DEFFILEMODE);
679  // O_SYNC doesn't work on all file systems
680  if (f >= 0) {
681  if (fdatasync(f) < 0)
682  LOG_ERROR_STR(*buf);
683  close(f);
684  remove(buf);
685  gettimeofday(&tp2, NULL);
686  double seconds = (((long long)tp2.tv_sec * 1000000 + tp2.tv_usec) - ((long long)tp1.tv_sec * 1000000 + tp1.tv_usec)) / 1000000.0;
687  if (seconds > 0.5)
688  dsyslog("SpinUpDisk took %.2f seconds", seconds);
689  return true;
690  }
691  else
692  LOG_ERROR_STR(*buf);
693  }
694  }
695  esyslog("ERROR: SpinUpDisk failed");
696  return false;
697 }
698 
699 void TouchFile(const char *FileName)
700 {
701  if (utime(FileName, NULL) == -1 && errno != ENOENT)
702  LOG_ERROR_STR(FileName);
703 }
704 
705 time_t LastModifiedTime(const char *FileName)
706 {
707  struct stat fs;
708  if (stat(FileName, &fs) == 0)
709  return fs.st_mtime;
710  return 0;
711 }
712 
713 off_t FileSize(const char *FileName)
714 {
715  struct stat fs;
716  if (stat(FileName, &fs) == 0)
717  return fs.st_size;
718  return -1;
719 }
720 
721 // --- cTimeMs ---------------------------------------------------------------
722 
724 {
725  if (Ms >= 0)
726  Set(Ms);
727  else
728  begin = 0;
729 }
730 
731 uint64_t cTimeMs::Now(void)
732 {
733 #if _POSIX_TIMERS > 0 && defined(_POSIX_MONOTONIC_CLOCK)
734 #define MIN_RESOLUTION 5 // ms
735  static bool initialized = false;
736  static bool monotonic = false;
737  struct timespec tp;
738  if (!initialized) {
739  // check if monotonic timer is available and provides enough accurate resolution:
740  if (clock_getres(CLOCK_MONOTONIC, &tp) == 0) {
741  long Resolution = tp.tv_nsec;
742  // require a minimum resolution:
743  if (tp.tv_sec == 0 && tp.tv_nsec <= MIN_RESOLUTION * 1000000) {
744  if (clock_gettime(CLOCK_MONOTONIC, &tp) == 0) {
745  dsyslog("cTimeMs: using monotonic clock (resolution is %ld ns)", Resolution);
746  monotonic = true;
747  }
748  else
749  esyslog("cTimeMs: clock_gettime(CLOCK_MONOTONIC) failed");
750  }
751  else
752  dsyslog("cTimeMs: not using monotonic clock - resolution is too bad (%ld s %ld ns)", tp.tv_sec, tp.tv_nsec);
753  }
754  else
755  esyslog("cTimeMs: clock_getres(CLOCK_MONOTONIC) failed");
756  initialized = true;
757  }
758  if (monotonic) {
759  if (clock_gettime(CLOCK_MONOTONIC, &tp) == 0)
760  return (uint64_t(tp.tv_sec)) * 1000 + tp.tv_nsec / 1000000;
761  esyslog("cTimeMs: clock_gettime(CLOCK_MONOTONIC) failed");
762  monotonic = false;
763  // fall back to gettimeofday()
764  }
765 #else
766 # warning Posix monotonic clock not available
767 #endif
768  struct timeval t;
769  if (gettimeofday(&t, NULL) == 0)
770  return (uint64_t(t.tv_sec)) * 1000 + t.tv_usec / 1000;
771  return 0;
772 }
773 
774 void cTimeMs::Set(int Ms)
775 {
776  begin = Now() + Ms;
777 }
778 
779 bool cTimeMs::TimedOut(void) const
780 {
781  return Now() >= begin;
782 }
783 
784 uint64_t cTimeMs::Elapsed(void) const
785 {
786  return Now() - begin;
787 }
788 
789 // --- UTF-8 support ---------------------------------------------------------
790 
791 static uint SystemToUtf8[128] = { 0 };
792 
793 int Utf8CharLen(const char *s)
794 {
796  return 1;
797 #define MT(s, m, v) ((*(s) & (m)) == (v)) // Mask Test
798  if (MT(s, 0xE0, 0xC0) && MT(s + 1, 0xC0, 0x80))
799  return 2;
800  if (MT(s, 0xF0, 0xE0) && MT(s + 1, 0xC0, 0x80) && MT(s + 2, 0xC0, 0x80))
801  return 3;
802  if (MT(s, 0xF8, 0xF0) && MT(s + 1, 0xC0, 0x80) && MT(s + 2, 0xC0, 0x80) && MT(s + 3, 0xC0, 0x80))
803  return 4;
804  return 1;
805 }
806 
807 uint Utf8CharGet(const char *s, int Length)
808 {
810  return (uchar)*s < 128 ? *s : SystemToUtf8[(uchar)*s - 128];
811  if (!Length)
812  Length = Utf8CharLen(s);
813  switch (Length) {
814  case 2: return ((*s & 0x1F) << 6) | (*(s + 1) & 0x3F);
815  case 3: return ((*s & 0x0F) << 12) | ((*(s + 1) & 0x3F) << 6) | (*(s + 2) & 0x3F);
816  case 4: return ((*s & 0x07) << 18) | ((*(s + 1) & 0x3F) << 12) | ((*(s + 2) & 0x3F) << 6) | (*(s + 3) & 0x3F);
817  default: ;
818  }
819  return *s;
820 }
821 
822 int Utf8CharSet(uint c, char *s)
823 {
824  if (c < 0x80 || cCharSetConv::SystemCharacterTable()) {
825  if (s)
826  *s = c;
827  return 1;
828  }
829  if (c < 0x800) {
830  if (s) {
831  *s++ = ((c >> 6) & 0x1F) | 0xC0;
832  *s = (c & 0x3F) | 0x80;
833  }
834  return 2;
835  }
836  if (c < 0x10000) {
837  if (s) {
838  *s++ = ((c >> 12) & 0x0F) | 0xE0;
839  *s++ = ((c >> 6) & 0x3F) | 0x80;
840  *s = (c & 0x3F) | 0x80;
841  }
842  return 3;
843  }
844  if (c < 0x110000) {
845  if (s) {
846  *s++ = ((c >> 18) & 0x07) | 0xF0;
847  *s++ = ((c >> 12) & 0x3F) | 0x80;
848  *s++ = ((c >> 6) & 0x3F) | 0x80;
849  *s = (c & 0x3F) | 0x80;
850  }
851  return 4;
852  }
853  return 0; // can't convert to UTF-8
854 }
855 
856 int Utf8SymChars(const char *s, int Symbols)
857 {
859  return Symbols;
860  int n = 0;
861  while (*s && Symbols--) {
862  int sl = Utf8CharLen(s);
863  s += sl;
864  n += sl;
865  }
866  return n;
867 }
868 
869 int Utf8StrLen(const char *s)
870 {
872  return strlen(s);
873  int n = 0;
874  while (*s) {
875  s += Utf8CharLen(s);
876  n++;
877  }
878  return n;
879 }
880 
881 char *Utf8Strn0Cpy(char *Dest, const char *Src, int n)
882 {
884  return strn0cpy(Dest, Src, n);
885  char *d = Dest;
886  while (*Src) {
887  int sl = Utf8CharLen(Src);
888  n -= sl;
889  if (n > 0) {
890  while (sl--)
891  *d++ = *Src++;
892  }
893  else
894  break;
895  }
896  *d = 0;
897  return Dest;
898 }
899 
900 int Utf8ToArray(const char *s, uint *a, int Size)
901 {
902  int n = 0;
903  while (*s && --Size > 0) {
905  *a++ = (uchar)(*s++);
906  else {
907  int sl = Utf8CharLen(s);
908  *a++ = Utf8CharGet(s, sl);
909  s += sl;
910  }
911  n++;
912  }
913  if (Size > 0)
914  *a = 0;
915  return n;
916 }
917 
918 int Utf8FromArray(const uint *a, char *s, int Size, int Max)
919 {
920  int NumChars = 0;
921  int NumSyms = 0;
922  while (*a && NumChars < Size) {
923  if (Max >= 0 && NumSyms++ >= Max)
924  break;
926  *s++ = *a++;
927  NumChars++;
928  }
929  else {
930  int sl = Utf8CharSet(*a);
931  if (NumChars + sl <= Size) {
932  Utf8CharSet(*a, s);
933  a++;
934  s += sl;
935  NumChars += sl;
936  }
937  else
938  break;
939  }
940  }
941  if (NumChars < Size)
942  *s = 0;
943  return NumChars;
944 }
945 
946 // --- cCharSetConv ----------------------------------------------------------
947 
949 
950 cCharSetConv::cCharSetConv(const char *FromCode, const char *ToCode)
951 {
952  if (!FromCode)
953  FromCode = systemCharacterTable ? systemCharacterTable : "UTF-8";
954  if (!ToCode)
955  ToCode = "UTF-8";
956  cd = iconv_open(ToCode, FromCode);
957  result = NULL;
958  length = 0;
959 }
960 
962 {
963  free(result);
964  if (cd != (iconv_t)-1)
965  iconv_close(cd);
966 }
967 
968 void cCharSetConv::SetSystemCharacterTable(const char *CharacterTable)
969 {
970  free(systemCharacterTable);
971  systemCharacterTable = NULL;
972  if (!strcasestr(CharacterTable, "UTF-8")) {
973  // Set up a map for the character values 128...255:
974  char buf[129];
975  for (int i = 0; i < 128; i++)
976  buf[i] = i + 128;
977  buf[128] = 0;
978  cCharSetConv csc(CharacterTable);
979  const char *s = csc.Convert(buf);
980  int i = 0;
981  while (*s) {
982  int sl = Utf8CharLen(s);
983  SystemToUtf8[i] = Utf8CharGet(s, sl);
984  s += sl;
985  i++;
986  }
987  systemCharacterTable = strdup(CharacterTable);
988  }
989 }
990 
991 const char *cCharSetConv::Convert(const char *From, char *To, size_t ToLength)
992 {
993  if (cd != (iconv_t)-1 && From && *From) {
994  char *FromPtr = (char *)From;
995  size_t FromLength = strlen(From);
996  char *ToPtr = To;
997  if (!ToPtr) {
998  int NewLength = max(length, FromLength * 2); // some reserve to avoid later reallocations
999  if (char *NewBuffer = (char *)realloc(result, NewLength)) {
1000  length = NewLength;
1001  result = NewBuffer;
1002  }
1003  else {
1004  esyslog("ERROR: out of memory");
1005  return From;
1006  }
1007  ToPtr = result;
1008  ToLength = length;
1009  }
1010  else if (!ToLength)
1011  return From; // can't convert into a zero sized buffer
1012  ToLength--; // save space for terminating 0
1013  char *Converted = ToPtr;
1014  while (FromLength > 0) {
1015  if (iconv(cd, &FromPtr, &FromLength, &ToPtr, &ToLength) == size_t(-1)) {
1016  if (errno == E2BIG || errno == EILSEQ && ToLength < 1) {
1017  if (To)
1018  break; // caller provided a fixed size buffer, but it was too small
1019  // The result buffer is too small, so increase it:
1020  size_t d = ToPtr - result;
1021  size_t r = length / 2;
1022  int NewLength = length + r;
1023  if (char *NewBuffer = (char *)realloc(result, NewLength)) {
1024  length = NewLength;
1025  Converted = result = NewBuffer;
1026  }
1027  else {
1028  esyslog("ERROR: out of memory");
1029  return From;
1030  }
1031  ToLength += r;
1032  ToPtr = result + d;
1033  }
1034  if (errno == EILSEQ) {
1035  // A character can't be converted, so mark it with '?' and proceed:
1036  FromPtr++;
1037  FromLength--;
1038  *ToPtr++ = '?';
1039  ToLength--;
1040  }
1041  else if (errno != E2BIG)
1042  return From; // unknown error, return original string
1043  }
1044  }
1045  *ToPtr = 0;
1046  return Converted;
1047  }
1048  return From;
1049 }
1050 
1051 // --- cString ---------------------------------------------------------------
1052 
1053 cString::cString(const char *S, bool TakePointer)
1054 {
1055  s = TakePointer ? (char *)S : S ? strdup(S) : NULL;
1056 }
1057 
1058 cString::cString(const char *S, const char *To)
1059 {
1060  if (!S)
1061  s = NULL;
1062  else if (!To)
1063  s = strdup(S);
1064  else {
1065  int l = To - S;
1066  s = MALLOC(char, l + 1);
1067  strncpy(s, S, l);
1068  s[l] = 0;
1069  }
1070 }
1071 
1073 {
1074  s = String.s ? strdup(String.s) : NULL;
1075 }
1076 
1078 {
1079  free(s);
1080 }
1081 
1083 {
1084  if (this == &String)
1085  return *this;
1086  free(s);
1087  s = String.s ? strdup(String.s) : NULL;
1088  return *this;
1089 }
1090 
1091 cString &cString::operator=(const char *String)
1092 {
1093  if (s == String)
1094  return *this;
1095  free(s);
1096  s = String ? strdup(String) : NULL;
1097  return *this;
1098 }
1099 
1100 cString &cString::Append(const char *String)
1101 {
1102  if (String) {
1103  int l1 = s ? strlen(s) : 0;
1104  int l2 = strlen(String);
1105  if (char *p = (char *)realloc(s, l1 + l2 + 1)) {
1106  s = p;
1107  strcpy(s + l1, String);
1108  }
1109  else
1110  esyslog("ERROR: out of memory");
1111  }
1112  return *this;
1113 }
1114 
1116 {
1117  int l = strlen(s);
1118  if (Index < 0)
1119  Index = l + Index;
1120  if (Index >= 0 && Index < l)
1121  s[Index] = 0;
1122  return *this;
1123 }
1124 
1126 {
1127  compactchars(s, c);
1128  return *this;
1129 }
1130 
1131 cString cString::sprintf(const char *fmt, ...)
1132 {
1133  va_list ap;
1134  va_start(ap, fmt);
1135  char *buffer;
1136  if (!fmt || vasprintf(&buffer, fmt, ap) < 0) {
1137  esyslog("error in vasprintf('%s', ...)", fmt);
1138  buffer = strdup("???");
1139  }
1140  va_end(ap);
1141  return cString(buffer, true);
1142 }
1143 
1144 cString cString::vsprintf(const char *fmt, va_list &ap)
1145 {
1146  char *buffer;
1147  if (!fmt || vasprintf(&buffer, fmt, ap) < 0) {
1148  esyslog("error in vasprintf('%s', ...)", fmt);
1149  buffer = strdup("???");
1150  }
1151  return cString(buffer, true);
1152 }
1153 
1154 cString WeekDayName(int WeekDay)
1155 {
1156  char buffer[16];
1157  WeekDay = WeekDay == 0 ? 6 : WeekDay - 1; // we start with Monday==0!
1158  if (0 <= WeekDay && WeekDay <= 6) {
1159  // TRANSLATORS: abbreviated weekdays, beginning with monday (must all be 3 letters!)
1160  const char *day = tr("MonTueWedThuFriSatSun");
1161  day += Utf8SymChars(day, WeekDay * 3);
1162  strn0cpy(buffer, day, min(Utf8SymChars(day, 3) + 1, int(sizeof(buffer))));
1163  return buffer;
1164  }
1165  else
1166  return "???";
1167 }
1168 
1170 {
1171  struct tm tm_r;
1172  return WeekDayName(localtime_r(&t, &tm_r)->tm_wday);
1173 }
1174 
1176 {
1177  WeekDay = WeekDay == 0 ? 6 : WeekDay - 1; // we start with Monday==0!
1178  switch (WeekDay) {
1179  case 0: return tr("Monday");
1180  case 1: return tr("Tuesday");
1181  case 2: return tr("Wednesday");
1182  case 3: return tr("Thursday");
1183  case 4: return tr("Friday");
1184  case 5: return tr("Saturday");
1185  case 6: return tr("Sunday");
1186  default: return "???";
1187  }
1188 }
1189 
1191 {
1192  struct tm tm_r;
1193  return WeekDayNameFull(localtime_r(&t, &tm_r)->tm_wday);
1194 }
1195 
1197 {
1198  char buffer[32];
1199  if (t == 0)
1200  time(&t);
1201  struct tm tm_r;
1202  tm *tm = localtime_r(&t, &tm_r);
1203  snprintf(buffer, sizeof(buffer), "%s %02d.%02d. %02d:%02d", *WeekDayName(tm->tm_wday), tm->tm_mday, tm->tm_mon + 1, tm->tm_hour, tm->tm_min);
1204  return buffer;
1205 }
1206 
1208 {
1209  char buffer[32];
1210  if (ctime_r(&t, buffer)) {
1211  buffer[strlen(buffer) - 1] = 0; // strip trailing newline
1212  return buffer;
1213  }
1214  return "???";
1215 }
1216 
1218 {
1219  char buf[32];
1220  struct tm tm_r;
1221  tm *tm = localtime_r(&t, &tm_r);
1222  char *p = stpcpy(buf, WeekDayName(tm->tm_wday));
1223  *p++ = ' ';
1224  strftime(p, sizeof(buf) - (p - buf), "%d.%m.%Y", tm);
1225  return buf;
1226 }
1227 
1229 {
1230  char buf[32];
1231  struct tm tm_r;
1232  tm *tm = localtime_r(&t, &tm_r);
1233  strftime(buf, sizeof(buf), "%d.%m.%y", tm);
1234  return buf;
1235 }
1236 
1238 {
1239  char buf[25];
1240  struct tm tm_r;
1241  strftime(buf, sizeof(buf), "%R", localtime_r(&t, &tm_r));
1242  return buf;
1243 }
1244 
1245 // --- RgbToJpeg -------------------------------------------------------------
1246 
1247 #define JPEGCOMPRESSMEM 500000
1248 
1249 struct tJpegCompressData {
1250  int size;
1251  uchar *mem;
1252  };
1253 
1254 static void JpegCompressInitDestination(j_compress_ptr cinfo)
1255 {
1256  tJpegCompressData *jcd = (tJpegCompressData *)cinfo->client_data;
1257  if (jcd) {
1258  cinfo->dest->free_in_buffer = jcd->size = JPEGCOMPRESSMEM;
1259  cinfo->dest->next_output_byte = jcd->mem = MALLOC(uchar, jcd->size);
1260  }
1261 }
1262 
1263 static boolean JpegCompressEmptyOutputBuffer(j_compress_ptr cinfo)
1264 {
1265  tJpegCompressData *jcd = (tJpegCompressData *)cinfo->client_data;
1266  if (jcd) {
1267  int Used = jcd->size;
1268  int NewSize = jcd->size + JPEGCOMPRESSMEM;
1269  if (uchar *NewBuffer = (uchar *)realloc(jcd->mem, NewSize)) {
1270  jcd->size = NewSize;
1271  jcd->mem = NewBuffer;
1272  }
1273  else {
1274  esyslog("ERROR: out of memory");
1275  return FALSE;
1276  }
1277  if (jcd->mem) {
1278  cinfo->dest->next_output_byte = jcd->mem + Used;
1279  cinfo->dest->free_in_buffer = jcd->size - Used;
1280  return TRUE;
1281  }
1282  }
1283  return FALSE;
1284 }
1285 
1286 static void JpegCompressTermDestination(j_compress_ptr cinfo)
1287 {
1288  tJpegCompressData *jcd = (tJpegCompressData *)cinfo->client_data;
1289  if (jcd) {
1290  int Used = cinfo->dest->next_output_byte - jcd->mem;
1291  if (Used < jcd->size) {
1292  if (uchar *NewBuffer = (uchar *)realloc(jcd->mem, Used)) {
1293  jcd->size = Used;
1294  jcd->mem = NewBuffer;
1295  }
1296  else
1297  esyslog("ERROR: out of memory");
1298  }
1299  }
1300 }
1301 
1302 uchar *RgbToJpeg(uchar *Mem, int Width, int Height, int &Size, int Quality)
1303 {
1304  if (Quality < 0)
1305  Quality = 0;
1306  else if (Quality > 100)
1307  Quality = 100;
1308 
1309  jpeg_destination_mgr jdm;
1310 
1311  jdm.init_destination = JpegCompressInitDestination;
1312  jdm.empty_output_buffer = JpegCompressEmptyOutputBuffer;
1313  jdm.term_destination = JpegCompressTermDestination;
1314 
1315  struct jpeg_compress_struct cinfo;
1316  struct jpeg_error_mgr jerr;
1317  cinfo.err = jpeg_std_error(&jerr);
1318  jpeg_create_compress(&cinfo);
1319  cinfo.dest = &jdm;
1320  tJpegCompressData jcd;
1321  cinfo.client_data = &jcd;
1322  cinfo.image_width = Width;
1323  cinfo.image_height = Height;
1324  cinfo.input_components = 3;
1325  cinfo.in_color_space = JCS_RGB;
1326 
1327  jpeg_set_defaults(&cinfo);
1328  jpeg_set_quality(&cinfo, Quality, TRUE);
1329  jpeg_start_compress(&cinfo, TRUE);
1330 
1331  int rs = Width * 3;
1332  JSAMPROW rp[Height];
1333  for (int k = 0; k < Height; k++)
1334  rp[k] = &Mem[rs * k];
1335  jpeg_write_scanlines(&cinfo, rp, Height);
1336  jpeg_finish_compress(&cinfo);
1337  jpeg_destroy_compress(&cinfo);
1338 
1339  Size = jcd.size;
1340  return jcd.mem;
1341 }
1342 
1343 // --- GetHostName -----------------------------------------------------------
1344 
1345 const char *GetHostName(void)
1346 {
1347  static char buffer[HOST_NAME_MAX] = "";
1348  if (!*buffer) {
1349  if (gethostname(buffer, sizeof(buffer)) < 0) {
1350  LOG_ERROR;
1351  strcpy(buffer, "vdr");
1352  }
1353  }
1354  return buffer;
1355 }
1356 
1357 // --- cBase64Encoder --------------------------------------------------------
1358 
1359 const char *cBase64Encoder::b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
1360 
1361 cBase64Encoder::cBase64Encoder(const uchar *Data, int Length, int MaxResult)
1362 {
1363  data = Data;
1364  length = Length;
1365  maxResult = MaxResult;
1366  i = 0;
1367  result = MALLOC(char, maxResult + 1);
1368 }
1369 
1371 {
1372  free(result);
1373 }
1374 
1375 const char *cBase64Encoder::NextLine(void)
1376 {
1377  int r = 0;
1378  while (i < length && r < maxResult - 3) {
1379  result[r++] = b64[(data[i] >> 2) & 0x3F];
1380  uchar c = (data[i] << 4) & 0x3F;
1381  if (++i < length)
1382  c |= (data[i] >> 4) & 0x0F;
1383  result[r++] = b64[c];
1384  if (i < length) {
1385  c = (data[i] << 2) & 0x3F;
1386  if (++i < length)
1387  c |= (data[i] >> 6) & 0x03;
1388  result[r++] = b64[c];
1389  }
1390  else {
1391  i++;
1392  result[r++] = '=';
1393  }
1394  if (i < length) {
1395  c = data[i] & 0x3F;
1396  result[r++] = b64[c];
1397  }
1398  else
1399  result[r++] = '=';
1400  i++;
1401  }
1402  if (r > 0) {
1403  result[r] = 0;
1404  return result;
1405  }
1406  return NULL;
1407 }
1408 
1409 // --- cBitStream ------------------------------------------------------------
1410 
1412 {
1413  if (index >= length)
1414  return 1;
1415  int r = (data[index >> 3] >> (7 - (index & 7))) & 1;
1416  ++index;
1417  return r;
1418 }
1419 
1420 uint32_t cBitStream::GetBits(int n)
1421 {
1422  uint32_t r = 0;
1423  while (n--)
1424  r |= GetBit() << n;
1425  return r;
1426 }
1427 
1429 {
1430  int n = index % 8;
1431  if (n > 0)
1432  SkipBits(8 - n);
1433 }
1434 
1436 {
1437  int n = index % 16;
1438  if (n > 0)
1439  SkipBits(16 - n);
1440 }
1441 
1442 bool cBitStream::SetLength(int Length)
1443 {
1444  if (Length > length)
1445  return false;
1446  length = Length;
1447  return true;
1448 }
1449 
1450 // --- cReadLine -------------------------------------------------------------
1451 
1453 {
1454  size = 0;
1455  buffer = NULL;
1456 }
1457 
1459 {
1460  free(buffer);
1461 }
1462 
1463 char *cReadLine::Read(FILE *f)
1464 {
1465  int n = getline(&buffer, &size, f);
1466  if (n > 0) {
1467  n--;
1468  if (buffer[n] == '\n') {
1469  buffer[n] = 0;
1470  if (n > 0) {
1471  n--;
1472  if (buffer[n] == '\r')
1473  buffer[n] = 0;
1474  }
1475  }
1476  return buffer;
1477  }
1478  return NULL;
1479 }
1480 
1481 // --- cPoller ---------------------------------------------------------------
1482 
1483 cPoller::cPoller(int FileHandle, bool Out)
1484 {
1485  numFileHandles = 0;
1486  Add(FileHandle, Out);
1487 }
1488 
1489 bool cPoller::Add(int FileHandle, bool Out)
1490 {
1491  if (FileHandle >= 0) {
1492  for (int i = 0; i < numFileHandles; i++) {
1493  if (pfd[i].fd == FileHandle && pfd[i].events == (Out ? POLLOUT : POLLIN))
1494  return true;
1495  }
1496  if (numFileHandles < MaxPollFiles) {
1497  pfd[numFileHandles].fd = FileHandle;
1498  pfd[numFileHandles].events = Out ? POLLOUT : POLLIN;
1499  pfd[numFileHandles].revents = 0;
1500  numFileHandles++;
1501  return true;
1502  }
1503  esyslog("ERROR: too many file handles in cPoller");
1504  }
1505  return false;
1506 }
1507 
1508 void cPoller::Del(int FileHandle, bool Out)
1509 {
1510  if (FileHandle >= 0) {
1511  for (int i = 0; i < numFileHandles; i++) {
1512  if (pfd[i].fd == FileHandle && pfd[i].events == (Out ? POLLOUT : POLLIN)) {
1513  if (i < numFileHandles - 1)
1514  memmove(&pfd[i], &pfd[i + 1], (numFileHandles - i - 1) * sizeof(pollfd));
1515  numFileHandles--;
1516  }
1517  }
1518  }
1519 }
1520 
1521 bool cPoller::Poll(int TimeoutMs)
1522 {
1523  if (numFileHandles) {
1524  if (poll(pfd, numFileHandles, TimeoutMs) != 0)
1525  return true; // returns true even in case of an error, to let the caller
1526  // access the file and thus see the error code
1527  }
1528  return false;
1529 }
1530 
1531 // --- cReadDir --------------------------------------------------------------
1532 
1533 cReadDir::cReadDir(const char *Directory)
1534 {
1535  directory = opendir(Directory);
1536 }
1537 
1539 {
1540  if (directory)
1541  closedir(directory);
1542 }
1543 
1544 struct dirent *cReadDir::Next(void)
1545 {
1546  if (directory) {
1547 #if !__GLIBC_PREREQ(2, 24) // readdir_r() is deprecated as of GLIBC 2.24
1548  while (readdir_r(directory, &u.d, &result) == 0 && result) {
1549 #else
1550  while ((result = readdir(directory)) != NULL) {
1551 #endif
1552  if (strcmp(result->d_name, ".") && strcmp(result->d_name, ".."))
1553  return result;
1554  }
1555  }
1556  return NULL;
1557 }
1558 
1559 // --- cStringList -----------------------------------------------------------
1560 
1562 {
1563  Clear();
1564 }
1565 
1566 int cStringList::Find(const char *s) const
1567 {
1568  for (int i = 0; i < Size(); i++) {
1569  if (!strcmp(s, At(i)))
1570  return i;
1571  }
1572  return -1;
1573 }
1574 
1576 {
1577  for (int i = 0; i < Size(); i++)
1578  free(At(i));
1580 }
1581 
1582 // --- cFileNameList ---------------------------------------------------------
1583 
1584 // TODO better GetFileNames(const char *Directory, cStringList *List)?
1585 cFileNameList::cFileNameList(const char *Directory, bool DirsOnly)
1586 {
1587  Load(Directory, DirsOnly);
1588 }
1589 
1590 bool cFileNameList::Load(const char *Directory, bool DirsOnly)
1591 {
1592  Clear();
1593  if (Directory) {
1594  cReadDir d(Directory);
1595  struct dirent *e;
1596  if (d.Ok()) {
1597  while ((e = d.Next()) != NULL) {
1598  if (DirsOnly) {
1599  struct stat ds;
1600  if (stat(AddDirectory(Directory, e->d_name), &ds) == 0) {
1601  if (!S_ISDIR(ds.st_mode))
1602  continue;
1603  }
1604  }
1605  Append(strdup(e->d_name));
1606  }
1607  Sort();
1608  return true;
1609  }
1610  else
1611  LOG_ERROR_STR(Directory);
1612  }
1613  return false;
1614 }
1615 
1616 // --- cFile -----------------------------------------------------------------
1617 
1618 bool cFile::files[FD_SETSIZE] = { false };
1619 int cFile::maxFiles = 0;
1620 
1622 {
1623  f = -1;
1624 }
1625 
1627 {
1628  Close();
1629 }
1630 
1631 bool cFile::Open(const char *FileName, int Flags, mode_t Mode)
1632 {
1633  if (!IsOpen())
1634  return Open(open(FileName, Flags, Mode));
1635  esyslog("ERROR: attempt to re-open %s", FileName);
1636  return false;
1637 }
1638 
1639 bool cFile::Open(int FileDes)
1640 {
1641  if (FileDes >= 0) {
1642  if (!IsOpen()) {
1643  f = FileDes;
1644  if (f >= 0) {
1645  if (f < FD_SETSIZE) {
1646  if (f >= maxFiles)
1647  maxFiles = f + 1;
1648  if (!files[f])
1649  files[f] = true;
1650  else
1651  esyslog("ERROR: file descriptor %d already in files[]", f);
1652  return true;
1653  }
1654  else
1655  esyslog("ERROR: file descriptor %d is larger than FD_SETSIZE (%d)", f, FD_SETSIZE);
1656  }
1657  }
1658  else
1659  esyslog("ERROR: attempt to re-open file descriptor %d", FileDes);
1660  }
1661  return false;
1662 }
1663 
1664 void cFile::Close(void)
1665 {
1666  if (f >= 0) {
1667  close(f);
1668  files[f] = false;
1669  f = -1;
1670  }
1671 }
1672 
1673 bool cFile::Ready(bool Wait)
1674 {
1675  return f >= 0 && AnyFileReady(f, Wait ? 1000 : 0);
1676 }
1677 
1678 bool cFile::AnyFileReady(int FileDes, int TimeoutMs)
1679 {
1680  fd_set set;
1681  FD_ZERO(&set);
1682  for (int i = 0; i < maxFiles; i++) {
1683  if (files[i])
1684  FD_SET(i, &set);
1685  }
1686  if (0 <= FileDes && FileDes < FD_SETSIZE && !files[FileDes])
1687  FD_SET(FileDes, &set); // in case we come in with an arbitrary descriptor
1688  if (TimeoutMs == 0)
1689  TimeoutMs = 10; // load gets too heavy with 0
1690  struct timeval timeout;
1691  timeout.tv_sec = TimeoutMs / 1000;
1692  timeout.tv_usec = (TimeoutMs % 1000) * 1000;
1693  return select(FD_SETSIZE, &set, NULL, NULL, &timeout) > 0 && (FileDes < 0 || FD_ISSET(FileDes, &set));
1694 }
1695 
1696 bool cFile::FileReady(int FileDes, int TimeoutMs)
1697 {
1698  fd_set set;
1699  struct timeval timeout;
1700  FD_ZERO(&set);
1701  FD_SET(FileDes, &set);
1702  if (TimeoutMs >= 0) {
1703  if (TimeoutMs < 100)
1704  TimeoutMs = 100;
1705  timeout.tv_sec = TimeoutMs / 1000;
1706  timeout.tv_usec = (TimeoutMs % 1000) * 1000;
1707  }
1708  return select(FD_SETSIZE, &set, NULL, NULL, (TimeoutMs >= 0) ? &timeout : NULL) > 0 && FD_ISSET(FileDes, &set);
1709 }
1710 
1711 bool cFile::FileReadyForWriting(int FileDes, int TimeoutMs)
1712 {
1713  fd_set set;
1714  struct timeval timeout;
1715  FD_ZERO(&set);
1716  FD_SET(FileDes, &set);
1717  if (TimeoutMs < 100)
1718  TimeoutMs = 100;
1719  timeout.tv_sec = 0;
1720  timeout.tv_usec = TimeoutMs * 1000;
1721  return select(FD_SETSIZE, NULL, &set, NULL, &timeout) > 0 && FD_ISSET(FileDes, &set);
1722 }
1723 
1724 // --- cSafeFile -------------------------------------------------------------
1725 
1726 cSafeFile::cSafeFile(const char *FileName)
1727 {
1728  f = NULL;
1729  fileName = ReadLink(FileName);
1730  tempName = fileName ? MALLOC(char, strlen(fileName) + 5) : NULL;
1731  if (tempName)
1732  strcat(strcpy(tempName, fileName), ".$$$");
1733 }
1734 
1736 {
1737  if (f)
1738  fclose(f);
1739  unlink(tempName);
1740  free(fileName);
1741  free(tempName);
1742 }
1743 
1745 {
1746  if (!f && fileName && tempName) {
1747  f = fopen(tempName, "w");
1748  if (!f)
1749  LOG_ERROR_STR(tempName);
1750  }
1751  return f != NULL;
1752 }
1753 
1755 {
1756  bool result = true;
1757  if (f) {
1758  if (ferror(f) != 0) {
1759  LOG_ERROR_STR(tempName);
1760  result = false;
1761  }
1762  fflush(f);
1763  fsync(fileno(f));
1764  if (fclose(f) < 0) {
1765  LOG_ERROR_STR(tempName);
1766  result = false;
1767  }
1768  f = NULL;
1769  if (result && rename(tempName, fileName) < 0) {
1770  LOG_ERROR_STR(fileName);
1771  result = false;
1772  }
1773  }
1774  else
1775  result = false;
1776  return result;
1777 }
1778 
1779 // --- cUnbufferedFile -------------------------------------------------------
1780 
1781 #ifndef USE_FADVISE_READ
1782 #define USE_FADVISE_READ 0
1783 #endif
1784 #ifndef USE_FADVISE_WRITE
1785 #define USE_FADVISE_WRITE 1
1786 #endif
1787 
1788 #define WRITE_BUFFER KILOBYTE(800)
1789 
1791 {
1792  fd = -1;
1793 }
1794 
1796 {
1797  Close();
1798 }
1799 
1800 int cUnbufferedFile::Open(const char *FileName, int Flags, mode_t Mode)
1801 {
1802  Close();
1803  fd = open(FileName, Flags, Mode);
1804  curpos = 0;
1805 #if USE_FADVISE_READ || USE_FADVISE_WRITE
1806  begin = lastpos = ahead = 0;
1807  cachedstart = 0;
1808  cachedend = 0;
1809  readahead = KILOBYTE(128);
1810  written = 0;
1811  totwritten = 0;
1812  if (fd >= 0)
1813  posix_fadvise(fd, 0, 0, POSIX_FADV_RANDOM); // we could use POSIX_FADV_SEQUENTIAL, but we do our own readahead, disabling the kernel one.
1814 #endif
1815  return fd;
1816 }
1817 
1819 {
1820  if (fd >= 0) {
1821 #if USE_FADVISE_READ || USE_FADVISE_WRITE
1822  if (totwritten) // if we wrote anything make sure the data has hit the disk before
1823  fdatasync(fd); // calling fadvise, as this is our last chance to un-cache it.
1824  posix_fadvise(fd, 0, 0, POSIX_FADV_DONTNEED);
1825 #endif
1826  int OldFd = fd;
1827  fd = -1;
1828  return close(OldFd);
1829  }
1830  errno = EBADF;
1831  return -1;
1832 }
1833 
1834 // When replaying and going e.g. FF->PLAY the position jumps back 2..8M
1835 // hence we do not want to drop recently accessed data at once.
1836 // We try to handle the common cases such as PLAY->FF->PLAY, small
1837 // jumps, moving editing marks etc.
1838 
1839 #define FADVGRAN KILOBYTE(4) // AKA fadvise-chunk-size; PAGE_SIZE or getpagesize(2) would also work.
1840 #define READCHUNK MEGABYTE(8)
1841 
1843 {
1844  readahead = ra;
1845 }
1846 
1847 int cUnbufferedFile::FadviseDrop(off_t Offset, off_t Len)
1848 {
1849  // rounding up the window to make sure that not PAGE_SIZE-aligned data gets freed.
1850  return posix_fadvise(fd, Offset - (FADVGRAN - 1), Len + (FADVGRAN - 1) * 2, POSIX_FADV_DONTNEED);
1851 }
1852 
1853 off_t cUnbufferedFile::Seek(off_t Offset, int Whence)
1854 {
1855  if (Whence == SEEK_SET && Offset == curpos)
1856  return curpos;
1857  curpos = lseek(fd, Offset, Whence);
1858  return curpos;
1859 }
1860 
1861 ssize_t cUnbufferedFile::Read(void *Data, size_t Size)
1862 {
1863  if (fd >= 0) {
1864 #if USE_FADVISE_READ
1865  off_t jumped = curpos-lastpos; // nonzero means we're not at the last offset
1866  if ((cachedstart < cachedend) && (curpos < cachedstart || curpos > cachedend)) {
1867  // current position is outside the cached window -- invalidate it.
1868  FadviseDrop(cachedstart, cachedend-cachedstart);
1869  cachedstart = curpos;
1870  cachedend = curpos;
1871  }
1872  cachedstart = min(cachedstart, curpos);
1873 #endif
1874  ssize_t bytesRead = safe_read(fd, Data, Size);
1875  if (bytesRead > 0) {
1876  curpos += bytesRead;
1877 #if USE_FADVISE_READ
1878  cachedend = max(cachedend, curpos);
1879 
1880  // Read ahead:
1881  // no jump? (allow small forward jump still inside readahead window).
1882  if (jumped >= 0 && jumped <= (off_t)readahead) {
1883  // Trigger the readahead IO, but only if we've used at least
1884  // 1/2 of the previously requested area. This avoids calling
1885  // fadvise() after every read() call.
1886  if (ahead - curpos < (off_t)(readahead / 2)) {
1887  posix_fadvise(fd, curpos, readahead, POSIX_FADV_WILLNEED);
1888  ahead = curpos + readahead;
1889  cachedend = max(cachedend, ahead);
1890  }
1891  if (readahead < Size * 32) { // automagically tune readahead size.
1892  readahead = Size * 32;
1893  }
1894  }
1895  else
1896  ahead = curpos; // jumped -> we really don't want any readahead, otherwise e.g. fast-rewind gets in trouble.
1897 #endif
1898  }
1899 #if USE_FADVISE_READ
1900  if (cachedstart < cachedend) {
1901  if (curpos - cachedstart > READCHUNK * 2) {
1902  // current position has moved forward enough, shrink tail window.
1903  FadviseDrop(cachedstart, curpos - READCHUNK - cachedstart);
1904  cachedstart = curpos - READCHUNK;
1905  }
1906  else if (cachedend > ahead && cachedend - curpos > READCHUNK * 2) {
1907  // current position has moved back enough, shrink head window.
1908  FadviseDrop(curpos + READCHUNK, cachedend - (curpos + READCHUNK));
1909  cachedend = curpos + READCHUNK;
1910  }
1911  }
1912  lastpos = curpos;
1913 #endif
1914  return bytesRead;
1915  }
1916  return -1;
1917 }
1918 
1919 ssize_t cUnbufferedFile::Write(const void *Data, size_t Size)
1920 {
1921  if (fd >=0) {
1922  ssize_t bytesWritten = safe_write(fd, Data, Size);
1923 #if USE_FADVISE_WRITE
1924  if (bytesWritten > 0) {
1925  begin = min(begin, curpos);
1926  curpos += bytesWritten;
1927  written += bytesWritten;
1928  lastpos = max(lastpos, curpos);
1929  if (written > WRITE_BUFFER) {
1930  if (lastpos > begin) {
1931  // Now do three things:
1932  // 1) Start writeback of begin..lastpos range
1933  // 2) Drop the already written range (by the previous fadvise call)
1934  // 3) Handle nonpagealigned data.
1935  // This is why we double the WRITE_BUFFER; the first time around the
1936  // last (partial) page might be skipped, writeback will start only after
1937  // second call; the third call will still include this page and finally
1938  // drop it from cache.
1939  off_t headdrop = min(begin, off_t(WRITE_BUFFER * 2));
1940  posix_fadvise(fd, begin - headdrop, lastpos - begin + headdrop, POSIX_FADV_DONTNEED);
1941  }
1942  begin = lastpos = curpos;
1943  totwritten += written;
1944  written = 0;
1945  // The above fadvise() works when writing slowly (recording), but could
1946  // leave cached data around when writing at a high rate, e.g. when cutting,
1947  // because by the time we try to flush the cached pages (above) the data
1948  // can still be dirty - we are faster than the disk I/O.
1949  // So we do another round of flushing, just like above, but at larger
1950  // intervals -- this should catch any pages that couldn't be released
1951  // earlier.
1952  if (totwritten > MEGABYTE(32)) {
1953  // It seems in some setups, fadvise() does not trigger any I/O and
1954  // a fdatasync() call would be required do all the work (reiserfs with some
1955  // kind of write gathering enabled), but the syncs cause (io) load..
1956  // Uncomment the next line if you think you need them.
1957  //fdatasync(fd);
1958  off_t headdrop = min(off_t(curpos - totwritten), off_t(totwritten * 2));
1959  posix_fadvise(fd, curpos - totwritten - headdrop, totwritten + headdrop, POSIX_FADV_DONTNEED);
1960  totwritten = 0;
1961  }
1962  }
1963  }
1964 #endif
1965  return bytesWritten;
1966  }
1967  return -1;
1968 }
1969 
1970 cUnbufferedFile *cUnbufferedFile::Create(const char *FileName, int Flags, mode_t Mode)
1971 {
1972  cUnbufferedFile *File = new cUnbufferedFile;
1973  if (File->Open(FileName, Flags, Mode) < 0) {
1974  delete File;
1975  File = NULL;
1976  }
1977  return File;
1978 }
1979 
1980 // --- cLockFile -------------------------------------------------------------
1981 
1982 #define LOCKFILENAME ".lock-vdr"
1983 #define LOCKFILESTALETIME 600 // seconds before considering a lock file "stale"
1984 
1985 cLockFile::cLockFile(const char *Directory)
1986 {
1987  fileName = NULL;
1988  f = -1;
1989  if (DirectoryOk(Directory))
1990  fileName = strdup(AddDirectory(Directory, LOCKFILENAME));
1991 }
1992 
1994 {
1995  Unlock();
1996  free(fileName);
1997 }
1998 
1999 bool cLockFile::Lock(int WaitSeconds)
2000 {
2001  if (f < 0 && fileName) {
2002  time_t Timeout = time(NULL) + WaitSeconds;
2003  do {
2004  f = open(fileName, O_WRONLY | O_CREAT | O_EXCL, DEFFILEMODE);
2005  if (f < 0) {
2006  if (errno == EEXIST) {
2007  struct stat fs;
2008  if (stat(fileName, &fs) == 0) {
2009  if (abs(time(NULL) - fs.st_mtime) > LOCKFILESTALETIME) {
2010  esyslog("ERROR: removing stale lock file '%s'", fileName);
2011  if (remove(fileName) < 0) {
2012  LOG_ERROR_STR(fileName);
2013  break;
2014  }
2015  continue;
2016  }
2017  }
2018  else if (errno != ENOENT) {
2019  LOG_ERROR_STR(fileName);
2020  break;
2021  }
2022  }
2023  else {
2024  LOG_ERROR_STR(fileName);
2025  break;
2026  }
2027  if (WaitSeconds)
2028  cCondWait::SleepMs(1000);
2029  }
2030  } while (f < 0 && time(NULL) < Timeout);
2031  }
2032  return f >= 0;
2033 }
2034 
2036 {
2037  if (f >= 0) {
2038  close(f);
2039  remove(fileName);
2040  f = -1;
2041  }
2042 }
2043 
2044 // --- cListObject -----------------------------------------------------------
2045 
2047 {
2048  prev = next = NULL;
2049 }
2050 
2052 {
2053 }
2054 
2056 {
2057  next = Object;
2058  Object->prev = this;
2059 }
2060 
2062 {
2063  prev = Object;
2064  Object->next = this;
2065 }
2066 
2068 {
2069  if (next)
2070  next->prev = prev;
2071  if (prev)
2072  prev->next = next;
2073  next = prev = NULL;
2074 }
2075 
2076 int cListObject::Index(void) const
2077 {
2078  cListObject *p = prev;
2079  int i = 0;
2080 
2081  while (p) {
2082  i++;
2083  p = p->prev;
2084  }
2085  return i;
2086 }
2087 
2088 // --- cListGarbageCollector -------------------------------------------------
2089 
2090 #define LIST_GARBAGE_COLLECTOR_TIMEOUT 5 // seconds
2091 
2093 
2095 {
2096  objects = NULL;
2097  lastPut = 0;
2098 }
2099 
2101 {
2102  if (objects)
2103  esyslog("ERROR: ListGarbageCollector destroyed without prior Purge()!");
2104 }
2105 
2107 {
2108  mutex.Lock();
2109  Object->next = objects;
2110  objects = Object;
2111  lastPut = time(NULL);
2112  mutex.Unlock();
2113 }
2114 
2116 {
2117  mutex.Lock();
2118  if (objects && (time(NULL) - lastPut > LIST_GARBAGE_COLLECTOR_TIMEOUT || Force)) {
2119  // We make sure that any object stays in the garbage collector for at least
2120  // LIST_GARBAGE_COLLECTOR_TIMEOUT seconds, to give objects that have pointers
2121  // to them a chance to drop these references before the object is finally
2122  // deleted.
2123  while (cListObject *Object = objects) {
2124  objects = Object->next;
2125  delete Object;
2126  }
2127  }
2128  mutex.Unlock();
2129 }
2130 
2131 // --- cListBase -------------------------------------------------------------
2132 
2133 cListBase::cListBase(const char *NeedsLocking)
2134 :stateLock(NeedsLocking)
2135 {
2136  objects = lastObject = NULL;
2137  count = 0;
2138  needsLocking = NeedsLocking;
2140 }
2141 
2143 {
2144  Clear();
2145 }
2146 
2147 bool cListBase::Lock(cStateKey &StateKey, bool Write, int TimeoutMs) const
2148 {
2149  if (needsLocking)
2150  return stateLock.Lock(StateKey, Write, TimeoutMs);
2151  else
2152  esyslog("ERROR: cListBase::Lock() called for a list that doesn't require locking");
2153  return false;
2154 }
2155 
2157 {
2158  if (After && After != lastObject) {
2159  After->Next()->Insert(Object);
2160  After->Append(Object);
2161  }
2162  else {
2163  if (lastObject)
2164  lastObject->Append(Object);
2165  else
2166  objects = Object;
2167  lastObject = Object;
2168  }
2169  count++;
2170 }
2171 
2173 {
2174  if (Before && Before != objects) {
2175  Before->Prev()->Append(Object);
2176  Before->Insert(Object);
2177  }
2178  else {
2179  if (objects)
2180  objects->Insert(Object);
2181  else
2182  lastObject = Object;
2183  objects = Object;
2184  }
2185  count++;
2186 }
2187 
2188 void cListBase::Del(cListObject *Object, bool DeleteObject)
2189 {
2190  if (Object == objects)
2191  objects = Object->Next();
2192  if (Object == lastObject)
2193  lastObject = Object->Prev();
2194  Object->Unlink();
2195  if (DeleteObject) {
2196  if (useGarbageCollector)
2197  ListGarbageCollector.Put(Object);
2198  else
2199  delete Object;
2200  }
2201  count--;
2202 }
2203 
2204 void cListBase::Move(int From, int To)
2205 {
2206  Move(Get(From), Get(To));
2207 }
2208 
2210 {
2211  if (From && To && From != To) {
2212  if (From->Index() < To->Index())
2213  To = To->Next();
2214  if (From == objects)
2215  objects = From->Next();
2216  if (From == lastObject)
2217  lastObject = From->Prev();
2218  From->Unlink();
2219  if (To) {
2220  if (To->Prev())
2221  To->Prev()->Append(From);
2222  From->Append(To);
2223  }
2224  else {
2225  lastObject->Append(From);
2226  lastObject = From;
2227  }
2228  if (!From->Prev())
2229  objects = From;
2230  }
2231 }
2232 
2234 {
2235  while (objects) {
2236  cListObject *object = objects->Next();
2237  delete objects;
2238  objects = object;
2239  }
2240  objects = lastObject = NULL;
2241  count = 0;
2242 }
2243 
2244 bool cListBase::Contains(const cListObject *Object) const
2245 {
2246  for (const cListObject *o = objects; o; o = o->Next()) {
2247  if (o == Object)
2248  return true;
2249  }
2250  return false;
2251 }
2252 
2254 {
2256 }
2257 
2259 {
2261 }
2262 
2263 const cListObject *cListBase::Get(int Index) const
2264 {
2265  if (Index < 0)
2266  return NULL;
2267  const cListObject *object = objects;
2268  while (object && Index-- > 0)
2269  object = object->Next();
2270  return object;
2271 }
2272 
2273 static int CompareListObjects(const void *a, const void *b)
2274 {
2275  const cListObject *la = *(const cListObject **)a;
2276  const cListObject *lb = *(const cListObject **)b;
2277  return la->Compare(*lb);
2278 }
2279 
2281 {
2282  int n = Count();
2283  cListObject **a = MALLOC(cListObject *, n);
2284  if (a == NULL)
2285  return;
2286  cListObject *object = objects;
2287  int i = 0;
2288  while (object && i < n) {
2289  a[i++] = object;
2290  object = object->Next();
2291  }
2292  qsort(a, n, sizeof(cListObject *), CompareListObjects);
2293  objects = lastObject = NULL;
2294  for (i = 0; i < n; i++) {
2295  a[i]->Unlink();
2296  count--;
2297  Add(a[i]);
2298  }
2299  free(a);
2300 }
2301 
2302 // --- cDynamicBuffer --------------------------------------------------------
2303 
2305 {
2306  initialSize = InitialSize;
2307  buffer = NULL;
2308  size = used = 0;
2309 }
2310 
2312 {
2313  free(buffer);
2314 }
2315 
2316 bool cDynamicBuffer::Realloc(int NewSize)
2317 {
2318  if (size < NewSize) {
2319  NewSize = max(NewSize, size ? size * 3 / 2 : initialSize); // increase size by at least 50%
2320  if (uchar *NewBuffer = (uchar *)realloc(buffer, NewSize)) {
2321  buffer = NewBuffer;
2322  size = NewSize;
2323  }
2324  else {
2325  esyslog("ERROR: out of memory");
2326  return false;
2327  }
2328  }
2329  return true;
2330 }
2331 
2332 void cDynamicBuffer::Append(const uchar *Data, int Length)
2333 {
2334  if (Assert(used + Length)) {
2335  memcpy(buffer + used, Data, Length);
2336  used += Length;
2337  }
2338 }
2339 
2340 // --- cHashBase -------------------------------------------------------------
2341 
2342 cHashBase::cHashBase(int Size, bool OwnObjects)
2343 {
2344  size = Size;
2345  ownObjects = OwnObjects;
2346  hashTable = (cList<cHashObject>**)calloc(size, sizeof(cList<cHashObject>*));
2347 }
2348 
2350 {
2351  Clear();
2352  free(hashTable);
2353 }
2354 
2355 void cHashBase::Add(cListObject *Object, unsigned int Id)
2356 {
2357  unsigned int hash = hashfn(Id);
2358  if (!hashTable[hash])
2359  hashTable[hash] = new cList<cHashObject>;
2360  hashTable[hash]->Add(new cHashObject(Object, Id));
2361 }
2362 
2363 void cHashBase::Del(cListObject *Object, unsigned int Id)
2364 {
2365  cList<cHashObject> *list = hashTable[hashfn(Id)];
2366  if (list) {
2367  for (cHashObject *hob = list->First(); hob; hob = list->Next(hob)) {
2368  if (hob->object == Object) {
2369  list->Del(hob);
2370  break;
2371  }
2372  }
2373  }
2374 }
2375 
2377 {
2378  for (int i = 0; i < size; i++) {
2379  if (ownObjects) {
2380  cList<cHashObject> *list = hashTable[i];
2381  if (list) {
2382  for (cHashObject *hob = list->First(); hob; hob = list->Next(hob))
2383  delete hob->object;
2384  }
2385  }
2386  delete hashTable[i];
2387  hashTable[i] = NULL;
2388  }
2389 }
2390 
2391 cListObject *cHashBase::Get(unsigned int Id) const
2392 {
2393  cList<cHashObject> *list = hashTable[hashfn(Id)];
2394  if (list) {
2395  for (cHashObject *hob = list->First(); hob; hob = list->Next(hob)) {
2396  if (hob->id == Id)
2397  return hob->object;
2398  }
2399  }
2400  return NULL;
2401 }
2402 
2404 {
2405  return hashTable[hashfn(Id)];
2406 }
char * result
Definition: tools.h:329
cBase64Encoder(const uchar *Data, int Length, int MaxResult=64)
Sets up a new base 64 encoder for the given Data, with the given Length.
Definition: tools.c:1361
~cBase64Encoder()
Definition: tools.c:1370
int length
Definition: tools.h:326
const char * NextLine(void)
Returns the next line of encoded data (terminated by '\0'), or NULL if there is no more encoded data.
Definition: tools.c:1375
const uchar * data
Definition: tools.h:325
int maxResult
Definition: tools.h:327
static const char * b64
Definition: tools.h:330
void WordAlign(void)
Definition: tools.c:1435
bool SetLength(int Length)
Definition: tools.c:1442
int length
Definition: tools.h:350
const uint8_t * data
Definition: tools.h:349
int index
Definition: tools.h:351
int Length(void) const
Definition: tools.h:364
void SkipBits(int n)
Definition: tools.h:360
uint32_t GetBits(int n)
Definition: tools.c:1420
void ByteAlign(void)
Definition: tools.c:1428
int GetBit(void)
Definition: tools.c:1411
cCharSetConv(const char *FromCode=NULL, const char *ToCode=NULL)
Sets up a character set converter to convert from FromCode to ToCode.
Definition: tools.c:950
static void SetSystemCharacterTable(const char *CharacterTable)
Definition: tools.c:968
char * result
Definition: tools.h:152
size_t length
Definition: tools.h:153
iconv_t cd
Definition: tools.h:151
static char * systemCharacterTable
Definition: tools.h:154
~cCharSetConv()
Definition: tools.c:961
static const char * SystemCharacterTable(void)
Definition: tools.h:172
const char * Convert(const char *From, char *To=NULL, size_t ToLength=0)
Converts the given Text from FromCode to ToCode (as set in the constructor).
Definition: tools.c:991
static void SleepMs(int TimeoutMs)
Creates a cCondWait object and uses it to sleep for TimeoutMs milliseconds, immediately giving up the...
Definition: thread.c:72
cDynamicBuffer(int InitialSize=1024)
Definition: tools.c:2304
bool Realloc(int NewSize)
Definition: tools.c:2316
int Length(void)
Definition: tools.h:849
void Append(const uchar *Data, int Length)
Definition: tools.c:2332
uchar * Data(void)
Definition: tools.h:848
uchar * buffer
Definition: tools.h:834
~cDynamicBuffer()
Definition: tools.c:2311
bool Assert(int NewSize)
Definition: tools.h:839
int initialSize
Definition: tools.h:835
bool Load(const char *Directory, bool DirsOnly=false)
Definition: tools.c:1590
cFileNameList(const char *Directory=NULL, bool DirsOnly=false)
Definition: tools.c:1585
static bool FileReadyForWriting(int FileDes, int TimeoutMs=1000)
Definition: tools.c:1711
static int maxFiles
Definition: tools.h:431
static bool FileReady(int FileDes, int TimeoutMs=1000)
Definition: tools.c:1696
static bool files[]
Definition: tools.h:430
static bool AnyFileReady(int FileDes=-1, int TimeoutMs=1000)
Definition: tools.c:1678
bool Ready(bool Wait=true)
Definition: tools.c:1673
bool Open(const char *FileName, int Flags, mode_t Mode=DEFFILEMODE)
Definition: tools.c:1631
cFile(void)
Definition: tools.c:1621
~cFile()
Definition: tools.c:1626
void Close(void)
Definition: tools.c:1664
void Del(cListObject *Object, unsigned int Id)
Definition: tools.c:2363
cListObject * Get(unsigned int Id) const
Definition: tools.c:2391
cList< cHashObject > ** hashTable
Definition: tools.h:864
int size
Definition: tools.h:865
bool ownObjects
Definition: tools.h:866
virtual ~cHashBase()
Definition: tools.c:2349
cList< cHashObject > * GetList(unsigned int Id) const
Definition: tools.c:2403
cHashBase(int Size, bool OwnObjects)
Creates a new hash of the given Size.
Definition: tools.c:2342
void Clear(void)
Definition: tools.c:2376
void Add(cListObject *Object, unsigned int Id)
Definition: tools.c:2355
unsigned int hashfn(unsigned int Id) const
Definition: tools.h:867
virtual void Clear(void)
Definition: tools.c:2233
void Ins(cListObject *Object, cListObject *Before=NULL)
Definition: tools.c:2172
bool Contains(const cListObject *Object) const
If a pointer to an object contained in this list has been obtained while holding a lock,...
Definition: tools.c:2244
void Del(cListObject *Object, bool DeleteObject=true)
Definition: tools.c:2188
cListObject * lastObject
Definition: tools.h:535
virtual void Move(int From, int To)
Definition: tools.c:2204
cStateLock stateLock
Definition: tools.h:537
bool useGarbageCollector
Definition: tools.h:539
void SetExplicitModify(void)
If you have obtained a write lock on this list, and you don't want it to be automatically marked as m...
Definition: tools.c:2253
void SetModified(void)
Unconditionally marks this list as modified.
Definition: tools.c:2258
virtual ~cListBase()
Definition: tools.c:2142
bool Lock(cStateKey &StateKey, bool Write=false, int TimeoutMs=0) const
Tries to get a lock on this list and returns true if successful.
Definition: tools.c:2147
int count
Definition: tools.h:536
cListObject * objects
Definition: tools.h:535
const char * needsLocking
Definition: tools.h:538
cListBase(const char *NeedsLocking=NULL)
Definition: tools.c:2133
const cListObject * Get(int Index) const
Definition: tools.c:2263
int Count(void) const
Definition: tools.h:596
void Add(cListObject *Object, cListObject *After=NULL)
Definition: tools.c:2156
void Sort(void)
Definition: tools.c:2280
void Purge(bool Force=false)
Definition: tools.c:2115
cListGarbageCollector(void)
Definition: tools.c:2094
void Put(cListObject *Object)
Definition: tools.c:2106
void Unlink(void)
Definition: tools.c:2067
cListObject * next
Definition: tools.h:502
cListObject(void)
Definition: tools.c:2046
cListObject * Prev(void) const
Definition: tools.h:515
cListObject * prev
Definition: tools.h:502
int Index(void) const
Definition: tools.c:2076
virtual int Compare(const cListObject &ListObject) const
Must return 0 if this object is equal to ListObject, a positive value if it is "greater",...
Definition: tools.h:508
cListObject * Next(void) const
Definition: tools.h:516
void Insert(cListObject *Object)
Definition: tools.c:2061
virtual ~cListObject()
Definition: tools.c:2051
void Append(cListObject *Object)
Definition: tools.c:2055
const T * Next(const T *Object) const
< Returns the element immediately before Object in this list, or NULL if Object is the first element ...
Definition: tools.h:619
const T * First(void) const
Returns the first element in this list, or NULL if the list is empty.
Definition: tools.h:612
bool Lock(int WaitSeconds=0)
Definition: tools.c:1999
void Unlock(void)
Definition: tools.c:2035
~cLockFile()
Definition: tools.c:1993
cLockFile(const char *Directory)
Definition: tools.c:1985
Definition: tools.h:399
cPoller(int FileHandle=-1, bool Out=false)
Definition: tools.c:1483
int numFileHandles
Definition: tools.h:403
bool Add(int FileHandle, bool Out)
Definition: tools.c:1489
@ MaxPollFiles
Definition: tools.h:401
bool Poll(int TimeoutMs=0)
Definition: tools.c:1521
void Del(int FileHandle, bool Out)
Definition: tools.c:1508
pollfd pfd[MaxPollFiles]
Definition: tools.h:402
struct dirent * result
Definition: tools.h:414
cReadDir(const char *Directory)
Definition: tools.c:1533
DIR * directory
Definition: tools.h:413
~cReadDir()
Definition: tools.c:1538
struct dirent * Next(void)
Definition: tools.c:1544
union cReadDir::@24 u
struct dirent d
Definition: tools.h:417
bool Ok(void)
Definition: tools.h:424
cReadLine(void)
Definition: tools.c:1452
char * buffer
Definition: tools.h:392
size_t size
Definition: tools.h:391
char * Read(FILE *f)
Definition: tools.c:1463
~cReadLine()
Definition: tools.c:1458
~cSafeFile()
Definition: tools.c:1735
cSafeFile(const char *FileName)
Definition: tools.c:1726
bool Open(void)
Definition: tools.c:1744
bool Close(void)
Definition: tools.c:1754
void SetExplicitModify(void)
If you have obtained a write lock on this lock, and you don't want its state to be automatically incr...
Definition: thread.c:810
void SetModified(void)
Sets this lock to have its state incremented when the current write lock state key is removed.
Definition: thread.c:825
bool Lock(cStateKey &StateKey, bool Write=false, int TimeoutMs=0)
Tries to get a lock and returns true if successful.
Definition: thread.c:723
virtual ~cStringList()
Definition: tools.c:1561
virtual void Clear(void)
Definition: tools.c:1575
int Find(const char *s) const
Definition: tools.c:1566
Definition: tools.h:176
cString & CompactChars(char c)
Compact any sequence of characters 'c' to a single character, and strip all of them from the beginnin...
Definition: tools.c:1125
static cString static cString vsprintf(const char *fmt, va_list &ap)
Definition: tools.c:1144
virtual ~cString()
Definition: tools.c:1077
cString(const char *S=NULL, bool TakePointer=false)
Definition: tools.c:1053
static cString sprintf(const char *fmt,...) __attribute__((format(printf
Definition: tools.c:1131
cString & operator=(const cString &String)
Definition: tools.c:1082
char * s
Definition: tools.h:178
cString & Append(const char *String)
Definition: tools.c:1100
cString & Truncate(int Index)
Truncate the string at the given Index (if Index is < 0 it is counted from the end of the string).
Definition: tools.c:1115
static tThreadId ThreadId(void)
Definition: thread.c:372
Definition: tools.h:369
uint64_t Elapsed(void) const
Definition: tools.c:784
void Set(int Ms=0)
Sets the timer.
Definition: tools.c:774
bool TimedOut(void) const
Definition: tools.c:779
cTimeMs(int Ms=0)
Creates a timer with ms resolution and an initial timeout of Ms.
Definition: tools.c:723
uint64_t begin
Definition: tools.h:371
static uint64_t Now(void)
Definition: tools.c:731
cUnbufferedFile is used for large files that are mainly written or read in a streaming manner,...
Definition: tools.h:463
static cUnbufferedFile * Create(const char *FileName, int Flags, mode_t Mode=DEFFILEMODE)
Definition: tools.c:1970
void SetReadAhead(size_t ra)
Definition: tools.c:1842
ssize_t Write(const void *Data, size_t Size)
Definition: tools.c:1919
int Close(void)
Definition: tools.c:1818
int Open(const char *FileName, int Flags, mode_t Mode=DEFFILEMODE)
Definition: tools.c:1800
ssize_t Read(void *Data, size_t Size)
Definition: tools.c:1861
int FadviseDrop(off_t Offset, off_t Len)
Definition: tools.c:1847
off_t Seek(off_t Offset, int Whence)
Definition: tools.c:1853
cUnbufferedFile(void)
Definition: tools.c:1790
~cUnbufferedFile()
Definition: tools.c:1795
virtual void Clear(void)
Definition: tools.h:774
#define tr(s)
Definition: i18n.h:85
#define WRITE_BUFFER
Definition: tools.c:1788
static boolean JpegCompressEmptyOutputBuffer(j_compress_ptr cinfo)
Definition: tools.c:1263
cString TimeString(time_t t)
Converts the given time to a string of the form "hh:mm".
Definition: tools.c:1237
#define LIST_GARBAGE_COLLECTOR_TIMEOUT
Definition: tools.c:2090
static void JpegCompressInitDestination(j_compress_ptr cinfo)
Definition: tools.c:1254
void TouchFile(const char *FileName)
Definition: tools.c:699
cString WeekDayNameFull(int WeekDay)
Converts the given WeekDay (0=Sunday, 1=Monday, ...) to a full day name.
Definition: tools.c:1175
char * strcpyrealloc(char *dest, const char *src)
Definition: tools.c:114
int FreeDiskSpaceMB(const char *Directory, int *UsedMB)
Definition: tools.c:446
bool isempty(const char *s)
Definition: tools.c:331
int Utf8ToArray(const char *s, uint *a, int Size)
Converts the given character bytes (including the terminating 0) into an array of UTF-8 symbols of th...
Definition: tools.c:900
cString strescape(const char *s, const char *chars)
Definition: tools.c:254
#define LOCKFILENAME
Definition: tools.c:1982
#define MT(s, m, v)
#define READCHUNK
Definition: tools.c:1840
int Utf8CharSet(uint c, char *s)
Converts the given UTF-8 symbol to a sequence of character bytes and copies them to the given string.
Definition: tools.c:822
int strcountchr(const char *s, char c)
returns the number of occurrences of 'c' in 's'.
Definition: tools.c:189
cString TimeToString(time_t t)
Converts the given time to a string of the form "www mmm dd hh:mm:ss yyyy".
Definition: tools.c:1207
char * Utf8Strn0Cpy(char *Dest, const char *Src, int n)
Copies at most n character bytes from Src to Dest, making sure that the resulting copy ends with a co...
Definition: tools.c:881
bool SpinUpDisk(const char *FileName)
Definition: tools.c:667
bool MakeDirs(const char *FileName, bool IsDirectory)
Definition: tools.c:481
int Utf8StrLen(const char *s)
Returns the number of UTF-8 symbols formed by the given string of character bytes.
Definition: tools.c:869
#define LOCKFILESTALETIME
Definition: tools.c:1983
#define FADVGRAN
Definition: tools.c:1839
cString WeekDayName(int WeekDay)
Converts the given WeekDay (0=Sunday, 1=Monday, ...) to a three letter day name.
Definition: tools.c:1154
bool startswith(const char *s, const char *p)
Definition: tools.c:311
void syslog_with_tid(int priority, const char *format,...)
Definition: tools.c:35
uchar * RgbToJpeg(uchar *Mem, int Width, int Height, int &Size, int Quality)
Converts the given Memory to a JPEG image and returns a pointer to the resulting image.
Definition: tools.c:1302
cString dtoa(double d, const char *Format)
Converts the given double value to a string, making sure it uses a '.
Definition: tools.c:414
char * compactchars(char *s, char c)
removes all occurrences of 'c' from the beginning an end of 's' and replaces sequences of multiple 'c...
Definition: tools.c:230
time_t LastModifiedTime(const char *FileName)
Definition: tools.c:705
double atod(const char *s)
Converts the given string, which is a floating point number using a '.
Definition: tools.c:393
cString ShortDateString(time_t t)
Converts the given time to a string of the form "dd.mm.yy".
Definition: tools.c:1228
char * strreplace(char *s, char c1, char c2)
Definition: tools.c:139
ssize_t safe_read(int filedes, void *buffer, size_t size)
Definition: tools.c:53
#define JPEGCOMPRESSMEM
Definition: tools.c:1247
static int CompareListObjects(const void *a, const void *b)
Definition: tools.c:2273
bool StrInArray(const char *a[], const char *s)
Returns true if the string s is equal to one of the strings pointed to by the (NULL terminated) array...
Definition: tools.c:372
const char * GetHostName(void)
Gets the host name of this machine.
Definition: tools.c:1345
cString strgetval(const char *s, const char *name, char d)
Returns the value part of a 'name=value' pair in s.
Definition: tools.c:277
char * stripspace(char *s)
Definition: tools.c:201
ssize_t safe_write(int filedes, const void *buffer, size_t size)
Definition: tools.c:65
int numdigits(int n)
Definition: tools.c:336
int Utf8SymChars(const char *s, int Symbols)
Returns the number of character bytes at the beginning of the given string that form at most the give...
Definition: tools.c:856
bool RemoveEmptyDirectories(const char *DirName, bool RemoveThis, const char *IgnoreFiles[])
Removes all empty directories under the given directory DirName.
Definition: tools.c:567
#define DECIMAL_POINT_C
Definition: tools.c:391
static void JpegCompressTermDestination(j_compress_ptr cinfo)
Definition: tools.c:1286
char * ReadLink(const char *FileName)
returns a new string allocated on the heap, which the caller must delete (or NULL in case of an error...
Definition: tools.c:653
uint Utf8CharGet(const char *s, int Length)
Returns the UTF-8 symbol at the beginning of the given string.
Definition: tools.c:807
#define MAXSYSLOGBUF
Definition: tools.c:33
int DirSizeMB(const char *DirName)
returns the total size of the files in the given directory, or -1 in case of an error
Definition: tools.c:621
cString DateString(time_t t)
Converts the given time to a string of the form "www dd.mm.yyyy".
Definition: tools.c:1217
int SysLogLevel
Definition: tools.c:31
bool DirectoryOk(const char *DirName, bool LogErrors)
Definition: tools.c:463
int WriteAllOrNothing(int fd, const uchar *Data, int Length, int TimeoutMs, int RetryMs)
Writes either all Data to the given file descriptor, or nothing at all.
Definition: tools.c:90
char * strn0cpy(char *dest, const char *src, size_t n)
Definition: tools.c:131
int Utf8FromArray(const uint *a, char *s, int Size, int Max)
Converts the given array of UTF-8 symbols (including the terminating 0) into a sequence of character ...
Definition: tools.c:918
int Utf8CharLen(const char *s)
Returns the number of character bytes at the beginning of the given string that form a UTF-8 symbol.
Definition: tools.c:793
cString DayDateTime(time_t t)
Converts the given time to a string of the form "www dd.mm. hh:mm".
Definition: tools.c:1196
char * strshift(char *s, int n)
Shifts the given string to the left by the given number of bytes, thus removing the first n bytes fro...
Definition: tools.c:299
bool RemoveFileOrDir(const char *FileName, bool FollowSymlinks)
Definition: tools.c:509
char * compactspace(char *s)
Definition: tools.c:213
off_t FileSize(const char *FileName)
returns the size of the given file, or -1 in case of an error (e.g. if the file doesn't exist)
Definition: tools.c:713
bool EntriesOnSameFileSystem(const char *File1, const char *File2)
Checks whether the given files are on the same file system.
Definition: tools.c:431
const char * strchrn(const char *s, char c, size_t n)
returns a pointer to the n'th occurrence (counting from 1) of c in s, or NULL if no such character wa...
Definition: tools.c:176
int BCD2INT(int x)
Definition: tools.c:45
static uint SystemToUtf8[128]
Definition: tools.c:791
bool endswith(const char *s, const char *p)
Definition: tools.c:320
cString itoa(int n)
Definition: tools.c:424
bool isnumber(const char *s)
Definition: tools.c:346
cString AddDirectory(const char *DirName, const char *FileName)
Definition: tools.c:384
void writechar(int filedes, char c)
Definition: tools.c:85
cListGarbageCollector ListGarbageCollector
Definition: tools.c:2092
int64_t StrToNum(const char *s)
Converts the given string to a number.
Definition: tools.c:357
#define FATALERRNO
Definition: tools.h:52
#define MEGABYTE(n)
Definition: tools.h:45
char * skipspace(const char *s)
Definition: tools.h:209
#define BCDCHARTOINT(x)
Definition: tools.h:72
#define LOG_ERROR_STR(s)
Definition: tools.h:40
unsigned char uchar
Definition: tools.h:31
#define dsyslog(a...)
Definition: tools.h:37
#define MALLOC(type, size)
Definition: tools.h:47
T min(T a, T b)
Definition: tools.h:59
T max(T a, T b)
Definition: tools.h:60
#define esyslog(a...)
Definition: tools.h:35
#define LOG_ERROR
Definition: tools.h:39
#define KILOBYTE(n)
Definition: tools.h:44