summaryrefslogtreecommitdiff
path: root/files/src/android/goldfish/IniFile.cpp
blob: a9c53bed1ec9174a09cb545efe7044a82fe75859 (plain)
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
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
// Copyright 2015 The Android Open Source Project
//
// This software is licensed under the terms of the GNU General Public
// License version 2, as published by the Free Software Foundation, and
// may be copied, distributed, and modified under those terms.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.

#include "android/goldfish/IniFile.h"

#include <filesystem>

#include "aemu/base/logging/Log.h"
#include "android/base/system/System.h"

#ifdef _MSC_VER
#include "aemu/base/system/Win32UnicodeString.h"
#endif

#ifdef _MSC_VER
#include "msvc-posix.h"
#endif

#include <assert.h>
#include <string.h>

#include <fstream>
#include <iomanip>
#include <istream>
#include <sstream>
#include <streambuf>
#include <string>
#include <string_view>
#include <utility>

namespace android {
namespace goldfish {

using std::ifstream;
using std::ios_base;
using std::string;
using std::to_string;

static bool move(const std::string &from, const std::string &to) {
  // std::rename returns 0 on success.
  if (std::rename(from.c_str(), to.c_str())) {
    if (errno == ENOENT) {
      return false;
    }

#ifdef _SUPPORT_FILESYSTEM
    // Rename can fail if files are on different disks
    if (std::filesystem::copy_file(from.c_str(), to.c_str())) {
      std::filesystem::remove(from.c_str());
      return true;
    } else {
      return false;
    }
#else  // _SUPPORT_FILESYSTEM
    return false;
#endif // _SUPPORT_FILESYSTEM
  }
  return true;
}

IniFile::IniFile(const char *data, int size) {
  readFromMemory(std::string_view(data, size));
}

void IniFile::setBackingFile(std::filesystem::path filePath) {
  // We have no idea what the new backing file contains.
  mDirty = true;
  mBackingFilePath = filePath;
}

static bool isSpaceChar(unsigned uc) {
  return uc == ' ' || uc == '\r' || uc == '\t';
}

static bool isValueChar(unsigned uc) { return uc != '\r' && uc != '\n'; }

static bool isKeyStartChar(unsigned uc) {
  static const unsigned smallRange = 'z' - 'a' + 1;
  static const unsigned capitalRange = 'Z' - 'A' + 1;
  return (uc - 'a' < smallRange) || (uc - 'A' < capitalRange) || (uc == '_');
}

static bool isKeyChar(unsigned uc) {
  static const unsigned numRange = '9' - '0' + 1;
  return isKeyStartChar(uc) || (uc - '0' < numRange) || (uc == '.') ||
         (uc == '-');
}

template <typename CIterator, typename Pred>
static CIterator eat(CIterator citer, CIterator cend, Pred pred) {
  while (citer != cend && pred(*citer)) {
    ++citer;
  }
  return citer;
}

void IniFile::parseStream(std::istream *in, bool keepComments) {
  string line;
  int lineno = 0;
  // This is the line number we'd print at if the IniFile were immediately
  // written back. Unlike |line|, this will not be incremented for invalid
  // lines, since they're completely dropped.
  int outputLineno = 0;
  while (std::getline(*in, line)) {
    ++lineno;
    ++outputLineno;

    const string &cline = line;
    auto citer = std::begin(cline);
    auto cend = std::end(cline);
    citer = eat(citer, cend, isSpaceChar);

    // Handle empty lines, comments.
    if (citer == cend) {
      LOG(DEBUG) << "Line " << lineno << ": Skipped empty line.";
      if (keepComments) {
        mComments.emplace_back(outputLineno, std::move(line));
      }
      continue;
    }
    if (*citer == '#' || *citer == ';') {
      LOG(DEBUG) << "Line " << lineno << ": Skipped comment line.";
      if (keepComments) {
        mComments.emplace_back(outputLineno, std::move(line));
      }
      continue;
    }

    // Extract and validate key.
    const auto keyStartIter = citer;
    if (!isKeyStartChar(*citer)) {
      LOG(DEBUG) << "Line " << lineno
                 << ": Key does not start with a valid character."
                 << " Skipped line.";
      --outputLineno;
      continue;
    }
    ++citer;
    citer = eat(citer, cend, isKeyChar);
    auto key = string(keyStartIter, citer);

    // Gobble the = sign.
    citer = eat(citer, cend, isSpaceChar);
    if (citer == cend || *citer != '=') {
      LOG(DEBUG) << "Line " << lineno
                 << ": Missing expected assignment operator (=)."
                 << " Skipped line.";
      --outputLineno;
      continue;
    }
    ++citer;

    // Extract the value.
    citer = eat(citer, cend, isSpaceChar);
    const auto valueStartIter = citer;
    citer = eat(citer, cend, isValueChar);
    auto value = string(valueStartIter, citer);
    // Remove trailing space.
    auto trailingSpaceIter = eat(value.rbegin(), value.rend(), isSpaceChar);
    value.erase(trailingSpaceIter.base(), value.end());

    // Ensure there's no invalid remainder.
    citer = eat(citer, cend, isSpaceChar);
    if (citer != cend) {
      LOG(DEBUG) << "Line " << lineno
                 << ": Contains invalid character in the value."
                 << " Skipped line.";
      --outputLineno;
      continue;
    }

    // Everything parsed.
    auto insertRes = mData.emplace(std::move(key), std::string());
    insertRes.first->second = std::move(value);
    if (insertRes.second) {
      mOrderList.push_back(&*insertRes.first);
    }
  }
}

bool IniFile::read(bool keepComments) {
  mDirty = false;
  mData.clear();
  mOrderList.clear();
  mComments.clear();

  if (mBackingFilePath.empty()) {
    LOG(WARNING) << "Read called without a backing file!";
    return false;
  }

#ifdef _MSC_VER
  Win32UnicodeString wBackingFilePath(mBackingFilePath);
  ifstream inFile(wBackingFilePath.c_str(), ios_base::in | ios_base::ate);
#else
  ifstream inFile(mBackingFilePath, ios_base::in | ios_base::ate);
#endif

  if (!inFile) {
    LOG(WARNING) << "Failed to process .ini file " << mBackingFilePath
                 << " for reading.";
    return false;
  }

  // avoid reading a very large file that was passed by mistake
  // this threshold is quite liberal.
  static const auto kMaxIniFileSize = ifstream::pos_type(655360);
  static const auto kInvalidPos = ifstream::pos_type(-1);
  const ifstream::pos_type endPos = inFile.tellg();
  inFile.seekg(0, ios_base::beg);
  const ifstream::pos_type begPos = inFile.tellg();
  if (begPos == kInvalidPos || endPos == kInvalidPos ||
      endPos - begPos > kMaxIniFileSize) {
    LOG(WARNING) << ".ini File " << mBackingFilePath << " too large ("
                 << (endPos - begPos) << " bytes)";
    return false;
  }

  parseStream(&inFile, keepComments);
  return true;
}

bool IniFile::readFromMemory(std::string_view data) {
  mDirty = false;
  mData.clear();
  mOrderList.clear();
  mComments.clear();

  // Create a streambuf that's able to do a single pass over an array only.
  class OnePassIBuf : public std::streambuf {
  public:
    explicit OnePassIBuf(std::string_view data) {
      setg(const_cast<char *>(data.data()), const_cast<char *>(data.data()),
           const_cast<char *>(data.data()) + data.size());
    }
  };
  OnePassIBuf ibuf(data);
  std::istream in(&ibuf);
  if (!in) {
    LOG(WARNING) << "Failed to process input data for reading.";
    return false;
  }

  parseStream(&in, true);
  return true;
}

bool IniFile::writeCommonImpl(bool discardEmpty, const std::string &filePath) {
#ifdef _MSC_VER
  Win32UnicodeString wFilePath(filePath);
  std::ofstream outFile(wFilePath.c_str(), ios_base::out | ios_base::trunc);
#else
  std::ofstream outFile(filePath, std::ios_base::out | std::ios_base::trunc);
#endif

  if (!outFile) {
    LOG(WARNING) << "Failed to open '" << filePath << "' for writing.";
    return false;
  }

  int lineno = 0;
  auto commentIter = std::begin(mComments);
  for (const auto &pair : mOrderList) {
    ++lineno;

    // Write comments
    for (; commentIter != std::end(mComments) && lineno >= commentIter->first;
         ++commentIter, ++lineno) {
      outFile << commentIter->second << "\n";
    }

    const string &value = pair->second;
    if (discardEmpty && value.empty()) {
      continue;
    }
    const string &key = pair->first;
    outFile << key << " = " << value << '\n';
  }

  mDirty = false;
  return true;
}

// 1. write config to mBackingFilePath.new
// 2. rename mBackingFilePath to mBackingFilePath.old
// 3. rename mBackingFilePath.new to mBackingFilePath
// 4. delete mBackingFilePath.old
bool IniFile::writeCommon(const bool discardEmpty) {
  if (mBackingFilePath.empty()) {
    LOG(WARNING) << "Write called without a backing file!";
    return false;
  }

  const std::string iniFileNew = mBackingFilePath + ".new";
  if (!writeCommonImpl(discardEmpty, iniFileNew)) {
    return false;
  }

  const std::string iniFileOld = mBackingFilePath + ".old";
  std::filesystem::remove(
      iniFileOld.c_str()); // just in case `myRemove` below failed

  const bool deleteOldConfig =
      move(mBackingFilePath.c_str(), iniFileOld.c_str());

  if (!move(iniFileNew.c_str(), mBackingFilePath.c_str())) {
    if (deleteOldConfig) {
      // try to revert the first `rename`
      if (!move(iniFileOld.c_str(), mBackingFilePath.c_str())) {
        // mBackingFilePath is missing here
        LOG(ERROR) << "Failed to update '" << mBackingFilePath
                   << "', the file no longer exists";
      } else {
        // mBackingFilePath is reverted back
        LOG(WARNING) << "Failed to update '" << mBackingFilePath << "'";
      }
    } else {
      // mBackingFilePath could be read-only
      LOG(WARNING) << "Failed to save '" << mBackingFilePath << "'";
    }

    std::filesystem::remove(iniFileNew.c_str());
    return false;
  }

  if (deleteOldConfig) {
    std::filesystem::remove(iniFileOld.c_str());
  }

  return true;
}

bool IniFile::write() { return writeCommon(false); }

bool IniFile::writeDiscardingEmpty() { return writeCommon(true); }

bool IniFile::writeIfChanged() { return !mDirty || writeCommon(false); }

int IniFile::size() const { return static_cast<int>(mData.size()); }

bool IniFile::hasKey(std::string_view key) const {
  return mData.find(key.data()) != std::end(mData);
}

std::string IniFile::makeValidKey(std::string_view str) {
  std::ostringstream res;
  res << std::hex << std::uppercase;
  res << '_'; // mark all keys passed through this function with a leading
              // underscore
  for (char c : str) {
    if (isKeyChar(c)) {
      res << c;
    } else {
      res << '.' << std::setw(2) << std::setfill('0') << static_cast<int>(c);
    }
  }
  return res.str();
}

string IniFile::makeValidValue(std::string_view str) {
  std::ostringstream res;
  for (auto ch = str.begin(); ch != str.end() && *ch != '\0'; ch++) {
    if (*ch == '%')
      res << *ch;
    res << *ch;
  }
  return res.str();
}

// Substitute environment variables inside a string.
// Substitution is based on %ENVIRONMENT_VARIABLE%
// Double %% is treated as an escape.
// If a string is not terminated (i.e a starting %, but
// no ending %) the whole string will be returned.
//
// For example:
// "%PAGER%" => "less"
// "%PAG%%ER%" => "" ("PAG%ER" is not a valid name)
// "%FOO" => "%FOO" (Not terminated)
// "%%HI%%" => "%HI%" (Escaped)
// Note that: %%%USER%%% is parsed as %(USER)% and not %(USER%)%
static string envSubst(const std::string_view fix) {
  size_t len = fix.size();

  string res;
  string var;
  string *curr = &res;
  for (unsigned int i = 0; i < len; i++) {
    char ch = fix[i];

    // A normal character will be added to the current string
    if (ch != '%') {
      curr->push_back(ch);
      continue;
    }

    // Let's see if we are closing
    if (curr == &var) {
      string env = base::System::get()->envGet(var);
      if (env.empty()) {
        LOG(WARNING) << "Environment variable " << var << " is not set";
      }
      res.append(env);
      var.clear();
      curr = &res;
      continue;
    }

    // Check if we have a case of escapism..
    // Note that len-1 >= 0
    char next = (i < len - 1) ? fix[i + 1] : '\0';

    if (next == '%') {
      // Escaped, let's skip it.
      curr->push_back(ch);
      i++;
    } else {
      // We open and start a env variable name.
      curr = &var;
    }
  }

  // Return full string for unterminated piece.
  if (curr == &var) {
    res.push_back('%');
    res.append(var);
  }

  return res;
}

string IniFile::getString(const string &key,
                          std::string_view defaultValue) const {
  auto citer = mData.find(key);
  return envSubst((citer == std::end(mData)) ? defaultValue
                                             : std::string_view(citer->second));
}

int IniFile::getInt(const string &key, int defaultValue) const {
  if (mData.find(key) == std::end(mData)) {
    return defaultValue;
  }

  auto value = getString(key, "");
  char *end;
  errno = 0;
  const int result = strtol(value.c_str(), &end, 10);
  if (errno || *end != 0) {
    LOG(DEBUG) << "Malformed int value " << value << " for key " << key;
    return defaultValue;
  }
  return result;
}

int64_t IniFile::getInt64(const string &key, int64_t defaultValue) const {
  if (mData.find(key) == std::end(mData)) {
    return defaultValue;
  }

  auto value = getString(key, "");
  char *end;
  errno = 0;
  const int64_t result = strtoll(value.c_str(), &end, 10);
  if (errno || *end != 0) {
    LOG(DEBUG) << "Malformed int64 value " << value << " for key " << key;
    return defaultValue;
  }
  return result;
}

double IniFile::getDouble(const string &key, double defaultValue) const {
  if (mData.find(key) == std::end(mData)) {
    return defaultValue;
  }

  auto value = getString(key, "");
  char *end;
  errno = 0;
  const double result = strtod(value.c_str(), &end);
  if (errno || *end != 0) {
    LOG(DEBUG) << "Malformed double value " << value << " for key " << key;
    return defaultValue;
  }
  return result;
}

static bool isBoolTrue(std::string_view value) {
  const char *cstr = value.data();
  const size_t size = value.size();

  return strncasecmp("yes", cstr, size) == 0 ||
         strncasecmp("true", cstr, size) == 0 ||
         strncasecmp("1", cstr, size) == 0;
}

static bool isBoolFalse(std::string_view value) {
  const char *cstr = value.data();
  const size_t size = value.size();
  return strncasecmp("no", cstr, size) == 0 ||
         strncasecmp("false", cstr, size) == 0 ||
         strncasecmp("0", cstr, size) == 0;
}

bool IniFile::getBool(const string &key, bool defaultValue) const {
  if (mData.find(key) == std::end(mData)) {
    return defaultValue;
  }

  const string &value = getString(key, "");
  if (isBoolTrue(value)) {
    return true;
  } else if (isBoolFalse(value)) {
    return false;
  } else {
    LOG(DEBUG) << "Malformed bool value " << value << " for key " << key;
    return defaultValue;
  }
}

bool IniFile::getBool(const string &key, std::string_view defaultValue) const {
  return getBool(key, isBoolTrue(defaultValue));
}

// If not nullptr, |*outMalformed| is set to true if |valueStr| is malformed.
static IniFile::DiskSize parseDiskSize(std::string_view valueStr,
                                       IniFile::DiskSize defaultValue,
                                       bool *outMalformed) {
  if (outMalformed) {
    *outMalformed = false;
  }

  char *end;
  errno = 0;
  std::string safe_str = std::string(valueStr);
  IniFile::DiskSize result = strtoll(safe_str.c_str(), &end, 10);
  bool malformed = (errno != 0);
  if (!malformed) {
    switch (*end) {
    case 0:
      break;
    case 'k':
    case 'K':
      result *= 1024ULL;
      break;
    case 'm':
    case 'M':
      result *= 1024 * 1024ULL;
      break;
    case 'g':
    case 'G':
      result *= 1024 * 1024 * 1024ULL;
      break;
    default:
      malformed = true;
    }
  }

  if (malformed) {
    if (outMalformed) {
      *outMalformed = true;
    }
    return defaultValue;
  }
  return result;
}

IniFile::DiskSize IniFile::getDiskSize(const string &key,
                                       IniFile::DiskSize defaultValue) const {
  if (!hasKey(key)) {
    return defaultValue;
  }
  bool malformed = false;
  auto value = getString(key, "");
  IniFile::DiskSize result = parseDiskSize(value, defaultValue, &malformed);

  LOG_IF(VERBOSE, malformed)
      << "Malformed DiskSize value " << value << " for key " << key;
  return result;
}

IniFile::DiskSize IniFile::getDiskSize(const string &key,
                                       std::string_view defaultValue) const {
  return getDiskSize(key, parseDiskSize(defaultValue, 0, nullptr));
}

void IniFile::updateData(const string &key, string &&value) {
  mDirty = true;
  // note: may not move here, as it's currently unspecified if failed
  //  insertion moves from |value| or not. Move it separately instead.
  auto result = mData.emplace(key, std::string());
  result.first->second = std::move(value);
  if (result.second) {
    // New element was created.
    mOrderList.push_back(&*result.first);
  }
}

void IniFile::setString(const string &key, std::string_view value) {
  updateData(key, value.data());
}

void IniFile::setInt(const string &key, int value) {
  updateData(key, to_string(value));
}

void IniFile::setInt64(const string &key, int64_t value) {
  // long long is at least 64 bit in C++0x.
  updateData(key, to_string(static_cast<long long>(value)));
}

void IniFile::setDouble(const string &key, double value) {
  updateData(key, to_string(value));
}

void IniFile::setBool(const string &key, bool value) {
  updateData(key, value ? "true" : "false");
}

void IniFile::setDiskSize(const string &key, DiskSize value) {
  static const DiskSize kKilo = 1024;
  static const DiskSize kMega = 1024 * kKilo;
  static const DiskSize kGiga = 1024 * kMega;

  char suffix = 0;
  if (value >= kGiga && !(value % kGiga)) {
    value /= kGiga;
    suffix = 'g';
  } else if (value >= kMega && !(value % kMega)) {
    value /= kMega;
    suffix = 'm';
  } else if (value >= kKilo && !(value % kKilo)) {
    value /= kKilo;
    suffix = 'k';
  }

  auto valueStr = to_string(value);
  if (suffix) {
    valueStr += suffix;
  }
  updateData(key, std::move(valueStr));
}

} // namespace goldfish
} // namespace android