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.
4
5 #include "chrome/test/chromedriver/capabilities.h"
6
7 #include <map>
8
9 #include "base/bind.h"
10 #include "base/callback.h"
11 #include "base/json/string_escape.h"
12 #include "base/logging.h"
13 #include "base/strings/string_number_conversions.h"
14 #include "base/strings/string_split.h"
15 #include "base/strings/string_tokenizer.h"
16 #include "base/strings/string_util.h"
17 #include "base/strings/stringprintf.h"
18 #include "base/strings/utf_string_conversions.h"
19 #include "base/values.h"
20 #include "chrome/test/chromedriver/chrome/mobile_device.h"
21 #include "chrome/test/chromedriver/chrome/status.h"
22 #include "chrome/test/chromedriver/logging.h"
23 #include "net/base/net_util.h"
24
25 namespace {
26
27 typedef base::Callback<Status(const base::Value&, Capabilities*)> Parser;
28
ParseBoolean(bool * to_set,const base::Value & option,Capabilities * capabilities)29 Status ParseBoolean(
30 bool* to_set,
31 const base::Value& option,
32 Capabilities* capabilities) {
33 if (!option.GetAsBoolean(to_set))
34 return Status(kUnknownError, "must be a boolean");
35 return Status(kOk);
36 }
37
ParseString(std::string * to_set,const base::Value & option,Capabilities * capabilities)38 Status ParseString(std::string* to_set,
39 const base::Value& option,
40 Capabilities* capabilities) {
41 std::string str;
42 if (!option.GetAsString(&str))
43 return Status(kUnknownError, "must be a string");
44 if (str.empty())
45 return Status(kUnknownError, "cannot be empty");
46 *to_set = str;
47 return Status(kOk);
48 }
49
ParseFilePath(base::FilePath * to_set,const base::Value & option,Capabilities * capabilities)50 Status ParseFilePath(base::FilePath* to_set,
51 const base::Value& option,
52 Capabilities* capabilities) {
53 base::FilePath::StringType str;
54 if (!option.GetAsString(&str))
55 return Status(kUnknownError, "must be a string");
56 *to_set = base::FilePath(str);
57 return Status(kOk);
58 }
59
ParseDict(scoped_ptr<base::DictionaryValue> * to_set,const base::Value & option,Capabilities * capabilities)60 Status ParseDict(scoped_ptr<base::DictionaryValue>* to_set,
61 const base::Value& option,
62 Capabilities* capabilities) {
63 const base::DictionaryValue* dict = NULL;
64 if (!option.GetAsDictionary(&dict))
65 return Status(kUnknownError, "must be a dictionary");
66 to_set->reset(dict->DeepCopy());
67 return Status(kOk);
68 }
69
IgnoreDeprecatedOption(const char * option_name,const base::Value & option,Capabilities * capabilities)70 Status IgnoreDeprecatedOption(
71 const char* option_name,
72 const base::Value& option,
73 Capabilities* capabilities) {
74 LOG(WARNING) << "Deprecated chrome option is ignored: " << option_name;
75 return Status(kOk);
76 }
77
IgnoreCapability(const base::Value & option,Capabilities * capabilities)78 Status IgnoreCapability(const base::Value& option, Capabilities* capabilities) {
79 return Status(kOk);
80 }
81
ParseLogPath(const base::Value & option,Capabilities * capabilities)82 Status ParseLogPath(const base::Value& option, Capabilities* capabilities) {
83 if (!option.GetAsString(&capabilities->log_path))
84 return Status(kUnknownError, "must be a string");
85 return Status(kOk);
86 }
87
ParseDeviceName(std::string device_name,Capabilities * capabilities)88 Status ParseDeviceName(std::string device_name, Capabilities* capabilities) {
89 scoped_ptr<MobileDevice> device;
90 Status status = FindMobileDevice(device_name, &device);
91
92 if (status.IsError()) {
93 return Status(kUnknownError,
94 "'" + device_name + "' must be a valid device",
95 status);
96 }
97
98 capabilities->device_metrics.reset(device->device_metrics.release());
99 capabilities->switches.SetSwitch("user-agent", device->user_agent);
100
101 return Status(kOk);
102 }
103
ParseMobileEmulation(const base::Value & option,Capabilities * capabilities)104 Status ParseMobileEmulation(const base::Value& option,
105 Capabilities* capabilities) {
106 const base::DictionaryValue* mobile_emulation;
107 if (!option.GetAsDictionary(&mobile_emulation))
108 return Status(kUnknownError, "'mobileEmulation' must be a dictionary");
109
110 if (mobile_emulation->HasKey("deviceName")) {
111 // Cannot use any other options with deviceName.
112 if (mobile_emulation->size() > 1)
113 return Status(kUnknownError, "'deviceName' must be used alone");
114
115 std::string device_name;
116 if (!mobile_emulation->GetString("deviceName", &device_name))
117 return Status(kUnknownError, "'deviceName' must be a string");
118
119 return ParseDeviceName(device_name, capabilities);
120 }
121
122 if (mobile_emulation->HasKey("deviceMetrics")) {
123 const base::DictionaryValue* metrics;
124 if (!mobile_emulation->GetDictionary("deviceMetrics", &metrics))
125 return Status(kUnknownError, "'deviceMetrics' must be a dictionary");
126
127 int width;
128 int height;
129 double device_scale_factor;
130 if (!metrics->GetInteger("width", &width) ||
131 !metrics->GetInteger("height", &height) ||
132 !metrics->GetDouble("pixelRatio", &device_scale_factor))
133 return Status(kUnknownError, "invalid 'deviceMetrics'");
134
135 DeviceMetrics* device_metrics =
136 new DeviceMetrics(width, height, device_scale_factor);
137 capabilities->device_metrics =
138 scoped_ptr<DeviceMetrics>(device_metrics);
139 }
140
141 if (mobile_emulation->HasKey("userAgent")) {
142 std::string user_agent;
143 if (!mobile_emulation->GetString("userAgent", &user_agent))
144 return Status(kUnknownError, "'userAgent' must be a string");
145
146 capabilities->switches.SetSwitch("user-agent", user_agent);
147 }
148
149 return Status(kOk);
150 }
151
ParseSwitches(const base::Value & option,Capabilities * capabilities)152 Status ParseSwitches(const base::Value& option,
153 Capabilities* capabilities) {
154 const base::ListValue* switches_list = NULL;
155 if (!option.GetAsList(&switches_list))
156 return Status(kUnknownError, "must be a list");
157 for (size_t i = 0; i < switches_list->GetSize(); ++i) {
158 std::string arg_string;
159 if (!switches_list->GetString(i, &arg_string))
160 return Status(kUnknownError, "each argument must be a string");
161 capabilities->switches.SetUnparsedSwitch(arg_string);
162 }
163 return Status(kOk);
164 }
165
ParseExtensions(const base::Value & option,Capabilities * capabilities)166 Status ParseExtensions(const base::Value& option, Capabilities* capabilities) {
167 const base::ListValue* extensions = NULL;
168 if (!option.GetAsList(&extensions))
169 return Status(kUnknownError, "must be a list");
170 for (size_t i = 0; i < extensions->GetSize(); ++i) {
171 std::string extension;
172 if (!extensions->GetString(i, &extension)) {
173 return Status(kUnknownError,
174 "each extension must be a base64 encoded string");
175 }
176 capabilities->extensions.push_back(extension);
177 }
178 return Status(kOk);
179 }
180
ParseProxy(const base::Value & option,Capabilities * capabilities)181 Status ParseProxy(const base::Value& option, Capabilities* capabilities) {
182 const base::DictionaryValue* proxy_dict;
183 if (!option.GetAsDictionary(&proxy_dict))
184 return Status(kUnknownError, "must be a dictionary");
185 std::string proxy_type;
186 if (!proxy_dict->GetString("proxyType", &proxy_type))
187 return Status(kUnknownError, "'proxyType' must be a string");
188 proxy_type = StringToLowerASCII(proxy_type);
189 if (proxy_type == "direct") {
190 capabilities->switches.SetSwitch("no-proxy-server");
191 } else if (proxy_type == "system") {
192 // Chrome default.
193 } else if (proxy_type == "pac") {
194 CommandLine::StringType proxy_pac_url;
195 if (!proxy_dict->GetString("proxyAutoconfigUrl", &proxy_pac_url))
196 return Status(kUnknownError, "'proxyAutoconfigUrl' must be a string");
197 capabilities->switches.SetSwitch("proxy-pac-url", proxy_pac_url);
198 } else if (proxy_type == "autodetect") {
199 capabilities->switches.SetSwitch("proxy-auto-detect");
200 } else if (proxy_type == "manual") {
201 const char* proxy_servers_options[][2] = {
202 {"ftpProxy", "ftp"}, {"httpProxy", "http"}, {"sslProxy", "https"}};
203 const base::Value* option_value = NULL;
204 std::string proxy_servers;
205 for (size_t i = 0; i < arraysize(proxy_servers_options); ++i) {
206 if (!proxy_dict->Get(proxy_servers_options[i][0], &option_value) ||
207 option_value->IsType(base::Value::TYPE_NULL)) {
208 continue;
209 }
210 std::string value;
211 if (!option_value->GetAsString(&value)) {
212 return Status(
213 kUnknownError,
214 base::StringPrintf("'%s' must be a string",
215 proxy_servers_options[i][0]));
216 }
217 // Converts into Chrome proxy scheme.
218 // Example: "http=localhost:9000;ftp=localhost:8000".
219 if (!proxy_servers.empty())
220 proxy_servers += ";";
221 proxy_servers += base::StringPrintf(
222 "%s=%s", proxy_servers_options[i][1], value.c_str());
223 }
224
225 std::string proxy_bypass_list;
226 if (proxy_dict->Get("noProxy", &option_value) &&
227 !option_value->IsType(base::Value::TYPE_NULL)) {
228 if (!option_value->GetAsString(&proxy_bypass_list))
229 return Status(kUnknownError, "'noProxy' must be a string");
230 }
231
232 if (proxy_servers.empty() && proxy_bypass_list.empty()) {
233 return Status(kUnknownError,
234 "proxyType is 'manual' but no manual "
235 "proxy capabilities were found");
236 }
237 if (!proxy_servers.empty())
238 capabilities->switches.SetSwitch("proxy-server", proxy_servers);
239 if (!proxy_bypass_list.empty()) {
240 capabilities->switches.SetSwitch("proxy-bypass-list",
241 proxy_bypass_list);
242 }
243 } else {
244 return Status(kUnknownError, "unrecognized proxy type:" + proxy_type);
245 }
246 return Status(kOk);
247 }
248
ParseExcludeSwitches(const base::Value & option,Capabilities * capabilities)249 Status ParseExcludeSwitches(const base::Value& option,
250 Capabilities* capabilities) {
251 const base::ListValue* switches = NULL;
252 if (!option.GetAsList(&switches))
253 return Status(kUnknownError, "must be a list");
254 for (size_t i = 0; i < switches->GetSize(); ++i) {
255 std::string switch_name;
256 if (!switches->GetString(i, &switch_name)) {
257 return Status(kUnknownError,
258 "each switch to be removed must be a string");
259 }
260 capabilities->exclude_switches.insert(switch_name);
261 }
262 return Status(kOk);
263 }
264
ParseUseRemoteBrowser(const base::Value & option,Capabilities * capabilities)265 Status ParseUseRemoteBrowser(const base::Value& option,
266 Capabilities* capabilities) {
267 std::string server_addr;
268 if (!option.GetAsString(&server_addr))
269 return Status(kUnknownError, "must be 'host:port'");
270
271 std::vector<std::string> values;
272 base::SplitString(server_addr, ':', &values);
273 if (values.size() != 2)
274 return Status(kUnknownError, "must be 'host:port'");
275
276 int port = 0;
277 base::StringToInt(values[1], &port);
278 if (port <= 0)
279 return Status(kUnknownError, "port must be > 0");
280
281 capabilities->debugger_address = NetAddress(values[0], port);
282 return Status(kOk);
283 }
284
ParseLoggingPrefs(const base::Value & option,Capabilities * capabilities)285 Status ParseLoggingPrefs(const base::Value& option,
286 Capabilities* capabilities) {
287 const base::DictionaryValue* logging_prefs = NULL;
288 if (!option.GetAsDictionary(&logging_prefs))
289 return Status(kUnknownError, "must be a dictionary");
290
291 for (base::DictionaryValue::Iterator pref(*logging_prefs);
292 !pref.IsAtEnd(); pref.Advance()) {
293 std::string type = pref.key();
294 Log::Level level;
295 std::string level_name;
296 if (!pref.value().GetAsString(&level_name) ||
297 !WebDriverLog::NameToLevel(level_name, &level)) {
298 return Status(kUnknownError, "invalid log level for '" + type + "' log");
299 }
300 capabilities->logging_prefs.insert(std::make_pair(type, level));
301 }
302 return Status(kOk);
303 }
304
ParseChromeOptions(const base::Value & capability,Capabilities * capabilities)305 Status ParseChromeOptions(
306 const base::Value& capability,
307 Capabilities* capabilities) {
308 const base::DictionaryValue* chrome_options = NULL;
309 if (!capability.GetAsDictionary(&chrome_options))
310 return Status(kUnknownError, "must be a dictionary");
311
312 bool is_android = chrome_options->HasKey("androidPackage");
313 bool is_remote = chrome_options->HasKey("debuggerAddress");
314
315 std::map<std::string, Parser> parser_map;
316 // Ignore 'args', 'binary' and 'extensions' capabilities by default, since the
317 // Java client always passes them.
318 parser_map["args"] = base::Bind(&IgnoreCapability);
319 parser_map["binary"] = base::Bind(&IgnoreCapability);
320 parser_map["extensions"] = base::Bind(&IgnoreCapability);
321 if (is_android) {
322 parser_map["androidActivity"] =
323 base::Bind(&ParseString, &capabilities->android_activity);
324 parser_map["androidDeviceSerial"] =
325 base::Bind(&ParseString, &capabilities->android_device_serial);
326 parser_map["androidPackage"] =
327 base::Bind(&ParseString, &capabilities->android_package);
328 parser_map["androidProcess"] =
329 base::Bind(&ParseString, &capabilities->android_process);
330 parser_map["androidUseRunningApp"] =
331 base::Bind(&ParseBoolean, &capabilities->android_use_running_app);
332 parser_map["args"] = base::Bind(&ParseSwitches);
333 parser_map["loadAsync"] = base::Bind(&IgnoreDeprecatedOption, "loadAsync");
334 } else if (is_remote) {
335 parser_map["debuggerAddress"] = base::Bind(&ParseUseRemoteBrowser);
336 } else {
337 parser_map["args"] = base::Bind(&ParseSwitches);
338 parser_map["binary"] = base::Bind(&ParseFilePath, &capabilities->binary);
339 parser_map["detach"] = base::Bind(&ParseBoolean, &capabilities->detach);
340 parser_map["mobileEmulation"] = base::Bind(&ParseMobileEmulation);
341 parser_map["excludeSwitches"] = base::Bind(&ParseExcludeSwitches);
342 parser_map["extensions"] = base::Bind(&ParseExtensions);
343 parser_map["forceDevToolsScreenshot"] = base::Bind(
344 &ParseBoolean, &capabilities->force_devtools_screenshot);
345 parser_map["loadAsync"] = base::Bind(&IgnoreDeprecatedOption, "loadAsync");
346 parser_map["localState"] =
347 base::Bind(&ParseDict, &capabilities->local_state);
348 parser_map["logPath"] = base::Bind(&ParseLogPath);
349 parser_map["minidumpPath"] =
350 base::Bind(&ParseString, &capabilities->minidump_path);
351 parser_map["prefs"] = base::Bind(&ParseDict, &capabilities->prefs);
352 }
353
354 for (base::DictionaryValue::Iterator it(*chrome_options); !it.IsAtEnd();
355 it.Advance()) {
356 if (parser_map.find(it.key()) == parser_map.end()) {
357 return Status(kUnknownError,
358 "unrecognized chrome option: " + it.key());
359 }
360 Status status = parser_map[it.key()].Run(it.value(), capabilities);
361 if (status.IsError())
362 return Status(kUnknownError, "cannot parse " + it.key(), status);
363 }
364 return Status(kOk);
365 }
366
367 } // namespace
368
Switches()369 Switches::Switches() {}
370
~Switches()371 Switches::~Switches() {}
372
SetSwitch(const std::string & name)373 void Switches::SetSwitch(const std::string& name) {
374 SetSwitch(name, NativeString());
375 }
376
SetSwitch(const std::string & name,const std::string & value)377 void Switches::SetSwitch(const std::string& name, const std::string& value) {
378 #if defined(OS_WIN)
379 SetSwitch(name, base::UTF8ToUTF16(value));
380 #else
381 switch_map_[name] = value;
382 #endif
383 }
384
SetSwitch(const std::string & name,const base::string16 & value)385 void Switches::SetSwitch(const std::string& name, const base::string16& value) {
386 #if defined(OS_WIN)
387 switch_map_[name] = value;
388 #else
389 SetSwitch(name, base::UTF16ToUTF8(value));
390 #endif
391 }
392
SetSwitch(const std::string & name,const base::FilePath & value)393 void Switches::SetSwitch(const std::string& name, const base::FilePath& value) {
394 SetSwitch(name, value.value());
395 }
396
SetFromSwitches(const Switches & switches)397 void Switches::SetFromSwitches(const Switches& switches) {
398 for (SwitchMap::const_iterator iter = switches.switch_map_.begin();
399 iter != switches.switch_map_.end();
400 ++iter) {
401 switch_map_[iter->first] = iter->second;
402 }
403 }
404
SetUnparsedSwitch(const std::string & unparsed_switch)405 void Switches::SetUnparsedSwitch(const std::string& unparsed_switch) {
406 std::string value;
407 size_t equals_index = unparsed_switch.find('=');
408 if (equals_index != std::string::npos)
409 value = unparsed_switch.substr(equals_index + 1);
410
411 std::string name;
412 size_t start_index = 0;
413 if (unparsed_switch.substr(0, 2) == "--")
414 start_index = 2;
415 name = unparsed_switch.substr(start_index, equals_index - start_index);
416
417 SetSwitch(name, value);
418 }
419
RemoveSwitch(const std::string & name)420 void Switches::RemoveSwitch(const std::string& name) {
421 switch_map_.erase(name);
422 }
423
HasSwitch(const std::string & name) const424 bool Switches::HasSwitch(const std::string& name) const {
425 return switch_map_.count(name) > 0;
426 }
427
GetSwitchValue(const std::string & name) const428 std::string Switches::GetSwitchValue(const std::string& name) const {
429 NativeString value = GetSwitchValueNative(name);
430 #if defined(OS_WIN)
431 return base::UTF16ToUTF8(value);
432 #else
433 return value;
434 #endif
435 }
436
GetSwitchValueNative(const std::string & name) const437 Switches::NativeString Switches::GetSwitchValueNative(
438 const std::string& name) const {
439 SwitchMap::const_iterator iter = switch_map_.find(name);
440 if (iter == switch_map_.end())
441 return NativeString();
442 return iter->second;
443 }
444
GetSize() const445 size_t Switches::GetSize() const {
446 return switch_map_.size();
447 }
448
AppendToCommandLine(CommandLine * command) const449 void Switches::AppendToCommandLine(CommandLine* command) const {
450 for (SwitchMap::const_iterator iter = switch_map_.begin();
451 iter != switch_map_.end();
452 ++iter) {
453 command->AppendSwitchNative(iter->first, iter->second);
454 }
455 }
456
ToString() const457 std::string Switches::ToString() const {
458 std::string str;
459 SwitchMap::const_iterator iter = switch_map_.begin();
460 while (iter != switch_map_.end()) {
461 str += "--" + iter->first;
462 std::string value = GetSwitchValue(iter->first);
463 if (value.length()) {
464 if (value.find(' ') != std::string::npos)
465 value = base::GetQuotedJSONString(value);
466 str += "=" + value;
467 }
468 ++iter;
469 if (iter == switch_map_.end())
470 break;
471 str += " ";
472 }
473 return str;
474 }
475
Capabilities()476 Capabilities::Capabilities()
477 : android_use_running_app(false),
478 detach(false),
479 force_devtools_screenshot(false) {}
480
~Capabilities()481 Capabilities::~Capabilities() {}
482
IsAndroid() const483 bool Capabilities::IsAndroid() const {
484 return !android_package.empty();
485 }
486
IsRemoteBrowser() const487 bool Capabilities::IsRemoteBrowser() const {
488 return debugger_address.IsValid();
489 }
490
Parse(const base::DictionaryValue & desired_caps)491 Status Capabilities::Parse(const base::DictionaryValue& desired_caps) {
492 std::map<std::string, Parser> parser_map;
493 parser_map["chromeOptions"] = base::Bind(&ParseChromeOptions);
494 parser_map["loggingPrefs"] = base::Bind(&ParseLoggingPrefs);
495 parser_map["proxy"] = base::Bind(&ParseProxy);
496 for (std::map<std::string, Parser>::iterator it = parser_map.begin();
497 it != parser_map.end(); ++it) {
498 const base::Value* capability = NULL;
499 if (desired_caps.Get(it->first, &capability)) {
500 Status status = it->second.Run(*capability, this);
501 if (status.IsError()) {
502 return Status(
503 kUnknownError, "cannot parse capability: " + it->first, status);
504 }
505 }
506 }
507 return Status(kOk);
508 }
509