/
headless_shell.cc
909 lines (814 loc) · 32.1 KB
/
headless_shell.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
// Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <memory>
#include <sstream>
#include <string>
#include <utility>
#include "base/base_switches.h"
#include "base/bind.h"
#include "base/callback.h"
#include "base/command_line.h"
#include "base/containers/adapters.h"
#include "base/environment.h"
#include "base/files/file_path.h"
#include "base/files/file_util.h"
#include "base/i18n/rtl.h"
#include "base/json/json_writer.h"
#include "base/location.h"
#include "base/memory/weak_ptr.h"
#include "base/numerics/safe_conversions.h"
#include "base/path_service.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/utf_string_conversions.h"
#include "base/task/task_runner_util.h"
#include "base/task/thread_pool.h"
#include "build/branding_buildflags.h"
#include "build/build_config.h"
#include "cc/base/switches.h"
#include "components/viz/common/switches.h"
#include "content/public/app/content_main.h"
#include "content/public/browser/browser_task_traits.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/render_process_host.h"
#include "content/public/common/content_switches.h"
#include "headless/app/headless_shell.h"
#include "headless/app/headless_shell_switches.h"
#include "headless/lib/browser/headless_browser_impl.h"
#include "headless/lib/browser/headless_devtools.h"
#include "headless/lib/headless_content_main_delegate.h"
#include "headless/public/headless_devtools_target.h"
#include "net/base/filename_util.h"
#include "net/base/host_port_pair.h"
#include "net/base/io_buffer.h"
#include "net/base/ip_address.h"
#include "net/base/net_errors.h"
#include "net/http/http_util.h"
#include "net/socket/ssl_client_socket.h"
#include "net/ssl/ssl_key_logger_impl.h"
#include "services/network/public/cpp/network_switches.h"
#include "third_party/blink/public/common/switches.h"
#include "ui/gfx/geometry/size.h"
#if BUILDFLAG(IS_WIN)
#include "components/crash/core/app/crash_switches.h" // nogncheck
#include "components/crash/core/app/run_as_crashpad_handler_win.h"
#include "sandbox/win/src/sandbox_types.h"
#endif
#if BUILDFLAG(IS_MAC)
#include "components/os_crypt/os_crypt_switches.h" // nogncheck
#endif
#if defined(HEADLESS_USE_POLICY)
#include "headless/lib/browser/policy/headless_mode_policy.h"
#endif
namespace headless {
namespace {
// By default listen to incoming DevTools connections on localhost.
const char kUseLocalHostForDevToolsHttpServer[] = "localhost";
// Default file name for screenshot. Can be overriden by "--screenshot" switch.
const char kDefaultScreenshotFileName[] = "screenshot.png";
// Default file name for pdf. Can be overriden by "--print-to-pdf" switch.
const char kDefaultPDFFileName[] = "output.pdf";
bool ParseWindowSize(const std::string& window_size,
gfx::Size* parsed_window_size) {
int width = 0;
int height = 0;
if (sscanf(window_size.c_str(), "%d%*[x,]%d", &width, &height) >= 2 &&
width >= 0 && height >= 0) {
parsed_window_size->set_width(width);
parsed_window_size->set_height(height);
return true;
}
return false;
}
bool ParseFontRenderHinting(
const std::string& font_render_hinting_string,
gfx::FontRenderParams::Hinting* font_render_hinting) {
if (font_render_hinting_string == "max") {
*font_render_hinting = gfx::FontRenderParams::Hinting::HINTING_MAX;
} else if (font_render_hinting_string == "full") {
*font_render_hinting = gfx::FontRenderParams::Hinting::HINTING_FULL;
} else if (font_render_hinting_string == "medium") {
*font_render_hinting = gfx::FontRenderParams::Hinting::HINTING_MEDIUM;
} else if (font_render_hinting_string == "slight") {
*font_render_hinting = gfx::FontRenderParams::Hinting::HINTING_SLIGHT;
} else if (font_render_hinting_string == "none") {
*font_render_hinting = gfx::FontRenderParams::Hinting::HINTING_NONE;
} else {
return false;
}
return true;
}
GURL ConvertArgumentToURL(const base::CommandLine::StringType& arg) {
#if BUILDFLAG(IS_WIN)
GURL url(base::WideToUTF8(arg));
#else
GURL url(arg);
#endif
if (url.is_valid() && url.has_scheme())
return url;
return net::FilePathToFileURL(
base::MakeAbsoluteFilePath(base::FilePath(arg)));
}
std::vector<GURL> ConvertArgumentsToURLs(
const base::CommandLine::StringVector& args) {
std::vector<GURL> urls;
urls.reserve(args.size());
for (const auto& arg : base::Reversed(args))
urls.push_back(ConvertArgumentToURL(arg));
return urls;
}
// Gets file path into ssl_keylog_file from command line argument or
// environment variable. Command line argument has priority when
// both specified.
base::FilePath GetSSLKeyLogFile(const base::CommandLine* command_line) {
if (command_line->HasSwitch(switches::kSSLKeyLogFile)) {
base::FilePath path =
command_line->GetSwitchValuePath(switches::kSSLKeyLogFile);
if (!path.empty())
return path;
LOG(WARNING) << "ssl-key-log-file argument missing";
}
std::unique_ptr<base::Environment> env(base::Environment::Create());
std::string path_str;
env->GetVar("SSLKEYLOGFILE", &path_str);
#if BUILDFLAG(IS_WIN)
// base::Environment returns environment variables in UTF-8 on Windows.
return base::FilePath(base::UTF8ToWide(path_str));
#else
return base::FilePath(path_str);
#endif
}
int RunContentMain(
HeadlessBrowser::Options options,
base::OnceCallback<void(HeadlessBrowser*)> on_browser_start_callback) {
content::ContentMainParams params(nullptr);
#if BUILDFLAG(IS_WIN)
// Sandbox info has to be set and initialized.
CHECK(options.sandbox_info);
params.instance = options.instance;
params.sandbox_info = std::move(options.sandbox_info);
#elif !BUILDFLAG(IS_ANDROID)
params.argc = options.argc;
params.argv = options.argv;
#endif
// TODO(skyostil): Implement custom message pumps.
DCHECK(!options.message_pump);
auto browser = std::make_unique<HeadlessBrowserImpl>(
std::move(on_browser_start_callback), std::move(options));
HeadlessContentMainDelegate delegate(std::move(browser));
params.delegate = &delegate;
return content::ContentMain(std::move(params));
}
bool ValidateCommandLine(const base::CommandLine& command_line) {
if (!command_line.HasSwitch(switches::kRemoteDebuggingPort) &&
!command_line.HasSwitch(switches::kRemoteDebuggingPipe)) {
if (command_line.GetArgs().size() <= 1)
return true;
LOG(ERROR) << "Open multiple tabs is only supported when "
<< "remote debugging is enabled.";
return false;
}
if (command_line.HasSwitch(switches::kDefaultBackgroundColor)) {
LOG(ERROR) << "Setting default background color is disabled "
<< "when remote debugging is enabled.";
return false;
}
if (command_line.HasSwitch(switches::kDumpDom)) {
LOG(ERROR) << "Dump DOM is disabled when remote debugging is enabled.";
return false;
}
if (command_line.HasSwitch(switches::kPrintToPDF)) {
LOG(ERROR) << "Print to PDF is disabled "
<< "when remote debugging is enabled.";
return false;
}
if (command_line.HasSwitch(switches::kRepl)) {
LOG(ERROR) << "Evaluate Javascript is disabled "
<< "when remote debugging is enabled.";
return false;
}
if (command_line.HasSwitch(switches::kScreenshot)) {
LOG(ERROR) << "Capture screenshot is disabled "
<< "when remote debugging is enabled.";
return false;
}
if (command_line.HasSwitch(switches::kTimeout)) {
LOG(ERROR) << "Navigation timeout is disabled "
<< "when remote debugging is enabled.";
return false;
}
if (command_line.HasSwitch(switches::kVirtualTimeBudget)) {
LOG(ERROR) << "Virtual time budget is disabled "
<< "when remote debugging is enabled.";
return false;
}
return true;
}
} // namespace
HeadlessShell::HeadlessShell() = default;
HeadlessShell::~HeadlessShell() = default;
void HeadlessShell::OnStart(HeadlessBrowser* browser) {
browser_ = browser;
#if defined(HEADLESS_USE_POLICY)
if (policy::HeadlessModePolicy::IsHeadlessDisabled(
static_cast<HeadlessBrowserImpl*>(browser)->GetPrefs())) {
LOG(ERROR) << "Headless mode is disabled by policy.";
ShutdownSoon();
return;
}
#endif
devtools_client_ = HeadlessDevToolsClient::Create();
file_task_runner_ = base::ThreadPool::CreateSequencedTaskRunner(
{base::MayBlock(), base::TaskPriority::BEST_EFFORT});
HeadlessBrowserContext::Builder context_builder =
browser_->CreateBrowserContextBuilder();
// TODO(eseckler): These switches should also affect BrowserContexts that
// are created via DevTools later.
base::FilePath ssl_keylog_file =
GetSSLKeyLogFile(base::CommandLine::ForCurrentProcess());
if (!ssl_keylog_file.empty()) {
net::SSLClientSocket::SetSSLKeyLogger(
std::make_unique<net::SSLKeyLoggerImpl>(ssl_keylog_file));
}
// Retrieve the locale set by InitApplicationLocale() in
// headless_content_main_delegate.cc in a way that is free of side-effects.
context_builder.SetAcceptLanguage(base::i18n::GetConfiguredLocale());
browser_context_ = context_builder.Build();
browser_->SetDefaultBrowserContext(browser_context_);
base::CommandLine::StringVector args =
base::CommandLine::ForCurrentProcess()->GetArgs();
// If no explicit URL is present, navigate to about:blank, unless we're being
// driven by debugger.
if (args.empty() && !base::CommandLine::ForCurrentProcess()->HasSwitch(
switches::kRemoteDebuggingPipe)) {
#if BUILDFLAG(IS_WIN)
args.push_back(L"about:blank");
#else
args.push_back("about:blank");
#endif
}
if (!args.empty()) {
base::PostTaskAndReplyWithResult(
file_task_runner_.get(), FROM_HERE,
base::BindOnce(&ConvertArgumentsToURLs, args),
base::BindOnce(&HeadlessShell::OnGotURLs, weak_factory_.GetWeakPtr()));
}
}
void HeadlessShell::OnGotURLs(const std::vector<GURL>& urls) {
HeadlessWebContents::Builder builder(
browser_context_->CreateWebContentsBuilder());
for (const auto& url : urls) {
HeadlessWebContents* web_contents = builder.SetInitialURL(url).Build();
if (!web_contents) {
LOG(ERROR) << "Navigation to " << url << " failed";
browser_->Shutdown();
return;
}
if (!web_contents_ && !RemoteDebuggingEnabled()) {
// TODO(jzfeng): Support observing multiple targets.
url_ = url;
web_contents_ = web_contents;
web_contents_->AddObserver(this);
}
}
}
void HeadlessShell::Detach() {
if (!RemoteDebuggingEnabled()) {
devtools_client_->GetEmulation()->GetExperimental()->RemoveObserver(this);
devtools_client_->GetInspector()->GetExperimental()->RemoveObserver(this);
devtools_client_->GetPage()->GetExperimental()->RemoveObserver(this);
if (web_contents_->GetDevToolsTarget()) {
web_contents_->GetDevToolsTarget()->DetachClient(devtools_client_.get());
}
}
web_contents_->RemoveObserver(this);
web_contents_ = nullptr;
}
void HeadlessShell::ShutdownSoon() {
if (shutdown_pending_)
return;
shutdown_pending_ = true;
DCHECK(browser_);
if (web_contents_)
web_contents_->Close();
DCHECK(!web_contents_);
browser_->BrowserMainThread()->PostTask(
FROM_HERE,
base::BindOnce(&HeadlessShell::Shutdown, weak_factory_.GetWeakPtr()));
}
void HeadlessShell::Shutdown() {
DCHECK(!web_contents_);
if (content::RenderProcessHost::run_renderer_in_process())
content::RenderProcessHost::ShutDownInProcessRenderer();
browser_->Shutdown();
}
void HeadlessShell::DevToolsTargetReady() {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
HeadlessDevToolsTarget* target = web_contents_->GetDevToolsTarget();
target->AttachClient(devtools_client_.get());
if (!target->IsAttached()) {
LOG(ERROR) << "Could not attach DevTools target.";
ShutdownSoon();
return;
}
devtools_client_->GetInspector()->GetExperimental()->AddObserver(this);
devtools_client_->GetPage()->GetExperimental()->AddObserver(this);
devtools_client_->GetPage()->Enable();
devtools_client_->GetEmulation()->GetExperimental()->AddObserver(this);
if (base::CommandLine::ForCurrentProcess()->HasSwitch(
switches::kDefaultBackgroundColor)) {
std::string color_hex =
base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
switches::kDefaultBackgroundColor);
uint32_t color;
CHECK(base::HexStringToUInt(color_hex, &color))
<< "Expected a hex value for --default-background-color=";
auto rgba = dom::RGBA::Builder()
.SetR((color & 0xff000000) >> 24)
.SetG((color & 0x00ff0000) >> 16)
.SetB((color & 0x0000ff00) >> 8)
.SetA(color & 0x000000ff)
.Build();
devtools_client_->GetEmulation()
->GetExperimental()
->SetDefaultBackgroundColorOverride(
emulation::SetDefaultBackgroundColorOverrideParams::Builder()
.SetColor(std::move(rgba))
.Build());
}
if (base::CommandLine::ForCurrentProcess()->HasSwitch(
switches::kVirtualTimeBudget)) {
std::string budget_ms_ascii =
base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
switches::kVirtualTimeBudget);
int budget_ms;
CHECK(base::StringToInt(budget_ms_ascii, &budget_ms))
<< "Expected an integer value for --virtual-time-budget=";
devtools_client_->GetEmulation()->GetExperimental()->SetVirtualTimePolicy(
emulation::SetVirtualTimePolicyParams::Builder()
.SetPolicy(
emulation::VirtualTimePolicy::PAUSE_IF_NETWORK_FETCHES_PENDING)
.SetBudget(budget_ms)
.Build());
} else {
// Check if the document had already finished loading by the time we
// attached.
PollReadyState();
}
if (base::CommandLine::ForCurrentProcess()->HasSwitch(switches::kTimeout)) {
std::string timeout_ms_ascii =
base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
switches::kTimeout);
int timeout_ms;
CHECK(base::StringToInt(timeout_ms_ascii, &timeout_ms))
<< "Expected an integer value for --timeout=";
browser_->BrowserMainThread()->PostDelayedTask(
FROM_HERE,
base::BindOnce(&HeadlessShell::FetchTimeout,
weak_factory_.GetWeakPtr()),
base::Milliseconds(timeout_ms));
}
// TODO(skyostil): Implement more features to demonstrate the devtools API.
}
void HeadlessShell::HeadlessWebContentsDestroyed() {
// Detach now, but defer shutdown till the HeadlessWebContents
// removal is complete.
Detach();
ShutdownSoon();
}
void HeadlessShell::FetchTimeout() {
LOG(INFO) << "Timeout.";
devtools_client_->GetPage()->GetExperimental()->StopLoading(
page::StopLoadingParams::Builder().Build());
// After calling page.stopLoading() the page will not fire any
// life cycle events, so we have to proceed on our own.
browser_->BrowserMainThread()->PostTask(
FROM_HERE,
base::BindOnce(&HeadlessShell::OnPageReady, weak_factory_.GetWeakPtr()));
}
void HeadlessShell::OnTargetCrashed(
const inspector::TargetCrashedParams& params) {
LOG(ERROR) << "Abnormal renderer termination.";
// NB this never gets called if remote debugging is enabled.
ShutdownSoon();
}
void HeadlessShell::PollReadyState() {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
// We need to check the current location in addition to the ready state to
// be sure the expected page is ready.
devtools_client_->GetRuntime()->Evaluate(
"document.readyState + ' ' + document.location.href",
base::BindOnce(&HeadlessShell::OnReadyState, weak_factory_.GetWeakPtr()));
}
void HeadlessShell::OnReadyState(
std::unique_ptr<runtime::EvaluateResult> result) {
// |result| can be nullptr if HeadlessDevToolsClientImpl::DispatchMessageReply
// sees an error.
if (result && result->GetResult()->GetValue()->is_string()) {
std::stringstream stream(result->GetResult()->GetValue()->GetString());
std::string ready_state;
std::string url;
stream >> ready_state;
stream >> url;
if (ready_state == "complete" &&
(url_.spec() == url || url != "about:blank")) {
OnPageReady();
return;
}
}
}
// emulation::Observer implementation:
void HeadlessShell::OnVirtualTimeBudgetExpired(
const emulation::VirtualTimeBudgetExpiredParams& params) {
OnPageReady();
}
// page::Observer implementation:
void HeadlessShell::OnLoadEventFired(const page::LoadEventFiredParams& params) {
if (base::CommandLine::ForCurrentProcess()->HasSwitch(
switches::kVirtualTimeBudget)) {
return;
}
OnPageReady();
}
void HeadlessShell::OnPageReady() {
if (processed_page_ready_)
return;
processed_page_ready_ = true;
if (base::CommandLine::ForCurrentProcess()->HasSwitch(switches::kDumpDom)) {
FetchDom();
} else if (base::CommandLine::ForCurrentProcess()->HasSwitch(
switches::kRepl)) {
LOG(INFO)
<< "Type a Javascript expression to evaluate or \"quit\" to exit.";
InputExpression();
} else if (base::CommandLine::ForCurrentProcess()->HasSwitch(
switches::kScreenshot)) {
CaptureScreenshot();
} else if (base::CommandLine::ForCurrentProcess()->HasSwitch(
switches::kPrintToPDF)) {
PrintToPDF();
} else {
ShutdownSoon();
}
}
void HeadlessShell::FetchDom() {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
devtools_client_->GetRuntime()->Evaluate(
"(document.doctype ? new "
"XMLSerializer().serializeToString(document.doctype) + '\\n' : '') + "
"document.documentElement.outerHTML",
base::BindOnce(&HeadlessShell::OnDomFetched, weak_factory_.GetWeakPtr()));
}
void HeadlessShell::OnDomFetched(
std::unique_ptr<runtime::EvaluateResult> result) {
if (result->HasExceptionDetails()) {
LOG(ERROR) << "Failed to serialize document: "
<< result->GetExceptionDetails()->GetText();
} else {
printf("%s\n", result->GetResult()->GetValue()->GetString().c_str());
}
ShutdownSoon();
}
void HeadlessShell::InputExpression() {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
// Note that a real system should read user input asynchronously, because
// otherwise all other browser activity is suspended (e.g., page loading).
printf(">>> ");
std::stringstream expression;
while (true) {
int c = fgetc(stdin);
if (c == '\n')
break;
if (c == EOF) {
// If there's no expression, then quit.
if (expression.str().size() == 0) {
printf("\n");
ShutdownSoon();
return;
}
break;
}
expression << static_cast<char>(c);
}
if (expression.str() == "quit") {
ShutdownSoon();
return;
}
devtools_client_->GetRuntime()->Evaluate(
expression.str(), base::BindOnce(&HeadlessShell::OnExpressionResult,
weak_factory_.GetWeakPtr()));
}
void HeadlessShell::OnExpressionResult(
std::unique_ptr<runtime::EvaluateResult> result) {
std::unique_ptr<base::Value> value = result->Serialize();
std::string result_json;
base::JSONWriter::Write(*value, &result_json);
printf("%s\n", result_json.c_str());
InputExpression();
}
void HeadlessShell::CaptureScreenshot() {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
devtools_client_->GetPage()->GetExperimental()->CaptureScreenshot(
page::CaptureScreenshotParams::Builder().Build(),
base::BindOnce(&HeadlessShell::OnScreenshotCaptured,
weak_factory_.GetWeakPtr()));
}
void HeadlessShell::OnScreenshotCaptured(
std::unique_ptr<page::CaptureScreenshotResult> result) {
if (!result) {
LOG(ERROR) << "Capture screenshot failed";
ShutdownSoon();
return;
}
WriteFile(switches::kScreenshot, kDefaultScreenshotFileName,
result->GetData());
}
void HeadlessShell::PrintToPDF() {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
bool display_header_footer =
!base::CommandLine::ForCurrentProcess()->HasSwitch(
switches::kPrintToPDFNoHeader);
devtools_client_->GetPage()->GetExperimental()->PrintToPDF(
page::PrintToPDFParams::Builder()
.SetDisplayHeaderFooter(display_header_footer)
.SetPrintBackground(true)
.SetPreferCSSPageSize(true)
.Build(),
base::BindOnce(&HeadlessShell::OnPDFCreated, weak_factory_.GetWeakPtr()));
}
void HeadlessShell::OnPDFCreated(
std::unique_ptr<page::PrintToPDFResult> result) {
if (!result) {
LOG(ERROR) << "Print to PDF failed";
ShutdownSoon();
return;
}
WriteFile(switches::kPrintToPDF, kDefaultPDFFileName, result->GetData());
}
void HeadlessShell::WriteFile(const std::string& file_path_switch,
const std::string& default_file_name,
const protocol::Binary& data) {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
base::FilePath file_name =
base::CommandLine::ForCurrentProcess()->GetSwitchValuePath(
file_path_switch);
if (file_name.empty())
file_name = base::FilePath().AppendASCII(default_file_name);
file_proxy_ = std::make_unique<base::FileProxy>(file_task_runner_.get());
if (!file_proxy_->CreateOrOpen(
file_name, base::File::FLAG_CREATE_ALWAYS | base::File::FLAG_WRITE,
base::BindOnce(&HeadlessShell::OnFileOpened,
weak_factory_.GetWeakPtr(), data, file_name))) {
// Operation could not be started.
OnFileOpened(protocol::Binary(), file_name, base::File::FILE_ERROR_FAILED);
}
}
void HeadlessShell::OnFileOpened(const protocol::Binary& data,
const base::FilePath file_name,
base::File::Error error_code) {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
if (!file_proxy_->IsValid()) {
LOG(ERROR) << "Writing to file " << file_name.value()
<< " was unsuccessful, could not open file: "
<< base::File::ErrorToString(error_code);
ShutdownSoon();
return;
}
if (!file_proxy_->Write(
0, reinterpret_cast<const char*>(data.data()), data.size(),
base::BindOnce(&HeadlessShell::OnFileWritten,
weak_factory_.GetWeakPtr(), file_name, data.size()))) {
// Operation may have completed successfully or failed.
OnFileWritten(file_name, data.size(), base::File::FILE_ERROR_FAILED, 0);
}
}
void HeadlessShell::OnFileWritten(const base::FilePath file_name,
const size_t length,
base::File::Error error_code,
int write_result) {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
if (write_result < static_cast<int>(length)) {
// TODO(eseckler): Support recovering from partial writes.
LOG(ERROR) << "Writing to file " << file_name.value()
<< " was unsuccessful: "
<< base::File::ErrorToString(error_code);
} else {
LOG(INFO) << "Written to file " << file_name.value() << ".";
}
if (!file_proxy_->Close(base::BindOnce(&HeadlessShell::OnFileClosed,
weak_factory_.GetWeakPtr()))) {
// Operation could not be started.
OnFileClosed(base::File::FILE_ERROR_FAILED);
}
}
void HeadlessShell::OnFileClosed(base::File::Error error_code) {
ShutdownSoon();
}
bool HeadlessShell::RemoteDebuggingEnabled() const {
const base::CommandLine& command_line =
*base::CommandLine::ForCurrentProcess();
return (command_line.HasSwitch(switches::kRemoteDebuggingPort) ||
command_line.HasSwitch(switches::kRemoteDebuggingPipe));
}
#if BUILDFLAG(IS_WIN)
int HeadlessShellMain(HINSTANCE instance,
sandbox::SandboxInterfaceInfo* sandbox_info) {
base::CommandLine::Init(0, nullptr);
#if defined(HEADLESS_USE_CRASHPAD)
std::string process_type =
base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
::switches::kProcessType);
if (process_type == crash_reporter::switches::kCrashpadHandler) {
return crash_reporter::RunAsCrashpadHandler(
*base::CommandLine::ForCurrentProcess(), base::FilePath(),
::switches::kProcessType, switches::kUserDataDir);
}
#endif // defined(HEADLESS_USE_CRASHPAD)
RunChildProcessIfNeeded(instance, sandbox_info);
HeadlessBrowser::Options::Builder builder(0, nullptr);
builder.SetInstance(instance);
builder.SetSandboxInfo(std::move(sandbox_info));
#else
int HeadlessShellMain(int argc, const char** argv) {
base::CommandLine::Init(argc, argv);
RunChildProcessIfNeeded(argc, argv);
HeadlessBrowser::Options::Builder builder(argc, argv);
#endif // BUILDFLAG(IS_WIN)
HeadlessShell shell;
#if BUILDFLAG(IS_FUCHSIA)
// TODO(fuchsia): Remove this when GPU accelerated compositing is ready.
base::CommandLine::ForCurrentProcess()->AppendSwitch(::switches::kDisableGpu);
#endif
base::CommandLine& command_line(*base::CommandLine::ForCurrentProcess());
if (!ValidateCommandLine(command_line))
return EXIT_FAILURE;
#if BUILDFLAG(IS_MAC)
command_line.AppendSwitch(os_crypt::switches::kUseMockKeychain);
#endif
if (command_line.HasSwitch(switches::kDeterministicMode)) {
command_line.AppendSwitch(switches::kEnableBeginFrameControl);
// Compositor flags
command_line.AppendSwitch(::switches::kRunAllCompositorStagesBeforeDraw);
command_line.AppendSwitch(::switches::kDisableNewContentRenderingTimeout);
// Ensure that image animations don't resync their animation timestamps when
// looping back around.
command_line.AppendSwitch(blink::switches::kDisableImageAnimationResync);
// Renderer flags
command_line.AppendSwitch(cc::switches::kDisableThreadedAnimation);
command_line.AppendSwitch(blink::switches::kDisableThreadedScrolling);
command_line.AppendSwitch(cc::switches::kDisableCheckerImaging);
}
if (command_line.HasSwitch(switches::kEnableBeginFrameControl))
builder.SetEnableBeginFrameControl(true);
if (command_line.HasSwitch(switches::kEnableCrashReporter))
builder.SetCrashReporterEnabled(true);
if (command_line.HasSwitch(switches::kDisableCrashReporter))
builder.SetCrashReporterEnabled(false);
if (command_line.HasSwitch(switches::kCrashDumpsDir)) {
builder.SetCrashDumpsDir(
command_line.GetSwitchValuePath(switches::kCrashDumpsDir));
}
// Enable devtools if requested, by specifying a port (and optional address).
if (command_line.HasSwitch(::switches::kRemoteDebuggingPort)) {
std::string address = kUseLocalHostForDevToolsHttpServer;
if (command_line.HasSwitch(switches::kRemoteDebuggingAddress)) {
address =
command_line.GetSwitchValueASCII(switches::kRemoteDebuggingAddress);
net::IPAddress parsed_address;
if (!parsed_address.AssignFromIPLiteral(address)) {
LOG(ERROR) << "Invalid devtools server address";
return EXIT_FAILURE;
}
}
int parsed_port;
std::string port_str =
command_line.GetSwitchValueASCII(::switches::kRemoteDebuggingPort);
if (!base::StringToInt(port_str, &parsed_port) ||
!base::IsValueInRangeForNumericType<uint16_t>(parsed_port)) {
LOG(ERROR) << "Invalid devtools server port";
return EXIT_FAILURE;
}
const net::HostPortPair endpoint(address,
base::checked_cast<uint16_t>(parsed_port));
builder.EnableDevToolsServer(endpoint);
}
if (command_line.HasSwitch(::switches::kRemoteDebuggingPipe))
builder.EnableDevToolsPipe();
if (command_line.HasSwitch(switches::kProxyServer)) {
std::string proxy_server =
command_line.GetSwitchValueASCII(switches::kProxyServer);
auto proxy_config = std::make_unique<net::ProxyConfig>();
proxy_config->proxy_rules().ParseFromString(proxy_server);
if (command_line.HasSwitch(switches::kProxyBypassList)) {
std::string bypass_list =
command_line.GetSwitchValueASCII(switches::kProxyBypassList);
proxy_config->proxy_rules().bypass_rules.ParseFromString(bypass_list);
}
builder.SetProxyConfig(std::move(proxy_config));
}
if (command_line.HasSwitch(switches::kUseGL)) {
builder.SetGLImplementation(
command_line.GetSwitchValueASCII(switches::kUseGL));
}
if (command_line.HasSwitch(switches::kUseANGLE)) {
builder.SetANGLEImplementation(
command_line.GetSwitchValueASCII(switches::kUseANGLE));
}
if (command_line.HasSwitch(switches::kUserDataDir)) {
builder.SetUserDataDir(
command_line.GetSwitchValuePath(switches::kUserDataDir));
if (!command_line.HasSwitch(switches::kIncognito))
builder.SetIncognitoMode(false);
}
if (command_line.HasSwitch(switches::kWindowSize)) {
std::string window_size =
command_line.GetSwitchValueASCII(switches::kWindowSize);
gfx::Size parsed_window_size;
if (!ParseWindowSize(window_size, &parsed_window_size)) {
LOG(ERROR) << "Malformed window size";
return EXIT_FAILURE;
}
builder.SetWindowSize(parsed_window_size);
}
if (command_line.HasSwitch(switches::kHideScrollbars)) {
builder.SetOverrideWebPreferencesCallback(
base::BindRepeating([](blink::web_pref::WebPreferences* preferences) {
preferences->hide_scrollbars = true;
}));
}
if (command_line.HasSwitch(switches::kUserAgent)) {
std::string ua = command_line.GetSwitchValueASCII(switches::kUserAgent);
if (net::HttpUtil::IsValidHeaderValue(ua))
builder.SetUserAgent(ua);
}
if (command_line.HasSwitch(switches::kFontRenderHinting)) {
std::string font_render_hinting_string =
command_line.GetSwitchValueASCII(switches::kFontRenderHinting);
gfx::FontRenderParams::Hinting font_render_hinting;
if (ParseFontRenderHinting(font_render_hinting_string,
&font_render_hinting)) {
builder.SetFontRenderHinting(font_render_hinting);
} else {
LOG(ERROR) << "Unknown font-render-hinting parameter value";
return EXIT_FAILURE;
}
}
if (command_line.HasSwitch(switches::kBlockNewWebContents))
builder.SetBlockNewWebContents(true);
return HeadlessBrowserMain(
builder.Build(),
base::BindOnce(&HeadlessShell::OnStart, base::Unretained(&shell)));
}
int HeadlessShellMain(const content::ContentMainParams& params) {
#if BUILDFLAG(IS_WIN)
return HeadlessShellMain(params.instance, params.sandbox_info);
#else
return HeadlessShellMain(params.argc, params.argv);
#endif
}
#if BUILDFLAG(IS_WIN)
void RunChildProcessIfNeeded(HINSTANCE instance,
sandbox::SandboxInterfaceInfo* sandbox_info) {
base::CommandLine::Init(0, nullptr);
HeadlessBrowser::Options::Builder builder(0, nullptr);
builder.SetInstance(instance);
builder.SetSandboxInfo(std::move(sandbox_info));
#else
void RunChildProcessIfNeeded(int argc, const char** argv) {
base::CommandLine::Init(argc, argv);
HeadlessBrowser::Options::Builder builder(argc, argv);
#endif // BUILDFLAG(IS_WIN)
const base::CommandLine& command_line(
*base::CommandLine::ForCurrentProcess());
if (!command_line.HasSwitch(::switches::kProcessType))
return;
if (command_line.HasSwitch(switches::kUserAgent)) {
std::string ua = command_line.GetSwitchValueASCII(switches::kUserAgent);
if (net::HttpUtil::IsValidHeaderValue(ua))
builder.SetUserAgent(ua);
}
int rc = RunContentMain(builder.Build(),
base::OnceCallback<void(HeadlessBrowser*)>());
// Note that exiting from here means that base::AtExitManager objects will not
// have a chance to be destroyed (typically in main/WinMain).
// Use TerminateCurrentProcessImmediately instead of exit to avoid shutdown
// crashes and slowdowns on shutdown.
base::Process::TerminateCurrentProcessImmediately(rc);
}
int HeadlessBrowserMain(
HeadlessBrowser::Options options,
base::OnceCallback<void(HeadlessBrowser*)> on_browser_start_callback) {
DCHECK(!on_browser_start_callback.is_null());
#if DCHECK_IS_ON()
// The browser can only be initialized once.
static bool browser_was_initialized;
DCHECK(!browser_was_initialized);
browser_was_initialized = true;
// Child processes should not end up here.
DCHECK(!base::CommandLine::ForCurrentProcess()->HasSwitch(
::switches::kProcessType));
#endif
return RunContentMain(std::move(options),
std::move(on_browser_start_callback));
}
} // namespace headless