summaryrefslogtreecommitdiffstats
path: root/chrome/browser/policy/config_dir_policy_provider.cc
blob: 6875bd7c5d292c4345b424917dbf3b4442f24fc6 (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
// Copyright (c) 2010 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/config_dir_policy_provider.h"

#include <set>

#include "base/file_util.h"
#include "base/logging.h"
#include "base/utf_string_conversions.h"
#include "base/values.h"
#include "chrome/common/json_value_serializer.h"

namespace {

// Amount of time we wait for the files in the policy directory to settle before
// trying to load it. This alleviates the problem of reading partially written
// files and allows to batch quasi-simultaneous changes.
const int kSettleIntervalSeconds = 5;

// The time interval for rechecking policy. This is our fallback in case the
// directory watch fails or doesn't report a change.
const int kReloadIntervalMinutes = 15;

}  // namespace

// PolicyDirLoader implementation:

PolicyDirLoader::PolicyDirLoader(
    base::WeakPtr<ConfigDirPolicyProvider> provider,
    const FilePath& config_dir,
    int settle_interval_seconds,
    int reload_interval_minutes)
    : provider_(provider),
      origin_loop_(MessageLoop::current()),
      config_dir_(config_dir),
      reload_task_(NULL),
      settle_interval_seconds_(settle_interval_seconds),
      reload_interval_minutes_(reload_interval_minutes) {
  // Force an initial load, so GetPolicy() works.
  policy_.reset(Load());
  DCHECK(policy_.get());
}

void PolicyDirLoader::Stop() {
  if (!ChromeThread::CurrentlyOn(ChromeThread::FILE)) {
    ChromeThread::PostTask(ChromeThread::FILE, FROM_HERE,
                           NewRunnableMethod(this, &PolicyDirLoader::Stop));
    return;
  }

  if (reload_task_) {
    reload_task_->Cancel();
    reload_task_ = NULL;
  }
}

void PolicyDirLoader::Reload() {
  DCHECK(ChromeThread::CurrentlyOn(ChromeThread::FILE));

  // Check the directory time in order to see whether a reload is required.
  base::TimeDelta delay;
  base::Time now = base::Time::Now();
  if (!IsSafeToReloadPolicy(now, &delay)) {
    ScheduleReloadTask(delay);
    return;
  }

  // Load the policy definitions.
  scoped_ptr<DictionaryValue> new_policy(Load());

  // Check again in case the directory has changed while reading it.
  if (!IsSafeToReloadPolicy(now, &delay)) {
    ScheduleReloadTask(delay);
    return;
  }

  // Replace policy definition.
  bool changed = false;
  {
    AutoLock lock(lock_);
    changed = !policy_->Equals(new_policy.get());
    policy_.reset(new_policy.release());
  }

  // There's a change, report it!
  if (changed) {
    LOG(INFO) << "Policy reload from " << config_dir_.value() << " succeeded.";
    origin_loop_->PostTask(FROM_HERE,
        NewRunnableMethod(this, &PolicyDirLoader::NotifyPolicyChanged));
  }

  // As a safeguard in case the file watcher fails, schedule a reload task
  // that'll make us recheck after a reasonable interval.
  ScheduleReloadTask(base::TimeDelta::FromMinutes(reload_interval_minutes_));
}

DictionaryValue* PolicyDirLoader::GetPolicy() {
  AutoLock lock(lock_);
  return static_cast<DictionaryValue*>(policy_->DeepCopy());
}

void PolicyDirLoader::OnFilePathChanged(const FilePath& path) {
  DCHECK(ChromeThread::CurrentlyOn(ChromeThread::FILE));
  Reload();
}

void PolicyDirLoader::OnError() {
  LOG(ERROR) << "FileWatcher on " << config_dir_.value() << " failed.";
}

DictionaryValue* PolicyDirLoader::Load() {
  // Enumerate the files and sort them lexicographically.
  std::set<FilePath> files;
  file_util::FileEnumerator file_enumerator(config_dir_, false,
                                            file_util::FileEnumerator::FILES);
  for (FilePath config_file_path = file_enumerator.Next();
       !config_file_path.empty(); config_file_path = file_enumerator.Next())
    files.insert(config_file_path);

  // Start with an empty dictionary and merge the files' contents.
  DictionaryValue* policy = new DictionaryValue;
  for (std::set<FilePath>::iterator config_file_iter = files.begin();
       config_file_iter != files.end(); ++config_file_iter) {
    JSONFileValueSerializer deserializer(*config_file_iter);
    int error_code = 0;
    std::string error_msg;
    scoped_ptr<Value> value(deserializer.Deserialize(&error_code, &error_msg));
    if (!value.get()) {
      LOG(WARNING) << "Failed to read configuration file "
                   << config_file_iter->value() << ": " << error_msg;
      continue;
    }
    if (!value->IsType(Value::TYPE_DICTIONARY)) {
      LOG(WARNING) << "Expected JSON dictionary in configuration file "
                   << config_file_iter->value();
      continue;
    }
    policy->MergeDictionary(static_cast<DictionaryValue*>(value.get()));
  }

  return policy;
}

bool PolicyDirLoader::IsSafeToReloadPolicy(const base::Time& now,
                                           base::TimeDelta* delay) {
  DCHECK(delay);
  file_util::FileInfo dir_info;

  // Reading an empty directory or a file is always safe.
  if (!file_util::GetFileInfo(config_dir_, &dir_info) ||
      !dir_info.is_directory) {
    last_modification_file_ = base::Time();
    return true;
  }

  // If there was a change since the last recorded modification, wait some more.
  base::TimeDelta settleInterval(
      base::TimeDelta::FromSeconds(settle_interval_seconds_));
  if (dir_info.last_modified != last_modification_file_) {
    last_modification_file_ = dir_info.last_modified;
    last_modification_clock_ = now;
    *delay = settleInterval;
    return false;
  }

  // Check whether the settle interval has elapsed.
  base::TimeDelta age = now - last_modification_clock_;
  if (age < settleInterval) {
    *delay = settleInterval - age;
    return false;
  }

  return true;
}

void PolicyDirLoader::ScheduleReloadTask(const base::TimeDelta& delay) {
  DCHECK(ChromeThread::CurrentlyOn(ChromeThread::FILE));

  if (reload_task_)
    reload_task_->Cancel();

  reload_task_ = NewRunnableMethod(this, &PolicyDirLoader::ReloadFromTask);
  ChromeThread::PostDelayedTask(ChromeThread::FILE, FROM_HERE, reload_task_,
                                delay.InMilliseconds());
}

void PolicyDirLoader::NotifyPolicyChanged() {
  DCHECK_EQ(origin_loop_, MessageLoop::current());
  if (provider_)
    provider_->NotifyStoreOfPolicyChange();
}

void PolicyDirLoader::ReloadFromTask() {
  DCHECK(ChromeThread::CurrentlyOn(ChromeThread::FILE));

  // Drop the reference to the reload task, since the task might be the only
  // referer that keeps us alive, so we should not Cancel() it.
  reload_task_ = NULL;

  Reload();
}

// PolicyDirWatcher implementation:

void PolicyDirWatcher::Init(PolicyDirLoader* loader) {
  // Initialization can happen early when the file thread is not yet available.
  // So post a task to ourselves on th UI thread which will run after threading
  // is up and schedule watch initialization on the file thread.
  ChromeThread::PostTask(ChromeThread::UI, FROM_HERE,
      NewRunnableMethod(this,
                        &PolicyDirWatcher::InitWatcher,
                        scoped_refptr<PolicyDirLoader>(loader)));
}

void PolicyDirWatcher::InitWatcher(
    const scoped_refptr<PolicyDirLoader>& loader) {
  if (!ChromeThread::CurrentlyOn(ChromeThread::FILE)) {
    ChromeThread::PostTask(ChromeThread::FILE, FROM_HERE,
        NewRunnableMethod(this, &PolicyDirWatcher::InitWatcher, loader));
    return;
  }

  if (!Watch(loader->config_dir(), loader.get()))
    loader->OnError();

  // There might have been changes to the directory in the time between
  // construction of the loader and initialization of the watcher. Call reload
  // to detect if that is the case.
  loader->Reload();
}

// ConfigDirPolicyProvider implementation:

ConfigDirPolicyProvider::ConfigDirPolicyProvider(const FilePath& config_dir) {
  loader_ = new PolicyDirLoader(AsWeakPtr(), config_dir, kSettleIntervalSeconds,
                                kReloadIntervalMinutes);
  watcher_ = new PolicyDirWatcher;
  watcher_->Init(loader_.get());
}

ConfigDirPolicyProvider::~ConfigDirPolicyProvider() {
  loader_->Stop();
}

bool ConfigDirPolicyProvider::Provide(ConfigurationPolicyStore* store) {
  scoped_ptr<DictionaryValue> policy(loader_->GetPolicy());
  DCHECK(policy.get());
  DecodePolicyValueTree(policy.get(), store);
  return true;
}

void ConfigDirPolicyProvider::DecodePolicyValueTree(
    DictionaryValue* policies,
    ConfigurationPolicyStore* store) {
  const PolicyValueMap* mapping = PolicyValueMapping();
  for (PolicyValueMap::const_iterator i = mapping->begin();
       i != mapping->end(); ++i) {
    const PolicyValueMapEntry& entry(*i);
    Value* value;
    if (policies->Get(entry.name, &value) && value->IsType(entry.value_type))
      store->Apply(entry.policy_type, value->DeepCopy());
  }

  // TODO(mnissler): Handle preference overrides once |ConfigurationPolicyStore|
  // supports it.
}