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