blob: 9144feee151afcbd311f2611d389a875a0e3c8cf [file] [log] [blame]
// Copyright 2017 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 "chrome/browser/chromeos/printing/zeroconf_printer_detector.h"
#include <map>
#include <string>
#include <utility>
#include <vector>
#include "base/md5.h"
#include "base/observer_list_threadsafe.h"
#include "base/stl_util.h"
#include "base/strings/stringprintf.h"
#include "base/synchronization/lock.h"
#include "chrome/browser/local_discovery/service_discovery_device_lister.h"
#include "chrome/browser/local_discovery/service_discovery_shared_client.h"
#include "chrome/browser/profiles/profile.h"
namespace chromeos {
// Supported service names for printers.
const char* ZeroconfPrinterDetector::kIppServiceName = "_ipp._tcp.local";
const char* ZeroconfPrinterDetector::kIppsServiceName = "_ipps._tcp.local";
// IppEverywhere printers are also required to advertise these services.
const char* ZeroconfPrinterDetector::kIppEverywhereServiceName =
"_ipp._tcp.local,_print";
const char* ZeroconfPrinterDetector::kIppsEverywhereServiceName =
"_ipps._tcp.local,_print";
namespace {
using local_discovery::ServiceDescription;
using local_discovery::ServiceDiscoveryDeviceLister;
using local_discovery::ServiceDiscoverySharedClient;
// These (including the default values) come from section 9.2 of the Bonjour
// Printing Spec v1.2, and the field names follow the spec definitions instead
// of the canonical Chromium style.
//
// Not all of these will necessarily be specified for a given printer. Also, we
// only define the fields that we care about, others not listed here we just
// ignore.
class ParsedMetadata {
public:
std::string adminurl;
std::string air = "none";
std::string note;
std::string pdl = "application/postscript";
// We stray slightly from the spec for product. In the bonjour spec, product
// is always enclosed in parentheses because...reasons. We strip out parens.
std::string product;
std::string rp;
std::string ty;
std::string usb_MDL;
std::string usb_MFG;
std::string UUID;
// Parse out metadata from sd to fill this structure.
explicit ParsedMetadata(const ServiceDescription& sd) {
for (const std::string& m : sd.metadata) {
size_t equal_pos = m.find('=');
if (equal_pos == std::string::npos) {
// Malformed, skip it.
continue;
}
base::StringPiece key(m.data(), equal_pos);
base::StringPiece value(m.data() + equal_pos + 1,
m.length() - (equal_pos + 1));
if (key == "note") {
note = value.as_string();
} else if (key == "pdl") {
pdl = value.as_string();
} else if (key == "product") {
// Strip parens; ignore anything not enclosed in parens as malformed.
if (value.starts_with("(") && value.ends_with(")")) {
product = value.substr(1, value.size() - 2).as_string();
}
} else if (key == "rp") {
rp = value.as_string();
} else if (key == "ty") {
ty = value.as_string();
} else if (key == "usb_MDL") {
usb_MDL = value.as_string();
} else if (key == "usb_MFG") {
usb_MFG = value.as_string();
} else if (key == "UUID") {
UUID = value.as_string();
}
}
}
ParsedMetadata(const ParsedMetadata& other) = delete;
};
// Create a unique identifier for this printer based on the ServiceDescription.
// This is what is used to determine whether or not this is the same printer
// when seen again later. We use an MD5 hash of fields we expect to be
// immutable.
//
// These ids are persistent in synced storage; if you change this function
// carelessly, you will create mismatches between users' stored printer
// configurations and the printers themselves.
//
// Note we explicitly *don't* use the service type in this hash, because the
// same printer may export multiple services (ipp and ipps), and we want them
// all to be considered the same printer.
std::string ZeroconfPrinterId(const ServiceDescription& service,
const ParsedMetadata& metadata) {
base::MD5Context ctx;
base::MD5Init(&ctx);
base::MD5Update(&ctx, service.instance_name());
base::MD5Update(&ctx, metadata.product);
base::MD5Update(&ctx, metadata.UUID);
base::MD5Update(&ctx, metadata.usb_MFG);
base::MD5Update(&ctx, metadata.usb_MDL);
base::MD5Update(&ctx, metadata.ty);
base::MD5Update(&ctx, metadata.rp);
base::MD5Digest digest;
base::MD5Final(&digest, &ctx);
return base::StringPrintf("zeroconf-%s",
base::MD5DigestToBase16(digest).c_str());
}
// Attempt to fill |detected_printer| using the information in
// |service_description| and |metadata|. Return true on success, false on
// failure.
bool ConvertToPrinter(const ServiceDescription& service_description,
const ParsedMetadata& metadata,
PrinterDetector::DetectedPrinter* detected_printer) {
// If we don't have the minimum information needed to attempt a setup, fail.
// Also fail on a port of 0, as this is used to indicate that the service
// doesn't *actually* exist, the device just wants to guard the name.
if (service_description.service_name.empty() || metadata.ty.empty() ||
service_description.ip_address.empty() ||
(service_description.address.port() == 0)) {
return false;
}
Printer& printer = detected_printer->printer;
printer.set_id(ZeroconfPrinterId(service_description, metadata));
printer.set_uuid(metadata.UUID);
printer.set_display_name(metadata.ty);
printer.set_description(metadata.note);
printer.set_make_and_model(metadata.product);
const char* uri_protocol;
if ((service_description.service_type() ==
base::StringPiece(ZeroconfPrinterDetector::kIppServiceName)) ||
(service_description.service_type() ==
base::StringPiece(ZeroconfPrinterDetector::kIppEverywhereServiceName))) {
uri_protocol = "ipp";
} else if ((service_description.service_type() ==
base::StringPiece(ZeroconfPrinterDetector::kIppsServiceName)) ||
(service_description.service_type() ==
base::StringPiece(
ZeroconfPrinterDetector::kIppsEverywhereServiceName))) {
uri_protocol = "ipps";
} else {
// Since we only register for these services, we should never get back
// a service other than the ones above.
NOTREACHED() << "Zeroconf printer with unknown service type"
<< service_description.service_type();
return false;
}
printer.set_uri(base::StringPrintf(
"%s://%s/%s", uri_protocol,
service_description.address.ToString().c_str(), metadata.rp.c_str()));
// Use an effective URI with a pre-resolved ip address and port, since CUPS
// can't resolve these addresses in ChromeOS (crbug/626377).
printer.set_effective_uri(base::StringPrintf(
"%s://%s:%d/%s", uri_protocol,
service_description.ip_address.ToString().c_str(),
service_description.address.port(), metadata.rp.c_str()));
// Per the IPP Everywhere Standard 5100.14-2013, section 4.2.1, IPP
// everywhere-capable printers advertise services suffixed with ",_print"
// (possibly in addition to suffix-free versions). If we get a printer from a
// ,_print service type, it should be auto-configurable with IPP Everywhere.
printer.mutable_ppd_reference()->autoconf =
base::StringPiece(service_description.service_type())
.ends_with(",_print");
// gather ppd identification candidates.
if (!metadata.ty.empty()) {
detected_printer->ppd_search_data.make_and_model.push_back(metadata.ty);
}
if (!metadata.product.empty()) {
detected_printer->ppd_search_data.make_and_model.push_back(
metadata.product);
}
if (!metadata.usb_MFG.empty() && !metadata.usb_MDL.empty()) {
detected_printer->ppd_search_data.make_and_model.push_back(
base::StringPrintf("%s %s", metadata.usb_MFG.c_str(),
metadata.usb_MDL.c_str()));
}
return true;
}
class ZeroconfPrinterDetectorImpl : public ZeroconfPrinterDetector {
public:
// Normal constructor, connects to service discovery.
ZeroconfPrinterDetectorImpl()
: discovery_client_(ServiceDiscoverySharedClient::GetInstance()),
observer_list_(new base::ObserverListThreadSafe<Observer>()) {
CreateDeviceLister(kIppServiceName);
CreateDeviceLister(kIppsServiceName);
CreateDeviceLister(kIppEverywhereServiceName);
CreateDeviceLister(kIppsEverywhereServiceName);
}
// Testing constructor, uses injected backends.
explicit ZeroconfPrinterDetectorImpl(
std::map<std::string, std::unique_ptr<ServiceDiscoveryDeviceLister>>*
device_listers)
: observer_list_(new base::ObserverListThreadSafe<Observer>()) {
device_listers_.swap(*device_listers);
for (auto& entry : device_listers_) {
entry.second->Start();
entry.second->DiscoverNewDevices();
}
}
~ZeroconfPrinterDetectorImpl() override {}
std::vector<DetectedPrinter> GetPrinters() override {
base::AutoLock auto_lock(printers_lock_);
return GetPrintersLocked();
}
void AddObserver(Observer* observer) override {
observer_list_->AddObserver(observer);
}
void RemoveObserver(Observer* observer) override {
observer_list_->RemoveObserver(observer);
}
// ServiceDiscoveryDeviceLister::Delegate implementation
void OnDeviceChanged(const std::string& service_type,
bool added,
const ServiceDescription& service_description) override {
// We don't care if it was added or not; we generate an update either way.
ParsedMetadata metadata(service_description);
DetectedPrinter printer;
if (!ConvertToPrinter(service_description, metadata, &printer)) {
return;
}
base::AutoLock auto_lock(printers_lock_);
printers_[service_type][service_description.instance_name()] = printer;
observer_list_->Notify(FROM_HERE,
&PrinterDetector::Observer::OnPrintersFound,
GetPrintersLocked());
}
// ServiceDiscoveryDeviceLister::Delegate implementation. Remove the
// given device if we know about it.
void OnDeviceRemoved(const std::string& service_type,
const std::string& service_name) override {
// Leverage ServiceDescription parsing to pull out the instance name.
ServiceDescription service_description;
service_description.service_name = service_name;
base::AutoLock auto_lock(printers_lock_);
auto& service_type_map = printers_[service_type];
auto it = service_type_map.find(service_description.instance_name());
if (it != service_type_map.end()) {
service_type_map.erase(it);
observer_list_->Notify(FROM_HERE,
&PrinterDetector::Observer::OnPrintersFound,
GetPrintersLocked());
} else {
LOG(WARNING) << "Device removal requested for unknown '" << service_name
<< "'";
}
}
// Remove all devices that originated on this service type, and request
// a new round of discovery.
void OnDeviceCacheFlushed(const std::string& service_type) override {
base::AutoLock auto_lock(printers_lock_);
if (!printers_[service_type].empty()) {
printers_[service_type].clear();
observer_list_->Notify(FROM_HERE,
&PrinterDetector::Observer::OnPrintersFound,
GetPrintersLocked());
}
// Request a new round of discovery from the lister.
auto lister_entry = device_listers_.find(service_type);
DCHECK(lister_entry != device_listers_.end());
lister_entry->second->DiscoverNewDevices();
}
// Create a new device lister for the given |service_type| and add it
// to the ones managed by this object.
void CreateDeviceLister(const std::string& service_type) {
auto lister = ServiceDiscoveryDeviceLister::Create(
this, discovery_client_.get(), service_type);
lister->Start();
lister->DiscoverNewDevices();
DCHECK(!base::ContainsKey(device_listers_, service_type));
device_listers_[service_type] = std::move(lister);
}
private:
// Requires that printers_lock_ be held.
std::vector<DetectedPrinter> GetPrintersLocked() {
printers_lock_.AssertAcquired();
std::map<std::string, DetectedPrinter> unified;
// The order in which we look through these maps defines priority -- earlier
// service types in this list will be used preferentially over later ones.
// This depends on the fact that map::insert will fail if the entry already
// exists.
for (const char* service_type : {
kIppsEverywhereServiceName, kIppEverywhereServiceName,
kIppsServiceName, kIppServiceName,
}) {
for (const auto& entry : printers_[service_type]) {
unified.insert({entry.first, entry.second});
}
}
std::vector<DetectedPrinter> ret;
ret.reserve(printers_.size());
for (const auto& entry : unified) {
ret.push_back(entry.second);
}
return ret;
}
// Map from service type to map from instance name to associated known
// printer, and associated lock.
std::map<std::string, std::map<std::string, DetectedPrinter>> printers_;
base::Lock printers_lock_;
// Keep a reference to the shared device client around for the lifetime of
// this object.
scoped_refptr<ServiceDiscoverySharedClient> discovery_client_;
// Map from service_type to associated lister.
std::map<std::string, std::unique_ptr<ServiceDiscoveryDeviceLister>>
device_listers_;
// Observers of this object.
scoped_refptr<base::ObserverListThreadSafe<Observer>> observer_list_;
};
} // namespace
// static
std::unique_ptr<ZeroconfPrinterDetector> ZeroconfPrinterDetector::Create() {
return std::make_unique<ZeroconfPrinterDetectorImpl>();
}
// static
std::unique_ptr<ZeroconfPrinterDetector>
ZeroconfPrinterDetector::CreateForTesting(
std::map<std::string, std::unique_ptr<ServiceDiscoveryDeviceLister>>*
device_listers) {
return std::make_unique<ZeroconfPrinterDetectorImpl>(device_listers);
}
} // namespace chromeos