1// Copyright 2013 The Chromium Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#include "components/policy/core/common/cloud/policy_header_io_helper.h"
6
7#include "base/bind.h"
8#include "base/location.h"
9#include "base/sequenced_task_runner.h"
10#include "components/policy/core/common/cloud/cloud_policy_constants.h"
11#include "net/url_request/url_request.h"
12
13namespace policy {
14
15PolicyHeaderIOHelper::PolicyHeaderIOHelper(
16    const std::string& server_url,
17    const std::string& initial_header_value,
18    const scoped_refptr<base::SequencedTaskRunner>& task_runner)
19    : server_url_(server_url),
20      io_task_runner_(task_runner),
21      policy_header_(initial_header_value) {
22}
23
24PolicyHeaderIOHelper::~PolicyHeaderIOHelper() {
25}
26
27// Sets any necessary policy headers on the passed request.
28void PolicyHeaderIOHelper::AddPolicyHeaders(const GURL& url,
29                                            net::URLRequest* request) const {
30  DCHECK(io_task_runner_->RunsTasksOnCurrentThread());
31  if (!policy_header_.empty() &&
32      url.spec().compare(0, server_url_.size(), server_url_) == 0) {
33    request->SetExtraRequestHeaderByName(kChromePolicyHeader,
34                                         policy_header_,
35                                         true /* overwrite */);
36  }
37}
38
39void PolicyHeaderIOHelper::UpdateHeader(const std::string& new_header) {
40  // Post a task to the IO thread to modify this.
41  io_task_runner_->PostTask(
42      FROM_HERE,
43      base::Bind(&PolicyHeaderIOHelper::UpdateHeaderOnIOThread,
44                 base::Unretained(this), new_header));
45}
46
47void PolicyHeaderIOHelper::UpdateHeaderOnIOThread(
48    const std::string& new_header) {
49  DCHECK(io_task_runner_->RunsTasksOnCurrentThread());
50  policy_header_ = new_header;
51}
52
53void PolicyHeaderIOHelper::SetServerURLForTest(const std::string& server_url) {
54  io_task_runner_->PostTask(
55      FROM_HERE,
56      base::Bind(&PolicyHeaderIOHelper::SetServerURLOnIOThread,
57                 base::Unretained(this), server_url));
58
59}
60
61void PolicyHeaderIOHelper::SetServerURLOnIOThread(
62    const std::string& server_url) {
63  DCHECK(io_task_runner_->RunsTasksOnCurrentThread());
64  server_url_ = server_url;
65}
66
67}  // namespace policy
68