summaryrefslogtreecommitdiffstats
path: root/chrome/browser/chromeos/gdata/gdata_util.cc
blob: e40fcaedaf7a763bfeaa1f705d1d1b63185cf845 (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
// Copyright (c) 2012 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/chromeos/gdata/gdata_util.h"

#include <string>
#include <vector>
#include <utility>

#include "base/basictypes.h"
#include "base/bind.h"
#include "base/bind_helpers.h"
#include "base/file_path.h"
#include "base/file_util.h"
#include "base/json/json_reader.h"
#include "base/logging.h"
#include "base/stringprintf.h"
#include "base/string_util.h"
#include "base/threading/sequenced_worker_pool.h"
#include "chrome/common/chrome_version_info.h"
#include "chrome/common/pref_names.h"
#include "chrome/common/url_constants.h"
#include "chrome/browser/chromeos/gdata/gdata.pb.h"
#include "chrome/browser/chromeos/gdata/gdata_file_system.h"
#include "chrome/browser/chromeos/gdata/gdata_system_service.h"
#include "chrome/browser/chromeos/login/user.h"
#include "chrome/browser/chromeos/login/user_manager.h"
#include "chrome/browser/prefs/pref_service.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_finder.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/child_process_security_policy.h"
#include "net/base/escape.h"
#include "third_party/libxml/chromium/libxml_utils.h"

using content::BrowserThread;

namespace gdata {
namespace util {

namespace {

const char kGDataSpecialRootPath[] = "/special";

const char kGDataMountPointPath[] = "/special/drive";

const FilePath::CharType* kGDataMountPointPathComponents[] = {
  "/", "special", "drive"
};

const int kReadOnlyFilePermissions = base::PLATFORM_FILE_OPEN |
                                     base::PLATFORM_FILE_READ |
                                     base::PLATFORM_FILE_EXCLUSIVE_READ |
                                     base::PLATFORM_FILE_ASYNC;

GDataFileSystem* GetGDataFileSystem(Profile* profile) {
  GDataSystemService* system_service =
      GDataSystemServiceFactory::GetForProfile(profile);
  return system_service ? system_service->file_system() : NULL;
}

GDataCache* GetGDataCache(Profile* profile) {
  GDataSystemService* system_service =
      GDataSystemServiceFactory::GetForProfile(profile);
  return system_service ? system_service->cache() : NULL;
}

void GetHostedDocumentURLBlockingThread(const FilePath& gdata_cache_path,
                                        GURL* url) {
  std::string json;
  if (!file_util::ReadFileToString(gdata_cache_path, &json)) {
    NOTREACHED() << "Unable to read file " << gdata_cache_path.value();
    return;
  }
  DVLOG(1) << "Hosted doc content " << json;
  scoped_ptr<base::Value> val(base::JSONReader::Read(json));
  base::DictionaryValue* dict_val;
  if (!val.get() || !val->GetAsDictionary(&dict_val)) {
    NOTREACHED() << "Parse failure for " << json;
    return;
  }
  std::string edit_url;
  if (!dict_val->GetString("url", &edit_url)) {
    NOTREACHED() << "url field doesn't exist in " << json;
    return;
  }
  *url = GURL(edit_url);
  DVLOG(1) << "edit url " << *url;
}

void OpenEditURLUIThread(Profile* profile, const GURL* edit_url) {
  Browser* browser = browser::FindLastActiveWithProfile(profile);
  if (browser) {
    browser->OpenURL(content::OpenURLParams(*edit_url, content::Referrer(),
        CURRENT_TAB, content::PAGE_TRANSITION_TYPED, false));
  }
}

// Invoked upon completion of GetFileInfoByResourceId initiated by
// ModifyGDataFileResourceUrl.
void OnGetFileInfoByResourceId(Profile* profile,
                               const std::string& resource_id,
                               base::PlatformFileError error,
                               const FilePath& /* gdata_file_path */,
                               scoped_ptr<GDataFileProto> file_proto) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));

  if (error != base::PLATFORM_FILE_OK)
    return;

  DCHECK(file_proto.get());
  const std::string& file_name = file_proto->gdata_entry().file_name();
  const GURL edit_url = GetFileResourceUrl(resource_id, file_name);
  OpenEditURLUIThread(profile, &edit_url);
  DVLOG(1) << "OnFindEntryByResourceId " << edit_url;
}

// Invoked upon completion of GetFileInfoByPath initiated by
// InsertGDataCachePathPermissions.
void OnGetFileInfoForInsertGDataCachePathsPermissions(
    Profile* profile,
    std::vector<std::pair<FilePath, int> >* cache_paths,
    const base::Closure& callback,
    base::PlatformFileError error,
    scoped_ptr<GDataFileProto> file_info) {
  DCHECK(profile);
  DCHECK(cache_paths);
  DCHECK(!callback.is_null());

  GDataCache* cache = GetGDataCache(profile);
  if (!cache || error != base::PLATFORM_FILE_OK) {
    callback.Run();
    return;
  }

  DCHECK(file_info.get());
  std::string resource_id = file_info->gdata_entry().resource_id();
  std::string file_md5 = file_info->file_md5();

  // We check permissions for raw cache file paths only for read-only
  // operations (when fileEntry.file() is called), so read only permissions
  // should be sufficient for all cache paths. For the rest of supported
  // operations the file access check is done for drive/ paths.
  cache_paths->push_back(std::make_pair(
      cache->GetCacheFilePath(resource_id, file_md5,
          GDataCache::CACHE_TYPE_PERSISTENT,
          GDataCache::CACHED_FILE_FROM_SERVER),
      kReadOnlyFilePermissions));
  // TODO(tbarzic): When we start supporting openFile operation, we may have to
  // change permission for localy modified files to match handler's permissions.
  cache_paths->push_back(std::make_pair(
      cache->GetCacheFilePath(resource_id, file_md5,
          GDataCache::CACHE_TYPE_PERSISTENT,
          GDataCache::CACHED_FILE_LOCALLY_MODIFIED),
     kReadOnlyFilePermissions));
  cache_paths->push_back(std::make_pair(
      cache->GetCacheFilePath(resource_id, file_md5,
          GDataCache::CACHE_TYPE_PERSISTENT,
          GDataCache::CACHED_FILE_MOUNTED),
     kReadOnlyFilePermissions));
  cache_paths->push_back(std::make_pair(
      cache->GetCacheFilePath(resource_id, file_md5,
          GDataCache::CACHE_TYPE_TMP,
          GDataCache::CACHED_FILE_FROM_SERVER),
      kReadOnlyFilePermissions));

  callback.Run();
}

}  // namespace

const FilePath& GetGDataMountPointPath() {
  CR_DEFINE_STATIC_LOCAL(FilePath, gdata_mount_path,
      (FilePath::FromUTF8Unsafe(kGDataMountPointPath)));
  return gdata_mount_path;
}

const std::string& GetGDataMountPointPathAsString() {
  CR_DEFINE_STATIC_LOCAL(std::string, gdata_mount_path_string,
      (kGDataMountPointPath));
  return gdata_mount_path_string;
}

const FilePath& GetSpecialRemoteRootPath() {
  CR_DEFINE_STATIC_LOCAL(FilePath, gdata_mount_path,
      (FilePath::FromUTF8Unsafe(kGDataSpecialRootPath)));
  return gdata_mount_path;
}

GURL GetFileResourceUrl(const std::string& resource_id,
                        const std::string& file_name) {
  std::string url(base::StringPrintf(
      "%s:%s",
      chrome::kDriveScheme,
      net::EscapePath(resource_id).c_str()));
  return GURL(url);
}

void ModifyGDataFileResourceUrl(Profile* profile,
                                const FilePath& gdata_cache_path,
                                GURL* url) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));

  GDataFileSystem* file_system = GetGDataFileSystem(profile);
  if (!file_system)
    return;
  GDataCache* cache = GetGDataCache(profile);
  if (!cache)
    return;

  if (cache->GetCacheDirectoryPath(
          GDataCache::CACHE_TYPE_TMP_DOCUMENTS).IsParent(
      gdata_cache_path)) {
    // Handle hosted documents. The edit url is in the temporary file, so we
    // read it on a blocking thread.
    GURL* edit_url = new GURL();
    content::BrowserThread::GetBlockingPool()->PostTaskAndReply(FROM_HERE,
        base::Bind(&GetHostedDocumentURLBlockingThread,
                   gdata_cache_path, edit_url),
        base::Bind(&OpenEditURLUIThread, profile, base::Owned(edit_url)));
    *url = GURL();
  } else if (cache->GetCacheDirectoryPath(
      GDataCache::CACHE_TYPE_TMP).IsParent(gdata_cache_path)) {
    // Handle all other gdata files.
    const std::string resource_id =
        gdata_cache_path.BaseName().RemoveExtension().AsUTF8Unsafe();
    file_system->GetFileInfoByResourceId(
        resource_id,
        base::Bind(&OnGetFileInfoByResourceId,
                   profile,
                   resource_id));
    *url = GURL();
  }
}

bool IsUnderGDataMountPoint(const FilePath& path) {
  return GetGDataMountPointPath() == path ||
         GetGDataMountPointPath().IsParent(path);
}

FilePath ExtractGDataPath(const FilePath& path) {
  if (!IsUnderGDataMountPoint(path))
    return FilePath();

  std::vector<FilePath::StringType> components;
  path.GetComponents(&components);

  // -1 to include 'drive'.
  FilePath extracted;
  for (size_t i = arraysize(kGDataMountPointPathComponents) - 1;
       i < components.size(); ++i) {
    extracted = extracted.Append(components[i]);
  }
  return extracted;
}

void InsertGDataCachePathsPermissions(
    Profile* profile,
    scoped_ptr<std::vector<FilePath> > gdata_paths,
    std::vector<std::pair<FilePath, int> >* cache_paths,
    const base::Closure& callback) {
  DCHECK(profile);
  DCHECK(gdata_paths.get());
  DCHECK(cache_paths);
  DCHECK(!callback.is_null());

  GDataFileSystem* file_system = GetGDataFileSystem(profile);
  if (!file_system || gdata_paths->empty()) {
    callback.Run();
    return;
  }

  // Remove one file path entry from the back of the input vector |gdata_paths|.
  FilePath gdata_path = gdata_paths->back();
  gdata_paths->pop_back();

  // Call GetFileInfoByPath() to get file info for |gdata_path| then insert
  // all possible cache paths to the output vector |cache_paths|.
  // Note that we can only process one file path at a time. Upon completion
  // of OnGetFileInfoForInsertGDataCachePathsPermissions(), we recursively call
  // InsertGDataCachePathsPermissions() to process the next file path from the
  // back of the input vector |gdata_paths| until it is empty.
  file_system->GetFileInfoByPath(
      gdata_path,
      base::Bind(&OnGetFileInfoForInsertGDataCachePathsPermissions,
                 profile,
                 cache_paths,
                 base::Bind(&InsertGDataCachePathsPermissions,
                             profile,
                             base::Passed(&gdata_paths),
                             cache_paths,
                             callback)));
}

bool IsGDataAvailable(Profile* profile) {
  if (!chromeos::UserManager::Get()->IsUserLoggedIn() ||
      chromeos::UserManager::Get()->IsLoggedInAsGuest() ||
      chromeos::UserManager::Get()->IsLoggedInAsDemoUser())
    return false;

  // Do not allow GData for incognito windows / guest mode.
  if (profile->IsOffTheRecord())
    return false;

  // Disable gdata if preference is set.  This can happen with commandline flag
  // --disable-gdata or enterprise policy, or probably with user settings too
  // in the future.
  if (profile->GetPrefs()->GetBoolean(prefs::kDisableGData))
    return false;

  return true;
}

std::string EscapeCacheFileName(const std::string& filename) {
  // This is based on net/base/escape.cc: net::(anonymous namespace)::Escape
  std::string escaped;
  for (size_t i = 0; i < filename.size(); ++i) {
    char c = filename[i];
    if (c == '%' || c == '.' || c == '/') {
      base::StringAppendF(&escaped, "%%%02X", c);
    } else {
      escaped.push_back(c);
    }
  }
  return escaped;
}

std::string UnescapeCacheFileName(const std::string& filename) {
  std::string unescaped;
  for (size_t i = 0; i < filename.size(); ++i) {
    char c = filename[i];
    if (c == '%' && i + 2 < filename.length()) {
      c = (HexDigitToInt(filename[i + 1]) << 4) +
           HexDigitToInt(filename[i + 2]);
      i += 2;
    }
    unescaped.push_back(c);
  }
  return unescaped;
}

void ParseCacheFilePath(const FilePath& path,
                        std::string* resource_id,
                        std::string* md5,
                        std::string* extra_extension) {
  DCHECK(resource_id);
  DCHECK(md5);
  DCHECK(extra_extension);

  // Extract up to two extensions from the right.
  FilePath base_name = path.BaseName();
  const int kNumExtensionsToExtract = 2;
  std::vector<FilePath::StringType> extensions;
  for (int i = 0; i < kNumExtensionsToExtract; ++i) {
    FilePath::StringType extension = base_name.Extension();
    if (!extension.empty()) {
      // FilePath::Extension returns ".", so strip it.
      extension = UnescapeCacheFileName(extension.substr(1));
      base_name = base_name.RemoveExtension();
      extensions.push_back(extension);
    } else {
      break;
    }
  }

  // The base_name here is already stripped of extensions in the loop above.
  *resource_id = UnescapeCacheFileName(base_name.value());

  // Assign the extracted extensions to md5 and extra_extension.
  int extension_count = extensions.size();
  *md5 = (extension_count > 0) ? extensions[extension_count - 1] :
                                 std::string();
  *extra_extension = (extension_count > 1) ? extensions[extension_count - 2] :
                                             std::string();
}

}  // namespace util
}  // namespace gdata