[go: up one dir, main page]

File: Util.cc

package info (click to toggle)
ignition-common 1.1.1-1
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 1,856 kB
  • sloc: cpp: 22,616; python: 1,595; ansic: 484; sh: 125; makefile: 18
file content (514 lines) | stat: -rw-r--r-- 12,799 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
/*
 * Copyright (C) 2016 Open Source Robotics Foundation
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
*/
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

#ifdef __linux__
#include <sys/sendfile.h>
#endif

#include <iomanip>
#include <array>
#include <algorithm>
#include <sstream>
#include <fstream>
#include <cstdlib>
#include <cstring>
#include <cctype>

#include <ignition/common/config.hh>
#include <ignition/common/SystemPaths.hh>
#include <ignition/common/Util.hh>
#include <ignition/common/Uuid.hh>
#include <ignition/common/Console.hh>

#ifndef _WIN32
#include <dirent.h>
#include <limits.h>
#include <climits>
#include <ignition/common/ffmpeg_inc.hh>
#else
#include <io.h>
#include "win_dirent.h"
#endif


#define LEFT_ROTATE(x, n) (((x) << (n)) ^ ((x) >> (32-(n))))


#ifdef _WIN32
  const auto &ignstrtok = strtok_s;
#else
  const auto &ignstrtok = strtok_r;
#endif

/////////////////////////////////////////////////
// avcodec log callback. We use this to redirect message to gazebo's console
// messages.
#ifndef _WIN32
void logCallback(void *_ptr, int _level, const char *_fmt, va_list _args)
{
  static char message[8192];

  std::string msg = "ffmpeg ";

  // Get the ffmpeg module.
  if (_ptr)
  {
    AVClass *avc = *reinterpret_cast<AVClass**>(_ptr);
    const char *module = avc->item_name(_ptr);
    if (module)
      msg += std::string("[") + module + "] ";
  }

  // Create the actual message
  vsnprintf(message, sizeof(message), _fmt, _args);
  msg += message;

  // Output to the appropriate stream.
  switch (_level)
  {
    case AV_LOG_DEBUG:
      // There are a lot of debug messages. So we'll skip those.
      break;
    case AV_LOG_PANIC:
    case AV_LOG_FATAL:
    case AV_LOG_ERROR:
      ignerr << msg << std::endl;
      break;
    case AV_LOG_WARNING:
      ignwarn << msg << std::endl;
      break;
    default:
      ignmsg << msg << std::endl;
      break;
  }
}
#endif

static std::unique_ptr<ignition::common::SystemPaths> gSystemPaths(
    new ignition::common::SystemPaths);

/////////////////////////////////////////////////
// Internal class for SHA1 computation
class Sha1
{
  /// \brief Constructor
  public: Sha1() = default;

  /// \brief Get the SHA1 digest
  /// \param[in] _digest Digest types
  public: bool Digest(void const *_buffer, std::size_t _byteCount,
                      std::array<unsigned int, 5> &_digest);

  /// \brief Helper function to process a byte
  /// \param[in] _byte Byte to process
  private: void Byte(std::array<unsigned int, 5> &_hash,
               const unsigned char _byte);

  /// \brief Byte block
  private: std::array<unsigned char, 64> block;

  /// \brief Byte block index
  private: std::size_t blockByteIndex = 0;

  /// \brief Bit low count
  private: std::size_t bitCountLow = 0;

  /// \brief Bit high count
  private: std::size_t bitCountHigh = 0;
};

/////////////////////////////////////////////////
void Sha1::Byte(std::array<unsigned int, 5> &_hash, const unsigned char _byte)
{
  this->block[this->blockByteIndex++] = _byte;

  if (this->blockByteIndex == 64)
  {
    unsigned int w[80];
    this->blockByteIndex = 0;

    for (std::size_t i = 0; i < 16; ++i)
    {
      w[i] = (this->block[i*4 + 0] << 24);
      w[i] |= (this->block[i*4 + 1] << 16);
      w[i] |= (this->block[i*4 + 2] << 8);
      w[i] |= this->block[i*4 + 3];
    }

    for (std::size_t i = 16; i < 80; ++i)
    {
      w[i] = LEFT_ROTATE((w[i-3] ^ w[i-8] ^ w[i-14] ^ w[i-16]), 1);
    }

    auto a = _hash[0];
    auto b = _hash[1];
    auto c = _hash[2];
    auto d = _hash[3];
    auto e = _hash[4];

    for (std::size_t i = 0; i < 80; ++i)
    {
      unsigned int f;
      unsigned int k;

      if (i < 20)
      {
        f = (b & c) | (~b & d);
        k = 0x5A827999;
      }
      else if (i < 40)
      {
        f = b ^ c ^ d;
        k = 0x6ED9EBA1;
      }
      else if (i < 60)
      {
        f = (b & c) | (b & d) | (c & d);
        k = 0x8F1BBCDC;
      }
      else
      {
        f = b ^ c ^ d;
        k = 0xCA62C1D6;
      }

      auto temp = LEFT_ROTATE(a, 5) + f + e + k + w[i];
      e = d;
      d = c;
      c = LEFT_ROTATE(b, 30);
      b = a;
      a = temp;
    }

    _hash[0] += a;
    _hash[1] += b;
    _hash[2] += c;
    _hash[3] += d;
    _hash[4] += e;
  }
}

/////////////////////////////////////////////////
bool Sha1::Digest(void const *_buffer, std::size_t _byteCount,
    std::array<unsigned int, 5> &_hash)
{
  _hash = {{0x67452301, 0xEFCDAB89, 0x98BADCFE, 0x10325476, 0xC3D2E1F0}};

  auto start = static_cast<unsigned char const*>(_buffer);
  auto end = static_cast<unsigned char const*>(start + _byteCount);

  for (; start != end; ++start)
  {
    this->Byte(_hash, *start);

    // size_t max value = 0xFFFFFFFF
    if (this->bitCountLow < 0xFFFFFFF8)
    {
      this->bitCountLow += 8;
    }
    else
    {
      this->bitCountLow = 0;

      if (this->bitCountHigh <= 0xFFFFFFFE)
      {
        ++this->bitCountHigh;
      }
      else
      {
        // Too many bytes
        return false;
      }
    }
  }

  // append the bit '1' to the message
  this->Byte(_hash, 0x80);

  // append k bits '0', where k is the minimum number >= 0
  // such that the resulting message length is congruent to 56 (mod 64)
  // check if there is enough space for padding and bit_count
  if (this->blockByteIndex > 56)
  {
    // finish this block
    while (this->blockByteIndex != 0)
      this->Byte(_hash, 0);

    // one more block
    while (this->blockByteIndex < 56)
      this->Byte(_hash, 0);
  }
  else
  {
    while (this->blockByteIndex < 56)
      this->Byte(_hash, 0);
  }

  // append length of message (before pre-processing)
  // as a 64-bit big-endian integer
  this->Byte(_hash,
      static_cast<unsigned char>((this->bitCountHigh>>24) & 0xFF));
  this->Byte(_hash,
      static_cast<unsigned char>((this->bitCountHigh>>16) & 0xFF));
  this->Byte(_hash,
      static_cast<unsigned char>((this->bitCountHigh>>8) & 0xFF));
  this->Byte(_hash,
      static_cast<unsigned char>((this->bitCountHigh) & 0xFF));
  this->Byte(_hash,
      static_cast<unsigned char>((this->bitCountLow>>24) & 0xFF));
  this->Byte(_hash,
      static_cast<unsigned char>((this->bitCountLow>>16) & 0xFF));
  this->Byte(_hash,
      static_cast<unsigned char>((this->bitCountLow>>8) & 0xFF));
  this->Byte(_hash,
      static_cast<unsigned char>((this->bitCountLow) & 0xFF));

  return true;
}

/////////////////////////////////////////////////
void ignition::common::load()
{
#ifndef _WIN32
  static bool first = true;
  if (first)
  {
    first = false;
#if LIBAVCODEC_VERSION_INT < AV_VERSION_INT(58, 9, 100)
    avcodec_register_all();
    av_register_all();
#endif

#if defined(__linux__) && defined(HAVE_AVDEVICE)
    avdevice_register_all();
#endif

    // Set the log callback function.
    av_log_set_callback(logCallback);
  }
#endif
}

/////////////////////////////////////////////////
std::string ignition::common::systemTimeISO()
{
  char isoStr[25];

  auto epoch = IGN_SYSTEM_TIME().time_since_epoch();
  auto sec = std::chrono::duration_cast<std::chrono::seconds>(epoch).count();
  auto nano = std::chrono::duration_cast<std::chrono::nanoseconds>(
      epoch).count() - sec * IGN_SEC_TO_NANO;

  time_t tmSec = static_cast<time_t>(sec);
  std::strftime(isoStr, sizeof(isoStr), "%FT%T", std::localtime(&tmSec));

  return std::string(isoStr) + "." + std::to_string(nano);
}

/////////////////////////////////////////////////
std::string ignition::common::logPath()
{
  return gSystemPaths->LogPath();
}

/////////////////////////////////////////////////
void ignition::common::addSearchPathSuffix(const std::string &_suffix)
{
  gSystemPaths->AddSearchPathSuffix(_suffix);
}

/////////////////////////////////////////////////
std::string ignition::common::findFile(const std::string &_file)
{
  return gSystemPaths->FindFile(_file, true);
}

/////////////////////////////////////////////////
std::string ignition::common::findFile(const std::string &_file,
                                       const bool _searchLocalPath)
{
  return gSystemPaths->FindFile(_file, _searchLocalPath);
}

/////////////////////////////////////////////////
std::string ignition::common::findFilePath(const std::string &_file)
{
  std::string filepath = findFile(_file);

  if (common::isDirectory(filepath))
  {
    return filepath;
  }
  else
  {
    int index = filepath.find_last_of("/");
    return filepath.substr(0, index);
  }
}

/////////////////////////////////////////////////
bool ignition::common::env(const std::string &_name, std::string &_value)
{
  std::string v;
#ifdef _WIN32
  const DWORD buffSize = 32767;
  static char buffer[buffSize];
  if (GetEnvironmentVariable(_name.c_str(), buffer, buffSize))
  {
    v = buffer;
  }
#else
  const char *cvar = std::getenv(_name.c_str());
  if (cvar)
    v = cvar;
#endif
  if (!v.empty())
  {
    _value = v;
    return true;
  }
  return false;
}

/////////////////////////////////////////////////
std::string ignition::common::sha1(void const *_buffer, std::size_t _byteCount)
{
  Sha1 sha1;
  std::stringstream stream;

  std::array<unsigned int, 5> hash;
  if (sha1.Digest(_buffer, _byteCount, hash))
  {
    for (auto const h : hash)
      stream << std::setfill('0') << std::setw(sizeof(h) * 2) << std::hex << h;
  }

  return stream.str();
}

/////////////////////////////////////////////////
std::string ignition::common::uuid()
{
  ignition::common::Uuid uuid;
  return uuid.String();
}

/////////////////////////////////////////////////
std::vector<std::string> ignition::common::split(const std::string &_str,
    const std::string &_delim)
{
  std::vector<std::string> tokens;
  char *saveptr;
  char *str = strdup(_str.c_str());

  auto token = ignstrtok(str, _delim.c_str(), &saveptr);

  while (token)
  {
    tokens.push_back(token);
    token = ignstrtok(NULL, _delim.c_str(), &saveptr);
  }

  free(str);
  return tokens;
}

/////////////////////////////////////////////////
void ignition::common::ltrim(std::string &_s)
{
  _s.erase(_s.begin(), std::find_if(_s.begin(), _s.end(),
        std::not1(std::ptr_fun<int, int>(std::isspace))));
}

/////////////////////////////////////////////////
void ignition::common::rtrim(std::string &_s)
{
  _s.erase(std::find_if(_s.rbegin(), _s.rend(),
        std::not1(std::ptr_fun<int, int>(std::isspace))).base(),
      _s.end());
}

/////////////////////////////////////////////////
void ignition::common::trim(std::string &_s)
{
  ignition::common::ltrim(_s);
  ignition::common::rtrim(_s);
}

/////////////////////////////////////////////////
std::string ignition::common::ltrimmed(std::string _s)
{
  ignition::common::ltrim(_s);
  return _s;
}

/////////////////////////////////////////////////
std::string ignition::common::rtrimmed(std::string _s)
{
  ignition::common::rtrim(_s);
  return _s;
}

/////////////////////////////////////////////////
std::string ignition::common::trimmed(std::string _s)
{
  ignition::common::trim(_s);
  return _s;
}

/////////////////////////////////////////////////
std::string ignition::common::lowercase(const std::string &_in)
{
  std::string out = _in;
  std::transform(out.begin(), out.end(), out.begin(), ::tolower);
  return out;
}

/////////////////////////////////////////////////
std::string ignition::common::lowercase(const char *_in)
{
  std::string ins = _in;
  return lowercase(ins);
}

/////////////////////////////////////////////////
void ignition::common::replaceAll(std::string &_result,
                                  const std::string &_orig,
                                  const std::string &_key,
                                  const std::string &_replacement)
{
  _result = _orig;
  size_t pos = 0;
  while ((pos = _result.find(_key, pos)) != std::string::npos)
  {
    _result = _result.replace(pos, _key.length(), _replacement);
    pos += _key.length() > _replacement.length() ? 0 : _replacement.length();
  }
}

/////////////////////////////////////////////////
std::string ignition::common::replaceAll(const std::string &_orig,
                                        const std::string &_key,
                                        const std::string &_replacement)
{
  std::string result;
  replaceAll(result, _orig, _key, _replacement);
  return result;
}