When Retrier succeeds, record errors it encountered.
[chromium-blink-merge.git] / webkit / appcache / view_appcache_internals_job.cc
blob1cff8e13dc0f1c3bebca15541743c46e249a828b
1 // Copyright (c) 2012 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.
5 #include <algorithm>
6 #include <string>
8 #include "webkit/appcache/view_appcache_internals_job.h"
10 #include "base/base64.h"
11 #include "base/bind.h"
12 #include "base/format_macros.h"
13 #include "base/i18n/time_formatting.h"
14 #include "base/logging.h"
15 #include "base/memory/weak_ptr.h"
16 #include "base/string_util.h"
17 #include "base/stringprintf.h"
18 #include "base/strings/string_number_conversions.h"
19 #include "base/utf_string_conversions.h"
20 #include "net/base/escape.h"
21 #include "net/base/io_buffer.h"
22 #include "net/base/net_errors.h"
23 #include "net/http/http_response_headers.h"
24 #include "net/url_request/url_request.h"
25 #include "net/url_request/url_request_simple_job.h"
26 #include "net/url_request/view_cache_helper.h"
27 #include "webkit/appcache/appcache.h"
28 #include "webkit/appcache/appcache_group.h"
29 #include "webkit/appcache/appcache_policy.h"
30 #include "webkit/appcache/appcache_response.h"
31 #include "webkit/appcache/appcache_service.h"
33 namespace appcache {
34 namespace {
36 const char kErrorMessage[] = "Error in retrieving Application Caches.";
37 const char kEmptyAppCachesMessage[] = "No available Application Caches.";
38 const char kManifestNotFoundMessage[] = "Manifest not found.";
39 const char kManifest[] = "Manifest: ";
40 const char kSize[] = "Size: ";
41 const char kCreationTime[] = "Creation Time: ";
42 const char kLastAccessTime[] = "Last Access Time: ";
43 const char kLastUpdateTime[] = "Last Update Time: ";
44 const char kFormattedDisabledAppCacheMsg[] =
45 "<b><i><font color=\"FF0000\">"
46 "This Application Cache is disabled by policy.</font></i></b><br/>";
47 const char kRemoveCacheLabel[] = "Remove";
48 const char kViewCacheLabel[] = "View Entries";
49 const char kRemoveCacheCommand[] = "remove-cache";
50 const char kViewCacheCommand[] = "view-cache";
51 const char kViewEntryCommand[] = "view-entry";
53 void EmitPageStart(std::string* out) {
54 out->append(
55 "<!DOCTYPE HTML>\n"
56 "<html><title>AppCache Internals</title>\n"
57 "<meta http-equiv=\"Content-Security-Policy\""
58 " content=\"object-src 'none'; script-src 'none'\">\n"
59 "<style>\n"
60 "body { font-family: sans-serif; font-size: 0.8em; }\n"
61 "tt, code, pre { font-family: WebKitHack, monospace; }\n"
62 "form { display: inline; }\n"
63 ".subsection_body { margin: 10px 0 10px 2em; }\n"
64 ".subsection_title { font-weight: bold; }\n"
65 "</style>\n"
66 "</head><body>\n");
69 void EmitPageEnd(std::string* out) {
70 out->append("</body></html>\n");
73 void EmitListItem(const std::string& label,
74 const std::string& data,
75 std::string* out) {
76 out->append("<li>");
77 out->append(net::EscapeForHTML(label));
78 out->append(net::EscapeForHTML(data));
79 out->append("</li>\n");
82 void EmitAnchor(const std::string& url, const std::string& text,
83 std::string* out) {
84 out->append("<a href=\"");
85 out->append(net::EscapeForHTML(url));
86 out->append("\">");
87 out->append(net::EscapeForHTML(text));
88 out->append("</a>");
91 void EmitCommandAnchor(const char* label,
92 const GURL& base_url,
93 const char* command,
94 const char* param,
95 std::string* out) {
96 std::string query(command);
97 query.push_back('=');
98 query.append(param);
99 GURL::Replacements replacements;
100 replacements.SetQuery(query.data(),
101 url_parse::Component(0, query.length()));
102 GURL command_url = base_url.ReplaceComponents(replacements);
103 EmitAnchor(command_url.spec(), label, out);
106 void EmitAppCacheInfo(const GURL& base_url,
107 AppCacheService* service,
108 const AppCacheInfo* info,
109 std::string* out) {
110 std::string manifest_url_base64;
111 base::Base64Encode(info->manifest_url.spec(), &manifest_url_base64);
113 out->append("\n<p>");
114 out->append(kManifest);
115 EmitAnchor(info->manifest_url.spec(), info->manifest_url.spec(), out);
116 out->append("<br/>\n");
117 if (!service->appcache_policy()->CanLoadAppCache(
118 info->manifest_url, info->manifest_url)) {
119 out->append(kFormattedDisabledAppCacheMsg);
121 out->append("\n<br/>\n");
122 EmitCommandAnchor(kRemoveCacheLabel, base_url,
123 kRemoveCacheCommand, manifest_url_base64.c_str(), out);
124 out->append("&nbsp;&nbsp;");
125 EmitCommandAnchor(kViewCacheLabel, base_url,
126 kViewCacheCommand, manifest_url_base64.c_str(), out);
127 out->append("\n<br/>\n");
128 out->append("<ul>");
129 EmitListItem(
130 kSize,
131 UTF16ToUTF8(FormatBytesUnlocalized(info->size)),
132 out);
133 EmitListItem(
134 kCreationTime,
135 UTF16ToUTF8(TimeFormatFriendlyDateAndTime(info->creation_time)),
136 out);
137 EmitListItem(
138 kLastUpdateTime,
139 UTF16ToUTF8(TimeFormatFriendlyDateAndTime(info->last_update_time)),
140 out);
141 EmitListItem(
142 kLastAccessTime,
143 UTF16ToUTF8(TimeFormatFriendlyDateAndTime(info->last_access_time)),
144 out);
145 out->append("</ul></p></br>\n");
148 void EmitAppCacheInfoVector(
149 const GURL& base_url,
150 AppCacheService* service,
151 const AppCacheInfoVector& appcaches,
152 std::string* out) {
153 for (std::vector<AppCacheInfo>::const_iterator info =
154 appcaches.begin();
155 info != appcaches.end(); ++info) {
156 EmitAppCacheInfo(base_url, service, &(*info), out);
160 void EmitTableData(const std::string& data, bool align_right, bool bold,
161 std::string* out) {
162 if (align_right)
163 out->append("<td align='right'>");
164 else
165 out->append("<td>");
166 if (bold)
167 out->append("<b>");
168 out->append(data);
169 if (bold)
170 out->append("</b>");
171 out->append("</td>");
174 std::string FormFlagsString(const AppCacheResourceInfo& info) {
175 std::string str;
176 if (info.is_manifest)
177 str.append("Manifest, ");
178 if (info.is_master)
179 str.append("Master, ");
180 if (info.is_intercept)
181 str.append("Intercept, ");
182 if (info.is_fallback)
183 str.append("Fallback, ");
184 if (info.is_explicit)
185 str.append("Explicit, ");
186 if (info.is_foreign)
187 str.append("Foreign, ");
188 return str;
191 std::string FormViewEntryAnchor(const GURL& base_url,
192 const GURL& manifest_url, const GURL& entry_url,
193 int64 response_id,
194 int64 group_id) {
195 std::string manifest_url_base64;
196 std::string entry_url_base64;
197 std::string response_id_string;
198 std::string group_id_string;
199 base::Base64Encode(manifest_url.spec(), &manifest_url_base64);
200 base::Base64Encode(entry_url.spec(), &entry_url_base64);
201 response_id_string = base::Int64ToString(response_id);
202 group_id_string = base::Int64ToString(group_id);
204 std::string query(kViewEntryCommand);
205 query.push_back('=');
206 query.append(manifest_url_base64);
207 query.push_back('|');
208 query.append(entry_url_base64);
209 query.push_back('|');
210 query.append(response_id_string);
211 query.push_back('|');
212 query.append(group_id_string);
214 GURL::Replacements replacements;
215 replacements.SetQuery(query.data(),
216 url_parse::Component(0, query.length()));
217 GURL view_entry_url = base_url.ReplaceComponents(replacements);
219 std::string anchor;
220 EmitAnchor(view_entry_url.spec(), entry_url.spec(), &anchor);
221 return anchor;
224 void EmitAppCacheResourceInfoVector(
225 const GURL& base_url,
226 const GURL& manifest_url,
227 const AppCacheResourceInfoVector& resource_infos,
228 int64 group_id,
229 std::string* out) {
230 out->append("<table border='0'>\n");
231 out->append("<tr>");
232 EmitTableData("Flags", false, true, out);
233 EmitTableData("URL", false, true, out);
234 EmitTableData("Size (headers and data)", true, true, out);
235 out->append("</tr>\n");
236 for (AppCacheResourceInfoVector::const_iterator
237 iter = resource_infos.begin();
238 iter != resource_infos.end(); ++iter) {
239 out->append("<tr>");
240 EmitTableData(FormFlagsString(*iter), false, false, out);
241 EmitTableData(FormViewEntryAnchor(base_url, manifest_url,
242 iter->url, iter->response_id,
243 group_id),
244 false, false, out);
245 EmitTableData(UTF16ToUTF8(FormatBytesUnlocalized(iter->size)),
246 true, false, out);
247 out->append("</tr>\n");
249 out->append("</table>\n");
252 void EmitResponseHeaders(net::HttpResponseHeaders* headers, std::string* out) {
253 out->append("<hr><pre>");
254 out->append(net::EscapeForHTML(headers->GetStatusLine()));
255 out->push_back('\n');
257 void* iter = NULL;
258 std::string name, value;
259 while (headers->EnumerateHeaderLines(&iter, &name, &value)) {
260 out->append(net::EscapeForHTML(name));
261 out->append(": ");
262 out->append(net::EscapeForHTML(value));
263 out->push_back('\n');
265 out->append("</pre>");
268 void EmitHexDump(const char *buf, size_t buf_len, size_t total_len,
269 std::string* out) {
270 out->append("<hr><pre>");
271 base::StringAppendF(out, "Showing %d of %d bytes\n\n",
272 static_cast<int>(buf_len), static_cast<int>(total_len));
273 net::ViewCacheHelper::HexDump(buf, buf_len, out);
274 if (buf_len < total_len)
275 out->append("\nNote: data is truncated...");
276 out->append("</pre>");
279 GURL DecodeBase64URL(const std::string& base64) {
280 std::string url;
281 base::Base64Decode(base64, &url);
282 return GURL(url);
285 bool ParseQuery(const std::string& query,
286 std::string* command, std::string* value) {
287 size_t position = query.find("=");
288 if (position == std::string::npos)
289 return false;
290 *command = query.substr(0, position);
291 *value = query.substr(position + 1);
292 return !command->empty() && !value->empty();
295 bool SortByManifestUrl(const AppCacheInfo& lhs,
296 const AppCacheInfo& rhs) {
297 return lhs.manifest_url.spec() < rhs.manifest_url.spec();
300 bool SortByResourceUrl(const AppCacheResourceInfo& lhs,
301 const AppCacheResourceInfo& rhs) {
302 return lhs.url.spec() < rhs.url.spec();
305 GURL ClearQuery(const GURL& url) {
306 GURL::Replacements replacements;
307 replacements.ClearQuery();
308 return url.ReplaceComponents(replacements);
311 // Simple base class for the job subclasses defined here.
312 class BaseInternalsJob : public net::URLRequestSimpleJob {
313 protected:
314 BaseInternalsJob(net::URLRequest* request,
315 net::NetworkDelegate* network_delegate,
316 AppCacheService* service)
317 : URLRequestSimpleJob(request, network_delegate),
318 appcache_service_(service) {}
319 virtual ~BaseInternalsJob() {}
321 AppCacheService* appcache_service_;
324 // Job that lists all appcaches in the system.
325 class MainPageJob : public BaseInternalsJob {
326 public:
327 MainPageJob(net::URLRequest* request,
328 net::NetworkDelegate* network_delegate,
329 AppCacheService* service)
330 : BaseInternalsJob(request, network_delegate, service),
331 weak_factory_(this) {
334 virtual void Start() OVERRIDE {
335 DCHECK(request_);
336 info_collection_ = new AppCacheInfoCollection;
337 appcache_service_->GetAllAppCacheInfo(
338 info_collection_, base::Bind(&MainPageJob::OnGotInfoComplete,
339 weak_factory_.GetWeakPtr()));
342 // Produces a page containing the listing
343 virtual int GetData(std::string* mime_type,
344 std::string* charset,
345 std::string* out,
346 const net::CompletionCallback& callback) const OVERRIDE {
347 mime_type->assign("text/html");
348 charset->assign("UTF-8");
350 out->clear();
351 EmitPageStart(out);
352 if (!info_collection_) {
353 out->append(kErrorMessage);
354 } else if (info_collection_->infos_by_origin.empty()) {
355 out->append(kEmptyAppCachesMessage);
356 } else {
357 typedef std::map<GURL, AppCacheInfoVector> InfoByOrigin;
358 AppCacheInfoVector appcaches;
359 for (InfoByOrigin::const_iterator origin =
360 info_collection_->infos_by_origin.begin();
361 origin != info_collection_->infos_by_origin.end(); ++origin) {
362 appcaches.insert(appcaches.end(),
363 origin->second.begin(), origin->second.end());
365 std::sort(appcaches.begin(), appcaches.end(), SortByManifestUrl);
367 GURL base_url = ClearQuery(request_->url());
368 EmitAppCacheInfoVector(base_url, appcache_service_, appcaches, out);
370 EmitPageEnd(out);
371 return net::OK;
374 private:
375 virtual ~MainPageJob() {}
377 void OnGotInfoComplete(int rv) {
378 if (rv != net::OK)
379 info_collection_ = NULL;
380 StartAsync();
383 base::WeakPtrFactory<MainPageJob> weak_factory_;
384 scoped_refptr<AppCacheInfoCollection> info_collection_;
385 DISALLOW_COPY_AND_ASSIGN(MainPageJob);
388 // Job that redirects back to the main appcache internals page.
389 class RedirectToMainPageJob : public BaseInternalsJob {
390 public:
391 RedirectToMainPageJob(net::URLRequest* request,
392 net::NetworkDelegate* network_delegate,
393 AppCacheService* service)
394 : BaseInternalsJob(request, network_delegate, service) {}
396 virtual int GetData(std::string* mime_type,
397 std::string* charset,
398 std::string* data,
399 const net::CompletionCallback& callback) const OVERRIDE {
400 return net::OK; // IsRedirectResponse induces a redirect.
403 virtual bool IsRedirectResponse(GURL* location,
404 int* http_status_code) OVERRIDE {
405 *location = ClearQuery(request_->url());
406 *http_status_code = 307;
407 return true;
410 protected:
411 virtual ~RedirectToMainPageJob() {}
414 // Job that removes an appcache and then redirects back to the main page.
415 class RemoveAppCacheJob : public RedirectToMainPageJob {
416 public:
417 RemoveAppCacheJob(
418 net::URLRequest* request,
419 net::NetworkDelegate* network_delegate,
420 AppCacheService* service,
421 const GURL& manifest_url)
422 : RedirectToMainPageJob(request, network_delegate, service),
423 manifest_url_(manifest_url),
424 weak_factory_(this) {
427 virtual void Start() OVERRIDE {
428 DCHECK(request_);
430 appcache_service_->DeleteAppCacheGroup(
431 manifest_url_,base::Bind(&RemoveAppCacheJob::OnDeleteAppCacheComplete,
432 weak_factory_.GetWeakPtr()));
435 private:
436 virtual ~RemoveAppCacheJob() {}
438 void OnDeleteAppCacheComplete(int rv) {
439 StartAsync(); // Causes the base class to redirect.
442 GURL manifest_url_;
443 base::WeakPtrFactory<RemoveAppCacheJob> weak_factory_;
447 // Job shows the details of a particular manifest url.
448 class ViewAppCacheJob : public BaseInternalsJob,
449 public AppCacheStorage::Delegate {
450 public:
451 ViewAppCacheJob(
452 net::URLRequest* request,
453 net::NetworkDelegate* network_delegate,
454 AppCacheService* service,
455 const GURL& manifest_url)
456 : BaseInternalsJob(request, network_delegate, service),
457 manifest_url_(manifest_url) {}
459 virtual void Start() OVERRIDE {
460 DCHECK(request_);
461 appcache_service_->storage()->LoadOrCreateGroup(manifest_url_, this);
464 // Produces a page containing the entries listing.
465 virtual int GetData(std::string* mime_type,
466 std::string* charset,
467 std::string* out,
468 const net::CompletionCallback& callback) const OVERRIDE {
469 mime_type->assign("text/html");
470 charset->assign("UTF-8");
471 out->clear();
472 EmitPageStart(out);
473 if (appcache_info_.manifest_url.is_empty()) {
474 out->append(kManifestNotFoundMessage);
475 } else {
476 GURL base_url = ClearQuery(request_->url());
477 EmitAppCacheInfo(base_url, appcache_service_, &appcache_info_, out);
478 EmitAppCacheResourceInfoVector(base_url,
479 manifest_url_,
480 resource_infos_,
481 appcache_info_.group_id,
482 out);
484 EmitPageEnd(out);
485 return net::OK;
488 private:
489 virtual ~ViewAppCacheJob() {
490 appcache_service_->storage()->CancelDelegateCallbacks(this);
493 // AppCacheStorage::Delegate override
494 virtual void OnGroupLoaded(
495 AppCacheGroup* group, const GURL& manifest_url) OVERRIDE {
496 DCHECK_EQ(manifest_url_, manifest_url);
497 if (group && group->newest_complete_cache()) {
498 appcache_info_.manifest_url = manifest_url;
499 appcache_info_.group_id = group->group_id();
500 appcache_info_.size = group->newest_complete_cache()->cache_size();
501 appcache_info_.creation_time = group->creation_time();
502 appcache_info_.last_update_time =
503 group->newest_complete_cache()->update_time();
504 appcache_info_.last_access_time = base::Time::Now();
505 group->newest_complete_cache()->ToResourceInfoVector(&resource_infos_);
506 std::sort(resource_infos_.begin(), resource_infos_.end(),
507 SortByResourceUrl);
509 StartAsync();
512 GURL manifest_url_;
513 AppCacheInfo appcache_info_;
514 AppCacheResourceInfoVector resource_infos_;
515 DISALLOW_COPY_AND_ASSIGN(ViewAppCacheJob);
518 // Job that shows the details of a particular cached resource.
519 class ViewEntryJob : public BaseInternalsJob,
520 public AppCacheStorage::Delegate {
521 public:
522 ViewEntryJob(
523 net::URLRequest* request,
524 net::NetworkDelegate* network_delegate,
525 AppCacheService* service,
526 const GURL& manifest_url,
527 const GURL& entry_url,
528 int64 response_id, int64 group_id)
529 : BaseInternalsJob(request, network_delegate, service),
530 manifest_url_(manifest_url), entry_url_(entry_url),
531 response_id_(response_id), group_id_(group_id), amount_read_(0) {
534 virtual void Start() OVERRIDE {
535 DCHECK(request_);
536 appcache_service_->storage()->LoadResponseInfo(
537 manifest_url_, group_id_, response_id_, this);
540 // Produces a page containing the response headers and data.
541 virtual int GetData(std::string* mime_type,
542 std::string* charset,
543 std::string* out,
544 const net::CompletionCallback& callback) const OVERRIDE {
545 mime_type->assign("text/html");
546 charset->assign("UTF-8");
547 out->clear();
548 EmitPageStart(out);
549 EmitAnchor(entry_url_.spec(), entry_url_.spec(), out);
550 out->append("<br/>\n");
551 if (response_info_) {
552 if (response_info_->http_response_info())
553 EmitResponseHeaders(response_info_->http_response_info()->headers, out);
554 else
555 out->append("Failed to read response headers.<br>");
557 if (response_data_) {
558 EmitHexDump(response_data_->data(), amount_read_,
559 response_info_->response_data_size(), out);
560 } else {
561 out->append("Failed to read response data.<br>");
563 } else {
564 out->append("Failed to read response headers and data.<br>");
566 EmitPageEnd(out);
567 return net::OK;
570 private:
571 virtual ~ViewEntryJob() {
572 appcache_service_->storage()->CancelDelegateCallbacks(this);
575 virtual void OnResponseInfoLoaded(
576 AppCacheResponseInfo* response_info, int64 response_id) OVERRIDE {
577 if (!response_info) {
578 StartAsync();
579 return;
581 response_info_ = response_info;
583 // Read the response data, truncating if its too large.
584 const int64 kLimit = 100 * 1000;
585 int64 amount_to_read =
586 std::min(kLimit, response_info->response_data_size());
587 response_data_ = new net::IOBuffer(amount_to_read);
589 reader_.reset(appcache_service_->storage()->CreateResponseReader(
590 manifest_url_, group_id_, response_id_));
591 reader_->ReadData(
592 response_data_, amount_to_read,
593 base::Bind(&ViewEntryJob::OnReadComplete, base::Unretained(this)));
596 void OnReadComplete(int result) {
597 reader_.reset();
598 amount_read_ = result;
599 if (result < 0)
600 response_data_ = NULL;
601 StartAsync();
604 GURL manifest_url_;
605 GURL entry_url_;
606 int64 response_id_;
607 int64 group_id_;
608 scoped_refptr<AppCacheResponseInfo> response_info_;
609 scoped_refptr<net::IOBuffer> response_data_;
610 int amount_read_;
611 scoped_ptr<AppCacheResponseReader> reader_;
614 } // namespace
616 net::URLRequestJob* ViewAppCacheInternalsJobFactory::CreateJobForRequest(
617 net::URLRequest* request,
618 net::NetworkDelegate* network_delegate,
619 AppCacheService* service) {
620 if (!request->url().has_query())
621 return new MainPageJob(request, network_delegate, service);
623 std::string command;
624 std::string param;
625 ParseQuery(request->url().query(), &command, &param);
627 if (command == kRemoveCacheCommand)
628 return new RemoveAppCacheJob(request, network_delegate, service,
629 DecodeBase64URL(param));
631 if (command == kViewCacheCommand)
632 return new ViewAppCacheJob(request, network_delegate, service,
633 DecodeBase64URL(param));
635 std::vector<std::string> tokens;
636 int64 response_id;
637 int64 group_id;
638 if (command == kViewEntryCommand && Tokenize(param, "|", &tokens) == 4u &&
639 base::StringToInt64(tokens[2], &response_id) &&
640 base::StringToInt64(tokens[3], &group_id)) {
641 return new ViewEntryJob(request, network_delegate, service,
642 DecodeBase64URL(tokens[0]), // manifest url
643 DecodeBase64URL(tokens[1]), // entry url
644 response_id, group_id);
647 return new RedirectToMainPageJob(request, network_delegate, service);
650 } // namespace appcache