summaryrefslogtreecommitdiffstats
path: root/chrome/browser/privacy_blacklist/blacklist_io.cc
blob: 9c61b12c75cc6aafa33e3ca28e55db0ddc55442e (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
// Copyright (c) 2009 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/privacy_blacklist/blacklist_io.h"

#include <algorithm>
#include <string>

#include "base/file_path.h"
#include "base/file_util.h"
#include "base/string_util.h"
#include "base/string_tokenizer.h"
#include "chrome/browser/privacy_blacklist/blacklist_store.h"

namespace {

const char header[] = "[Chromium::PrivacyBlacklist]";
const char name_tag[] = "Name:";
const char url_tag[] = "URL:";
const char arrow_tag[] = "=>";
const char eol[] = "\n\r";

class IsWhiteSpace {
 public:
  bool operator()(const char& c) const {
    return IsAsciiWhitespace(c);
  }
};

class IsNotWhiteSpace {
 public:
  bool operator()(const char& c) const {
    return !IsAsciiWhitespace(c);
  }
};

bool StartsWith(const char* cur, const char* end,
                const char* tag, std::size_t size) {
  return cur+size <= end && std::equal(tag, tag+size-1, cur);
}

}  // namespace

BlacklistIO::BlacklistIO() {}

BlacklistIO::~BlacklistIO() {
  for (std::list<Blacklist::Entry*>::iterator i = blacklist_.begin();
       i != blacklist_.end(); ++i) {
    delete *i;
  }
  for (std::list<Blacklist::Provider*>::iterator i = providers_.begin();
       i != providers_.end(); ++i) {
    delete *i;
  }
}

bool BlacklistIO::Read(const FilePath& file) {
  // Memory map for efficient parsing. If the file cannot fit in available
  // memory it would be the least of our worries. Typical blacklist files
  // are less than 200K.
  file_util::MemoryMappedFile input;
  if (!input.Initialize(file) || !input.data()) {
    last_error_ = ASCIIToUTF16("File I/O error. Check path and permissions.");
    return false;
  }

  const char* cur = reinterpret_cast<const char*>(input.data());
  const char* end = cur + input.length();

  // Check header.
  if (!StartsWith(cur, end, header, arraysize(header))) {
    last_error_ = ASCIIToUTF16("Incorrect header.");
    return false;
  }

  Blacklist::Provider* provider = new Blacklist::Provider;
  providers_.push_back(provider);

  cur = std::find(cur, end, '\n') + 1;  // Skip past EOL.

  // Each loop iteration takes care of one input line.
  while (cur < end) {
    // Skip whitespace at beginning of line.
    cur = std::find_if(cur, end, IsNotWhiteSpace());
    if (cur == end)
      break;

    if (*cur == '#') {
      cur = std::find(cur, end, '\n') + 1;
      continue;
    }

    if (*cur == '|') {
      ++cur;
      if (StartsWith(cur, end, name_tag, arraysize(name_tag))) {
        // Edge condition: if the find below fails, the next one will too,
        // so we'll just skip to the EOF below.
        cur = std::find_if(cur+arraysize(name_tag), end, IsNotWhiteSpace());
        const char* skip = std::find_if(cur, end, IsWhiteSpace());
        if (skip < end)
          provider->set_name(std::string(cur, skip));
      } else if (StartsWith(cur, end, url_tag, arraysize(url_tag))) {
        cur = std::find_if(cur+arraysize(url_tag), end, IsNotWhiteSpace());
        const char* skip = std::find_if(cur, end, IsWhiteSpace());
        if (skip < end)
          provider->set_url(std::string(cur, skip));
      }
      cur = std::find(cur, end, '\n') + 1;
      continue;
    }

    const char* skip = std::find_if(cur, end, IsWhiteSpace());
    std::string pattern(cur, skip);

    cur = std::find_if(cur+pattern.size(), end, IsNotWhiteSpace());
    if (!StartsWith(cur, end, arrow_tag, arraysize(arrow_tag))) {
      last_error_ = ASCIIToUTF16("Missing => in rule.");
      return false;
    }

    scoped_ptr<Blacklist::Entry> entry(new Blacklist::Entry(pattern, provider));

    cur = std::find_if(cur+arraysize(arrow_tag), end, IsNotWhiteSpace());
    skip = std::find_first_of(cur, end, eol, eol+2);
    std::string buf(cur, skip);
    cur = skip + 1;

    StringTokenizer tokenier(buf, " (),\n\r");
    tokenier.set_options(StringTokenizer::RETURN_DELIMS);

    bool in_attribute = false;
    unsigned int last_attribute = 0;

    while (tokenier.GetNext()) {
      if (tokenier.token_is_delim()) {
        switch (*tokenier.token_begin()) {
          case '(':
            if (in_attribute) {
              last_error_ =
                  ASCIIToUTF16("Unexpected ( in attribute parameters.");
              return false;
            }
            in_attribute = true;
            continue;
          case ')':
            if (!in_attribute) {
              last_error_ = ASCIIToUTF16("Unexpected ) in attribute list.");
              return false;
            }
            in_attribute = false;
            continue;
          default:
            // No state change for other delimiters.
            continue;
        }
      }

      if (in_attribute) {
        // The only attribute to support sub_tokens is kBlockByType, for now.
        if (last_attribute == Blacklist::kBlockByType)
          entry->AddType(tokenier.token());
      } else {
        // Filter attribute. Unrecognized attributes are ignored.
        last_attribute = Blacklist::String2Attribute(tokenier.token());
        entry->AddAttributes(last_attribute);
      }
    }
    blacklist_.push_back(entry.release());
  }
  return true;
}

bool BlacklistIO::Write(const FilePath& file) {
  BlacklistStoreOutput output(file_util::OpenFile(file, "wb"));
  if (!output.is_good()) {
    last_error_ = ASCIIToUTF16("Error opening file for writing.");
    return false;
  }

  // Output providers, give each one an index.
  std::map<const Blacklist::Provider*, uint32> index;
  uint32 current = 0;
  if (!output.ReserveProviders(providers_.size())) {
    last_error_ = ASCIIToUTF16("Error writing to file.");
    return false;
  }

  for (std::list<Blacklist::Provider*>::const_iterator i = providers_.begin();
       i != providers_.end(); ++i, ++current) {
    if (!output.StoreProvider((*i)->name(), (*i)->url())) {
      last_error_ = ASCIIToUTF16("Error writing to file.");
      return false;
    }
    index[*i] = current;
  }

  // Output entries, replacing the provider with its index.
  if (!output.ReserveEntries(blacklist_.size())) {
    last_error_ = ASCIIToUTF16("Error writing to file.");
    return false;
  }

  for (std::list<Blacklist::Entry*>::const_iterator i = blacklist_.begin();
       i != blacklist_.end(); ++i) {
    if (!output.StoreEntry((*i)->pattern_,
                           (*i)->attributes_,
                           (*i)->types_,
                           index[(*i)->provider_])) {
      last_error_ = ASCIIToUTF16("Error writing to file.");
      return false;
    }
  }
  return true;
}