summaryrefslogtreecommitdiffstats
path: root/chrome/browser/policy/policy_path_parser.cc
blob: e0ad428f9947845b9b5aff0db3a29b1f085ebc83 (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
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/policy/policy_path_parser.h"

#include "base/bind.h"
#include "base/files/file_path.h"

namespace {

void TrimQuotes(base::FilePath::StringType* path) {
  if (path->length() > 1 &&
      (((*path)[0] == FILE_PATH_LITERAL('"') &&
        (*path)[path->length() - 1] == FILE_PATH_LITERAL('"')) ||
       ((*path)[0] == FILE_PATH_LITERAL('\'') &&
        (*path)[path->length() - 1] == FILE_PATH_LITERAL('\'')))) {
    // Strip first and last char which should be matching quotes now.
    *path = path->substr(1, path->length() - 2);
  }
}

}  // namespace

namespace policy {

namespace path_parser {

namespace internal {

VariableNameAndValueCallback::VariableNameAndValueCallback(
    const base::FilePath::CharType* name,
    const internal::GetValueCallback value_callback)
    : name(name), value_callback(value_callback) {}

VariableNameAndValueCallback::~VariableNameAndValueCallback() {}

}  // namespace internal

// This function performs a lazy call to the GetValueCallback, that is the
// callback is invoked only if the variable is found in the path. This is done
// to reduce the overhead during initialization.
void ReplaceVariableInPathWithValue(
    const base::FilePath::StringType& variable,
    const policy::path_parser::internal::GetValueCallback& value_callback,
    base::FilePath::StringType* path) {
  size_t position = path->find(variable);
  base::FilePath::StringType value;
  if (position != base::FilePath::StringType::npos &&
      value_callback.Run(&value))
    path->replace(position, variable.length(), value);
}

// Replaces all variable occurrences in the policy string with the respective
// system settings values.
base::FilePath::StringType ExpandPathVariables(
    const base::FilePath::StringType& untranslated_string) {
  base::FilePath::StringType result(untranslated_string);

  if (result.length() == 0)
    return result;

  // Sanitize quotes in case of any around the whole string.
  TrimQuotes(&result);

  for (int i = 0; i < internal::kNoOfVariables; ++i) {
    ReplaceVariableInPathWithValue(
        base::FilePath::StringType(
            internal::kVariableNameAndValueCallbacks[i].name),
        internal::kVariableNameAndValueCallbacks[i].value_callback,
        &result);
  }

  return result;
}

}  // namespace path_parser

}  // namespace policy