Debian Codegraph @

Utils/Utils.cpp

raw symbols ◀ ▶
Source reconstructed at patch state 0 of 1 — not the installed (fully patched) source.
1 Debian patch touch this file
1 /*
2 RailControl - Model Railway Control Software
3
4 Copyright (c) 2017-2025 by Teddy / Dominik Mahrer - www.railcontrol.org
5
6 RailControl is free software; you can redistribute it and/or modify it
7 under the terms of the GNU General Public License as published by the
8 Free Software Foundation; either version 3, or (at your option) any
9 later version.
10
11 RailControl is distributed in the hope that it will be useful, but
12 WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
14 See the GNU General Public License for more details.
15
16 You should have received a copy of the GNU General Public License
17 along with RailControl; see the file LICENCE. If not see
18 <http://www.gnu.org/licenses/>.
19 */
20
21 #include <algorithm>
22 #include <arpa/inet.h>
23 #include <cstdarg> // va_* in xlog
24 #include <cstdio> // printf
25 #include <cstdlib> // exit(0);
26 #include <cstring> // memset
27 #include <dirent.h>
28 #include <fstream>
29 #include <iostream> // cout
30 #include <netdb.h>
31 #include <string>
32 #include <sys/time.h> // gettimeofday
33 #include <vector>
34
35 #include "Languages.h"
36 #include "Logger/Logger.h"
37 #include "Network/Select.h"
38 #include "Utils/Integer.h"
39 #include "Utils/Utils.h"
40
41 using std::cout;
42 using std::deque;
43 using std::endl;
44 using std::string;
45 using std::to_string;
46 using std::vector;
47
48 namespace Utils
49 {
50 void Utils::ReplaceString(std::string& str, const std::string& from, const std::string& to)
51 {
52 size_t lastOccurrence = 0;
53 while (true)
54 {
55 size_t startPos = str.find(from, lastOccurrence);
56 if (startPos == string::npos)
57 {
58 return;
59 }
60 str.replace(startPos, from.length(), to);
61 lastOccurrence = startPos + to.length();
62 }
63 }
64
65 void Utils::SplitString(const string& input, const string& delimiter, deque<string>& list)
66 {
67 size_t delimiterLength = delimiter.length();
68 string workingString(input);
69 while (true)
70 {
71 size_t pos = workingString.find(delimiter);
72 list.push_back(workingString.substr(0, pos));
73 if (pos == string::npos)
74 {
75 return;
76 }
77 workingString = string(workingString.substr(pos + delimiterLength, string::npos));
78 }
79 }
80
81 void Utils::SplitString(const string& input, const string& delimiter, string& first, string& second)
82 {
83 size_t delimiterLength = delimiter.length();
84 size_t pos = input.find(delimiter);
85 first = input.substr(0, pos);
86 second = input.substr(pos + delimiterLength);
87 }
88
89 string Utils::StringBeforeDelimiter(const std::string& input, const std::string& delimiter)
90 {
91 string ret;
92 string unused;
93 SplitString(input, delimiter, ret, unused);
94 return ret;
95 }
96
97 string Utils::UrlDecode(const string& value)
98 {
99 string output = value;
100 size_t startSearch = 0;
101 while (true)
102 {
103 size_t pos = output.find('%', startSearch);
104 if (pos == string::npos || pos + 3 > output.length())
105 {
106 break;
107 }
108 const unsigned char highNibble = Integer::HexToChar(output[pos + 1]);
109 const unsigned char lowNibble = Integer::HexToChar(output[pos + 2]);
110 const unsigned char c = (highNibble << 4) + lowNibble;
111 output.replace(pos, 3, 1, c);
112 startSearch = pos + 1;
113 }
114 return output;
115 }
116
117 string Utils::UrlEncode(const string& value)
118 {
119 string output = value;
120 ReplaceString(output, "%", "%25");
121 ReplaceString(output, "&", "%26");
122 ReplaceString(output, "=", "%3d");
123 return output;
124 }
125
126 string Utils::HtmlEncode(const string& value)
127 {
128 string modifiedValue = value;
129 ReplaceString(modifiedValue, "&", "&amp;");
130 ReplaceString(modifiedValue, "\"", "&quot;");
131 ReplaceString(modifiedValue, "'", "&apos;");
132 ReplaceString(modifiedValue, "<", "&lt;");
133 ReplaceString(modifiedValue, ">", "&gt;");
134 return modifiedValue;
135 }
136
137 const std::string& Utils::GetStringMapEntry(const std::map<std::string, std::string>& map, const std::string& key, const std::string& defaultValue)
138 {
139 if (map.count(key) == 0)
140 {
141 return defaultValue;
142 }
143 return map.at(key);
144 }
145
146 int Utils::GetIntegerMapEntry(const std::map<std::string, std::string>& map, const std::string& key, const int defaultValue)
147 {
148 if (map.count(key) == 0)
149 {
150 return defaultValue;
151 }
152 return Integer::StringToInteger(map.at(key), defaultValue);
153 }
154
155 bool Utils::GetBoolMapEntry(const std::map<std::string, std::string>& map, const std::string& key, const bool defaultValue)
156 {
157 if (map.count(key) == 0)
158 {
159 return defaultValue;
160 }
161 string value = map.at(key);
162 return (value.compare("true") == 0 || value.compare("on") == 0 || value.compare("1") == 0 || key.compare(value) == 0);
163 }
164
165 string Utils::ToStringWithLeadingZeros(const unsigned int number, const unsigned char chars)
166 {
167 string out = to_string(number);
168 while (out.length() < chars)
169 {
170 out.insert(0, "0");
171 }
172 return out;
173 }
174
175 bool Utils::StringToBool(const std::string& value, const bool defaultValue)
176 {
177 if (value.size() == 0)
178 {
179 return defaultValue;
180 }
181 int intValue = Integer::StringToInteger(value);
182 return intValue != 0;
183 }
184
185 string Utils::StringToLower(const string& input)
186 {
187 string output = input;
188 for(auto& c : output)
189 {
190 c = tolower(c);
191 }
192 return output;
193 }
194
195 void Utils::CopyFile(Logger::Logger* logger, const std::string& from, const std::string& to)
196 {
197 logger->Info(Languages::TextCopyingFromTo, from, to);
198 std::ifstream source(from, std::ios::binary);
199 std::ofstream destination(to, std::ios::binary);
200 destination << source.rdbuf();
201 source.close();
202 destination.close();
203 }
204
205 void Utils::RenameFile(Logger::Logger* logger, const std::string& from, const std::string& to)
206 {
207 if (logger != nullptr)
208 {
209 logger->Info(Languages::TextRenamingFromTo, from, to);
210 }
211 std::rename(from.c_str(), to.c_str());
212 }
213
214 void Utils::RemoveOldBackupFiles (Logger::Logger *logger,
215 const std::string &filename,
216 unsigned int keepBackups)
217 {
218 DIR *dir = opendir(".");
219 if (dir == nullptr)
220 {
221 return;
222 }
223 struct dirent *ent;
224 std::vector < string > fileNames;
225 const string filenameSearch = filename + ".";
226 const size_t filenameSearchLength = filenameSearch.length() + 10;
227 while (true)
228 {
229 ent = readdir(dir);
230 if (ent == nullptr)
231 {
232 break;
233 }
234 string fileName = ent->d_name;
235 if (fileName.length() != filenameSearchLength || fileName.find(filenameSearch) == string::npos)
236 {
237 continue;
238 }
239 fileNames.push_back(ent->d_name);
240 }
241 closedir(dir);
242 std::sort(fileNames.begin(), fileNames.end());
243
244 size_t numberOfFiles = fileNames.size();
245 if (numberOfFiles == 0 || numberOfFiles < keepBackups)
246 {
247 return;
248 }
249
250 unsigned int removeBackups = fileNames.size() - keepBackups;
251 ++removeBackups; // at shutdown we create another backupfile
252 for (auto &fileName : fileNames)
253 {
254 if (removeBackups == 0)
255 {
256 return;
257 }
258
259 --removeBackups;
260 logger->Info(Languages::TextRemoveBackupFile, fileName);
261 remove(fileName.c_str());
262 }
263 }
264
265 void Utils::SetMinThreadPriority()
266 {
267 sched_param param;
268 int policy;
269 pthread_t self = pthread_self();
270 pthread_getschedparam(self, &policy, &param);
271 param.sched_priority = sched_get_priority_min(policy);
272 pthread_setschedparam(self, policy, &param);
273 }
274
275 std::string Utils::TimestampToDate(const time_t timestamp)
276 {
277 struct tm *tm = localtime(&timestamp);
278 char date[20];
279 strftime(date, sizeof(date), "%Y-%m-%d %H:%M:%S", tm);
280 return date;
281 }
282
283 #ifdef __CYGWIN__
284 bool Utils::GetFilesInDir(vector<string>& filesFound, const string& path, const string& prefix)
285 {
286 bool ret = false;
287 size_t prefixLength = prefix.length();
288 DIR* dirp = opendir(path.c_str());
289 struct dirent* dp;
290 while ((dp = readdir(dirp)) != nullptr)
291 {
292 string file(dp->d_name);
293 string prefixRead = file.substr(0, prefixLength);
294 if (prefix.compare(prefixRead) != 0)
295 {
296 continue;
297 }
298 filesFound.push_back(file);
299 ret = true;
300 }
301 closedir(dirp);
302 return ret;
303 }
304
305 bool Utils::GetComPorts(std::vector<unsigned char>& comPorts)
306 {
307 vector<string> filesFound;
308 bool ret = GetFilesInDir(filesFound, "/dev/", "ttyS");
309 if (ret == false)
310 {
311 return false;
312 }
313 for (auto& file : filesFound)
314 {
315 string comPortString = file.substr(4);
316 unsigned char comPort = Integer::StringToInteger(comPortString);
317 comPorts.push_back(comPort);
318 }
319 return true;
320 }
321 #endif
322
323 uint8_t Utils::CalcXORCheckSum(const uint8_t* const buffer, size_t length)
324 {
325 uint8_t ret = 0;
326 for (size_t i = 0; i < length; ++i)
327 {
328 ret ^= buffer[i];
329 }
330 return ret;
331 }
332 }