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
|
// Copyright 2012 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "printing/backend/win_helper.h"
#include <stddef.h>
#include <wrl/client.h>
#include <algorithm>
#include <memory>
#include <string_view>
#include "base/check_op.h"
#include "base/compiler_specific.h"
#include "base/containers/fixed_flat_set.h"
#include "base/debug/alias.h"
#include "base/file_version_info.h"
#include "base/files/file_path.h"
#include "base/memory/free_deleter.h"
#include "base/metrics/histogram_functions.h"
#include "base/notreached.h"
#include "base/numerics/checked_math.h"
#include "base/numerics/safe_conversions.h"
#include "base/strings/strcat.h"
#include "base/strings/string_util.h"
#include "base/strings/stringprintf.h"
#include "base/strings/utf_string_conversions.h"
#include "base/threading/scoped_blocking_call.h"
#include "base/win/registry.h"
#include "base/win/windows_types.h"
#include "base/win/windows_version.h"
#include "printing/backend/print_backend.h"
#include "printing/backend/print_backend_consts.h"
#include "printing/backend/printing_info_win.h"
#include "printing/printing_features.h"
namespace printing {
namespace {
typedef HRESULT(WINAPI* PTOpenProviderProc)(PCWSTR printer_name,
DWORD version,
HPTPROVIDER* provider);
typedef HRESULT(WINAPI* PTGetPrintCapabilitiesProc)(HPTPROVIDER provider,
IStream* print_ticket,
IStream* capabilities,
BSTR* error_message);
typedef HRESULT(WINAPI* PTConvertDevModeToPrintTicketProc)(
HPTPROVIDER provider,
ULONG devmode_size_in_bytes,
PDEVMODE devmode,
EPrintTicketScope scope,
IStream* print_ticket);
typedef HRESULT(WINAPI* PTConvertPrintTicketToDevModeProc)(
HPTPROVIDER provider,
IStream* print_ticket,
EDefaultDevmodeType base_devmode_type,
EPrintTicketScope scope,
ULONG* devmode_byte_count,
PDEVMODE* devmode,
BSTR* error_message);
typedef HRESULT(WINAPI* PTMergeAndValidatePrintTicketProc)(
HPTPROVIDER provider,
IStream* base_ticket,
IStream* delta_ticket,
EPrintTicketScope scope,
IStream* result_ticket,
BSTR* error_message);
typedef HRESULT(WINAPI* PTReleaseMemoryProc)(PVOID buffer);
typedef HRESULT(WINAPI* PTCloseProviderProc)(HPTPROVIDER provider);
typedef HRESULT(WINAPI* StartXpsPrintJobProc)(
const LPCWSTR printer_name,
const LPCWSTR job_name,
const LPCWSTR output_file_name,
HANDLE progress_event,
HANDLE completion_event,
UINT8* printable_pages_on,
UINT32 printable_pages_on_count,
IXpsPrintJob** xps_print_job,
IXpsPrintJobStream** document_stream,
IXpsPrintJobStream** print_ticket_stream);
PTOpenProviderProc g_open_provider_proc = nullptr;
PTGetPrintCapabilitiesProc g_get_print_capabilities_proc = nullptr;
PTConvertDevModeToPrintTicketProc g_convert_devmode_to_print_ticket_proc =
nullptr;
PTConvertPrintTicketToDevModeProc g_convert_print_ticket_to_devmode_proc =
nullptr;
PTMergeAndValidatePrintTicketProc g_merge_and_validate_print_ticket_proc =
nullptr;
PTReleaseMemoryProc g_release_memory_proc = nullptr;
PTCloseProviderProc g_close_provider_proc = nullptr;
StartXpsPrintJobProc g_start_xps_print_job_proc = nullptr;
typedef std::string (*GetDisplayNameFunc)(const std::string& printer_name);
GetDisplayNameFunc g_get_display_name_func = nullptr;
PrinterBasicInfo InitializePrinterInfo(LPTSTR name, LPTSTR comment) {
PrinterBasicInfo printer_info;
printer_info.printer_name = base::WideToUTF8(name);
if (g_get_display_name_func) {
printer_info.display_name =
g_get_display_name_func(printer_info.printer_name);
} else {
printer_info.display_name = printer_info.printer_name;
}
if (comment) {
printer_info.printer_description = base::WideToUTF8(comment);
}
return printer_info;
}
HRESULT StreamFromPrintTicket(const std::string& print_ticket,
IStream** stream) {
DCHECK(stream);
HRESULT hr = CreateStreamOnHGlobal(nullptr, TRUE, stream);
if (FAILED(hr)) {
return hr;
}
ULONG bytes_written = 0;
(*stream)->Write(print_ticket.c_str(),
base::checked_cast<ULONG>(print_ticket.length()),
&bytes_written);
DCHECK(bytes_written == print_ticket.length());
LARGE_INTEGER pos = {};
ULARGE_INTEGER new_pos = {};
(*stream)->Seek(pos, STREAM_SEEK_SET, &new_pos);
return S_OK;
}
const char kXpsTicketTemplate[] =
"<?xml version='1.0' encoding='UTF-8'?>"
"<psf:PrintTicket "
"xmlns:psf='"
"http://schemas.microsoft.com/windows/2003/08/printing/"
"printschemaframework' "
"xmlns:psk="
"'http://schemas.microsoft.com/windows/2003/08/printing/"
"printschemakeywords' "
"version='1'>"
"<psf:Feature name='psk:PageOutputColor'>"
"<psf:Option name='psk:%s'>"
"</psf:Option>"
"</psf:Feature>"
"</psf:PrintTicket>";
const char kXpsTicketColor[] = "Color";
const char kXpsTicketMonochrome[] = "Monochrome";
// Registry path prefix for the printer drivers' keys.
constexpr wchar_t kDriversRegistryKeyPath[] =
L"SYSTEM\\CurrentControlSet\\Control\\Print\\Printers\\";
// Registry value names for info of a printer driver.
constexpr wchar_t kLocationRegistryValueName[] = L"Location";
constexpr wchar_t kPortRegistryValueName[] = L"Port";
// List of printer ports which are known to cause a UI dialog to be displayed
// when printing.
constexpr wchar_t kPrinterDriverPortFile[] = L"FILE:";
constexpr wchar_t kPrinterDriverPortPrompt[] = L"PORTPROMPT:";
constexpr wchar_t kPrinterDriverPortFax[] = L"SHRFAX:";
// Gets the port used for a particular printer driver. This can be found in
// the Windows registry entry for the driver.
std::wstring GetPrinterDriverPort(const std::string& printer_name) {
base::win::RegKey reg_key;
std::wstring root_key(std::wstring(kDriversRegistryKeyPath) +
base::UTF8ToWide(printer_name));
LONG result =
reg_key.Open(HKEY_LOCAL_MACHINE, root_key.c_str(), KEY_QUERY_VALUE);
if (result != ERROR_SUCCESS) {
return std::wstring();
}
std::wstring port_value_data;
result = reg_key.ReadValue(kPortRegistryValueName, &port_value_data);
if (result != ERROR_SUCCESS) {
return std::wstring();
}
return port_value_data;
}
std::string GetDriverVersionString(DWORDLONG version_number) {
// A Windows driver version number is four 16-bit unsigned integers
// concatenated together as w.x.y.z in a 64 bit unsigned int.
// https://learn.microsoft.com/en-us/windows-hardware/drivers/install/inf-driverver-directive
return base::StringPrintf(
"%u.%u.%u.%u", static_cast<uint16_t>((version_number >> 48) & 0xFFFF),
static_cast<uint16_t>((version_number >> 32) & 0xFFFF),
static_cast<uint16_t>((version_number >> 16) & 0xFFFF),
static_cast<uint16_t>(version_number & 0xFFFF));
}
std::optional<PrinterBasicInfo> GetBasicPrinterInfoMixedMethod(HANDLE printer) {
// `printer` already guaranteed to be non-null by caller.
CHECK(printer);
PrinterInfo1 info_1;
if (!info_1.Init(printer)) {
return std::nullopt;
}
PrinterBasicInfo printer_info =
InitializePrinterInfo(info_1.get()->pName, info_1.get()->pComment);
// Location is not available from the fast ::GetPrinter() call that uses
// PRINTER_INFO_1, it is only available with the potentially slow level
// PRINTER_INFO_2. Try to read the location information directly from the
// registry. Since the location metadata is not critical, do not fail if
// the printer cannot be found in the registry. Capture the success of this
// in a metric, as it will be of interest should finding the registry entry
// ever fail.
base::win::RegKey reg_key;
std::wstring root_key =
base::StrCat({kDriversRegistryKeyPath, info_1.get()->pName});
LONG result =
reg_key.Open(HKEY_LOCAL_MACHINE, root_key.c_str(), KEY_QUERY_VALUE);
base::UmaHistogramBoolean("Printing.EnumeratePrinters.BasicInfo.Registry",
result == ERROR_SUCCESS);
if (result == ERROR_SUCCESS) {
// Even though the registry entry for the printer is found, it isn't
// required to contain a value name for location.
std::wstring value_data;
result = reg_key.ReadValue(kLocationRegistryValueName, &value_data);
if (result == ERROR_SUCCESS && !value_data.empty()) {
printer_info.options[kLocationTagName] = base::WideToUTF8(value_data);
}
}
return printer_info;
}
} // namespace
// static
bool PrinterHandleTraits::CloseHandle(HANDLE handle) {
return ::ClosePrinter(handle) != FALSE;
}
// static
bool PrinterChangeHandleTraits::CloseHandle(HANDLE handle) {
::FindClosePrinterChangeNotification(handle);
return true;
}
bool ScopedPrinterHandle::OpenPrinterWithName(const wchar_t* printer) {
HANDLE temp_handle;
// ::OpenPrinter may return error but assign some value into handle.
if (::OpenPrinter(const_cast<LPTSTR>(printer), &temp_handle, nullptr)) {
Set(temp_handle);
}
return IsValid();
}
bool XPSModule::Init() {
static bool initialized = InitImpl();
return initialized;
}
bool XPSModule::InitImpl() {
HMODULE prntvpt_module = LoadLibrary(L"prntvpt.dll");
if (!prntvpt_module)
return false;
g_open_provider_proc = reinterpret_cast<PTOpenProviderProc>(
GetProcAddress(prntvpt_module, "PTOpenProvider"));
if (!g_open_provider_proc) {
NOTREACHED();
}
g_get_print_capabilities_proc = reinterpret_cast<PTGetPrintCapabilitiesProc>(
GetProcAddress(prntvpt_module, "PTGetPrintCapabilities"));
if (!g_get_print_capabilities_proc) {
NOTREACHED();
}
g_convert_devmode_to_print_ticket_proc =
reinterpret_cast<PTConvertDevModeToPrintTicketProc>(
GetProcAddress(prntvpt_module, "PTConvertDevModeToPrintTicket"));
if (!g_convert_devmode_to_print_ticket_proc) {
NOTREACHED();
}
g_convert_print_ticket_to_devmode_proc =
reinterpret_cast<PTConvertPrintTicketToDevModeProc>(
GetProcAddress(prntvpt_module, "PTConvertPrintTicketToDevMode"));
if (!g_convert_print_ticket_to_devmode_proc) {
NOTREACHED();
}
g_merge_and_validate_print_ticket_proc =
reinterpret_cast<PTMergeAndValidatePrintTicketProc>(
GetProcAddress(prntvpt_module, "PTMergeAndValidatePrintTicket"));
if (!g_merge_and_validate_print_ticket_proc) {
NOTREACHED();
}
g_release_memory_proc = reinterpret_cast<PTReleaseMemoryProc>(
GetProcAddress(prntvpt_module, "PTReleaseMemory"));
if (!g_release_memory_proc) {
NOTREACHED();
}
g_close_provider_proc = reinterpret_cast<PTCloseProviderProc>(
GetProcAddress(prntvpt_module, "PTCloseProvider"));
if (!g_close_provider_proc) {
NOTREACHED();
}
return true;
}
HRESULT XPSModule::OpenProvider(const std::wstring& printer_name,
DWORD version,
HPTPROVIDER* provider) {
base::ScopedBlockingCall scoped_blocking_call(FROM_HERE,
base::BlockingType::MAY_BLOCK);
return g_open_provider_proc(printer_name.c_str(), version, provider);
}
HRESULT XPSModule::GetPrintCapabilities(HPTPROVIDER provider,
IStream* print_ticket,
IStream* capabilities,
BSTR* error_message) {
base::ScopedBlockingCall scoped_blocking_call(FROM_HERE,
base::BlockingType::MAY_BLOCK);
return g_get_print_capabilities_proc(provider, print_ticket, capabilities,
error_message);
}
HRESULT XPSModule::ConvertDevModeToPrintTicket(HPTPROVIDER provider,
ULONG devmode_size_in_bytes,
PDEVMODE devmode,
EPrintTicketScope scope,
IStream* print_ticket) {
base::ScopedBlockingCall scoped_blocking_call(FROM_HERE,
base::BlockingType::MAY_BLOCK);
return g_convert_devmode_to_print_ticket_proc(provider, devmode_size_in_bytes,
devmode, scope, print_ticket);
}
HRESULT XPSModule::ConvertPrintTicketToDevMode(
HPTPROVIDER provider,
IStream* print_ticket,
EDefaultDevmodeType base_devmode_type,
EPrintTicketScope scope,
ULONG* devmode_byte_count,
PDEVMODE* devmode,
BSTR* error_message) {
base::ScopedBlockingCall scoped_blocking_call(FROM_HERE,
base::BlockingType::MAY_BLOCK);
return g_convert_print_ticket_to_devmode_proc(
provider, print_ticket, base_devmode_type, scope, devmode_byte_count,
devmode, error_message);
}
HRESULT XPSModule::MergeAndValidatePrintTicket(HPTPROVIDER provider,
IStream* base_ticket,
IStream* delta_ticket,
EPrintTicketScope scope,
IStream* result_ticket,
BSTR* error_message) {
base::ScopedBlockingCall scoped_blocking_call(FROM_HERE,
base::BlockingType::MAY_BLOCK);
return g_merge_and_validate_print_ticket_proc(
provider, base_ticket, delta_ticket, scope, result_ticket, error_message);
}
HRESULT XPSModule::ReleaseMemory(PVOID buffer) {
base::ScopedBlockingCall scoped_blocking_call(FROM_HERE,
base::BlockingType::MAY_BLOCK);
return g_release_memory_proc(buffer);
}
HRESULT XPSModule::CloseProvider(HPTPROVIDER provider) {
base::ScopedBlockingCall scoped_blocking_call(FROM_HERE,
base::BlockingType::MAY_BLOCK);
return g_close_provider_proc(provider);
}
ScopedXPSInitializer::ScopedXPSInitializer() : initialized_(false) {
if (!XPSModule::Init())
return;
// Calls to XPS APIs typically require the XPS provider to be opened with
// PTOpenProvider. PTOpenProvider calls CoInitializeEx with
// COINIT_MULTITHREADED. We have seen certain buggy HP printer driver DLLs
// that call CoInitializeEx with COINIT_APARTMENTTHREADED in the context of
// PTGetPrintCapabilities. This call fails but the printer driver calls
// CoUninitialize anyway. This results in the apartment being torn down too
// early and the msxml DLL being unloaded which in turn causes code in
// unidrvui.dll to have a dangling pointer to an XML document which causes a
// crash. To protect ourselves from such drivers we make sure we always have
// an extra CoInitialize (calls to CoInitialize/CoUninitialize are
// refcounted).
HRESULT hr = CoInitializeEx(nullptr, COINIT_MULTITHREADED);
// If this succeeded we are done because the PTOpenProvider call will provide
// the extra refcount on the apartment. If it failed because someone already
// called CoInitializeEx with COINIT_APARTMENTTHREADED, we try the other model
// to provide the additional refcount (since we don't know which model buggy
// printer drivers will use).
if (!SUCCEEDED(hr))
hr = CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED);
DCHECK(SUCCEEDED(hr));
initialized_ = true;
}
ScopedXPSInitializer::~ScopedXPSInitializer() {
if (initialized_)
CoUninitialize();
initialized_ = false;
}
bool XPSPrintModule::Init() {
static bool initialized = InitImpl();
return initialized;
}
bool XPSPrintModule::InitImpl() {
HMODULE xpsprint_module = LoadLibrary(L"xpsprint.dll");
if (!xpsprint_module)
return false;
g_start_xps_print_job_proc = reinterpret_cast<StartXpsPrintJobProc>(
GetProcAddress(xpsprint_module, "StartXpsPrintJob"));
if (!g_start_xps_print_job_proc) {
NOTREACHED();
}
return true;
}
HRESULT XPSPrintModule::StartXpsPrintJob(
const LPCWSTR printer_name,
const LPCWSTR job_name,
const LPCWSTR output_file_name,
HANDLE progress_event,
HANDLE completion_event,
UINT8* printable_pages_on,
UINT32 printable_pages_on_count,
IXpsPrintJob** xps_print_job,
IXpsPrintJobStream** document_stream,
IXpsPrintJobStream** print_ticket_stream) {
return g_start_xps_print_job_proc(
printer_name, job_name, output_file_name, progress_event,
completion_event, printable_pages_on, printable_pages_on_count,
xps_print_job, document_stream, print_ticket_stream);
}
void SetGetDisplayNameFunction(GetDisplayNameFunc get_display_name_func) {
DCHECK(get_display_name_func);
DCHECK(!g_get_display_name_func);
g_get_display_name_func = get_display_name_func;
}
std::optional<PrinterBasicInfo> GetBasicPrinterInfo(HANDLE printer) {
if (!printer) {
return std::nullopt;
}
if (base::FeatureList::IsEnabled(features::kFastEnumeratePrinters)) {
return GetBasicPrinterInfoMixedMethod(printer);
}
PrinterInfo2 info_2;
if (!info_2.Init(printer)) {
return std::nullopt;
}
PrinterBasicInfo printer_info =
InitializePrinterInfo(info_2.get()->pPrinterName, info_2.get()->pComment);
if (info_2.get()->pLocation) {
std::string location = base::WideToUTF8(info_2.get()->pLocation);
if (!location.empty()) {
printer_info.options[kLocationTagName] = std::move(location);
}
}
return printer_info;
}
std::optional<PrinterBasicInfo>
GetBasicPrinterInfoMixedMethodForTesting( // IN-TEST
HANDLE printer) {
return GetBasicPrinterInfoMixedMethod(printer);
}
std::vector<std::string> GetDriverInfo(HANDLE printer) {
DCHECK(printer);
std::vector<std::string> driver_info;
if (!printer) {
return driver_info;
}
DriverInfo6 info_6;
if (!info_6.Init(printer)) {
return driver_info;
}
driver_info.emplace_back(info_6.get()->pName
? base::WideToUTF8(info_6.get()->pName)
: std::string());
driver_info.emplace_back(
info_6.get()->dwlDriverVersion
? GetDriverVersionString(info_6.get()->dwlDriverVersion)
: std::string());
if (info_6.get()->pDriverPath) {
std::unique_ptr<FileVersionInfo> version_info(
FileVersionInfo::CreateFileVersionInfo(
base::FilePath(info_6.get()->pDriverPath)));
if (version_info.get()) {
driver_info.emplace_back(base::UTF16ToUTF8(version_info->file_version()));
driver_info.emplace_back(base::UTF16ToUTF8(version_info->product_name()));
}
}
return driver_info;
}
bool DoesDriverDisplayFileDialogForPrinting(const std::string& printer_name) {
static constexpr auto kPortNames = base::MakeFixedFlatSet<std::wstring_view>(
{kPrinterDriverPortFile, kPrinterDriverPortPrompt,
kPrinterDriverPortFax});
return kPortNames.contains(GetPrinterDriverPort(printer_name));
}
std::unique_ptr<DEVMODE, base::FreeDeleter> XpsTicketToDevMode(
const std::wstring& printer_name,
const std::string& print_ticket) {
std::unique_ptr<DEVMODE, base::FreeDeleter> dev_mode;
ScopedXPSInitializer xps_initializer;
if (!xps_initializer.initialized()) {
// TODO(sanjeevr): Handle legacy proxy case (with no prntvpt.dll)
return dev_mode;
}
ScopedPrinterHandle printer;
if (!printer.OpenPrinterWithName(printer_name.c_str()))
return dev_mode;
Microsoft::WRL::ComPtr<IStream> pt_stream;
HRESULT hr = StreamFromPrintTicket(print_ticket, &pt_stream);
if (FAILED(hr))
return dev_mode;
HPTPROVIDER provider = nullptr;
hr = XPSModule::OpenProvider(printer_name, 1, &provider);
if (SUCCEEDED(hr)) {
ULONG size = 0;
DEVMODE* dm = nullptr;
// Use kPTJobScope, because kPTDocumentScope breaks duplex.
hr = XPSModule::ConvertPrintTicketToDevMode(
provider, pt_stream.Get(), kUserDefaultDevmode, kPTJobScope, &size, &dm,
nullptr);
if (SUCCEEDED(hr)) {
// Correct DEVMODE using DocumentProperties. See documentation for
// PTConvertPrintTicketToDevMode.
dev_mode = CreateDevMode(printer.Get(), dm);
XPSModule::ReleaseMemory(dm);
}
XPSModule::CloseProvider(provider);
}
return dev_mode;
}
bool IsDevModeWithColor(const DEVMODE* devmode) {
return (devmode->dmFields & DM_COLOR) && (devmode->dmColor == DMCOLOR_COLOR);
}
std::unique_ptr<DEVMODE, base::FreeDeleter> CreateDevModeWithColor(
HANDLE printer,
const std::wstring& printer_name,
bool color) {
std::unique_ptr<DEVMODE, base::FreeDeleter> default_ticket =
CreateDevMode(printer, nullptr);
if (!default_ticket || IsDevModeWithColor(default_ticket.get()) == color)
return default_ticket;
default_ticket->dmFields |= DM_COLOR;
default_ticket->dmColor = color ? DMCOLOR_COLOR : DMCOLOR_MONOCHROME;
DriverInfo6 info_6;
if (!info_6.Init(printer))
return default_ticket;
const DRIVER_INFO_6* p = info_6.get();
// Only HP known to have issues.
if (!p->pszMfgName || UNSAFE_TODO(wcscmp(p->pszMfgName, L"HP")) != 0) {
return default_ticket;
}
// Need XPS for this workaround.
ScopedXPSInitializer xps_initializer;
if (!xps_initializer.initialized())
return default_ticket;
const char* xps_color = color ? kXpsTicketColor : kXpsTicketMonochrome;
std::string xps_ticket = base::StringPrintf(kXpsTicketTemplate, xps_color);
std::unique_ptr<DEVMODE, base::FreeDeleter> ticket =
XpsTicketToDevMode(printer_name, xps_ticket);
if (!ticket)
return default_ticket;
return ticket;
}
bool PrinterHasValidPaperSize(const wchar_t* name, const wchar_t* port) {
base::ScopedBlockingCall scoped_blocking_call(FROM_HERE,
base::BlockingType::MAY_BLOCK);
return DeviceCapabilities(name, port, DC_PAPERSIZE, nullptr, nullptr) > 0;
}
std::unique_ptr<DEVMODE, base::FreeDeleter> CreateDevMode(HANDLE printer,
DEVMODE* in) {
wchar_t* device_name_ptr = const_cast<wchar_t*>(L"");
LONG buffer_size;
{
base::ScopedBlockingCall scoped_blocking_call(
FROM_HERE, base::BlockingType::MAY_BLOCK);
buffer_size = DocumentProperties(nullptr, printer, device_name_ptr, nullptr,
nullptr, 0);
}
// TODO(thestig): Consider limiting `buffer_size` to avoid buggy printer
// drivers that return excessively large values.
if (buffer_size < static_cast<LONG>(sizeof(DEVMODE)))
return nullptr;
// Some drivers request buffers with size smaller than dmSize + dmDriverExtra.
// Examples: crbug.com/421402, crbug.com/780016
// Pad the `out` buffer so there is plenty of space. Calculate the size using
// `base::CheckedNumeric` to avoid a potential integer overflow.
base::CheckedNumeric<LONG> safe_buffer_size = buffer_size;
safe_buffer_size *= 2;
safe_buffer_size += 8192;
buffer_size = safe_buffer_size.ValueOrDie();
std::unique_ptr<DEVMODE, base::FreeDeleter> out(
reinterpret_cast<DEVMODE*>(calloc(buffer_size, 1)));
DWORD flags = (in ? (DM_IN_BUFFER) : 0) | DM_OUT_BUFFER;
PrinterInfo5 info_5;
if (!info_5.Init(printer))
return nullptr;
// Check that valid paper sizes exist; some old drivers return no paper sizes
// and crash in DocumentProperties if used with Win10. See crbug.com/679160,
// crbug.com/724595
const wchar_t* name = info_5.get()->pPrinterName;
const wchar_t* port = info_5.get()->pPortName;
if (!PrinterHasValidPaperSize(name, port)) {
return nullptr;
}
{
base::ScopedBlockingCall scoped_blocking_call(
FROM_HERE, base::BlockingType::MAY_BLOCK);
if (DocumentProperties(nullptr, printer, device_name_ptr, out.get(), in,
flags) != IDOK) {
return nullptr;
}
}
int size = out->dmSize;
int extra_size = out->dmDriverExtra;
// The CHECK_GE() below can fail. Alias the variable values so they are
// recorded in crash dumps.
// See https://crbug.com/780016 and https://crbug.com/806016 for example
// crashes.
// TODO(crbug.com/41352705): Remove this debug code if the CHECK_GE() below
// stops failing.
base::debug::Alias(&size);
base::debug::Alias(&extra_size);
base::debug::Alias(&buffer_size);
CHECK_GE(buffer_size, size + extra_size);
return out;
}
std::unique_ptr<DEVMODE, base::FreeDeleter> PromptDevMode(
HANDLE printer,
const std::wstring& printer_name,
DEVMODE* in,
HWND window,
bool* canceled) {
wchar_t* printer_name_ptr = const_cast<wchar_t*>(printer_name.c_str());
LONG buffer_size = DocumentProperties(window, printer, printer_name_ptr,
nullptr, nullptr, 0);
if (buffer_size < static_cast<int>(sizeof(DEVMODE)))
return std::unique_ptr<DEVMODE, base::FreeDeleter>();
// Some drivers request buffers with size smaller than dmSize + dmDriverExtra.
// crbug.com/421402
buffer_size *= 2;
std::unique_ptr<DEVMODE, base::FreeDeleter> out(
reinterpret_cast<DEVMODE*>(calloc(buffer_size, 1)));
DWORD flags = (in ? (DM_IN_BUFFER) : 0) | DM_OUT_BUFFER | DM_IN_PROMPT;
LONG result;
{
base::ScopedBlockingCall scoped_blocking_call(
FROM_HERE, base::BlockingType::MAY_BLOCK);
result = DocumentProperties(window, printer, printer_name_ptr, out.get(),
in, flags);
}
if (canceled)
*canceled = (result == IDCANCEL);
if (result != IDOK)
return std::unique_ptr<DEVMODE, base::FreeDeleter>();
int size = out->dmSize;
int extra_size = out->dmDriverExtra;
CHECK_GE(buffer_size, size + extra_size);
return out;
}
std::string GetDriverVersionStringForTesting(DWORDLONG version_number) {
return GetDriverVersionString(version_number);
}
mojom::ResultCode GetResultCodeFromSystemErrorCode(
logging::SystemErrorCode system_code) {
if (system_code == ERROR_ACCESS_DENIED) {
return mojom::ResultCode::kAccessDenied;
}
return mojom::ResultCode::kFailed;
}
} // namespace printing
|