libhomegear-base  0.7
Base library for Homegear and Homegear family modules.
HelperFunctions.h
Go to the documentation of this file.
1 /* Copyright 2013-2019 Homegear GmbH
2  *
3  * libhomegear-base is free software: you can redistribute it and/or
4  * modify it under the terms of the GNU Lesser General Public License as
5  * published by the Free Software Foundation, either version 3 of the
6  * License, or (at your option) any later version.
7  *
8  * libhomegear-base is distributed in the hope that it will be useful,
9  * but WITHOUT ANY WARRANTY; without even the implied warranty of
10  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11  * GNU Lesser General Public License for more details.
12  *
13  * You should have received a copy of the GNU Lesser General Public
14  * License along with libhomegear-base. If not, see
15  * <http://www.gnu.org/licenses/>.
16  *
17  * In addition, as a special exception, the copyright holders give
18  * permission to link the code of portions of this program with the
19  * OpenSSL library under certain conditions as described in each
20  * individual source file, and distribute linked combinations
21  * including the two.
22  * You must obey the GNU Lesser General Public License in all respects
23  * for all of the code used other than OpenSSL. If you modify
24  * file(s) with this exception, you may extend this exception to your
25  * version of the file(s), but you are not obligated to do so. If you
26  * do not wish to do so, delete this exception statement from your
27  * version. If you delete this exception statement from all source
28  * files in the program, then also delete it here.
29 */
30 
31 #ifndef HELPERFUNCTIONS_H_
32 #define HELPERFUNCTIONS_H_
33 
34 #include "../Variable.h"
35 
36 #include <algorithm>
37 #include <ctime>
38 #include <map>
39 #include <fstream>
40 #include <sstream>
41 #include <mutex>
42 #include <random>
43 #include <vector>
44 #include <regex>
45 #include <unordered_set>
46 
47 #include <gcrypt.h>
48 
49 namespace BaseLib {
50 class SharedObjects;
51 
56  public:
61 
69  static int32_t compareConstant(const std::string &s1, const std::string &s2);
70 
71  static int64_t getTimezoneOffset();
72 
78  static int64_t getLocalTime();
79 
88  static int64_t getTime();
89 
98  static int64_t getTimeMicroseconds();
99 
108  static int64_t getTimeNanoseconds();
109 
118  static int64_t getTimeSeconds();
119 
126  static int32_t getFileLastModifiedTime(const std::string &filename);
127 
134  static std::string getTimeString(int64_t time = 0);
135 
143  static std::string getTimeString(std::string format, int64_t time = 0);
144 
150  static std::string getTimeUuid();
151 
164  static std::string getUuid1(bool useRandomNodeId = false);
165 
172  static std::string getUuid4();
173 
182  static inline std::string &ltrim(std::string &s) {
183  s.erase(s.begin(), std::find_if(s.begin(), s.end(), std::not1(std::ptr_fun<int, int>(std::isspace))));
184  return s;
185  }
186 
195  static inline std::string &rtrim(std::string &s) {
196  s.erase(std::find_if(s.rbegin(), s.rend(), std::not1(std::ptr_fun<int, int>(std::isspace))).base(), s.end());
197  return s;
198  }
199 
208  static inline std::string &trim(std::string &s) {
209  return ltrim(rtrim(s));
210  }
211 
219  static inline std::string &toLower(std::string &s) {
220  std::transform(s.begin(), s.end(), s.begin(), ::tolower);
221  return s;
222  }
223 
231  static inline std::string &toUpper(std::string &s) {
232  std::transform(s.begin(), s.end(), s.begin(), ::toupper);
233  return s;
234  }
235 
242  static inline size_t utf8StringSize(const std::string &s) {
243  if (s.empty()) return 0;
244  const unsigned char *pS = (const unsigned char *)s.c_str();
245  size_t len = 0;
246  while (*pS) len += (*pS++ & 0xc0) != 0x80;
247  return len;
248  }
249 
258  static std::string utf8Substring(const std::string &s, uint32_t start, uint32_t length) {
259  //From http://www.zedwood.com/article/cpp-utf-8-mb_substr-function
260  if (length == 0) return "";
261  uint32_t c, i, ix, q, min = (unsigned)std::string::npos, max = (unsigned)std::string::npos;
262  for (q = 0, i = 0, ix = s.length(); i < ix; i++, q++) {
263  if (q == start) min = i;
264  if (q <= start + length || length == std::string::npos) max = i;
265 
266  c = (unsigned char)s[i];
267  if (c >= 0 && c <= 127) i += 0;
268  else if ((c & 0xE0) == 0xC0) i += 1;
269  else if ((c & 0xF0) == 0xE0) i += 2;
270  else if ((c & 0xF8) == 0xF0) i += 3;
271  else return ""; //invalid utf8
272  }
273  if (q <= start + length || length == (unsigned)std::string::npos) max = i;
274  if (min == (unsigned)std::string::npos || max == (unsigned)std::string::npos) return "";
275  return s.substr(min, max);
276  }
277 
286  static std::string &stringReplace(std::string &haystack, const std::string &search, const std::string &replace);
287 
297  static std::string &regexReplace(std::string &haystack, const std::string &search, const std::string &replace, bool ignoreCase);
298 
308  static std::pair<std::string, std::string> splitFirst(std::string string, char delimiter);
309 
319  static std::pair<std::string, std::string> splitLast(std::string string, char delimiter);
320 
329  static std::vector<std::string> splitAll(std::string string, char delimiter);
330 
339  static inline bool isNotAlphaNumeric(char c) {
340  return !(isalpha(c) || isdigit(c) || (c == '_') || (c == '-'));
341  }
342 
352  static bool isAlphaNumeric(std::string &s, std::unordered_set<char> additionalCharacters = std::unordered_set<char>()) {
353  return find_if
354  (
355  s.begin(),
356  s.end(),
357  [&](const char c) { return !(isalpha(c) || isdigit(c) || additionalCharacters.find(c) != additionalCharacters.end()); }
358  ) == s.end();
359  }
360 
370  static std::string stripNonAlphaNumeric(const std::string &s, const std::unordered_set<char> &whitelist = std::unordered_set<char>());
371 
378  static std::string stripNonPrintable(const std::string &s);
379 
380  static PVariable xml2variable(const xml_node *node, bool &isDataNode);
381 
382  static void variable2xml(xml_document *doc, xml_node *parentNode, const PVariable &variable);
383 
389  static bool getBigEndian();
390 
398  static int32_t getRandomNumber(int32_t min, int32_t max);
399 
406  static std::vector<uint8_t> getRandomBytes(uint32_t size);
407 
415  static void memcpyBigEndian(char *to, const char *from, const uint32_t &length);
416 
424  static void memcpyBigEndian(uint8_t *to, const uint8_t *from, const uint32_t &length);
425 
432  static void memcpyBigEndian(int32_t &to, const std::vector<uint8_t> &from);
433 
441  static void memcpyBigEndian(std::vector<uint8_t> &to, const int32_t &from);
442 
449  static void memcpyBigEndian(int64_t &to, const std::vector<uint8_t> &from);
450 
458  static void memcpyBigEndian(std::vector<uint8_t> &to, const int64_t &from);
459 
466  static std::vector<uint8_t> hexToBin(const std::string &data);
467 
475  static std::string getHexString(const uint8_t *buffer, uint32_t size);
476 
484  static std::string getHexString(const char *buffer, uint32_t size);
485 
492  static std::string getHexString(const std::vector<char> &data);
493 
500  static std::string getHexString(const std::string &data);
501 
508  static std::string getHexString(const std::vector<uint8_t> &data);
509 
516  static std::string getHexString(const std::vector<uint16_t> &data);
517 
525  static std::string getHexString(int32_t number, int32_t width = -1);
526 
534  static std::string getHexString(uint32_t number, int32_t width = -1);
535 
543  static std::string getHexString(int64_t number, int32_t width = -1);
544 
552  static std::string getHexString(uint64_t number, int32_t width = -1);
553 
560  static char getHexChar(int32_t nibble);
561 
568  static std::vector<char> getBinary(const std::string &hexString);
569 
577  static std::vector<uint8_t> getUBinary(const std::string &hexString);
578 
588  static std::vector<uint8_t> &getUBinary(const std::string &hexString, uint32_t size, std::vector<uint8_t> &binary);
589 
597  static std::vector<uint8_t> getUBinary(const std::vector<uint8_t> &hexData);
598 
605  static std::string getBinaryString(const std::string &hexString);
606 
613  static uid_t userId(const std::string &username);
614 
621  static gid_t groupId(const std::string &groupname);
622 
629  static std::string getGNUTLSCertVerificationError(uint32_t errorCode);
630 
637  static bool isShortCliCommand(const std::string &command);
638 
651  static bool checkCliCommand(const std::string &command, const std::string &longCommand, const std::string &shortCommand1, const std::string &shortCommand2, uint32_t minArgumentCount, std::vector<std::string> &arguments, bool &showHelp);
652 
656  static void *memrchr(const void *s, int c, size_t n);
657  private:
661  static const std::array<int32_t, 23> _asciiToBinaryTable;
662 
666  static const std::array<int32_t, 16> _binaryToASCIITable;
667 
671  static bool isBigEndian();
672 };
673 }
674 #endif
static std::string & stringReplace(std::string &haystack, const std::string &search, const std::string &replace)
Replaces substrings within a string.
Definition: HelperFunctions.cpp:442
static std::pair< std::string, std::string > splitLast(std::string string, char delimiter)
Splits a string at the last occurrence of a delimiter.
Definition: HelperFunctions.cpp:470
static void memcpyBigEndian(char *to, const char *from, const uint32_t &length)
Copies binary values from one memory location to another reversing the byte order when the system is ...
Definition: HelperFunctions.cpp:372
static std::string getTimeString(int64_t time=0)
Gets the current time as a string like "08/27/14 14:13:53.471".
Definition: HelperFunctions.cpp:91
static bool getBigEndian()
Returns the endianess of the system.
Definition: HelperFunctions.cpp:744
static std::vector< uint8_t > hexToBin(const std::string &data)
Converts a hex string to a byte array.
Definition: HelperFunctions.cpp:488
static PVariable xml2variable(const xml_node *node, bool &isDataNode)
Definition: HelperFunctions.cpp:239
static std::string getUuid1(bool useRandomNodeId=false)
Calculates a version 1 UUID (see RFC 4122) including a time stamp in 100-nanosecond intervals...
Definition: HelperFunctions.cpp:155
static std::pair< std::string, std::string > splitFirst(std::string string, char delimiter)
Splits a string at the first occurrence of a delimiter.
Definition: HelperFunctions.cpp:463
static gid_t groupId(const std::string &groupname)
Gets the GID of a group.
Definition: HelperFunctions.cpp:732
static std::string getHexString(const uint8_t *buffer, uint32_t size)
Converts a byte array to a hex string.
Definition: HelperFunctions.cpp:502
static std::string & rtrim(std::string &s)
Right trims a string.
Definition: HelperFunctions.h:195
static std::string & ltrim(std::string &s)
Left trims a string.
Definition: HelperFunctions.h:182
static std::string getUuid4()
Calculates a version 4 UUID (see RFC 4122).
Definition: HelperFunctions.cpp:200
Definition: BaseLib.cpp:34
static int64_t getLocalTime()
Gets the current local time as unix time stamp in milliseconds.
Definition: HelperFunctions.cpp:66
static int64_t getTimezoneOffset()
Definition: HelperFunctions.cpp:59
static bool isNotAlphaNumeric(char c)
Checks if a character is not alphanumeric (&#39;_&#39; and &#39;-&#39; are also regarded alphanumeric).
Definition: HelperFunctions.h:339
static bool isAlphaNumeric(std::string &s, std::unordered_set< char > additionalCharacters=std::unordered_set< char >())
Checks if a string is alphanumeric.
Definition: HelperFunctions.h:352
static char getHexChar(int32_t nibble)
Converts a nibble to a hex character.
Definition: HelperFunctions.cpp:497
static std::string & trim(std::string &s)
Trims a string.
Definition: HelperFunctions.h:208
static int32_t compareConstant(const std::string &s1, const std::string &s2)
Compares two strings in constant time.
Definition: HelperFunctions.cpp:48
static bool isShortCliCommand(const std::string &command)
Checks if a command is a short CLI command.
Definition: HelperFunctions.cpp:769
static int64_t getTimeSeconds()
Gets the current unix time stamp in seconds.
Definition: HelperFunctions.cpp:85
std::shared_ptr< Variable > PVariable
Definition: PhysicalInterfaceSettings.h:41
static std::string & regexReplace(std::string &haystack, const std::string &search, const std::string &replace, bool ignoreCase)
Replaces substrings within a string using regex.
Definition: HelperFunctions.cpp:454
This class provides functions to make your life easier.
Definition: HelperFunctions.h:55
static std::string getGNUTLSCertVerificationError(uint32_t errorCode)
Converts GNUTLS certificate verification error codes to human readable error messages.
Definition: HelperFunctions.cpp:758
static int32_t getRandomNumber(int32_t min, int32_t max)
Generates a random integer.
Definition: HelperFunctions.cpp:353
static std::string utf8Substring(const std::string &s, uint32_t start, uint32_t length)
Returns an UTF-8 substring.
Definition: HelperFunctions.h:258
static std::vector< uint8_t > getRandomBytes(uint32_t size)
Generates a random byte vector.
Definition: HelperFunctions.cpp:360
static std::string stripNonPrintable(const std::string &s)
Strips all non printable characters from a string.
Definition: HelperFunctions.cpp:230
static uid_t userId(const std::string &username)
Gets the UID of a user.
Definition: HelperFunctions.cpp:720
static std::string stripNonAlphaNumeric(const std::string &s, const std::unordered_set< char > &whitelist=std::unordered_set< char >())
Strips all non alphanumeric characters from a string (&#39;_&#39; and &#39;-&#39; are also regarded alphanumeric)...
Definition: HelperFunctions.cpp:221
static std::string & toLower(std::string &s)
Converts all characters of a string to lower case.
Definition: HelperFunctions.h:219
static int64_t getTime()
Gets the current unix time stamp in milliseconds.
Definition: HelperFunctions.cpp:73
static size_t utf8StringSize(const std::string &s)
Returns the size of a UTF-8 string.
Definition: HelperFunctions.h:242
static std::vector< std::string > splitAll(std::string string, char delimiter)
Splits a string at all occurrences of a delimiter.
Definition: HelperFunctions.cpp:477
static int32_t getFileLastModifiedTime(const std::string &filename)
Gets the last modified time of a file.
static std::vector< uint8_t > getUBinary(const std::string &hexString)
Converts a hex string to an unsigned char vector.
Definition: HelperFunctions.cpp:648
static int64_t getTimeNanoseconds()
Gets the current unix time stamp in microseconds.
Definition: HelperFunctions.cpp:81
static void * memrchr(const void *s, int c, size_t n)
Reverse memchr().
Definition: HelperFunctions.cpp:804
This class represents root of the DOM hierarchy.
Definition: rapidxml.h:729
Class representing a node of XML document.
Definition: rapidxml.h:539
static std::string getBinaryString(const std::string &hexString)
Converts a hex string to a binary array of type string.
Definition: HelperFunctions.cpp:620
static std::vector< char > getBinary(const std::string &hexString)
Converts a hex string to a char vector.
Definition: HelperFunctions.cpp:592
static void variable2xml(xml_document *doc, xml_node *parentNode, const PVariable &variable)
Definition: HelperFunctions.cpp:320
static bool checkCliCommand(const std::string &command, const std::string &longCommand, const std::string &shortCommand1, const std::string &shortCommand2, uint32_t minArgumentCount, std::vector< std::string > &arguments, bool &showHelp)
Checks if a string contains a CLI command and checks and returns the arguments.
Definition: HelperFunctions.cpp:776
static int64_t getTimeMicroseconds()
Gets the current unix time stamp in microseconds.
Definition: HelperFunctions.cpp:77
static std::string getTimeUuid()
Calculates a Homegear-specific UUID including a time stamp in 100-nanosecond intervals.
Definition: HelperFunctions.cpp:130
static std::string & toUpper(std::string &s)
Converts all characters of a string to upper case.
Definition: HelperFunctions.h:231
HelperFunctions()
Dummy constructor for backwards compatibility.
Definition: HelperFunctions.cpp:45