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