Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(72)

Side by Side Diff: chrome/browser/ui/webui/net_internals_ui.cc

Issue 9166009: Move about:net-internals webui files into a subdirectory + OWNERS (Closed) Base URL: svn://svn.chromium.org/chrome/trunk/src/
Patch Set: Update year Created 8 years, 11 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch | Annotate | Revision Log
OLDNEW
(Empty)
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.
4
5 #include "chrome/browser/ui/webui/net_internals_ui.h"
6
7 #include <algorithm>
8 #include <list>
9 #include <string>
10 #include <utility>
11 #include <vector>
12
13 #include "base/base64.h"
14 #include "base/bind.h"
15 #include "base/bind_helpers.h"
16 #include "base/command_line.h"
17 #include "base/memory/singleton.h"
18 #include "base/message_loop.h"
19 #include "base/message_loop_helpers.h"
20 #include "base/path_service.h"
21 #include "base/string_number_conversions.h"
22 #include "base/string_piece.h"
23 #include "base/string_split.h"
24 #include "base/string_util.h"
25 #include "base/utf_string_conversions.h"
26 #include "base/values.h"
27 #include "chrome/browser/browser_process.h"
28 #include "chrome/browser/browsing_data_remover.h"
29 #include "chrome/browser/io_thread.h"
30 #include "chrome/browser/net/chrome_net_log.h"
31 #include "chrome/browser/net/connection_tester.h"
32 #include "chrome/browser/net/passive_log_collector.h"
33 #include "chrome/browser/net/url_fixer_upper.h"
34 #include "chrome/browser/prefs/pref_member.h"
35 #include "chrome/browser/prerender/prerender_manager.h"
36 #include "chrome/browser/prerender/prerender_manager_factory.h"
37 #include "chrome/browser/profiles/profile.h"
38 #include "chrome/browser/ui/webui/chrome_url_data_manager.h"
39 #include "chrome/browser/ui/webui/chrome_web_ui_data_source.h"
40 #include "chrome/common/chrome_notification_types.h"
41 #include "chrome/common/chrome_paths.h"
42 #include "chrome/common/chrome_version_info.h"
43 #include "chrome/common/pref_names.h"
44 #include "chrome/common/url_constants.h"
45 #include "content/public/browser/browser_thread.h"
46 #include "content/public/browser/notification_details.h"
47 #include "content/public/browser/web_contents.h"
48 #include "content/public/browser/web_ui_message_handler.h"
49 #include "grit/generated_resources.h"
50 #include "grit/net_internals_resources.h"
51 #include "net/base/escape.h"
52 #include "net/base/host_cache.h"
53 #include "net/base/host_resolver.h"
54 #include "net/base/net_errors.h"
55 #include "net/base/net_util.h"
56 #include "net/base/sys_addrinfo.h"
57 #include "net/base/transport_security_state.h"
58 #include "net/base/x509_cert_types.h"
59 #include "net/disk_cache/disk_cache.h"
60 #include "net/http/http_cache.h"
61 #include "net/http/http_network_layer.h"
62 #include "net/http/http_network_session.h"
63 #include "net/http/http_server_properties.h"
64 #include "net/http/http_stream_factory.h"
65 #include "net/proxy/proxy_service.h"
66 #include "net/url_request/url_request_context.h"
67 #include "net/url_request/url_request_context_getter.h"
68 #include "ui/base/l10n/l10n_util.h"
69 #include "ui/base/resource/resource_bundle.h"
70
71 #ifdef OS_CHROMEOS
72 #include "chrome/browser/chromeos/cros/cros_library.h"
73 #include "chrome/browser/chromeos/cros/network_library.h"
74 #include "chrome/browser/chromeos/system/syslogs_provider.h"
75 #endif
76 #ifdef OS_WIN
77 #include "chrome/browser/net/service_providers_win.h"
78 #endif
79
80 using content::BrowserThread;
81 using content::WebContents;
82 using content::WebUIMessageHandler;
83
84 namespace {
85
86 // Delay between when an event occurs and when it is passed to the Javascript
87 // page. All events that occur during this period are grouped together and
88 // sent to the page at once, which reduces context switching and CPU usage.
89 const int kNetLogEventDelayMilliseconds = 100;
90
91 // about:net-internals will not even attempt to load a log dump when it
92 // encounters a new version. This should be incremented when significant
93 // changes are made that will invalidate the old loading code.
94 const int kLogFormatVersion = 1;
95
96 // Returns the HostCache for |context|'s primary HostResolver, or NULL if
97 // there is none.
98 net::HostCache* GetHostResolverCache(net::URLRequestContext* context) {
99 return context->host_resolver()->GetHostCache();
100 }
101
102 // Returns the disk cache backend for |context| if there is one, or NULL.
103 disk_cache::Backend* GetDiskCacheBackend(net::URLRequestContext* context) {
104 if (!context->http_transaction_factory())
105 return NULL;
106
107 net::HttpCache* http_cache = context->http_transaction_factory()->GetCache();
108 if (!http_cache)
109 return NULL;
110
111 return http_cache->GetCurrentBackend();
112 }
113
114 // Returns the http network session for |context| if there is one.
115 // Otherwise, returns NULL.
116 net::HttpNetworkSession* GetHttpNetworkSession(
117 net::URLRequestContext* context) {
118 if (!context->http_transaction_factory())
119 return NULL;
120
121 return context->http_transaction_factory()->GetSession();
122 }
123
124 Value* ExperimentToValue(const ConnectionTester::Experiment& experiment) {
125 DictionaryValue* dict = new DictionaryValue();
126
127 if (experiment.url.is_valid())
128 dict->SetString("url", experiment.url.spec());
129
130 dict->SetString("proxy_settings_experiment",
131 ConnectionTester::ProxySettingsExperimentDescription(
132 experiment.proxy_settings_experiment));
133 dict->SetString("host_resolver_experiment",
134 ConnectionTester::HostResolverExperimentDescription(
135 experiment.host_resolver_experiment));
136 return dict;
137 }
138
139 ChromeWebUIDataSource* CreateNetInternalsHTMLSource() {
140 ChromeWebUIDataSource* source =
141 new ChromeWebUIDataSource(chrome::kChromeUINetInternalsHost);
142
143 source->set_default_resource(IDR_NET_INTERNALS_INDEX_HTML);
144 source->add_resource_path("help.html", IDR_NET_INTERNALS_HELP_HTML);
145 source->add_resource_path("help.js", IDR_NET_INTERNALS_HELP_JS);
146 source->add_resource_path("index.js", IDR_NET_INTERNALS_INDEX_JS);
147 source->set_json_path("strings.js");
148 return source;
149 }
150
151 // This class receives javascript messages from the renderer.
152 // Note that the WebUI infrastructure runs on the UI thread, therefore all of
153 // this class's methods are expected to run on the UI thread.
154 //
155 // Since the network code we want to run lives on the IO thread, we proxy
156 // almost everything over to NetInternalsMessageHandler::IOThreadImpl, which
157 // runs on the IO thread.
158 //
159 // TODO(eroman): Can we start on the IO thread to begin with?
160 class NetInternalsMessageHandler
161 : public WebUIMessageHandler,
162 public base::SupportsWeakPtr<NetInternalsMessageHandler>,
163 public content::NotificationObserver {
164 public:
165 NetInternalsMessageHandler();
166 virtual ~NetInternalsMessageHandler();
167
168 // WebUIMessageHandler implementation.
169 virtual void RegisterMessages() OVERRIDE;
170
171 // Calls g_browser.receive in the renderer, passing in |command| and |arg|.
172 // Takes ownership of |arg|. If the renderer is displaying a log file, the
173 // message will be ignored.
174 void SendJavascriptCommand(const std::string& command, Value* arg);
175
176 // content::NotificationObserver implementation.
177 virtual void Observe(int type,
178 const content::NotificationSource& source,
179 const content::NotificationDetails& details) OVERRIDE;
180
181 // Javascript message handlers.
182 void OnRendererReady(const ListValue* list);
183 void OnEnableHttpThrottling(const ListValue* list);
184 void OnClearBrowserCache(const ListValue* list);
185 void OnGetPrerenderInfo(const ListValue* list);
186 #ifdef OS_CHROMEOS
187 void OnRefreshSystemLogs(const ListValue* list);
188 void OnGetSystemLog(const ListValue* list);
189 void OnImportONCFile(const ListValue* list);
190 #endif
191
192 private:
193 class IOThreadImpl;
194
195 #ifdef OS_CHROMEOS
196 // Class that is used for getting network related ChromeOS logs.
197 // Logs are fetched from ChromeOS libcros on user request, and only when we
198 // don't yet have a copy of logs. If a copy is present, we send back data from
199 // it, else we save request and answer to it when we get logs from libcros.
200 // If needed, we also send request for system logs to libcros.
201 // Logs refresh has to be done explicitly, by deleting old logs and then
202 // loading them again.
203 class SystemLogsGetter {
204 public:
205 SystemLogsGetter(NetInternalsMessageHandler* handler,
206 chromeos::system::SyslogsProvider* syslogs_provider);
207 ~SystemLogsGetter();
208
209 // Deletes logs copy we currently have, and resets logs_requested and
210 // logs_received flags.
211 void DeleteSystemLogs();
212 // Starts log fetching. If logs copy is present, requested logs are sent
213 // back.
214 // If syslogs load request hasn't been sent to libcros yet, we do that now,
215 // and postpone sending response.
216 // Request data is specified by args:
217 // $1 : key of the log we are interested in.
218 // $2 : string used to identify request.
219 void RequestSystemLog(const ListValue* args);
220 // Requests logs from libcros, but only if we don't have a copy.
221 void LoadSystemLogs();
222 // Processes callback from libcros containing system logs. Postponed
223 // request responses are sent.
224 void OnSystemLogsLoaded(chromeos::system::LogDictionaryType* sys_info,
225 std::string* ignored_content);
226
227 private:
228 // Struct we save postponed log request in.
229 struct SystemLogRequest {
230 std::string log_key;
231 std::string cell_id;
232 };
233
234 // Processes request.
235 void SendLogs(const SystemLogRequest& request);
236
237 NetInternalsMessageHandler* handler_;
238 chromeos::system::SyslogsProvider* syslogs_provider_;
239 // List of postponed requests.
240 std::list<SystemLogRequest> requests_;
241 scoped_ptr<chromeos::system::LogDictionaryType> logs_;
242 bool logs_received_;
243 bool logs_requested_;
244 CancelableRequestConsumer consumer_;
245 // Libcros request handle.
246 CancelableRequestProvider::Handle syslogs_request_id_;
247 };
248 #endif
249
250 // The pref member about whether HTTP throttling is enabled, which needs to
251 // be accessed on the UI thread.
252 BooleanPrefMember http_throttling_enabled_;
253
254 // The pref member that determines whether experimentation on HTTP throttling
255 // is allowed (this becomes false once the user explicitly sets the
256 // feature to on or off).
257 BooleanPrefMember http_throttling_may_experiment_;
258
259 // This is the "real" message handler, which lives on the IO thread.
260 scoped_refptr<IOThreadImpl> proxy_;
261
262 base::WeakPtr<prerender::PrerenderManager> prerender_manager_;
263
264 #ifdef OS_CHROMEOS
265 // Class that handles getting and filtering system logs.
266 scoped_ptr<SystemLogsGetter> syslogs_getter_;
267 #endif
268
269 DISALLOW_COPY_AND_ASSIGN(NetInternalsMessageHandler);
270 };
271
272 // This class is the "real" message handler. It is allocated and destroyed on
273 // the UI thread. With the exception of OnAddEntry, OnWebUIDeleted, and
274 // SendJavascriptCommand, its methods are all expected to be called from the IO
275 // thread. OnAddEntry and SendJavascriptCommand can be called from any thread,
276 // and OnWebUIDeleted can only be called from the UI thread.
277 class NetInternalsMessageHandler::IOThreadImpl
278 : public base::RefCountedThreadSafe<
279 NetInternalsMessageHandler::IOThreadImpl,
280 BrowserThread::DeleteOnUIThread>,
281 public ChromeNetLog::ThreadSafeObserverImpl,
282 public ConnectionTester::Delegate {
283 public:
284 // Type for methods that can be used as MessageHandler callbacks.
285 typedef void (IOThreadImpl::*MessageHandler)(const ListValue*);
286
287 // Creates a proxy for |handler| that will live on the IO thread.
288 // |handler| is a weak pointer, since it is possible for the
289 // WebUIMessageHandler to be deleted on the UI thread while we were executing
290 // on the IO thread. |io_thread| is the global IOThread (it is passed in as
291 // an argument since we need to grab it from the UI thread).
292 IOThreadImpl(
293 const base::WeakPtr<NetInternalsMessageHandler>& handler,
294 IOThread* io_thread,
295 net::URLRequestContextGetter* context_getter);
296
297 // Helper method to enable a callback that will be executed on the IO thread.
298 static void CallbackHelper(MessageHandler method,
299 scoped_refptr<IOThreadImpl> io_thread,
300 const ListValue* list);
301
302 // Called once the WebUI has been deleted (i.e. renderer went away), on the
303 // IO thread.
304 void Detach();
305
306 // Sends all passive log entries in |passive_entries| to the Javascript
307 // handler, called on the IO thread.
308 void SendPassiveLogEntries(const ChromeNetLog::EntryList& passive_entries);
309
310 // Called when the WebUI is deleted. Prevents calling Javascript functions
311 // afterwards. Called on UI thread.
312 void OnWebUIDeleted();
313
314 //--------------------------------
315 // Javascript message handlers:
316 //--------------------------------
317
318 void OnRendererReady(const ListValue* list);
319
320 void OnGetProxySettings(const ListValue* list);
321 void OnReloadProxySettings(const ListValue* list);
322 void OnGetBadProxies(const ListValue* list);
323 void OnClearBadProxies(const ListValue* list);
324 void OnGetHostResolverInfo(const ListValue* list);
325 void OnClearHostResolverCache(const ListValue* list);
326 void OnEnableIPv6(const ListValue* list);
327 void OnStartConnectionTests(const ListValue* list);
328 void OnHSTSQuery(const ListValue* list);
329 void OnHSTSAdd(const ListValue* list);
330 void OnHSTSDelete(const ListValue* list);
331 void OnGetHttpCacheInfo(const ListValue* list);
332 void OnGetSocketPoolInfo(const ListValue* list);
333 void OnCloseIdleSockets(const ListValue* list);
334 void OnFlushSocketPools(const ListValue* list);
335 void OnGetSpdySessionInfo(const ListValue* list);
336 void OnGetSpdyStatus(const ListValue* list);
337 void OnGetSpdyAlternateProtocolMappings(const ListValue* list);
338 #ifdef OS_WIN
339 void OnGetServiceProviders(const ListValue* list);
340 #endif
341 void OnGetHttpPipeliningStatus(const ListValue* list);
342 void OnSetLogLevel(const ListValue* list);
343
344 // ChromeNetLog::ThreadSafeObserver implementation:
345 virtual void OnAddEntry(net::NetLog::EventType type,
346 const base::TimeTicks& time,
347 const net::NetLog::Source& source,
348 net::NetLog::EventPhase phase,
349 net::NetLog::EventParameters* params);
350
351 // ConnectionTester::Delegate implementation:
352 virtual void OnStartConnectionTestSuite();
353 virtual void OnStartConnectionTestExperiment(
354 const ConnectionTester::Experiment& experiment);
355 virtual void OnCompletedConnectionTestExperiment(
356 const ConnectionTester::Experiment& experiment,
357 int result);
358 virtual void OnCompletedConnectionTestSuite();
359
360 // Helper that calls g_browser.receive in the renderer, passing in |command|
361 // and |arg|. Takes ownership of |arg|. If the renderer is displaying a log
362 // file, the message will be ignored. Note that this can be called from any
363 // thread.
364 void SendJavascriptCommand(const std::string& command, Value* arg);
365
366 // Helper that runs |method| with |arg|, and deletes |arg| on completion.
367 void DispatchToMessageHandler(ListValue* arg, MessageHandler method);
368
369 private:
370 friend struct BrowserThread::DeleteOnThread<BrowserThread::UI>;
371 friend class base::DeleteHelper<IOThreadImpl>;
372
373 ~IOThreadImpl();
374
375 // Adds |entry| to the queue of pending log entries to be sent to the page via
376 // Javascript. Must be called on the IO Thread. Also creates a delayed task
377 // that will call PostPendingEntries, if there isn't one already.
378 void AddEntryToQueue(Value* entry);
379
380 // Sends all pending entries to the page via Javascript, and clears the list
381 // of pending entries. Sending multiple entries at once results in a
382 // significant reduction of CPU usage when a lot of events are happening.
383 // Must be called on the IO Thread.
384 void PostPendingEntries();
385
386 // Pointer to the UI-thread message handler. Only access this from
387 // the UI thread.
388 base::WeakPtr<NetInternalsMessageHandler> handler_;
389
390 // The global IOThread, which contains the global NetLog to observer.
391 IOThread* io_thread_;
392
393 scoped_refptr<net::URLRequestContextGetter> context_getter_;
394
395 // Helper that runs the suite of connection tests.
396 scoped_ptr<ConnectionTester> connection_tester_;
397
398 // True if the Web UI has been deleted. This is used to prevent calling
399 // Javascript functions after the Web UI is destroyed. On refresh, the
400 // messages can end up being sent to the refreshed page, causing duplicate
401 // or partial entries.
402 //
403 // This is only read and written to on the UI thread.
404 bool was_webui_deleted_;
405
406 // True if we have attached an observer to the NetLog already.
407 bool is_observing_log_;
408
409 // Log entries that have yet to be passed along to Javascript page. Non-NULL
410 // when and only when there is a pending delayed task to call
411 // PostPendingEntries. Read and written to exclusively on the IO Thread.
412 scoped_ptr<ListValue> pending_entries_;
413 };
414
415 ////////////////////////////////////////////////////////////////////////////////
416 //
417 // NetInternalsMessageHandler
418 //
419 ////////////////////////////////////////////////////////////////////////////////
420
421 NetInternalsMessageHandler::NetInternalsMessageHandler() {}
422
423 NetInternalsMessageHandler::~NetInternalsMessageHandler() {
424 if (proxy_) {
425 proxy_.get()->OnWebUIDeleted();
426 // Notify the handler on the IO thread that the renderer is gone.
427 BrowserThread::PostTask(BrowserThread::IO, FROM_HERE,
428 base::Bind(&IOThreadImpl::Detach, proxy_.get()));
429 }
430 }
431
432 void NetInternalsMessageHandler::RegisterMessages() {
433 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
434
435 Profile* profile = Profile::FromWebUI(web_ui());
436 PrefService* pref_service = profile->GetPrefs();
437 http_throttling_enabled_.Init(
438 prefs::kHttpThrottlingEnabled, pref_service, this);
439 http_throttling_may_experiment_.Init(
440 prefs::kHttpThrottlingMayExperiment, pref_service, NULL);
441
442 proxy_ = new IOThreadImpl(this->AsWeakPtr(), g_browser_process->io_thread(),
443 profile->GetRequestContext());
444 #ifdef OS_CHROMEOS
445 syslogs_getter_.reset(new SystemLogsGetter(this,
446 chromeos::system::SyslogsProvider::GetInstance()));
447 #endif
448
449 prerender::PrerenderManager* prerender_manager =
450 prerender::PrerenderManagerFactory::GetForProfile(profile);
451 if (prerender_manager) {
452 prerender_manager_ = prerender_manager->AsWeakPtr();
453 } else {
454 prerender_manager_ = base::WeakPtr<prerender::PrerenderManager>();
455 }
456
457 web_ui()->RegisterMessageCallback(
458 "notifyReady",
459 base::Bind(&NetInternalsMessageHandler::OnRendererReady,
460 base::Unretained(this)));
461 web_ui()->RegisterMessageCallback(
462 "getProxySettings",
463 base::Bind(&IOThreadImpl::CallbackHelper,
464 &IOThreadImpl::OnGetProxySettings, proxy_));
465 web_ui()->RegisterMessageCallback(
466 "reloadProxySettings",
467 base::Bind(&IOThreadImpl::CallbackHelper,
468 &IOThreadImpl::OnReloadProxySettings, proxy_));
469 web_ui()->RegisterMessageCallback(
470 "getBadProxies",
471 base::Bind(&IOThreadImpl::CallbackHelper,
472 &IOThreadImpl::OnGetBadProxies, proxy_));
473 web_ui()->RegisterMessageCallback(
474 "clearBadProxies",
475 base::Bind(&IOThreadImpl::CallbackHelper,
476 &IOThreadImpl::OnClearBadProxies, proxy_));
477 web_ui()->RegisterMessageCallback(
478 "getHostResolverInfo",
479 base::Bind(&IOThreadImpl::CallbackHelper,
480 &IOThreadImpl::OnGetHostResolverInfo, proxy_));
481 web_ui()->RegisterMessageCallback(
482 "clearHostResolverCache",
483 base::Bind(&IOThreadImpl::CallbackHelper,
484 &IOThreadImpl::OnClearHostResolverCache, proxy_));
485 web_ui()->RegisterMessageCallback(
486 "enableIPv6",
487 base::Bind(&IOThreadImpl::CallbackHelper,
488 &IOThreadImpl::OnEnableIPv6, proxy_));
489 web_ui()->RegisterMessageCallback(
490 "startConnectionTests",
491 base::Bind(&IOThreadImpl::CallbackHelper,
492 &IOThreadImpl::OnStartConnectionTests, proxy_));
493 web_ui()->RegisterMessageCallback(
494 "hstsQuery",
495 base::Bind(&IOThreadImpl::CallbackHelper,
496 &IOThreadImpl::OnHSTSQuery, proxy_));
497 web_ui()->RegisterMessageCallback(
498 "hstsAdd",
499 base::Bind(&IOThreadImpl::CallbackHelper,
500 &IOThreadImpl::OnHSTSAdd, proxy_));
501 web_ui()->RegisterMessageCallback(
502 "hstsDelete",
503 base::Bind(&IOThreadImpl::CallbackHelper,
504 &IOThreadImpl::OnHSTSDelete, proxy_));
505 web_ui()->RegisterMessageCallback(
506 "getHttpCacheInfo",
507 base::Bind(&IOThreadImpl::CallbackHelper,
508 &IOThreadImpl::OnGetHttpCacheInfo, proxy_));
509 web_ui()->RegisterMessageCallback(
510 "getSocketPoolInfo",
511 base::Bind(&IOThreadImpl::CallbackHelper,
512 &IOThreadImpl::OnGetSocketPoolInfo, proxy_));
513 web_ui()->RegisterMessageCallback(
514 "closeIdleSockets",
515 base::Bind(&IOThreadImpl::CallbackHelper,
516 &IOThreadImpl::OnCloseIdleSockets, proxy_));
517 web_ui()->RegisterMessageCallback(
518 "flushSocketPools",
519 base::Bind(&IOThreadImpl::CallbackHelper,
520 &IOThreadImpl::OnFlushSocketPools, proxy_));
521 web_ui()->RegisterMessageCallback(
522 "getSpdySessionInfo",
523 base::Bind(&IOThreadImpl::CallbackHelper,
524 &IOThreadImpl::OnGetSpdySessionInfo, proxy_));
525 web_ui()->RegisterMessageCallback(
526 "getSpdyStatus",
527 base::Bind(&IOThreadImpl::CallbackHelper,
528 &IOThreadImpl::OnGetSpdyStatus, proxy_));
529 web_ui()->RegisterMessageCallback(
530 "getSpdyAlternateProtocolMappings",
531 base::Bind(&IOThreadImpl::CallbackHelper,
532 &IOThreadImpl::OnGetSpdyAlternateProtocolMappings, proxy_));
533 #ifdef OS_WIN
534 web_ui()->RegisterMessageCallback(
535 "getServiceProviders",
536 base::Bind(&IOThreadImpl::CallbackHelper,
537 &IOThreadImpl::OnGetServiceProviders, proxy_));
538 #endif
539
540 web_ui()->RegisterMessageCallback(
541 "getHttpPipeliningStatus",
542 base::Bind(&IOThreadImpl::CallbackHelper,
543 &IOThreadImpl::OnGetHttpPipeliningStatus, proxy_));
544 web_ui()->RegisterMessageCallback(
545 "setLogLevel",
546 base::Bind(&IOThreadImpl::CallbackHelper,
547 &IOThreadImpl::OnSetLogLevel, proxy_));
548 web_ui()->RegisterMessageCallback(
549 "enableHttpThrottling",
550 base::Bind(&NetInternalsMessageHandler::OnEnableHttpThrottling,
551 base::Unretained(this)));
552 web_ui()->RegisterMessageCallback(
553 "clearBrowserCache",
554 base::Bind(&NetInternalsMessageHandler::OnClearBrowserCache,
555 base::Unretained(this)));
556 web_ui()->RegisterMessageCallback(
557 "getPrerenderInfo",
558 base::Bind(&NetInternalsMessageHandler::OnGetPrerenderInfo,
559 base::Unretained(this)));
560 #ifdef OS_CHROMEOS
561 web_ui()->RegisterMessageCallback(
562 "refreshSystemLogs",
563 base::Bind(&NetInternalsMessageHandler::OnRefreshSystemLogs,
564 base::Unretained(this)));
565 web_ui()->RegisterMessageCallback(
566 "getSystemLog",
567 base::Bind(&NetInternalsMessageHandler::OnGetSystemLog,
568 base::Unretained(this)));
569 web_ui()->RegisterMessageCallback(
570 "importONCFile",
571 base::Bind(&NetInternalsMessageHandler::OnImportONCFile,
572 base::Unretained(this)));
573 #endif
574 }
575
576 void NetInternalsMessageHandler::SendJavascriptCommand(
577 const std::string& command,
578 Value* arg) {
579 scoped_ptr<Value> command_value(Value::CreateStringValue(command));
580 scoped_ptr<Value> value(arg);
581 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
582 if (value.get()) {
583 web_ui()->CallJavascriptFunction("g_browser.receive",
584 *command_value.get(),
585 *value.get());
586 } else {
587 web_ui()->CallJavascriptFunction("g_browser.receive",
588 *command_value.get());
589 }
590 }
591
592 void NetInternalsMessageHandler::Observe(
593 int type,
594 const content::NotificationSource& source,
595 const content::NotificationDetails& details) {
596 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
597 DCHECK_EQ(type, chrome::NOTIFICATION_PREF_CHANGED);
598
599 std::string* pref_name = content::Details<std::string>(details).ptr();
600 if (*pref_name == prefs::kHttpThrottlingEnabled) {
601 SendJavascriptCommand(
602 "receivedHttpThrottlingEnabledPrefChanged",
603 Value::CreateBooleanValue(*http_throttling_enabled_));
604 }
605 }
606
607 void NetInternalsMessageHandler::OnRendererReady(const ListValue* list) {
608 IOThreadImpl::CallbackHelper(&IOThreadImpl::OnRendererReady, proxy_, list);
609
610 SendJavascriptCommand(
611 "receivedHttpThrottlingEnabledPrefChanged",
612 Value::CreateBooleanValue(*http_throttling_enabled_));
613 }
614
615 void NetInternalsMessageHandler::OnEnableHttpThrottling(const ListValue* list) {
616 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
617
618 bool enable = false;
619 if (!list->GetBoolean(0, &enable)) {
620 NOTREACHED();
621 return;
622 }
623
624 http_throttling_enabled_.SetValue(enable);
625
626 // We never receive OnEnableHttpThrottling unless the user has modified
627 // the value of the checkbox on the about:net-internals page. Once the
628 // user does that, we no longer change its value automatically (e.g.
629 // by changing the default or running an experiment).
630 if (http_throttling_may_experiment_.GetValue()) {
631 http_throttling_may_experiment_.SetValue(false);
632 }
633 }
634
635 void NetInternalsMessageHandler::OnClearBrowserCache(const ListValue* list) {
636 BrowsingDataRemover* remover =
637 new BrowsingDataRemover(Profile::FromWebUI(web_ui()),
638 BrowsingDataRemover::EVERYTHING,
639 base::Time());
640 remover->Remove(BrowsingDataRemover::REMOVE_CACHE);
641 // BrowsingDataRemover deletes itself.
642 }
643
644 void NetInternalsMessageHandler::OnGetPrerenderInfo(const ListValue* list) {
645 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
646
647 DictionaryValue* value = NULL;
648 prerender::PrerenderManager* prerender_manager = prerender_manager_.get();
649 if (!prerender_manager) {
650 value = new DictionaryValue();
651 value->SetBoolean("enabled", false);
652 value->SetBoolean("omnibox_enabled", false);
653 } else {
654 value = prerender_manager->GetAsValue();
655 }
656 SendJavascriptCommand("receivedPrerenderInfo", value);
657 }
658
659
660 #ifdef OS_CHROMEOS
661 ////////////////////////////////////////////////////////////////////////////////
662 //
663 // NetInternalsMessageHandler::SystemLogsGetter
664 //
665 ////////////////////////////////////////////////////////////////////////////////
666
667 NetInternalsMessageHandler::SystemLogsGetter::SystemLogsGetter(
668 NetInternalsMessageHandler* handler,
669 chromeos::system::SyslogsProvider* syslogs_provider)
670 : handler_(handler),
671 syslogs_provider_(syslogs_provider),
672 logs_(NULL),
673 logs_received_(false),
674 logs_requested_(false) {
675 if (!syslogs_provider_)
676 LOG(ERROR) << "System access library not loaded";
677 }
678
679 NetInternalsMessageHandler::SystemLogsGetter::~SystemLogsGetter() {
680 DeleteSystemLogs();
681 }
682
683 void NetInternalsMessageHandler::SystemLogsGetter::DeleteSystemLogs() {
684 if (syslogs_provider_ && logs_requested_ && !logs_received_) {
685 syslogs_provider_->CancelRequest(syslogs_request_id_);
686 }
687 logs_requested_ = false;
688 logs_received_ = false;
689 logs_.reset();
690 }
691
692 void NetInternalsMessageHandler::SystemLogsGetter::RequestSystemLog(
693 const ListValue* args) {
694 if (!logs_requested_) {
695 DCHECK(!logs_received_);
696 LoadSystemLogs();
697 }
698 SystemLogRequest log_request;
699 args->GetString(0, &log_request.log_key);
700 args->GetString(1, &log_request.cell_id);
701
702 if (logs_received_) {
703 SendLogs(log_request);
704 } else {
705 requests_.push_back(log_request);
706 }
707 }
708
709 void NetInternalsMessageHandler::SystemLogsGetter::LoadSystemLogs() {
710 if (logs_requested_ || !syslogs_provider_)
711 return;
712 logs_requested_ = true;
713 syslogs_request_id_ = syslogs_provider_->RequestSyslogs(
714 false, // compress logs.
715 chromeos::system::SyslogsProvider::SYSLOGS_NETWORK,
716 &consumer_,
717 base::Bind(
718 &NetInternalsMessageHandler::SystemLogsGetter::OnSystemLogsLoaded,
719 base::Unretained(this)));
720 }
721
722 void NetInternalsMessageHandler::SystemLogsGetter::OnSystemLogsLoaded(
723 chromeos::system::LogDictionaryType* sys_info,
724 std::string* ignored_content) {
725 DCHECK(!ignored_content);
726 logs_.reset(sys_info);
727 logs_received_ = true;
728 for (std::list<SystemLogRequest>::iterator request_it = requests_.begin();
729 request_it != requests_.end();
730 ++request_it) {
731 SendLogs(*request_it);
732 }
733 requests_.clear();
734 }
735
736 void NetInternalsMessageHandler::SystemLogsGetter::SendLogs(
737 const SystemLogRequest& request) {
738 DictionaryValue* result = new DictionaryValue();
739 chromeos::system::LogDictionaryType::iterator log_it =
740 logs_->find(request.log_key);
741 if (log_it != logs_->end()) {
742 if (!log_it->second.empty()) {
743 result->SetString("log", log_it->second);
744 } else {
745 result->SetString("log", "<no relevant lines found>");
746 }
747 } else {
748 result->SetString("log", "<invalid log name>");
749 }
750 result->SetString("cellId", request.cell_id);
751
752 handler_->SendJavascriptCommand("getSystemLogCallback", result);
753 }
754 #endif
755 ////////////////////////////////////////////////////////////////////////////////
756 //
757 // NetInternalsMessageHandler::IOThreadImpl
758 //
759 ////////////////////////////////////////////////////////////////////////////////
760
761 NetInternalsMessageHandler::IOThreadImpl::IOThreadImpl(
762 const base::WeakPtr<NetInternalsMessageHandler>& handler,
763 IOThread* io_thread,
764 net::URLRequestContextGetter* context_getter)
765 : ThreadSafeObserverImpl(net::NetLog::LOG_ALL_BUT_BYTES),
766 handler_(handler),
767 io_thread_(io_thread),
768 context_getter_(context_getter),
769 was_webui_deleted_(false),
770 is_observing_log_(false) {
771 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
772 }
773
774 NetInternalsMessageHandler::IOThreadImpl::~IOThreadImpl() {
775 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
776 }
777
778 void NetInternalsMessageHandler::IOThreadImpl::CallbackHelper(
779 MessageHandler method,
780 scoped_refptr<IOThreadImpl> io_thread,
781 const ListValue* list) {
782 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
783
784 // We need to make a copy of the value in order to pass it over to the IO
785 // thread. We will delete this in IOThreadImpl::DispatchMessageHandler().
786 ListValue* list_copy =
787 static_cast<ListValue*>(list ? list->DeepCopy() : NULL);
788
789 if (!BrowserThread::PostTask(
790 BrowserThread::IO, FROM_HERE,
791 base::Bind(method, io_thread, list_copy))) {
792 // Failed posting the task, avoid leaking |list_copy|.
793 delete list_copy;
794 }
795 }
796
797 void NetInternalsMessageHandler::IOThreadImpl::Detach() {
798 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
799 // Unregister with network stack to observe events.
800 if (is_observing_log_) {
801 is_observing_log_ = false;
802 RemoveAsObserver();
803 }
804
805 // Cancel any in-progress connection tests.
806 connection_tester_.reset();
807 }
808
809 void NetInternalsMessageHandler::IOThreadImpl::SendPassiveLogEntries(
810 const ChromeNetLog::EntryList& passive_entries) {
811 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
812 ListValue* dict_list = new ListValue();
813 for (size_t i = 0; i < passive_entries.size(); ++i) {
814 const ChromeNetLog::Entry& e = passive_entries[i];
815 dict_list->Append(net::NetLog::EntryToDictionaryValue(e.type,
816 e.time,
817 e.source,
818 e.phase,
819 e.params,
820 false));
821 }
822
823 SendJavascriptCommand("receivedPassiveLogEntries", dict_list);
824 }
825
826 void NetInternalsMessageHandler::IOThreadImpl::OnWebUIDeleted() {
827 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
828 was_webui_deleted_ = true;
829 }
830
831 void NetInternalsMessageHandler::IOThreadImpl::OnRendererReady(
832 const ListValue* list) {
833 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
834 DCHECK(!is_observing_log_) << "notifyReady called twice";
835
836 SendJavascriptCommand("receivedConstants",
837 NetInternalsUI::GetConstants());
838
839 // Register with network stack to observe events.
840 is_observing_log_ = true;
841 ChromeNetLog::EntryList entries;
842 AddAsObserverAndGetAllPassivelyCapturedEvents(io_thread_->net_log(),
843 &entries);
844 SendPassiveLogEntries(entries);
845 }
846
847 void NetInternalsMessageHandler::IOThreadImpl::OnGetProxySettings(
848 const ListValue* list) {
849 net::URLRequestContext* context = context_getter_->GetURLRequestContext();
850 net::ProxyService* proxy_service = context->proxy_service();
851
852 DictionaryValue* dict = new DictionaryValue();
853 if (proxy_service->fetched_config().is_valid())
854 dict->Set("original", proxy_service->fetched_config().ToValue());
855 if (proxy_service->config().is_valid())
856 dict->Set("effective", proxy_service->config().ToValue());
857
858 SendJavascriptCommand("receivedProxySettings", dict);
859 }
860
861 void NetInternalsMessageHandler::IOThreadImpl::OnReloadProxySettings(
862 const ListValue* list) {
863 net::URLRequestContext* context = context_getter_->GetURLRequestContext();
864 context->proxy_service()->ForceReloadProxyConfig();
865
866 // Cause the renderer to be notified of the new values.
867 OnGetProxySettings(NULL);
868 }
869
870 void NetInternalsMessageHandler::IOThreadImpl::OnGetBadProxies(
871 const ListValue* list) {
872 net::URLRequestContext* context = context_getter_->GetURLRequestContext();
873
874 const net::ProxyRetryInfoMap& bad_proxies_map =
875 context->proxy_service()->proxy_retry_info();
876
877 ListValue* dict_list = new ListValue();
878
879 for (net::ProxyRetryInfoMap::const_iterator it = bad_proxies_map.begin();
880 it != bad_proxies_map.end(); ++it) {
881 const std::string& proxy_uri = it->first;
882 const net::ProxyRetryInfo& retry_info = it->second;
883
884 DictionaryValue* dict = new DictionaryValue();
885 dict->SetString("proxy_uri", proxy_uri);
886 dict->SetString("bad_until",
887 net::NetLog::TickCountToString(retry_info.bad_until));
888
889 dict_list->Append(dict);
890 }
891
892 SendJavascriptCommand("receivedBadProxies", dict_list);
893 }
894
895 void NetInternalsMessageHandler::IOThreadImpl::OnClearBadProxies(
896 const ListValue* list) {
897 net::URLRequestContext* context = context_getter_->GetURLRequestContext();
898 context->proxy_service()->ClearBadProxiesCache();
899
900 // Cause the renderer to be notified of the new values.
901 OnGetBadProxies(NULL);
902 }
903
904 void NetInternalsMessageHandler::IOThreadImpl::OnGetHostResolverInfo(
905 const ListValue* list) {
906 net::URLRequestContext* context = context_getter_->GetURLRequestContext();
907 net::HostCache* cache = GetHostResolverCache(context);
908
909 if (!cache) {
910 SendJavascriptCommand("receivedHostResolverInfo", NULL);
911 return;
912 }
913
914 DictionaryValue* dict = new DictionaryValue();
915
916 dict->SetInteger(
917 "default_address_family",
918 static_cast<int>(context->host_resolver()->GetDefaultAddressFamily()));
919
920 DictionaryValue* cache_info_dict = new DictionaryValue();
921
922 cache_info_dict->SetInteger(
923 "capacity",
924 static_cast<int>(cache->max_entries()));
925 cache_info_dict->SetInteger(
926 "ttl_success_ms",
927 static_cast<int>(cache->success_entry_ttl().InMilliseconds()));
928 cache_info_dict->SetInteger(
929 "ttl_failure_ms",
930 static_cast<int>(cache->failure_entry_ttl().InMilliseconds()));
931
932 ListValue* entry_list = new ListValue();
933
934 for (net::HostCache::EntryMap::const_iterator it =
935 cache->entries().begin();
936 it != cache->entries().end();
937 ++it) {
938 const net::HostCache::Key& key = it->first;
939 const net::HostCache::Entry* entry = it->second.get();
940
941 DictionaryValue* entry_dict = new DictionaryValue();
942
943 entry_dict->SetString("hostname", key.hostname);
944 entry_dict->SetInteger("address_family",
945 static_cast<int>(key.address_family));
946 entry_dict->SetString("expiration",
947 net::NetLog::TickCountToString(entry->expiration));
948
949 if (entry->error != net::OK) {
950 entry_dict->SetInteger("error", entry->error);
951 } else {
952 // Append all of the resolved addresses.
953 ListValue* address_list = new ListValue();
954 const struct addrinfo* current_address = entry->addrlist.head();
955 while (current_address) {
956 address_list->Append(Value::CreateStringValue(
957 net::NetAddressToStringWithPort(current_address)));
958 current_address = current_address->ai_next;
959 }
960 entry_dict->Set("addresses", address_list);
961 }
962
963 entry_list->Append(entry_dict);
964 }
965
966 cache_info_dict->Set("entries", entry_list);
967 dict->Set("cache", cache_info_dict);
968
969 SendJavascriptCommand("receivedHostResolverInfo", dict);
970 }
971
972 void NetInternalsMessageHandler::IOThreadImpl::OnClearHostResolverCache(
973 const ListValue* list) {
974 net::HostCache* cache =
975 GetHostResolverCache(context_getter_->GetURLRequestContext());
976
977 if (cache)
978 cache->clear();
979
980 // Cause the renderer to be notified of the new values.
981 OnGetHostResolverInfo(NULL);
982 }
983
984 void NetInternalsMessageHandler::IOThreadImpl::OnEnableIPv6(
985 const ListValue* list) {
986 net::URLRequestContext* context = context_getter_->GetURLRequestContext();
987 net::HostResolver* host_resolver = context->host_resolver();
988
989 host_resolver->SetDefaultAddressFamily(net::ADDRESS_FAMILY_UNSPECIFIED);
990
991 // Cause the renderer to be notified of the new value.
992 OnGetHostResolverInfo(NULL);
993 }
994
995 void NetInternalsMessageHandler::IOThreadImpl::OnStartConnectionTests(
996 const ListValue* list) {
997 // |value| should be: [<URL to test>].
998 string16 url_str;
999 CHECK(list->GetString(0, &url_str));
1000
1001 // Try to fix-up the user provided URL into something valid.
1002 // For example, turn "www.google.com" into "http://www.google.com".
1003 GURL url(URLFixerUpper::FixupURL(UTF16ToUTF8(url_str), std::string()));
1004
1005 connection_tester_.reset(new ConnectionTester(
1006 this, io_thread_->globals()->proxy_script_fetcher_context.get()));
1007 connection_tester_->RunAllTests(url);
1008 }
1009
1010 void SPKIHashesToString(const net::FingerprintVector& hashes,
1011 std::string* string) {
1012 for (net::FingerprintVector::const_iterator
1013 i = hashes.begin(); i != hashes.end(); ++i) {
1014 base::StringPiece hash_str(reinterpret_cast<const char*>(i->data),
1015 arraysize(i->data));
1016 std::string encoded;
1017 base::Base64Encode(hash_str, &encoded);
1018
1019 if (i != hashes.begin())
1020 *string += ",";
1021 *string += "sha1/" + encoded;
1022 }
1023 }
1024
1025 void NetInternalsMessageHandler::IOThreadImpl::OnHSTSQuery(
1026 const ListValue* list) {
1027 // |list| should be: [<domain to query>].
1028 std::string domain;
1029 CHECK(list->GetString(0, &domain));
1030 DictionaryValue* result = new(DictionaryValue);
1031
1032 if (!IsStringASCII(domain)) {
1033 result->SetString("error", "non-ASCII domain name");
1034 } else {
1035 net::TransportSecurityState* transport_security_state =
1036 context_getter_->GetURLRequestContext()->transport_security_state();
1037 if (!transport_security_state) {
1038 result->SetString("error", "no TransportSecurityState active");
1039 } else {
1040 net::TransportSecurityState::DomainState state;
1041 const bool found = transport_security_state->HasMetadata(
1042 &state, domain, true);
1043
1044 result->SetBoolean("result", found);
1045 if (found) {
1046 result->SetInteger("mode", static_cast<int>(state.mode));
1047 result->SetBoolean("subdomains", state.include_subdomains);
1048 result->SetBoolean("preloaded", state.preloaded);
1049 result->SetString("domain", state.domain);
1050 result->SetDouble("expiry", state.expiry.ToDoubleT());
1051 result->SetDouble("dynamic_spki_hashes_expiry",
1052 state.dynamic_spki_hashes_expiry.ToDoubleT());
1053
1054 std::string hashes;
1055 SPKIHashesToString(state.preloaded_spki_hashes, &hashes);
1056 result->SetString("preloaded_spki_hashes", hashes);
1057
1058 hashes.clear();
1059 SPKIHashesToString(state.dynamic_spki_hashes, &hashes);
1060 result->SetString("dynamic_spki_hashes", hashes);
1061 }
1062 }
1063 }
1064
1065 SendJavascriptCommand("receivedHSTSResult", result);
1066 }
1067
1068 void NetInternalsMessageHandler::IOThreadImpl::OnHSTSAdd(
1069 const ListValue* list) {
1070 // |list| should be: [<domain to query>, <include subdomains>, <cert pins>].
1071 std::string domain;
1072 CHECK(list->GetString(0, &domain));
1073 if (!IsStringASCII(domain)) {
1074 // Silently fail. The user will get a helpful error if they query for the
1075 // name.
1076 return;
1077 }
1078 bool include_subdomains;
1079 CHECK(list->GetBoolean(1, &include_subdomains));
1080 std::string hashes_str;
1081 CHECK(list->GetString(2, &hashes_str));
1082
1083 net::TransportSecurityState* transport_security_state =
1084 context_getter_->GetURLRequestContext()->transport_security_state();
1085 if (!transport_security_state)
1086 return;
1087
1088 net::TransportSecurityState::DomainState state;
1089 state.expiry = state.created + base::TimeDelta::FromDays(1000);
1090 state.include_subdomains = include_subdomains;
1091 if (!hashes_str.empty()) {
1092 std::vector<std::string> type_and_b64s;
1093 base::SplitString(hashes_str, ',', &type_and_b64s);
1094 for (std::vector<std::string>::const_iterator
1095 i = type_and_b64s.begin(); i != type_and_b64s.end(); i++) {
1096 std::string type_and_b64;
1097 RemoveChars(*i, " \t\r\n", &type_and_b64);
1098 net::SHA1Fingerprint hash;
1099 if (!net::TransportSecurityState::ParsePin(type_and_b64, &hash))
1100 continue;
1101
1102 state.dynamic_spki_hashes.push_back(hash);
1103 }
1104 }
1105
1106 transport_security_state->EnableHost(domain, state);
1107 }
1108
1109 void NetInternalsMessageHandler::IOThreadImpl::OnHSTSDelete(
1110 const ListValue* list) {
1111 // |list| should be: [<domain to query>].
1112 std::string domain;
1113 CHECK(list->GetString(0, &domain));
1114 if (!IsStringASCII(domain)) {
1115 // There cannot be a unicode entry in the HSTS set.
1116 return;
1117 }
1118 net::TransportSecurityState* transport_security_state =
1119 context_getter_->GetURLRequestContext()->transport_security_state();
1120 if (!transport_security_state)
1121 return;
1122
1123 transport_security_state->DeleteHost(domain);
1124 }
1125
1126 void NetInternalsMessageHandler::IOThreadImpl::OnGetHttpCacheInfo(
1127 const ListValue* list) {
1128 DictionaryValue* info_dict = new DictionaryValue();
1129 DictionaryValue* stats_dict = new DictionaryValue();
1130
1131 disk_cache::Backend* disk_cache = GetDiskCacheBackend(
1132 context_getter_->GetURLRequestContext());
1133
1134 if (disk_cache) {
1135 // Extract the statistics key/value pairs from the backend.
1136 std::vector<std::pair<std::string, std::string> > stats;
1137 disk_cache->GetStats(&stats);
1138 for (size_t i = 0; i < stats.size(); ++i) {
1139 stats_dict->Set(stats[i].first,
1140 Value::CreateStringValue(stats[i].second));
1141 }
1142 }
1143
1144 info_dict->Set("stats", stats_dict);
1145
1146 SendJavascriptCommand("receivedHttpCacheInfo", info_dict);
1147 }
1148
1149 void NetInternalsMessageHandler::IOThreadImpl::OnGetSocketPoolInfo(
1150 const ListValue* list) {
1151 net::HttpNetworkSession* http_network_session =
1152 GetHttpNetworkSession(context_getter_->GetURLRequestContext());
1153
1154 Value* socket_pool_info = NULL;
1155 if (http_network_session)
1156 socket_pool_info = http_network_session->SocketPoolInfoToValue();
1157
1158 SendJavascriptCommand("receivedSocketPoolInfo", socket_pool_info);
1159 }
1160
1161
1162 void NetInternalsMessageHandler::IOThreadImpl::OnFlushSocketPools(
1163 const ListValue* list) {
1164 net::HttpNetworkSession* http_network_session =
1165 GetHttpNetworkSession(context_getter_->GetURLRequestContext());
1166
1167 if (http_network_session)
1168 http_network_session->CloseAllConnections();
1169 }
1170
1171 void NetInternalsMessageHandler::IOThreadImpl::OnCloseIdleSockets(
1172 const ListValue* list) {
1173 net::HttpNetworkSession* http_network_session =
1174 GetHttpNetworkSession(context_getter_->GetURLRequestContext());
1175
1176 if (http_network_session)
1177 http_network_session->CloseIdleConnections();
1178 }
1179
1180 void NetInternalsMessageHandler::IOThreadImpl::OnGetSpdySessionInfo(
1181 const ListValue* list) {
1182 net::HttpNetworkSession* http_network_session =
1183 GetHttpNetworkSession(context_getter_->GetURLRequestContext());
1184
1185 Value* spdy_info = NULL;
1186 if (http_network_session) {
1187 spdy_info = http_network_session->SpdySessionPoolInfoToValue();
1188 }
1189
1190 SendJavascriptCommand("receivedSpdySessionInfo", spdy_info);
1191 }
1192
1193 void NetInternalsMessageHandler::IOThreadImpl::OnGetSpdyStatus(
1194 const ListValue* list) {
1195 DictionaryValue* status_dict = new DictionaryValue();
1196
1197 status_dict->Set("spdy_enabled",
1198 Value::CreateBooleanValue(
1199 net::HttpStreamFactory::spdy_enabled()));
1200 status_dict->Set("use_alternate_protocols",
1201 Value::CreateBooleanValue(
1202 net::HttpStreamFactory::use_alternate_protocols()));
1203 status_dict->Set("force_spdy_over_ssl",
1204 Value::CreateBooleanValue(
1205 net::HttpStreamFactory::force_spdy_over_ssl()));
1206 status_dict->Set("force_spdy_always",
1207 Value::CreateBooleanValue(
1208 net::HttpStreamFactory::force_spdy_always()));
1209
1210 // The next_protos may not be specified for certain configurations of SPDY.
1211 Value* next_protos_value;
1212 if (net::HttpStreamFactory::has_next_protos()) {
1213 next_protos_value = Value::CreateStringValue(
1214 JoinString(net::HttpStreamFactory::next_protos(), ','));
1215 } else {
1216 next_protos_value = Value::CreateStringValue("");
1217 }
1218 status_dict->Set("next_protos", next_protos_value);
1219
1220 SendJavascriptCommand("receivedSpdyStatus", status_dict);
1221 }
1222
1223 void
1224 NetInternalsMessageHandler::IOThreadImpl::OnGetSpdyAlternateProtocolMappings(
1225 const ListValue* list) {
1226 ListValue* dict_list = new ListValue();
1227
1228 const net::HttpServerProperties& http_server_properties =
1229 *context_getter_->GetURLRequestContext()->http_server_properties();
1230
1231 const net::AlternateProtocolMap& map =
1232 http_server_properties.alternate_protocol_map();
1233
1234 for (net::AlternateProtocolMap::const_iterator it = map.begin();
1235 it != map.end(); ++it) {
1236 DictionaryValue* dict = new DictionaryValue();
1237 dict->SetString("host_port_pair", it->first.ToString());
1238 dict->SetString("alternate_protocol", it->second.ToString());
1239 dict_list->Append(dict);
1240 }
1241
1242 SendJavascriptCommand("receivedSpdyAlternateProtocolMappings", dict_list);
1243 }
1244
1245 #ifdef OS_WIN
1246 void NetInternalsMessageHandler::IOThreadImpl::OnGetServiceProviders(
1247 const ListValue* list) {
1248
1249 DictionaryValue* service_providers = new DictionaryValue();
1250
1251 WinsockLayeredServiceProviderList layered_providers;
1252 GetWinsockLayeredServiceProviders(&layered_providers);
1253 ListValue* layered_provider_list = new ListValue();
1254 for (size_t i = 0; i < layered_providers.size(); ++i) {
1255 DictionaryValue* service_dict = new DictionaryValue();
1256 service_dict->SetString("name", layered_providers[i].name);
1257 service_dict->SetInteger("version", layered_providers[i].version);
1258 service_dict->SetInteger("chain_length", layered_providers[i].chain_length);
1259 service_dict->SetInteger("socket_type", layered_providers[i].socket_type);
1260 service_dict->SetInteger("socket_protocol",
1261 layered_providers[i].socket_protocol);
1262 service_dict->SetString("path", layered_providers[i].path);
1263
1264 layered_provider_list->Append(service_dict);
1265 }
1266 service_providers->Set("service_providers", layered_provider_list);
1267
1268 WinsockNamespaceProviderList namespace_providers;
1269 GetWinsockNamespaceProviders(&namespace_providers);
1270 ListValue* namespace_list = new ListValue;
1271 for (size_t i = 0; i < namespace_providers.size(); ++i) {
1272 DictionaryValue* namespace_dict = new DictionaryValue();
1273 namespace_dict->SetString("name", namespace_providers[i].name);
1274 namespace_dict->SetBoolean("active", namespace_providers[i].active);
1275 namespace_dict->SetInteger("version", namespace_providers[i].version);
1276 namespace_dict->SetInteger("type", namespace_providers[i].type);
1277
1278 namespace_list->Append(namespace_dict);
1279 }
1280 service_providers->Set("namespace_providers", namespace_list);
1281
1282 SendJavascriptCommand("receivedServiceProviders", service_providers);
1283 }
1284 #endif
1285
1286 #ifdef OS_CHROMEOS
1287 void NetInternalsMessageHandler::OnRefreshSystemLogs(const ListValue* list) {
1288 DCHECK(syslogs_getter_.get());
1289 syslogs_getter_->DeleteSystemLogs();
1290 syslogs_getter_->LoadSystemLogs();
1291 }
1292
1293 void NetInternalsMessageHandler::OnGetSystemLog(const ListValue* list) {
1294 DCHECK(syslogs_getter_.get());
1295 syslogs_getter_->RequestSystemLog(list);
1296 }
1297
1298 void NetInternalsMessageHandler::OnImportONCFile(const ListValue* list) {
1299 std::string onc_blob;
1300 std::string passcode;
1301 if (list->GetSize() != 2 ||
1302 !list->GetString(0, &onc_blob) ||
1303 !list->GetString(1, &passcode)) {
1304 NOTREACHED();
1305 }
1306
1307 std::string error;
1308 chromeos::CrosLibrary::Get()->GetNetworkLibrary()->
1309 LoadOncNetworks(onc_blob, passcode,
1310 chromeos::NetworkUIData::ONC_SOURCE_USER_IMPORT, &error);
1311 SendJavascriptCommand("receivedONCFileParse",
1312 Value::CreateStringValue(error));
1313 }
1314 #endif
1315
1316 void NetInternalsMessageHandler::IOThreadImpl::OnGetHttpPipeliningStatus(
1317 const ListValue* list) {
1318 DictionaryValue* status_dict = new DictionaryValue();
1319
1320 status_dict->Set("pipelining_enabled",
1321 Value::CreateBooleanValue(
1322 net::HttpStreamFactory::http_pipelining_enabled()));
1323
1324 net::HttpNetworkSession* http_network_session =
1325 GetHttpNetworkSession(context_getter_->GetURLRequestContext());
1326 Value* pipelined_conneciton_info =
1327 http_network_session->http_stream_factory()->PipelineInfoToValue();
1328 status_dict->Set("pipelined_connection_info", pipelined_conneciton_info);
1329
1330 const net::HttpServerProperties& http_server_properties =
1331 *context_getter_->GetURLRequestContext()->http_server_properties();
1332
1333 // TODO(simonjam): This call is slow.
1334 const net::PipelineCapabilityMap pipeline_capability_map =
1335 http_server_properties.GetPipelineCapabilityMap();
1336
1337 ListValue* known_hosts_list = new ListValue();
1338 net::PipelineCapabilityMap::const_iterator it;
1339 for (it = pipeline_capability_map.begin();
1340 it != pipeline_capability_map.end(); ++it) {
1341 DictionaryValue* host_dict = new DictionaryValue();
1342 host_dict->SetString("host", it->first.ToString());
1343 std::string capability;
1344 switch (it->second) {
1345 case net::PIPELINE_CAPABLE:
1346 capability = "capable";
1347 break;
1348
1349 case net::PIPELINE_PROBABLY_CAPABLE:
1350 capability = "probably capable";
1351 break;
1352
1353 case net::PIPELINE_INCAPABLE:
1354 capability = "incapable";
1355 break;
1356
1357 case net::PIPELINE_UNKNOWN:
1358 default:
1359 capability = "unknown";
1360 break;
1361 }
1362 host_dict->SetString("capability", capability);
1363 known_hosts_list->Append(host_dict);
1364 }
1365 status_dict->Set("pipelined_host_info", known_hosts_list);
1366
1367 SendJavascriptCommand("receivedHttpPipeliningStatus", status_dict);
1368 }
1369
1370 void NetInternalsMessageHandler::IOThreadImpl::OnSetLogLevel(
1371 const ListValue* list) {
1372 int log_level;
1373 std::string log_level_string;
1374 if (!list->GetString(0, &log_level_string) ||
1375 !base::StringToInt(log_level_string, &log_level)) {
1376 NOTREACHED();
1377 return;
1378 }
1379
1380 DCHECK_GE(log_level, net::NetLog::LOG_ALL);
1381 DCHECK_LE(log_level, net::NetLog::LOG_BASIC);
1382 SetLogLevel(static_cast<net::NetLog::LogLevel>(log_level));
1383 }
1384
1385 // Note that unlike other methods of IOThreadImpl, this function
1386 // can be called from ANY THREAD.
1387 void NetInternalsMessageHandler::IOThreadImpl::OnAddEntry(
1388 net::NetLog::EventType type,
1389 const base::TimeTicks& time,
1390 const net::NetLog::Source& source,
1391 net::NetLog::EventPhase phase,
1392 net::NetLog::EventParameters* params) {
1393 BrowserThread::PostTask(
1394 BrowserThread::IO, FROM_HERE,
1395 base::Bind(&IOThreadImpl::AddEntryToQueue, this,
1396 net::NetLog::EntryToDictionaryValue(type, time, source, phase,
1397 params, false)));
1398 }
1399
1400 void NetInternalsMessageHandler::IOThreadImpl::AddEntryToQueue(Value* entry) {
1401 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
1402 if (!pending_entries_.get()) {
1403 pending_entries_.reset(new ListValue());
1404 BrowserThread::PostDelayedTask(
1405 BrowserThread::IO, FROM_HERE,
1406 base::Bind(&IOThreadImpl::PostPendingEntries, this),
1407 kNetLogEventDelayMilliseconds);
1408 }
1409 pending_entries_->Append(entry);
1410 }
1411
1412 void NetInternalsMessageHandler::IOThreadImpl::PostPendingEntries() {
1413 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
1414 SendJavascriptCommand("receivedLogEntries", pending_entries_.release());
1415 }
1416
1417 void NetInternalsMessageHandler::IOThreadImpl::OnStartConnectionTestSuite() {
1418 SendJavascriptCommand("receivedStartConnectionTestSuite", NULL);
1419 }
1420
1421 void NetInternalsMessageHandler::IOThreadImpl::OnStartConnectionTestExperiment(
1422 const ConnectionTester::Experiment& experiment) {
1423 SendJavascriptCommand(
1424 "receivedStartConnectionTestExperiment",
1425 ExperimentToValue(experiment));
1426 }
1427
1428 void
1429 NetInternalsMessageHandler::IOThreadImpl::OnCompletedConnectionTestExperiment(
1430 const ConnectionTester::Experiment& experiment,
1431 int result) {
1432 DictionaryValue* dict = new DictionaryValue();
1433
1434 dict->Set("experiment", ExperimentToValue(experiment));
1435 dict->SetInteger("result", result);
1436
1437 SendJavascriptCommand(
1438 "receivedCompletedConnectionTestExperiment",
1439 dict);
1440 }
1441
1442 void
1443 NetInternalsMessageHandler::IOThreadImpl::OnCompletedConnectionTestSuite() {
1444 SendJavascriptCommand(
1445 "receivedCompletedConnectionTestSuite",
1446 NULL);
1447 }
1448
1449 void NetInternalsMessageHandler::IOThreadImpl::DispatchToMessageHandler(
1450 ListValue* arg, MessageHandler method) {
1451 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
1452 (this->*method)(arg);
1453 delete arg;
1454 }
1455
1456 // Note that this can be called from ANY THREAD.
1457 void NetInternalsMessageHandler::IOThreadImpl::SendJavascriptCommand(
1458 const std::string& command,
1459 Value* arg) {
1460 if (BrowserThread::CurrentlyOn(BrowserThread::UI)) {
1461 if (handler_ && !was_webui_deleted_) {
1462 // We check |handler_| in case it was deleted on the UI thread earlier
1463 // while we were running on the IO thread.
1464 handler_->SendJavascriptCommand(command, arg);
1465 } else {
1466 delete arg;
1467 }
1468 return;
1469 }
1470
1471 if (!BrowserThread::PostTask(
1472 BrowserThread::UI, FROM_HERE,
1473 base::Bind(&IOThreadImpl::SendJavascriptCommand, this, command, arg))) {
1474 // Failed posting the task, avoid leaking.
1475 delete arg;
1476 }
1477 }
1478
1479 } // namespace
1480
1481
1482 ////////////////////////////////////////////////////////////////////////////////
1483 //
1484 // NetInternalsUI
1485 //
1486 ////////////////////////////////////////////////////////////////////////////////
1487
1488 // static
1489 Value* NetInternalsUI::GetConstants() {
1490 DictionaryValue* constants_dict = new DictionaryValue();
1491
1492 // Version of the file format.
1493 constants_dict->SetInteger("logFormatVersion", kLogFormatVersion);
1494
1495 // Add a dictionary with information on the relationship between event type
1496 // enums and their symbolic names.
1497 {
1498 std::vector<net::NetLog::EventType> event_types =
1499 net::NetLog::GetAllEventTypes();
1500
1501 DictionaryValue* dict = new DictionaryValue();
1502
1503 for (size_t i = 0; i < event_types.size(); ++i) {
1504 const char* name = net::NetLog::EventTypeToString(event_types[i]);
1505 dict->SetInteger(name, static_cast<int>(event_types[i]));
1506 }
1507 constants_dict->Set("logEventTypes", dict);
1508 }
1509
1510 // Add a dictionary with the version of the client and its command line
1511 // arguments.
1512 {
1513 DictionaryValue* dict = new DictionaryValue();
1514
1515 chrome::VersionInfo version_info;
1516
1517 if (!version_info.is_valid()) {
1518 DLOG(ERROR) << "Unable to create chrome::VersionInfo";
1519 } else {
1520 // We have everything we need to send the right values.
1521 dict->SetString("name", version_info.Name());
1522 dict->SetString("version", version_info.Version());
1523 dict->SetString("cl", version_info.LastChange());
1524 dict->SetString("version_mod",
1525 chrome::VersionInfo::GetVersionStringModifier());
1526 dict->SetString("official",
1527 version_info.IsOfficialBuild() ? "official" :
1528 "unofficial");
1529 dict->SetString("os_type", version_info.OSType());
1530 dict->SetString("command_line",
1531 CommandLine::ForCurrentProcess()->GetCommandLineString());
1532 }
1533
1534 constants_dict->Set("clientInfo", dict);
1535 }
1536
1537 // Add a dictionary with information about the relationship between load flag
1538 // enums and their symbolic names.
1539 {
1540 DictionaryValue* dict = new DictionaryValue();
1541
1542 #define LOAD_FLAG(label, value) \
1543 dict->SetInteger(# label, static_cast<int>(value));
1544 #include "net/base/load_flags_list.h"
1545 #undef LOAD_FLAG
1546
1547 constants_dict->Set("loadFlag", dict);
1548 }
1549
1550 // Add information on the relationship between net error codes and their
1551 // symbolic names.
1552 {
1553 DictionaryValue* dict = new DictionaryValue();
1554
1555 #define NET_ERROR(label, value) \
1556 dict->SetInteger(# label, static_cast<int>(value));
1557 #include "net/base/net_error_list.h"
1558 #undef NET_ERROR
1559
1560 constants_dict->Set("netError", dict);
1561 }
1562
1563 // Information about the relationship between event phase enums and their
1564 // symbolic names.
1565 {
1566 DictionaryValue* dict = new DictionaryValue();
1567
1568 dict->SetInteger("PHASE_BEGIN", net::NetLog::PHASE_BEGIN);
1569 dict->SetInteger("PHASE_END", net::NetLog::PHASE_END);
1570 dict->SetInteger("PHASE_NONE", net::NetLog::PHASE_NONE);
1571
1572 constants_dict->Set("logEventPhase", dict);
1573 }
1574
1575 // Information about the relationship between source type enums and
1576 // their symbolic names.
1577 {
1578 DictionaryValue* dict = new DictionaryValue();
1579
1580 #define SOURCE_TYPE(label, value) dict->SetInteger(# label, value);
1581 #include "net/base/net_log_source_type_list.h"
1582 #undef SOURCE_TYPE
1583
1584 constants_dict->Set("logSourceType", dict);
1585 }
1586
1587 // Information about the relationship between LogLevel enums and their
1588 // symbolic names.
1589 {
1590 DictionaryValue* dict = new DictionaryValue();
1591
1592 dict->SetInteger("LOG_ALL", net::NetLog::LOG_ALL);
1593 dict->SetInteger("LOG_ALL_BUT_BYTES", net::NetLog::LOG_ALL_BUT_BYTES);
1594 dict->SetInteger("LOG_BASIC", net::NetLog::LOG_BASIC);
1595
1596 constants_dict->Set("logLevelType", dict);
1597 }
1598
1599 // Information about the relationship between address family enums and
1600 // their symbolic names.
1601 {
1602 DictionaryValue* dict = new DictionaryValue();
1603
1604 dict->SetInteger("ADDRESS_FAMILY_UNSPECIFIED",
1605 net::ADDRESS_FAMILY_UNSPECIFIED);
1606 dict->SetInteger("ADDRESS_FAMILY_IPV4",
1607 net::ADDRESS_FAMILY_IPV4);
1608 dict->SetInteger("ADDRESS_FAMILY_IPV6",
1609 net::ADDRESS_FAMILY_IPV6);
1610
1611 constants_dict->Set("addressFamily", dict);
1612 }
1613
1614 // Information about how the "time ticks" values we have given it relate to
1615 // actual system times. (We used time ticks throughout since they are stable
1616 // across system clock changes).
1617 {
1618 int64 cur_time_ms = (base::Time::Now() - base::Time()).InMilliseconds();
1619
1620 int64 cur_time_ticks_ms =
1621 (base::TimeTicks::Now() - base::TimeTicks()).InMilliseconds();
1622
1623 // If we add this number to a time tick value, it gives the timestamp.
1624 int64 tick_to_time_ms = cur_time_ms - cur_time_ticks_ms;
1625
1626 // Chrome on all platforms stores times using the Windows epoch
1627 // (Jan 1 1601), but the javascript wants a unix epoch.
1628 // TODO(eroman): Getting the timestamp relative to the unix epoch should
1629 // be part of the time library.
1630 const int64 kUnixEpochMs = 11644473600000LL;
1631 int64 tick_to_unix_time_ms = tick_to_time_ms - kUnixEpochMs;
1632
1633 // Pass it as a string, since it may be too large to fit in an integer.
1634 constants_dict->SetString("timeTickOffset",
1635 base::Int64ToString(tick_to_unix_time_ms));
1636 }
1637 return constants_dict;
1638 }
1639
1640 NetInternalsUI::NetInternalsUI(WebContents* contents) : WebUI(contents) {
1641 AddMessageHandler(new NetInternalsMessageHandler());
1642
1643 // Set up the chrome://net-internals/ source.
1644 Profile* profile = Profile::FromBrowserContext(contents->GetBrowserContext());
1645 profile->GetChromeURLDataManager()->AddDataSource(
1646 CreateNetInternalsHTMLSource());
1647 }
OLDNEW
« no previous file with comments | « chrome/browser/ui/webui/net_internals_ui.h ('k') | chrome/browser/ui/webui/net_internals_ui_browsertest.cc » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698