vdr  2.0.2
tools.h
Go to the documentation of this file.
1 /*
2  * tools.h: 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.h 2.24 2013/02/17 13:18:06 kls Exp $
8  */
9 
10 #ifndef __TOOLS_H
11 #define __TOOLS_H
12 
13 #include <dirent.h>
14 #include <errno.h>
15 #include <fcntl.h>
16 #include <float.h>
17 #include <iconv.h>
18 #include <math.h>
19 #include <poll.h>
20 #include <stdarg.h>
21 #include <stddef.h>
22 #include <stdint.h>
23 #include <stdio.h>
24 #include <stdlib.h>
25 #include <string.h>
26 #include <syslog.h>
27 #include <sys/stat.h>
28 #include <sys/types.h>
29 
30 typedef unsigned char uchar;
31 
32 extern int SysLogLevel;
33 
34 #define esyslog(a...) void( (SysLogLevel > 0) ? syslog_with_tid(LOG_ERR, a) : void() )
35 #define isyslog(a...) void( (SysLogLevel > 1) ? syslog_with_tid(LOG_ERR, a) : void() )
36 #define dsyslog(a...) void( (SysLogLevel > 2) ? syslog_with_tid(LOG_ERR, a) : void() )
37 
38 #define LOG_ERROR esyslog("ERROR (%s,%d): %m", __FILE__, __LINE__)
39 #define LOG_ERROR_STR(s) esyslog("ERROR (%s,%d): %s: %m", __FILE__, __LINE__, s)
40 
41 #define SECSINDAY 86400
42 
43 #define KILOBYTE(n) ((n) * 1024)
44 #define MEGABYTE(n) ((n) * 1024LL * 1024LL)
45 
46 #define MALLOC(type, size) (type *)malloc(sizeof(type) * (size))
47 
48 template<class T> inline void DELETENULL(T *&p) { T *q = p; p = NULL; delete q; }
49 
50 #define CHECK(s) { if ((s) < 0) LOG_ERROR; } // used for 'ioctl()' calls
51 #define FATALERRNO (errno && errno != EAGAIN && errno != EINTR)
52 
53 #ifndef __STL_CONFIG_H // in case some plugin needs to use the STL
54 template<class T> inline T min(T a, T b) { return a <= b ? a : b; }
55 template<class T> inline T max(T a, T b) { return a >= b ? a : b; }
56 template<class T> inline int sgn(T a) { return a < 0 ? -1 : a > 0 ? 1 : 0; }
57 template<class T> inline void swap(T &a, T &b) { T t = a; a = b; b = t; }
58 #endif
59 
60 template<class T> inline T constrain(T v, T l, T h) { return v < l ? l : v > h ? h : v; }
61 
62 void syslog_with_tid(int priority, const char *format, ...) __attribute__ ((format (printf, 2, 3)));
63 
64 #define BCDCHARTOINT(x) (10 * ((x & 0xF0) >> 4) + (x & 0xF))
65 int BCD2INT(int x);
66 
67 // Unfortunately there are no platform independent macros for unaligned
68 // access, so we do it this way:
69 
70 template<class T> inline T get_unaligned(T *p)
71 {
72  struct s { T v; } __attribute__((packed));
73  return ((s *)p)->v;
74 }
75 
76 template<class T> inline void put_unaligned(unsigned int v, T* p)
77 {
78  struct s { T v; } __attribute__((packed));
79  ((s *)p)->v = v;
80 }
81 
82 // Comparing doubles for equality is unsafe, but unfortunately we can't
83 // overwrite operator==(double, double), so this will have to do:
84 
85 inline bool DoubleEqual(double a, double b)
86 {
87  return fabs(a - b) <= DBL_EPSILON;
88 }
89 
90 // When handling strings that might contain UTF-8 characters, it may be necessary
91 // to process a "symbol" that consists of several actual character bytes. The
92 // following functions allow transparently accessing a "char *" string without
93 // having to worry about what character set is actually used.
94 
95 int Utf8CharLen(const char *s);
98 uint Utf8CharGet(const char *s, int Length = 0);
102 int Utf8CharSet(uint c, char *s = NULL);
106 int Utf8SymChars(const char *s, int Symbols);
109 int Utf8StrLen(const char *s);
112 char *Utf8Strn0Cpy(char *Dest, const char *Src, int n);
117 int Utf8ToArray(const char *s, uint *a, int Size);
121 int Utf8FromArray(const uint *a, char *s, int Size, int Max = -1);
127 
128 // When allocating buffer space, make sure we reserve enough space to hold
129 // a string in UTF-8 representation:
130 
131 #define Utf8BufSize(s) ((s) * 4)
132 
133 // The following macros automatically use the correct versions of the character
134 // class functions:
135 
136 #define Utf8to(conv, c) (cCharSetConv::SystemCharacterTable() ? to##conv(c) : tow##conv(c))
137 #define Utf8is(ccls, c) (cCharSetConv::SystemCharacterTable() ? is##ccls(c) : isw##ccls(c))
138 
140 private:
141  iconv_t cd;
142  char *result;
143  size_t length;
144  static char *systemCharacterTable;
145 public:
146  cCharSetConv(const char *FromCode = NULL, const char *ToCode = NULL);
151  ~cCharSetConv();
152  const char *Convert(const char *From, char *To = NULL, size_t ToLength = 0);
162  static const char *SystemCharacterTable(void) { return systemCharacterTable; }
163  static void SetSystemCharacterTable(const char *CharacterTable);
164  };
165 
166 class cString {
167 private:
168  char *s;
169 public:
170  cString(const char *S = NULL, bool TakePointer = false);
171  cString(const cString &String);
172  virtual ~cString();
173  operator const void * () const { return s; } // to catch cases where operator*() should be used
174  operator const char * () const { return s; } // for use in (const char *) context
175  const char * operator*() const { return s; } // for use in (const void *) context (printf() etc.)
176  cString &operator=(const cString &String);
177  cString &operator=(const char *String);
178  cString &Truncate(int Index);
179  static cString sprintf(const char *fmt, ...) __attribute__ ((format (printf, 1, 2)));
180  static cString vsprintf(const char *fmt, va_list &ap);
181  };
182 
183 ssize_t safe_read(int filedes, void *buffer, size_t size);
184 ssize_t safe_write(int filedes, const void *buffer, size_t size);
185 void writechar(int filedes, char c);
186 int WriteAllOrNothing(int fd, const uchar *Data, int Length, int TimeoutMs = 0, int RetryMs = 0);
190 char *strcpyrealloc(char *dest, const char *src);
191 char *strn0cpy(char *dest, const char *src, size_t n);
192 char *strreplace(char *s, char c1, char c2);
193 char *strreplace(char *s, const char *s1, const char *s2);
194 inline char *skipspace(const char *s)
195 {
196  if ((uchar)*s > ' ') // most strings don't have any leading space, so handle this case as fast as possible
197  return (char *)s;
198  while (*s && (uchar)*s <= ' ') // avoiding isspace() here, because it is much slower
199  s++;
200  return (char *)s;
201 }
202 char *stripspace(char *s);
203 char *compactspace(char *s);
204 cString strescape(const char *s, const char *chars);
205 bool startswith(const char *s, const char *p);
206 bool endswith(const char *s, const char *p);
207 bool isempty(const char *s);
208 int numdigits(int n);
209 bool isnumber(const char *s);
210 int64_t StrToNum(const char *s);
216 bool StrInArray(const char *a[], const char *s);
219 double atod(const char *s);
223 cString dtoa(double d, const char *Format = "%f");
227 cString itoa(int n);
228 cString AddDirectory(const char *DirName, const char *FileName);
229 bool EntriesOnSameFileSystem(const char *File1, const char *File2);
230 int FreeDiskSpaceMB(const char *Directory, int *UsedMB = NULL);
231 bool DirectoryOk(const char *DirName, bool LogErrors = false);
232 bool MakeDirs(const char *FileName, bool IsDirectory = false);
233 bool RemoveFileOrDir(const char *FileName, bool FollowSymlinks = false);
234 bool RemoveEmptyDirectories(const char *DirName, bool RemoveThis = false, const char *IgnoreFiles[] = NULL);
240 int DirSizeMB(const char *DirName);
241 char *ReadLink(const char *FileName);
242 bool SpinUpDisk(const char *FileName);
243 void TouchFile(const char *FileName);
244 time_t LastModifiedTime(const char *FileName);
245 off_t FileSize(const char *FileName);
246 cString WeekDayName(int WeekDay);
249 cString WeekDayName(time_t t);
251 cString WeekDayNameFull(int WeekDay);
254 cString WeekDayNameFull(time_t t);
256 cString DayDateTime(time_t t = 0);
259 cString TimeToString(time_t t);
261 cString DateString(time_t t);
263 cString ShortDateString(time_t t);
265 cString TimeString(time_t t);
267 uchar *RgbToJpeg(uchar *Mem, int Width, int Height, int &Size, int Quality = 100);
276 
278 private:
279  const uchar *data;
280  int length;
282  int i;
283  char *result;
284  static const char *b64;
285 public:
286  cBase64Encoder(const uchar *Data, int Length, int MaxResult = 64);
292  ~cBase64Encoder();
293  const char *NextLine(void);
299  };
300 
301 class cBitStream {
302 private:
303  const uint8_t *data;
304  int length; // in bits
305  int index; // in bits
306 public:
307  cBitStream(const uint8_t *Data, int Length) : data(Data), length(Length), index(0) {}
309  int GetBit(void);
310  uint32_t GetBits(int n);
311  void ByteAlign(void);
312  void WordAlign(void);
313  bool SetLength(int Length);
314  void SkipBits(int n) { index += n; }
315  void SkipBit(void) { SkipBits(1); }
316  bool IsEOF(void) const { return index >= length; }
317  void Reset(void) { index = 0; }
318  int Length(void) const { return length; }
319  int Index(void) const { return (IsEOF() ? length : index); }
320  const uint8_t *GetData(void) const { return (IsEOF() ? NULL : data + (index / 8)); }
321  };
322 
323 class cTimeMs {
324 private:
325  uint64_t begin;
326 public:
327  cTimeMs(int Ms = 0);
331  static uint64_t Now(void);
332  void Set(int Ms = 0);
333  bool TimedOut(void);
334  uint64_t Elapsed(void);
335  };
336 
337 class cReadLine {
338 private:
339  size_t size;
340  char *buffer;
341 public:
342  cReadLine(void);
343  ~cReadLine();
344  char *Read(FILE *f);
345  };
346 
347 class cPoller {
348 private:
349  enum { MaxPollFiles = 16 };
350  pollfd pfd[MaxPollFiles];
352 public:
353  cPoller(int FileHandle = -1, bool Out = false);
354  bool Add(int FileHandle, bool Out);
355  bool Poll(int TimeoutMs = 0);
356  };
357 
358 class cReadDir {
359 private:
360  DIR *directory;
361  struct dirent *result;
362  union { // according to "The GNU C Library Reference Manual"
363  struct dirent d;
364  char b[offsetof(struct dirent, d_name) + NAME_MAX + 1];
365  } u;
366 public:
367  cReadDir(const char *Directory);
368  ~cReadDir();
369  bool Ok(void) { return directory != NULL; }
370  struct dirent *Next(void);
371  };
372 
373 class cFile {
374 private:
375  static bool files[];
376  static int maxFiles;
377  int f;
378 public:
379  cFile(void);
380  ~cFile();
381  operator int () { return f; }
382  bool Open(const char *FileName, int Flags, mode_t Mode = DEFFILEMODE);
383  bool Open(int FileDes);
384  void Close(void);
385  bool IsOpen(void) { return f >= 0; }
386  bool Ready(bool Wait = true);
387  static bool AnyFileReady(int FileDes = -1, int TimeoutMs = 1000);
388  static bool FileReady(int FileDes, int TimeoutMs = 1000);
389  static bool FileReadyForWriting(int FileDes, int TimeoutMs = 1000);
390  };
391 
392 class cSafeFile {
393 private:
394  FILE *f;
395  char *fileName;
396  char *tempName;
397 public:
398  cSafeFile(const char *FileName);
399  ~cSafeFile();
400  operator FILE* () { return f; }
401  bool Open(void);
402  bool Close(void);
403  };
404 
407 
409 private:
410  int fd;
411  off_t curpos;
412  off_t cachedstart;
413  off_t cachedend;
414  off_t begin;
415  off_t lastpos;
416  off_t ahead;
417  size_t readahead;
418  size_t written;
419  size_t totwritten;
420  int FadviseDrop(off_t Offset, off_t Len);
421 public:
422  cUnbufferedFile(void);
423  ~cUnbufferedFile();
424  int Open(const char *FileName, int Flags, mode_t Mode = DEFFILEMODE);
425  int Close(void);
426  void SetReadAhead(size_t ra);
427  off_t Seek(off_t Offset, int Whence);
428  ssize_t Read(void *Data, size_t Size);
429  ssize_t Write(const void *Data, size_t Size);
430  static cUnbufferedFile *Create(const char *FileName, int Flags, mode_t Mode = DEFFILEMODE);
431  };
432 
433 class cLockFile {
434 private:
435  char *fileName;
436  int f;
437 public:
438  cLockFile(const char *Directory);
439  ~cLockFile();
440  bool Lock(int WaitSeconds = 0);
441  void Unlock(void);
442  };
443 
444 class cListObject {
445 private:
446  cListObject *prev, *next;
447 public:
448  cListObject(void);
449  virtual ~cListObject();
450  virtual int Compare(const cListObject &ListObject) const { return 0; }
453  void Append(cListObject *Object);
454  void Insert(cListObject *Object);
455  void Unlink(void);
456  int Index(void) const;
457  cListObject *Prev(void) const { return prev; }
458  cListObject *Next(void) const { return next; }
459  };
460 
461 class cListBase {
462 protected:
463  cListObject *objects, *lastObject;
464  cListBase(void);
465  int count;
466 public:
467  virtual ~cListBase();
468  void Add(cListObject *Object, cListObject *After = NULL);
469  void Ins(cListObject *Object, cListObject *Before = NULL);
470  void Del(cListObject *Object, bool DeleteObject = true);
471  virtual void Move(int From, int To);
472  void Move(cListObject *From, cListObject *To);
473  virtual void Clear(void);
474  cListObject *Get(int Index) const;
475  int Count(void) const { return count; }
476  void Sort(void);
477  };
478 
479 template<class T> class cList : public cListBase {
480 public:
481  T *Get(int Index) const { return (T *)cListBase::Get(Index); }
482  T *First(void) const { return (T *)objects; }
483  T *Last(void) const { return (T *)lastObject; }
484  T *Prev(const T *object) const { return (T *)object->cListObject::Prev(); } // need to call cListObject's members to
485  T *Next(const T *object) const { return (T *)object->cListObject::Next(); } // avoid ambiguities in case of a "list of lists"
486  };
487 
488 template<class T> class cVector {
490 private:
491  mutable int allocated;
492  mutable int size;
493  mutable T *data;
494  cVector(const cVector &Vector) {} // don't copy...
495  cVector &operator=(const cVector &Vector) { return *this; } // ...or assign this!
496  void Realloc(int Index) const
497  {
498  if (++Index > allocated) {
499  data = (T *)realloc(data, Index * sizeof(T));
500  if (!data) {
501  esyslog("ERROR: out of memory - abort!");
502  abort();
503  }
504  for (int i = allocated; i < Index; i++)
505  data[i] = T(0);
506  allocated = Index;
507  }
508  }
509 public:
510  cVector(int Allocated = 10)
511  {
512  allocated = 0;
513  size = 0;
514  data = NULL;
515  Realloc(Allocated);
516  }
517  virtual ~cVector() { free(data); }
518  T& At(int Index) const
519  {
520  Realloc(Index);
521  if (Index >= size)
522  size = Index + 1;
523  return data[Index];
524  }
525  const T& operator[](int Index) const
526  {
527  return At(Index);
528  }
529  T& operator[](int Index)
530  {
531  return At(Index);
532  }
533  int Size(void) const { return size; }
534  virtual void Insert(T Data, int Before = 0)
535  {
536  if (Before < size) {
537  Realloc(size);
538  memmove(&data[Before + 1], &data[Before], (size - Before) * sizeof(T));
539  size++;
540  data[Before] = Data;
541  }
542  else
543  Append(Data);
544  }
545  virtual void Append(T Data)
546  {
547  if (size >= allocated)
548  Realloc(allocated * 3 / 2); // increase size by 50%
549  data[size++] = Data;
550  }
551  virtual void Remove(int Index)
552  {
553  if (Index < size - 1)
554  memmove(&data[Index], &data[Index + 1], (size - Index) * sizeof(T));
555  size--;
556  }
557  virtual void Clear(void)
558  {
559  for (int i = 0; i < size; i++)
560  data[i] = T(0);
561  size = 0;
562  }
563  void Sort(__compar_fn_t Compare)
564  {
565  qsort(data, size, sizeof(T), Compare);
566  }
567  };
568 
569 inline int CompareStrings(const void *a, const void *b)
570 {
571  return strcmp(*(const char **)a, *(const char **)b);
572 }
573 
574 inline int CompareStringsIgnoreCase(const void *a, const void *b)
575 {
576  return strcasecmp(*(const char **)a, *(const char **)b);
577 }
578 
579 class cStringList : public cVector<char *> {
580 public:
581  cStringList(int Allocated = 10): cVector<char *>(Allocated) {}
582  virtual ~cStringList();
583  int Find(const char *s) const;
584  void Sort(bool IgnoreCase = false)
585  {
586  if (IgnoreCase)
588  else
590  }
591  virtual void Clear(void);
592  };
593 
594 class cFileNameList : public cStringList {
595 public:
596  cFileNameList(const char *Directory = NULL, bool DirsOnly = false);
597  bool Load(const char *Directory, bool DirsOnly = false);
598  };
599 
600 class cHashObject : public cListObject {
601  friend class cHashBase;
602 private:
603  unsigned int id;
605 public:
606  cHashObject(cListObject *Object, unsigned int Id) { object = Object; id = Id; }
607  cListObject *Object(void) { return object; }
608  };
609 
610 class cHashBase {
611 private:
613  int size;
614  unsigned int hashfn(unsigned int Id) const { return Id % size; }
615 protected:
616  cHashBase(int Size);
617 public:
618  virtual ~cHashBase();
619  void Add(cListObject *Object, unsigned int Id);
620  void Del(cListObject *Object, unsigned int Id);
621  void Clear(void);
622  cListObject *Get(unsigned int Id) const;
623  cList<cHashObject> *GetList(unsigned int Id) const;
624  };
625 
626 #define HASHSIZE 512
627 
628 template<class T> class cHash : public cHashBase {
629 public:
630  cHash(int Size = HASHSIZE) : cHashBase(Size) {}
631  T *Get(unsigned int Id) const { return (T *)cHashBase::Get(Id); }
632 };
633 
634 #endif //__TOOLS_H
635