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.
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"
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
) {
56 "<html><title>AppCache Internals</title>\n"
57 "<meta http-equiv=\"Content-Security-Policy\""
58 " content=\"object-src 'none'; script-src 'none'\">\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"
69 void EmitPageEnd(std::string
* out
) {
70 out
->append("</body></html>\n");
73 void EmitListItem(const std::string
& label
,
74 const std::string
& data
,
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
,
84 out
->append("<a href=\"");
85 out
->append(net::EscapeForHTML(url
));
87 out
->append(net::EscapeForHTML(text
));
91 void EmitCommandAnchor(const char* label
,
96 std::string
query(command
);
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
,
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(" ");
125 EmitCommandAnchor(kViewCacheLabel
, base_url
,
126 kViewCacheCommand
, manifest_url_base64
.c_str(), out
);
127 out
->append("\n<br/>\n");
131 UTF16ToUTF8(FormatBytesUnlocalized(info
->size
)),
135 UTF16ToUTF8(TimeFormatFriendlyDateAndTime(info
->creation_time
)),
139 UTF16ToUTF8(TimeFormatFriendlyDateAndTime(info
->last_update_time
)),
143 UTF16ToUTF8(TimeFormatFriendlyDateAndTime(info
->last_access_time
)),
145 out
->append("</ul></p></br>\n");
148 void EmitAppCacheInfoVector(
149 const GURL
& base_url
,
150 AppCacheService
* service
,
151 const AppCacheInfoVector
& appcaches
,
153 for (std::vector
<AppCacheInfo
>::const_iterator info
=
155 info
!= appcaches
.end(); ++info
) {
156 EmitAppCacheInfo(base_url
, service
, &(*info
), out
);
160 void EmitTableData(const std::string
& data
, bool align_right
, bool bold
,
163 out
->append("<td align='right'>");
171 out
->append("</td>");
174 std::string
FormFlagsString(const AppCacheResourceInfo
& info
) {
176 if (info
.is_manifest
)
177 str
.append("Manifest, ");
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, ");
187 str
.append("Foreign, ");
191 std::string
FormViewEntryAnchor(const GURL
& base_url
,
192 const GURL
& manifest_url
, const GURL
& entry_url
,
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
);
220 EmitAnchor(view_entry_url
.spec(), entry_url
.spec(), &anchor
);
224 void EmitAppCacheResourceInfoVector(
225 const GURL
& base_url
,
226 const GURL
& manifest_url
,
227 const AppCacheResourceInfoVector
& resource_infos
,
230 out
->append("<table border='0'>\n");
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
) {
240 EmitTableData(FormFlagsString(*iter
), false, false, out
);
241 EmitTableData(FormViewEntryAnchor(base_url
, manifest_url
,
242 iter
->url
, iter
->response_id
,
245 EmitTableData(UTF16ToUTF8(FormatBytesUnlocalized(iter
->size
)),
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');
258 std::string name
, value
;
259 while (headers
->EnumerateHeaderLines(&iter
, &name
, &value
)) {
260 out
->append(net::EscapeForHTML(name
));
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
,
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
) {
281 base::Base64Decode(base64
, &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
)
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
{
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
{
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
{
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
,
346 const net::CompletionCallback
& callback
) const OVERRIDE
{
347 mime_type
->assign("text/html");
348 charset
->assign("UTF-8");
352 if (!info_collection_
) {
353 out
->append(kErrorMessage
);
354 } else if (info_collection_
->infos_by_origin
.empty()) {
355 out
->append(kEmptyAppCachesMessage
);
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
);
375 virtual ~MainPageJob() {}
377 void OnGotInfoComplete(int rv
) {
379 info_collection_
= NULL
;
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
{
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
,
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;
411 virtual ~RedirectToMainPageJob() {}
414 // Job that removes an appcache and then redirects back to the main page.
415 class RemoveAppCacheJob
: public RedirectToMainPageJob
{
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
{
430 appcache_service_
->DeleteAppCacheGroup(
431 manifest_url_
,base::Bind(&RemoveAppCacheJob::OnDeleteAppCacheComplete
,
432 weak_factory_
.GetWeakPtr()));
436 virtual ~RemoveAppCacheJob() {}
438 void OnDeleteAppCacheComplete(int rv
) {
439 StartAsync(); // Causes the base class to redirect.
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
{
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
{
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
,
468 const net::CompletionCallback
& callback
) const OVERRIDE
{
469 mime_type
->assign("text/html");
470 charset
->assign("UTF-8");
473 if (appcache_info_
.manifest_url
.is_empty()) {
474 out
->append(kManifestNotFoundMessage
);
476 GURL base_url
= ClearQuery(request_
->url());
477 EmitAppCacheInfo(base_url
, appcache_service_
, &appcache_info_
, out
);
478 EmitAppCacheResourceInfoVector(base_url
,
481 appcache_info_
.group_id
,
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(),
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
{
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
{
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
,
544 const net::CompletionCallback
& callback
) const OVERRIDE
{
545 mime_type
->assign("text/html");
546 charset
->assign("UTF-8");
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
);
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
);
561 out
->append("Failed to read response data.<br>");
564 out
->append("Failed to read response headers and data.<br>");
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
) {
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_
));
592 response_data_
, amount_to_read
,
593 base::Bind(&ViewEntryJob::OnReadComplete
, base::Unretained(this)));
596 void OnReadComplete(int result
) {
598 amount_read_
= result
;
600 response_data_
= NULL
;
608 scoped_refptr
<AppCacheResponseInfo
> response_info_
;
609 scoped_refptr
<net::IOBuffer
> response_data_
;
611 scoped_ptr
<AppCacheResponseReader
> reader_
;
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
);
625 ParseQuery(request
->url().query(), &command
, ¶m
);
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
;
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