Disable view source for Developer Tools.
[chromium-blink-merge.git] / chrome / test / chromedriver / server / http_handler.cc
blob3c2ef724540f29175777414054dd07088e0f335c
1 // Copyright (c) 2013 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 "chrome/test/chromedriver/server/http_handler.h"
7 #include "base/bind.h"
8 #include "base/callback.h"
9 #include "base/json/json_reader.h"
10 #include "base/json/json_writer.h"
11 #include "base/logging.h" // For CHECK macros.
12 #include "base/memory/scoped_ptr.h"
13 #include "base/message_loop/message_loop.h"
14 #include "base/message_loop/message_loop_proxy.h"
15 #include "base/strings/string_split.h"
16 #include "base/strings/string_util.h"
17 #include "base/strings/stringprintf.h"
18 #include "base/sys_info.h"
19 #include "base/values.h"
20 #include "chrome/test/chromedriver/alert_commands.h"
21 #include "chrome/test/chromedriver/chrome/adb_impl.h"
22 #include "chrome/test/chromedriver/chrome/device_manager.h"
23 #include "chrome/test/chromedriver/chrome/status.h"
24 #include "chrome/test/chromedriver/net/port_server.h"
25 #include "chrome/test/chromedriver/net/url_request_context_getter.h"
26 #include "chrome/test/chromedriver/session.h"
27 #include "chrome/test/chromedriver/session_thread_map.h"
28 #include "chrome/test/chromedriver/util.h"
29 #include "chrome/test/chromedriver/version.h"
30 #include "net/server/http_server_request_info.h"
31 #include "net/server/http_server_response_info.h"
33 #if defined(OS_MACOSX)
34 #include "base/mac/scoped_nsautorelease_pool.h"
35 #endif
37 namespace {
39 const char kLocalStorage[] = "localStorage";
40 const char kSessionStorage[] = "sessionStorage";
41 const char kShutdownPath[] = "shutdown";
43 void UnimplementedCommand(
44 const base::DictionaryValue& params,
45 const std::string& session_id,
46 const CommandCallback& callback) {
47 callback.Run(Status(kUnknownCommand), scoped_ptr<base::Value>(), session_id);
50 } // namespace
52 CommandMapping::CommandMapping(HttpMethod method,
53 const std::string& path_pattern,
54 const Command& command)
55 : method(method), path_pattern(path_pattern), command(command) {}
57 CommandMapping::~CommandMapping() {}
59 HttpHandler::HttpHandler(const std::string& url_base)
60 : url_base_(url_base),
61 received_shutdown_(false),
62 command_map_(new CommandMap()),
63 weak_ptr_factory_(this) {}
65 HttpHandler::HttpHandler(
66 const base::Closure& quit_func,
67 const scoped_refptr<base::SingleThreadTaskRunner> io_task_runner,
68 const std::string& url_base,
69 int adb_port,
70 scoped_ptr<PortServer> port_server)
71 : quit_func_(quit_func),
72 url_base_(url_base),
73 received_shutdown_(false),
74 weak_ptr_factory_(this) {
75 #if defined(OS_MACOSX)
76 base::mac::ScopedNSAutoreleasePool autorelease_pool;
77 #endif
78 context_getter_ = new URLRequestContextGetter(io_task_runner);
79 socket_factory_ = CreateSyncWebSocketFactory(context_getter_.get());
80 adb_.reset(new AdbImpl(io_task_runner, adb_port));
81 device_manager_.reset(new DeviceManager(adb_.get()));
82 port_server_ = port_server.Pass();
83 port_manager_.reset(new PortManager(12000, 13000));
85 CommandMapping commands[] = {
86 CommandMapping(
87 kPost,
88 internal::kNewSessionPathPattern,
89 base::Bind(&ExecuteCreateSession,
90 &session_thread_map_,
91 WrapToCommand(
92 "InitSession",
93 base::Bind(&ExecuteInitSession,
94 InitSessionParams(context_getter_,
95 socket_factory_,
96 device_manager_.get(),
97 port_server_.get(),
98 port_manager_.get()))))),
99 CommandMapping(kGet,
100 "session/:sessionId",
101 WrapToCommand("GetSessionCapabilities",
102 base::Bind(&ExecuteGetSessionCapabilities))),
103 CommandMapping(kDelete,
104 "session/:sessionId",
105 base::Bind(&ExecuteSessionCommand,
106 &session_thread_map_,
107 "Quit",
108 base::Bind(&ExecuteQuit, false),
109 true)),
110 CommandMapping(kGet,
111 "session/:sessionId/window_handle",
112 WrapToCommand("GetWindow",
113 base::Bind(&ExecuteGetCurrentWindowHandle))),
114 CommandMapping(
115 kGet,
116 "session/:sessionId/window_handles",
117 WrapToCommand("GetWindows", base::Bind(&ExecuteGetWindowHandles))),
118 CommandMapping(kPost,
119 "session/:sessionId/url",
120 WrapToCommand("Navigate", base::Bind(&ExecuteGet))),
121 CommandMapping(kPost,
122 "session/:sessionId/chromium/launch_app",
123 WrapToCommand("LaunchApp", base::Bind(&ExecuteLaunchApp))),
124 CommandMapping(kGet,
125 "session/:sessionId/alert",
126 WrapToCommand("IsAlertOpen",
127 base::Bind(&ExecuteAlertCommand,
128 base::Bind(&ExecuteGetAlert)))),
129 CommandMapping(
130 kPost,
131 "session/:sessionId/dismiss_alert",
132 WrapToCommand("DismissAlert",
133 base::Bind(&ExecuteAlertCommand,
134 base::Bind(&ExecuteDismissAlert)))),
135 CommandMapping(
136 kPost,
137 "session/:sessionId/accept_alert",
138 WrapToCommand("AcceptAlert",
139 base::Bind(&ExecuteAlertCommand,
140 base::Bind(&ExecuteAcceptAlert)))),
141 CommandMapping(
142 kGet,
143 "session/:sessionId/alert_text",
144 WrapToCommand("GetAlertMessage",
145 base::Bind(&ExecuteAlertCommand,
146 base::Bind(&ExecuteGetAlertText)))),
147 CommandMapping(
148 kPost,
149 "session/:sessionId/alert_text",
150 WrapToCommand("SetAlertPrompt",
151 base::Bind(&ExecuteAlertCommand,
152 base::Bind(&ExecuteSetAlertValue)))),
153 CommandMapping(kPost,
154 "session/:sessionId/forward",
155 WrapToCommand("GoForward", base::Bind(&ExecuteGoForward))),
156 CommandMapping(kPost,
157 "session/:sessionId/back",
158 WrapToCommand("GoBack", base::Bind(&ExecuteGoBack))),
159 CommandMapping(kPost,
160 "session/:sessionId/refresh",
161 WrapToCommand("Refresh", base::Bind(&ExecuteRefresh))),
162 CommandMapping(
163 kPost,
164 "session/:sessionId/execute",
165 WrapToCommand("ExecuteScript", base::Bind(&ExecuteExecuteScript))),
166 CommandMapping(kPost,
167 "session/:sessionId/execute_async",
168 WrapToCommand("ExecuteAsyncScript",
169 base::Bind(&ExecuteExecuteAsyncScript))),
170 CommandMapping(
171 kGet,
172 "session/:sessionId/url",
173 WrapToCommand("GetUrl", base::Bind(&ExecuteGetCurrentUrl))),
174 CommandMapping(kGet,
175 "session/:sessionId/title",
176 WrapToCommand("GetTitle", base::Bind(&ExecuteGetTitle))),
177 CommandMapping(
178 kGet,
179 "session/:sessionId/source",
180 WrapToCommand("GetSource", base::Bind(&ExecuteGetPageSource))),
181 CommandMapping(
182 kGet,
183 "session/:sessionId/screenshot",
184 WrapToCommand("Screenshot", base::Bind(&ExecuteScreenshot))),
185 CommandMapping(
186 kGet,
187 "session/:sessionId/chromium/heap_snapshot",
188 WrapToCommand("HeapSnapshot", base::Bind(&ExecuteTakeHeapSnapshot))),
189 CommandMapping(kPost,
190 "session/:sessionId/visible",
191 base::Bind(&UnimplementedCommand)),
192 CommandMapping(kGet,
193 "session/:sessionId/visible",
194 base::Bind(&UnimplementedCommand)),
195 CommandMapping(
196 kPost,
197 "session/:sessionId/element",
198 WrapToCommand("FindElement", base::Bind(&ExecuteFindElement, 50))),
199 CommandMapping(
200 kPost,
201 "session/:sessionId/elements",
202 WrapToCommand("FindElements", base::Bind(&ExecuteFindElements, 50))),
203 CommandMapping(kPost,
204 "session/:sessionId/element/active",
205 WrapToCommand("GetActiveElement",
206 base::Bind(&ExecuteGetActiveElement))),
207 CommandMapping(kPost,
208 "session/:sessionId/element/:id/element",
209 WrapToCommand("FindChildElement",
210 base::Bind(&ExecuteFindChildElement, 50))),
211 CommandMapping(kPost,
212 "session/:sessionId/element/:id/elements",
213 WrapToCommand("FindChildElements",
214 base::Bind(&ExecuteFindChildElements, 50))),
215 CommandMapping(
216 kPost,
217 "session/:sessionId/element/:id/click",
218 WrapToCommand("ClickElement", base::Bind(&ExecuteClickElement))),
219 CommandMapping(
220 kPost,
221 "session/:sessionId/element/:id/clear",
222 WrapToCommand("ClearElement", base::Bind(&ExecuteClearElement))),
223 CommandMapping(
224 kPost,
225 "session/:sessionId/element/:id/submit",
226 WrapToCommand("SubmitElement", base::Bind(&ExecuteSubmitElement))),
227 CommandMapping(
228 kGet,
229 "session/:sessionId/element/:id/text",
230 WrapToCommand("GetElementText", base::Bind(&ExecuteGetElementText))),
231 CommandMapping(
232 kPost,
233 "session/:sessionId/element/:id/value",
234 WrapToCommand("TypeElement", base::Bind(&ExecuteSendKeysToElement))),
235 CommandMapping(
236 kPost,
237 "session/:sessionId/file",
238 WrapToCommand("UploadFile", base::Bind(&ExecuteUploadFile))),
239 CommandMapping(kGet,
240 "session/:sessionId/element/:id/value",
241 WrapToCommand("GetElementValue",
242 base::Bind(&ExecuteGetElementValue))),
243 CommandMapping(kGet,
244 "session/:sessionId/element/:id/name",
245 WrapToCommand("GetElementTagName",
246 base::Bind(&ExecuteGetElementTagName))),
247 CommandMapping(kGet,
248 "session/:sessionId/element/:id/selected",
249 WrapToCommand("IsElementSelected",
250 base::Bind(&ExecuteIsElementSelected))),
251 CommandMapping(kGet,
252 "session/:sessionId/element/:id/enabled",
253 WrapToCommand("IsElementEnabled",
254 base::Bind(&ExecuteIsElementEnabled))),
255 CommandMapping(kGet,
256 "session/:sessionId/element/:id/displayed",
257 WrapToCommand("IsElementDisplayed",
258 base::Bind(&ExecuteIsElementDisplayed))),
259 CommandMapping(
260 kPost,
261 "session/:sessionId/element/:id/hover",
262 WrapToCommand("HoverElement", base::Bind(&ExecuteHoverOverElement))),
263 CommandMapping(kGet,
264 "session/:sessionId/element/:id/location",
265 WrapToCommand("GetElementLocation",
266 base::Bind(&ExecuteGetElementLocation))),
267 CommandMapping(
268 kGet,
269 "session/:sessionId/element/:id/location_in_view",
270 WrapToCommand(
271 "GetElementLocationInView",
272 base::Bind(&ExecuteGetElementLocationOnceScrolledIntoView))),
273 CommandMapping(
274 kGet,
275 "session/:sessionId/element/:id/size",
276 WrapToCommand("GetElementSize", base::Bind(&ExecuteGetElementSize))),
277 CommandMapping(kGet,
278 "session/:sessionId/element/:id/attribute/:name",
279 WrapToCommand("GetElementAttribute",
280 base::Bind(&ExecuteGetElementAttribute))),
281 CommandMapping(
282 kGet,
283 "session/:sessionId/element/:id/equals/:other",
284 WrapToCommand("IsElementEqual", base::Bind(&ExecuteElementEquals))),
285 CommandMapping(
286 kGet,
287 "session/:sessionId/cookie",
288 WrapToCommand("GetCookies", base::Bind(&ExecuteGetCookies))),
289 CommandMapping(kPost,
290 "session/:sessionId/cookie",
291 WrapToCommand("AddCookie", base::Bind(&ExecuteAddCookie))),
292 CommandMapping(kDelete,
293 "session/:sessionId/cookie",
294 WrapToCommand("DeleteAllCookies",
295 base::Bind(&ExecuteDeleteAllCookies))),
296 CommandMapping(
297 kDelete,
298 "session/:sessionId/cookie/:name",
299 WrapToCommand("DeleteCookie", base::Bind(&ExecuteDeleteCookie))),
300 CommandMapping(
301 kPost,
302 "session/:sessionId/frame",
303 WrapToCommand("SwitchToFrame", base::Bind(&ExecuteSwitchToFrame))),
304 CommandMapping(
305 kPost,
306 "session/:sessionId/window",
307 WrapToCommand("SwitchToWindow", base::Bind(&ExecuteSwitchToWindow))),
308 CommandMapping(
309 kGet,
310 "session/:sessionId/window/:windowHandle/size",
311 WrapToCommand("GetWindowSize", base::Bind(&ExecuteGetWindowSize))),
312 CommandMapping(kGet,
313 "session/:sessionId/window/:windowHandle/position",
314 WrapToCommand("GetWindowPosition",
315 base::Bind(&ExecuteGetWindowPosition))),
316 CommandMapping(
317 kPost,
318 "session/:sessionId/window/:windowHandle/size",
319 WrapToCommand("SetWindowSize", base::Bind(&ExecuteSetWindowSize))),
320 CommandMapping(kPost,
321 "session/:sessionId/window/:windowHandle/position",
322 WrapToCommand("SetWindowPosition",
323 base::Bind(&ExecuteSetWindowPosition))),
324 CommandMapping(
325 kPost,
326 "session/:sessionId/window/:windowHandle/maximize",
327 WrapToCommand("MaximizeWindow", base::Bind(&ExecuteMaximizeWindow))),
328 CommandMapping(kDelete,
329 "session/:sessionId/window",
330 WrapToCommand("CloseWindow", base::Bind(&ExecuteClose))),
331 CommandMapping(kPost,
332 "session/:sessionId/element/:id/drag",
333 base::Bind(&UnimplementedCommand)),
334 CommandMapping(
335 kGet,
336 "session/:sessionId/element/:id/css/:propertyName",
337 WrapToCommand("GetElementCSSProperty",
338 base::Bind(&ExecuteGetElementValueOfCSSProperty))),
339 CommandMapping(
340 kPost,
341 "session/:sessionId/timeouts/implicit_wait",
342 WrapToCommand("SetImplicitWait", base::Bind(&ExecuteImplicitlyWait))),
343 CommandMapping(kPost,
344 "session/:sessionId/timeouts/async_script",
345 WrapToCommand("SetScriptTimeout",
346 base::Bind(&ExecuteSetScriptTimeout))),
347 CommandMapping(
348 kPost,
349 "session/:sessionId/timeouts",
350 WrapToCommand("SetTimeout", base::Bind(&ExecuteSetTimeout))),
351 CommandMapping(kPost,
352 "session/:sessionId/execute_sql",
353 base::Bind(&UnimplementedCommand)),
354 CommandMapping(
355 kGet,
356 "session/:sessionId/location",
357 WrapToCommand("GetGeolocation", base::Bind(&ExecuteGetLocation))),
358 CommandMapping(
359 kPost,
360 "session/:sessionId/location",
361 WrapToCommand("SetGeolocation", base::Bind(&ExecuteSetLocation))),
362 CommandMapping(kGet,
363 "session/:sessionId/application_cache/status",
364 base::Bind(&ExecuteGetStatus)),
365 CommandMapping(kGet,
366 "session/:sessionId/browser_connection",
367 base::Bind(&UnimplementedCommand)),
368 CommandMapping(kPost,
369 "session/:sessionId/browser_connection",
370 base::Bind(&UnimplementedCommand)),
371 CommandMapping(
372 kGet,
373 "session/:sessionId/local_storage/key/:key",
374 WrapToCommand("GetLocalStorageItem",
375 base::Bind(&ExecuteGetStorageItem, kLocalStorage))),
376 CommandMapping(
377 kDelete,
378 "session/:sessionId/local_storage/key/:key",
379 WrapToCommand("RemoveLocalStorageItem",
380 base::Bind(&ExecuteRemoveStorageItem, kLocalStorage))),
381 CommandMapping(
382 kGet,
383 "session/:sessionId/local_storage",
384 WrapToCommand("GetLocalStorageKeys",
385 base::Bind(&ExecuteGetStorageKeys, kLocalStorage))),
386 CommandMapping(
387 kPost,
388 "session/:sessionId/local_storage",
389 WrapToCommand("SetLocalStorageKeys",
390 base::Bind(&ExecuteSetStorageItem, kLocalStorage))),
391 CommandMapping(
392 kDelete,
393 "session/:sessionId/local_storage",
394 WrapToCommand("ClearLocalStorage",
395 base::Bind(&ExecuteClearStorage, kLocalStorage))),
396 CommandMapping(
397 kGet,
398 "session/:sessionId/local_storage/size",
399 WrapToCommand("GetLocalStorageSize",
400 base::Bind(&ExecuteGetStorageSize, kLocalStorage))),
401 CommandMapping(
402 kGet,
403 "session/:sessionId/session_storage/key/:key",
404 WrapToCommand("GetSessionStorageItem",
405 base::Bind(&ExecuteGetStorageItem, kSessionStorage))),
406 CommandMapping(kDelete,
407 "session/:sessionId/session_storage/key/:key",
408 WrapToCommand("RemoveSessionStorageItem",
409 base::Bind(&ExecuteRemoveStorageItem,
410 kSessionStorage))),
411 CommandMapping(
412 kGet,
413 "session/:sessionId/session_storage",
414 WrapToCommand("GetSessionStorageKeys",
415 base::Bind(&ExecuteGetStorageKeys, kSessionStorage))),
416 CommandMapping(
417 kPost,
418 "session/:sessionId/session_storage",
419 WrapToCommand("SetSessionStorageItem",
420 base::Bind(&ExecuteSetStorageItem, kSessionStorage))),
421 CommandMapping(
422 kDelete,
423 "session/:sessionId/session_storage",
424 WrapToCommand("ClearSessionStorage",
425 base::Bind(&ExecuteClearStorage, kSessionStorage))),
426 CommandMapping(
427 kGet,
428 "session/:sessionId/session_storage/size",
429 WrapToCommand("GetSessionStorageSize",
430 base::Bind(&ExecuteGetStorageSize, kSessionStorage))),
431 CommandMapping(kGet,
432 "session/:sessionId/orientation",
433 base::Bind(&UnimplementedCommand)),
434 CommandMapping(kPost,
435 "session/:sessionId/orientation",
436 base::Bind(&UnimplementedCommand)),
437 CommandMapping(kPost,
438 "session/:sessionId/click",
439 WrapToCommand("Click", base::Bind(&ExecuteMouseClick))),
440 CommandMapping(
441 kPost,
442 "session/:sessionId/doubleclick",
443 WrapToCommand("DoubleClick", base::Bind(&ExecuteMouseDoubleClick))),
444 CommandMapping(
445 kPost,
446 "session/:sessionId/buttondown",
447 WrapToCommand("MouseDown", base::Bind(&ExecuteMouseButtonDown))),
448 CommandMapping(
449 kPost,
450 "session/:sessionId/buttonup",
451 WrapToCommand("MouseUp", base::Bind(&ExecuteMouseButtonUp))),
452 CommandMapping(
453 kPost,
454 "session/:sessionId/moveto",
455 WrapToCommand("MouseMove", base::Bind(&ExecuteMouseMoveTo))),
456 CommandMapping(
457 kPost,
458 "session/:sessionId/keys",
459 WrapToCommand("Type", base::Bind(&ExecuteSendKeysToActiveElement))),
460 CommandMapping(kGet,
461 "session/:sessionId/ime/available_engines",
462 base::Bind(&UnimplementedCommand)),
463 CommandMapping(kGet,
464 "session/:sessionId/ime/active_engine",
465 base::Bind(&UnimplementedCommand)),
466 CommandMapping(kGet,
467 "session/:sessionId/ime/activated",
468 base::Bind(&UnimplementedCommand)),
469 CommandMapping(kPost,
470 "session/:sessionId/ime/deactivate",
471 base::Bind(&UnimplementedCommand)),
472 CommandMapping(kPost,
473 "session/:sessionId/ime/activate",
474 base::Bind(&UnimplementedCommand)),
475 CommandMapping(kPost,
476 "session/:sessionId/touch/click",
477 WrapToCommand("Tap", base::Bind(&ExecuteTouchSingleTap))),
478 CommandMapping(kPost,
479 "session/:sessionId/touch/down",
480 WrapToCommand("TouchDown", base::Bind(&ExecuteTouchDown))),
481 CommandMapping(kPost,
482 "session/:sessionId/touch/up",
483 WrapToCommand("TouchUp", base::Bind(&ExecuteTouchUp))),
484 CommandMapping(kPost,
485 "session/:sessionId/touch/move",
486 WrapToCommand("TouchMove", base::Bind(&ExecuteTouchMove))),
487 CommandMapping(kPost,
488 "session/:sessionId/touch/scroll",
489 base::Bind(&UnimplementedCommand)),
490 CommandMapping(kPost,
491 "session/:sessionId/touch/doubleclick",
492 base::Bind(&UnimplementedCommand)),
493 CommandMapping(kPost,
494 "session/:sessionId/touch/longclick",
495 base::Bind(&UnimplementedCommand)),
496 CommandMapping(kPost,
497 "session/:sessionId/touch/flick",
498 base::Bind(&UnimplementedCommand)),
499 CommandMapping(kPost,
500 "session/:sessionId/log",
501 WrapToCommand("GetLog", base::Bind(&ExecuteGetLog))),
502 CommandMapping(kGet,
503 "session/:sessionId/log/types",
504 WrapToCommand("GetLogTypes",
505 base::Bind(&ExecuteGetAvailableLogTypes))),
506 CommandMapping(kPost, "logs", base::Bind(&UnimplementedCommand)),
507 CommandMapping(kGet, "status", base::Bind(&ExecuteGetStatus)),
509 // Custom Chrome commands:
510 // Allow quit all to be called with GET or POST.
511 CommandMapping(
512 kGet,
513 kShutdownPath,
514 base::Bind(&ExecuteQuitAll,
515 WrapToCommand("QuitAll", base::Bind(&ExecuteQuit, true)),
516 &session_thread_map_)),
517 CommandMapping(
518 kPost,
519 kShutdownPath,
520 base::Bind(&ExecuteQuitAll,
521 WrapToCommand("QuitAll", base::Bind(&ExecuteQuit, true)),
522 &session_thread_map_)),
523 CommandMapping(kGet,
524 "session/:sessionId/is_loading",
525 WrapToCommand("IsLoading", base::Bind(&ExecuteIsLoading))),
526 CommandMapping(kGet,
527 "session/:sessionId/autoreport",
528 WrapToCommand("IsAutoReporting",
529 base::Bind(&ExecuteIsAutoReporting))),
530 CommandMapping(kPost,
531 "session/:sessionId/autoreport",
532 WrapToCommand(
533 "SetAutoReporting",
534 base::Bind(&ExecuteSetAutoReporting))),
536 command_map_.reset(
537 new CommandMap(commands, commands + arraysize(commands)));
540 HttpHandler::~HttpHandler() {}
542 void HttpHandler::Handle(const net::HttpServerRequestInfo& request,
543 const HttpResponseSenderFunc& send_response_func) {
544 CHECK(thread_checker_.CalledOnValidThread());
546 if (received_shutdown_)
547 return;
549 std::string path = request.path;
550 if (!StartsWithASCII(path, url_base_, true)) {
551 scoped_ptr<net::HttpServerResponseInfo> response(
552 new net::HttpServerResponseInfo(net::HTTP_BAD_REQUEST));
553 response->SetBody("unhandled request", "text/plain");
554 send_response_func.Run(response.Pass());
555 return;
558 path.erase(0, url_base_.length());
560 HandleCommand(request, path, send_response_func);
562 if (path == kShutdownPath)
563 received_shutdown_ = true;
566 Command HttpHandler::WrapToCommand(
567 const char* name,
568 const SessionCommand& session_command) {
569 return base::Bind(&ExecuteSessionCommand,
570 &session_thread_map_,
571 name,
572 session_command,
573 false);
576 Command HttpHandler::WrapToCommand(
577 const char* name,
578 const WindowCommand& window_command) {
579 return WrapToCommand(name, base::Bind(&ExecuteWindowCommand, window_command));
582 Command HttpHandler::WrapToCommand(
583 const char* name,
584 const ElementCommand& element_command) {
585 return WrapToCommand(name,
586 base::Bind(&ExecuteElementCommand, element_command));
589 void HttpHandler::HandleCommand(
590 const net::HttpServerRequestInfo& request,
591 const std::string& trimmed_path,
592 const HttpResponseSenderFunc& send_response_func) {
593 base::DictionaryValue params;
594 std::string session_id;
595 CommandMap::const_iterator iter = command_map_->begin();
596 while (true) {
597 if (iter == command_map_->end()) {
598 scoped_ptr<net::HttpServerResponseInfo> response(
599 new net::HttpServerResponseInfo(net::HTTP_NOT_FOUND));
600 response->SetBody("unknown command: " + trimmed_path, "text/plain");
601 send_response_func.Run(response.Pass());
602 return;
604 if (internal::MatchesCommand(
605 request.method, trimmed_path, *iter, &session_id, &params)) {
606 break;
608 ++iter;
611 if (request.data.length()) {
612 base::DictionaryValue* body_params;
613 scoped_ptr<base::Value> parsed_body(base::JSONReader::Read(request.data));
614 if (!parsed_body || !parsed_body->GetAsDictionary(&body_params)) {
615 scoped_ptr<net::HttpServerResponseInfo> response(
616 new net::HttpServerResponseInfo(net::HTTP_BAD_REQUEST));
617 response->SetBody("missing command parameters", "test/plain");
618 send_response_func.Run(response.Pass());
619 return;
621 params.MergeDictionary(body_params);
624 iter->command.Run(params,
625 session_id,
626 base::Bind(&HttpHandler::PrepareResponse,
627 weak_ptr_factory_.GetWeakPtr(),
628 trimmed_path,
629 send_response_func));
632 void HttpHandler::PrepareResponse(
633 const std::string& trimmed_path,
634 const HttpResponseSenderFunc& send_response_func,
635 const Status& status,
636 scoped_ptr<base::Value> value,
637 const std::string& session_id) {
638 CHECK(thread_checker_.CalledOnValidThread());
639 scoped_ptr<net::HttpServerResponseInfo> response =
640 PrepareResponseHelper(trimmed_path, status, value.Pass(), session_id);
641 send_response_func.Run(response.Pass());
642 if (trimmed_path == kShutdownPath)
643 quit_func_.Run();
646 scoped_ptr<net::HttpServerResponseInfo> HttpHandler::PrepareResponseHelper(
647 const std::string& trimmed_path,
648 const Status& status,
649 scoped_ptr<base::Value> value,
650 const std::string& session_id) {
651 if (status.code() == kUnknownCommand) {
652 scoped_ptr<net::HttpServerResponseInfo> response(
653 new net::HttpServerResponseInfo(net::HTTP_NOT_IMPLEMENTED));
654 response->SetBody("unimplemented command: " + trimmed_path, "text/plain");
655 return response.Pass();
658 if (status.IsError()) {
659 Status full_status(status);
660 full_status.AddDetails(base::StringPrintf(
661 "Driver info: chromedriver=%s,platform=%s %s %s",
662 kChromeDriverVersion,
663 base::SysInfo::OperatingSystemName().c_str(),
664 base::SysInfo::OperatingSystemVersion().c_str(),
665 base::SysInfo::OperatingSystemArchitecture().c_str()));
666 scoped_ptr<base::DictionaryValue> error(new base::DictionaryValue());
667 error->SetString("message", full_status.message());
668 value.reset(error.release());
670 if (!value)
671 value.reset(base::Value::CreateNullValue());
673 base::DictionaryValue body_params;
674 body_params.SetInteger("status", status.code());
675 body_params.Set("value", value.release());
676 body_params.SetString("sessionId", session_id);
677 std::string body;
678 base::JSONWriter::WriteWithOptions(
679 &body_params, base::JSONWriter::OPTIONS_OMIT_DOUBLE_TYPE_PRESERVATION,
680 &body);
681 scoped_ptr<net::HttpServerResponseInfo> response(
682 new net::HttpServerResponseInfo(net::HTTP_OK));
683 response->SetBody(body, "application/json; charset=utf-8");
684 return response.Pass();
687 namespace internal {
689 const char kNewSessionPathPattern[] = "session";
691 bool MatchesMethod(HttpMethod command_method, const std::string& method) {
692 std::string lower_method = StringToLowerASCII(method);
693 switch (command_method) {
694 case kGet:
695 return lower_method == "get";
696 case kPost:
697 return lower_method == "post" || lower_method == "put";
698 case kDelete:
699 return lower_method == "delete";
701 return false;
704 bool MatchesCommand(const std::string& method,
705 const std::string& path,
706 const CommandMapping& command,
707 std::string* session_id,
708 base::DictionaryValue* out_params) {
709 if (!MatchesMethod(command.method, method))
710 return false;
712 std::vector<std::string> path_parts;
713 base::SplitString(path, '/', &path_parts);
714 std::vector<std::string> command_path_parts;
715 base::SplitString(command.path_pattern, '/', &command_path_parts);
716 if (path_parts.size() != command_path_parts.size())
717 return false;
719 base::DictionaryValue params;
720 for (size_t i = 0; i < path_parts.size(); ++i) {
721 CHECK(command_path_parts[i].length());
722 if (command_path_parts[i][0] == ':') {
723 std::string name = command_path_parts[i];
724 name.erase(0, 1);
725 CHECK(name.length());
726 if (name == "sessionId")
727 *session_id = path_parts[i];
728 else
729 params.SetString(name, path_parts[i]);
730 } else if (command_path_parts[i] != path_parts[i]) {
731 return false;
734 out_params->MergeDictionary(&params);
735 return true;
738 } // namespace internal