forked from chromium/chromium
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathppd_provider.cc
1595 lines (1410 loc) · 59.3 KB
/
ppd_provider.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
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// 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 "chromeos/printing/ppd_provider.h"
#include <algorithm>
#include <memory>
#include <set>
#include <unordered_map>
#include <utility>
#include <vector>
#include "base/base64.h"
#include "base/bind.h"
#include "base/bind_helpers.h"
#include "base/containers/circular_deque.h"
#include "base/files/file.h"
#include "base/files/file_util.h"
#include "base/json/json_parser.h"
#include "base/optional.h"
#include "base/sequenced_task_runner.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_split.h"
#include "base/strings/string_tokenizer.h"
#include "base/strings/string_util.h"
#include "base/strings/stringprintf.h"
#include "base/synchronization/lock.h"
#include "base/task/post_task.h"
#include "base/task_runner_util.h"
#include "base/threading/scoped_blocking_call.h"
#include "base/threading/sequenced_task_runner_handle.h"
#include "base/time/time.h"
#include "base/values.h"
#include "chromeos/printing/epson_driver_matching.h"
#include "chromeos/printing/ppd_cache.h"
#include "chromeos/printing/ppd_line_reader.h"
#include "chromeos/printing/printing_constants.h"
#include "net/base/filename_util.h"
#include "net/base/load_flags.h"
#include "net/http/http_status_code.h"
#include "net/url_request/url_fetcher.h"
#include "net/url_request/url_fetcher_delegate.h"
#include "net/url_request/url_request_context_getter.h"
#include "services/network/public/cpp/resource_request.h"
#include "services/network/public/cpp/simple_url_loader.h"
#include "url/gurl.h"
namespace chromeos {
namespace {
const char kEpsonGenericPPD[] = "epson generic escpr printer";
// Holds a metadata_v2 reverse-index response
struct ReverseIndexJSON {
// Canonical name of printer
std::string effective_make_and_model;
// Name of printer manufacturer
std::string manufacturer;
// Name of printer model
std::string model;
// Restrictions for this manufacturer
PpdProvider::Restrictions restrictions;
};
// Holds a metadata_v2 manufacturers response
struct ManufacturersJSON {
// Name of printer manufacturer
std::string name;
// Key for lookup of this manutacturer's printers (JSON file)
std::string reference;
// Restrictions for this manufacturer
PpdProvider::Restrictions restrictions;
};
// Holds a metadata_v2 printers response
struct PrintersJSON {
// Name of printer
std::string name;
// Canonical name of printer
std::string effective_make_and_model;
// Restrictions for this printer
PpdProvider::Restrictions restrictions;
};
// Holds a metadata_v2 ppd-index response
struct PpdIndexJSON {
// Canonical name of printer
std::string effective_make_and_model;
// Ppd filename
std::string ppd_filename;
};
// A queued request to download printer information for a manufacturer.
// Note: Disabled copying/assigning since this holds a base::OnceCalback.
struct PrinterResolutionQueueEntry {
PrinterResolutionQueueEntry() = default;
PrinterResolutionQueueEntry(PrinterResolutionQueueEntry&& other) = default;
~PrinterResolutionQueueEntry() = default;
// Localized manufacturer name
std::string manufacturer;
// URL we are going to pull from.
GURL url;
// User callback on completion.
PpdProvider::ResolvePrintersCallback cb;
DISALLOW_COPY_AND_ASSIGN(PrinterResolutionQueueEntry);
};
// A queued request to download reverse index information for a make and model
// Note: Disabled copying/assigning since this holds a base::OnceCalback.
struct ReverseIndexQueueEntry {
ReverseIndexQueueEntry() = default;
ReverseIndexQueueEntry(ReverseIndexQueueEntry&& other) = default;
~ReverseIndexQueueEntry() = default;
// Canonical Printer Name
std::string effective_make_and_model;
// URL we are going to pull from.
GURL url;
// User callback on completion.
PpdProvider::ReverseLookupCallback cb;
DISALLOW_COPY_AND_ASSIGN(ReverseIndexQueueEntry);
};
// Holds manufacturer to printers relation
struct ManufacturerMetadata {
// Key used to look up the printer list on the server. This is initially
// populated.
std::string reference;
// Map from localized printer name to canonical-make-and-model string for
// the given printer. Populated on demand.
std::unique_ptr<std::unordered_map<std::string, PrintersJSON>> printers;
};
// Carried information for an inflight PPD resolution.
// Note: Disabled copying/assigning since this holds a base::OnceCalback.
struct PpdResolutionQueueEntry {
PpdResolutionQueueEntry() = default;
PpdResolutionQueueEntry(PpdResolutionQueueEntry&& other) = default;
~PpdResolutionQueueEntry() = default;
// Original reference being resolved.
Printer::PpdReference reference;
// If non-empty, the contents from the cache for this resolution.
std::string cached_contents;
// Callback to be invoked on completion.
PpdProvider::ResolvePpdCallback callback;
DISALLOW_COPY_AND_ASSIGN(PpdResolutionQueueEntry);
};
// Carried information for an inflight PPD reference resolution.
// Note: Disabled copying/assigning since this holds a base::OnceCalback.
struct PpdReferenceResolutionQueueEntry {
PpdReferenceResolutionQueueEntry() = default;
PpdReferenceResolutionQueueEntry(PpdReferenceResolutionQueueEntry&& other) =
default;
~PpdReferenceResolutionQueueEntry() = default;
// Metadata used to resolve to a unique PpdReference object.
PrinterSearchData search_data;
// If true, we have failed usb_index_resolution already.
bool usb_resolution_attempted = false;
// Callback to be invoked on completion.
PpdProvider::ResolvePpdReferenceCallback cb;
DISALLOW_COPY_AND_ASSIGN(PpdReferenceResolutionQueueEntry);
};
// Extract cupsFilter/cupsFilter2 filter names from a line from a ppd.
// cupsFilter2 lines look like this:
//
// *cupsFilter2: "application/vnd.cups-raster application/vnd.foo 100
// rastertofoo"
//
// cupsFilter lines look like this:
//
// *cupsFilter: "application/vnd.cups-raster 100 rastertofoo"
//
// |field_name| is the starting token we look for (*cupsFilter: or
// *cupsFilter2:).
//
// |num_value_tokens| is the number of tokens we expect to find in the
// value string. The filter is always the last of these.
//
// Return the name of the filter, if one is found.
//
// This would be simpler with re2, but re2 is not an allowed dependency in
// this part of the tree.
base::Optional<std::string> ExtractCupsFilter(const std::string& line,
const std::string& field_name,
int num_value_tokens) {
std::string delims(" \n\t\r\"");
base::StringTokenizer line_tok(line, delims);
if (!line_tok.GetNext()) {
return {};
}
if (line_tok.token_piece() != field_name) {
return {};
}
// Skip to the last of the value tokens.
for (int i = 0; i < num_value_tokens; ++i) {
if (!line_tok.GetNext()) {
return {};
}
}
if (line_tok.token_piece() != "") {
return line_tok.token_piece().as_string();
}
return {};
}
// Extract the used cups filters from a ppd.
//
// Note that CUPS (post 1.5) discards all cupsFilter lines if *any*
// cupsFilter2 lines exist.
//
std::vector<std::string> ExtractFiltersFromPpd(
const std::string& ppd_contents) {
std::string line;
base::Optional<std::string> tmp;
auto ppd_reader = PpdLineReader::Create(ppd_contents, 255);
std::vector<std::string> cups_filters;
std::vector<std::string> cups_filter2s;
while (ppd_reader->NextLine(&line)) {
tmp = ExtractCupsFilter(line, "*cupsFilter:", 3);
if (tmp.has_value()) {
cups_filters.push_back(tmp.value());
}
tmp = ExtractCupsFilter(line, "*cupsFilter2:", 4);
if (tmp.has_value()) {
cups_filter2s.push_back(tmp.value());
}
}
if (!cups_filter2s.empty()) {
return cups_filter2s;
}
return cups_filters;
}
// Returns false if there are obvious errors in the reference that will prevent
// resolution.
bool PpdReferenceIsWellFormed(const Printer::PpdReference& reference) {
int filled_fields = 0;
if (!reference.user_supplied_ppd_url.empty()) {
++filled_fields;
GURL tmp_url(reference.user_supplied_ppd_url);
if (!tmp_url.is_valid() || !tmp_url.SchemeIs("file")) {
LOG(ERROR) << "Invalid url for a user-supplied ppd: "
<< reference.user_supplied_ppd_url
<< " (must be a file:// URL)";
return false;
}
}
if (!reference.effective_make_and_model.empty()) {
++filled_fields;
}
// All effective-make-and-model strings should be lowercased, since v2.
// Since make-and-model strings could include non-Latin chars, only checking
// that it excludes all upper-case chars A-Z.
if (!std::all_of(reference.effective_make_and_model.begin(),
reference.effective_make_and_model.end(),
[](char c) -> bool { return !base::IsAsciiUpper(c); })) {
return false;
}
// Should have exactly one non-empty field.
return filled_fields == 1;
}
// Fetch the file pointed at by |url| and store it in |file_contents|.
// Returns true if the fetch was successful.
bool FetchFile(const GURL& url, std::string* file_contents) {
CHECK(url.is_valid());
CHECK(url.SchemeIs("file"));
base::ScopedBlockingCall scoped_blocking_call(FROM_HERE,
base::BlockingType::MAY_BLOCK);
// Here we are un-escaping the file path represented by the url. If we don't
// transform the url into a valid file path then the file may fail to be
// opened by the system later.
base::FilePath path;
if (!net::FileURLToFilePath(url, &path)) {
LOG(ERROR) << "Not a valid file URL.";
return false;
}
return base::ReadFileToString(path, file_contents);
}
// Constructs and returns a printers' restrictions parsed from |dict|.
PpdProvider::Restrictions ComputeRestrictions(const base::Value& dict) {
DCHECK(dict.is_dict());
PpdProvider::Restrictions restrictions;
const base::Value* min_milestone =
dict.FindKeyOfType({"min_milestone"}, base::Value::Type::DOUBLE);
const base::Value* max_milestone =
dict.FindKeyOfType({"max_milestone"}, base::Value::Type::DOUBLE);
if (min_milestone) {
restrictions.min_milestone =
base::Version(base::NumberToString(min_milestone->GetDouble()));
}
if (max_milestone) {
restrictions.max_milestone =
base::Version(base::NumberToString(max_milestone->GetDouble()));
}
return restrictions;
}
// Returns true if this |printer| is restricted from the
// |current_version|.
bool IsPrinterRestricted(const PrintersJSON& printer,
const base::Version& current_version) {
const PpdProvider::Restrictions& restrictions = printer.restrictions;
if (restrictions.min_milestone != base::Version("0.0") &&
restrictions.min_milestone > current_version) {
return true;
}
if (restrictions.max_milestone != base::Version("0.0") &&
restrictions.max_milestone < current_version) {
return true;
}
return false;
}
// Modifies |printers| by removing any restricted printers excluded from the
// current |version|, as judged by IsPrinterPermitted.
void FilterRestrictedPpdReferences(const base::Version& version,
std::vector<PrintersJSON>* printers) {
base::EraseIf(*printers, [&version](const PrintersJSON& printer) {
return IsPrinterRestricted(printer, version);
});
}
class PpdProviderImpl : public PpdProvider {
public:
// What kind of thing is the fetcher currently fetching? We use this to
// determine what to do when the fetcher returns a result.
enum FetcherTarget {
FT_LOCALES, // Locales metadata.
FT_MANUFACTURERS, // List of manufacturers metadata.
FT_PRINTERS, // List of printers from a manufacturer.
FT_PPD_INDEX, // Master ppd index.
FT_PPD, // A Ppd file.
FT_REVERSE_INDEX, // List of sharded printers from a manufacturer
FT_USB_DEVICES // USB device id to canonical name map.
};
PpdProviderImpl(const std::string& browser_locale,
network::mojom::URLLoaderFactory* loader_factory,
scoped_refptr<PpdCache> ppd_cache,
const base::Version& current_version,
const PpdProvider::Options& options)
: browser_locale_(browser_locale),
loader_factory_(loader_factory),
ppd_cache_(ppd_cache),
disk_task_runner_(base::CreateSequencedTaskRunnerWithTraits(
{base::TaskPriority::USER_VISIBLE, base::MayBlock(),
base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN})),
version_(current_version),
options_(options),
weak_factory_(this) {}
// Resolving manufacturers requires a couple of steps, because of
// localization. First we have to figure out what locale to use, which
// involves grabbing a list of available locales from the server. Once we
// have decided on a locale, we go out and fetch the manufacturers map in that
// localization.
//
// This means when a request comes in, we either queue it and start background
// fetches if necessary, or we satisfy it immediately from memory.
void ResolveManufacturers(ResolveManufacturersCallback cb) override {
CHECK(base::SequencedTaskRunnerHandle::IsSet())
<< "ResolveManufacturers must be called from a SequencedTaskRunner"
"context";
if (cached_metadata_.get() != nullptr) {
// We already have this in memory.
base::SequencedTaskRunnerHandle::Get()->PostTask(
FROM_HERE, base::BindOnce(std::move(cb), PpdProvider::SUCCESS,
GetManufacturerList()));
return;
}
manufacturers_resolution_queue_.push_back(std::move(cb));
MaybeStartFetch();
}
// If there are any queued ppd reference resolutions, attempt to make progress
// on them. Returns true if a fetch was started, false if no fetch was
// started.
bool MaybeStartNextPpdReferenceResolution() {
while (!ppd_reference_resolution_queue_.empty()) {
auto& next = ppd_reference_resolution_queue_.front();
auto& search_data = next.search_data;
// Have we successfully resolved next yet?
bool resolved_next = false;
if (!search_data.make_and_model.empty()) {
// Check the index for each make-and-model guess.
for (const std::string& make_and_model : search_data.make_and_model) {
// Check if we need to load its ppd_index
int ppd_index_shard = IndexShard(make_and_model);
if (!base::ContainsKey(cached_ppd_idxs_, ppd_index_shard)) {
StartFetch(GetPpdIndexURL(ppd_index_shard), FT_PPD_INDEX);
return true;
}
if (base::ContainsKey(cached_ppd_idxs_[ppd_index_shard],
make_and_model)) {
// Found a hit, satisfy this resolution.
Printer::PpdReference ret;
ret.effective_make_and_model = make_and_model;
base::SequencedTaskRunnerHandle::Get()->PostTask(
FROM_HERE,
base::BindOnce(std::move(next.cb), PpdProvider::SUCCESS, ret));
ppd_reference_resolution_queue_.pop_front();
resolved_next = true;
break;
}
}
}
if (resolved_next)
continue;
// If we get to this point, either we don't have any make and model
// guesses for the front entry, or they all missed. Try USB ids
// instead.
if (!next.usb_resolution_attempted && search_data.usb_vendor_id &&
search_data.usb_product_id) {
StartFetch(GetUsbURL(search_data.usb_vendor_id), FT_USB_DEVICES);
return true;
}
// If possible, here we fall back to OEM designated generic PPDs.
if (CanUseEpsonGenericPPD(search_data)) {
// Found a hit, satisfy this resolution.
Printer::PpdReference ret;
ret.effective_make_and_model = kEpsonGenericPPD;
base::SequencedTaskRunnerHandle::Get()->PostTask(
FROM_HERE,
base::BindOnce(std::move(next.cb), PpdProvider::SUCCESS, ret));
ppd_reference_resolution_queue_.pop_front();
} else {
// We don't have anything else left to try. NOT_FOUND it is.
base::SequencedTaskRunnerHandle::Get()->PostTask(
FROM_HERE,
base::BindOnce(std::move(next.cb), PpdProvider::NOT_FOUND,
Printer::PpdReference()));
ppd_reference_resolution_queue_.pop_front();
}
}
// Didn't start any fetches.
return false;
}
// If there is work outstanding that requires a URL fetch to complete, start
// going on it.
void MaybeStartFetch() {
if (fetch_inflight_) {
// We'll call this again when the outstanding fetch completes.
return;
}
if (MaybeStartNextPpdReferenceResolution()) {
return;
}
if (!manufacturers_resolution_queue_.empty() ||
!reverse_index_resolution_queue_.empty()) {
if (locale_.empty()) {
// Don't have a locale yet, figure that out first.
StartFetch(GetLocalesURL(), FT_LOCALES);
} else {
// Get manufacturers based on the locale we have.
if (!manufacturers_resolution_queue_.empty()) {
StartFetch(GetManufacturersURL(locale_), FT_MANUFACTURERS);
} else if (!reverse_index_resolution_queue_.empty()) {
// Update the url with the locale before fetching
ReverseIndexQueueEntry& entry =
reverse_index_resolution_queue_.front();
entry.url = GetReverseIndexURL(entry.effective_make_and_model);
StartFetch(entry.url, FT_REVERSE_INDEX);
}
}
return;
}
if (!printers_resolution_queue_.empty()) {
StartFetch(printers_resolution_queue_.front().url, FT_PRINTERS);
return;
}
while (!ppd_resolution_queue_.empty()) {
auto& next = ppd_resolution_queue_.front();
if (!next.reference.user_supplied_ppd_url.empty()) {
DCHECK(next.reference.effective_make_and_model.empty());
GURL url(next.reference.user_supplied_ppd_url);
DCHECK(url.is_valid());
StartFetch(url, FT_PPD);
return;
}
DCHECK(!next.reference.effective_make_and_model.empty());
int ppd_index_shard = IndexShard(next.reference.effective_make_and_model);
if (!base::ContainsKey(cached_ppd_idxs_, ppd_index_shard)) {
// Have to have the ppd index before we can resolve by ppd server
// key.
StartFetch(GetPpdIndexURL(ppd_index_shard), FT_PPD_INDEX);
return;
}
// Get the URL from the ppd index and start the fetch.
auto& cached_ppd_index = cached_ppd_idxs_[ppd_index_shard];
auto it = cached_ppd_index.find(next.reference.effective_make_and_model);
if (it != cached_ppd_index.end()) {
StartFetch(GetPpdURL(it->second), FT_PPD);
return;
}
// This ppd reference isn't in the index. That's not good. Fail
// out the current resolution and go try to start the next
// thing if there is one.
LOG(ERROR) << "PPD " << next.reference.effective_make_and_model
<< " not found in server index";
FinishPpdResolution(std::move(next.callback), {},
PpdProvider::INTERNAL_ERROR);
ppd_resolution_queue_.pop_front();
}
}
void ResolvePrinters(const std::string& manufacturer,
ResolvePrintersCallback cb) override {
std::unordered_map<std::string, ManufacturerMetadata>::iterator it;
if (cached_metadata_.get() == nullptr ||
(it = cached_metadata_->find(manufacturer)) ==
cached_metadata_->end()) {
// User error.
LOG(ERROR) << "Can't resolve printers for unknown manufacturer "
<< manufacturer;
base::SequencedTaskRunnerHandle::Get()->PostTask(
FROM_HERE, base::BindOnce(std::move(cb), PpdProvider::INTERNAL_ERROR,
ResolvedPrintersList()));
return;
}
if (it->second.printers.get() != nullptr) {
// Satisfy from the cache.
base::SequencedTaskRunnerHandle::Get()->PostTask(
FROM_HERE, base::BindOnce(std::move(cb), PpdProvider::SUCCESS,
GetManufacturerPrinterList(it->second)));
} else {
// We haven't resolved this manufacturer yet.
PrinterResolutionQueueEntry entry;
entry.manufacturer = manufacturer;
entry.url = GetPrintersURL(it->second.reference);
entry.cb = std::move(cb);
printers_resolution_queue_.push_back(std::move(entry));
MaybeStartFetch();
}
}
void ResolvePpdReference(const PrinterSearchData& search_data,
ResolvePpdReferenceCallback cb) override {
// In v2 metadata, we work with lowercased effective_make_and_models.
PrinterSearchData lowercase_search_data(search_data);
for (auto& make_and_model : lowercase_search_data.make_and_model) {
make_and_model = base::ToLowerASCII(make_and_model);
}
PpdReferenceResolutionQueueEntry entry;
entry.search_data = lowercase_search_data;
entry.cb = std::move(cb);
ppd_reference_resolution_queue_.push_back(std::move(entry));
MaybeStartFetch();
}
void ResolvePpd(const Printer::PpdReference& reference,
ResolvePpdCallback cb) override {
// In v2 metadata, we work with lowercased effective_make_and_models.
Printer::PpdReference lowercase_reference(reference);
lowercase_reference.effective_make_and_model =
base::ToLowerASCII(lowercase_reference.effective_make_and_model);
// Do a sanity check here, so we can assume |reference| is well-formed in
// the rest of this class.
if (!PpdReferenceIsWellFormed(lowercase_reference)) {
FinishPpdResolution(std::move(cb), {}, PpdProvider::INTERNAL_ERROR);
return;
}
// First step, check the cache. If the cache lookup fails, we'll (try to)
// consult the server.
ppd_cache_->Find(PpdReferenceToCacheKey(lowercase_reference),
base::BindOnce(&PpdProviderImpl::ResolvePpdCacheLookupDone,
weak_factory_.GetWeakPtr(),
lowercase_reference, std::move(cb)));
}
void ReverseLookup(const std::string& effective_make_and_model,
ReverseLookupCallback cb) override {
if (effective_make_and_model.empty()) {
LOG(WARNING) << "Cannot resolve an empty make and model";
PostReverseLookupFailure(PpdProvider::NOT_FOUND, std::move(cb));
return;
}
// In v2 metadata, we work with lowercased effective_make_and_models.
std::string lowercase_effective_make_and_model =
base::ToLowerASCII(effective_make_and_model);
ReverseIndexQueueEntry entry;
entry.effective_make_and_model = lowercase_effective_make_and_model;
entry.url = GetReverseIndexURL(lowercase_effective_make_and_model);
entry.cb = std::move(cb);
reverse_index_resolution_queue_.push_back(std::move(entry));
MaybeStartFetch();
}
// Common handler that gets called whenever a fetch completes. Note this
// is used both for |fetcher_| fetches (i.e. http[s]) and file-based fetches;
// |source| may be null in the latter case.
void OnURLFetchComplete(std::unique_ptr<std::string> body) {
response_body_ = std::move(body);
switch (fetcher_target_) {
case FT_LOCALES:
OnLocalesFetchComplete();
break;
case FT_MANUFACTURERS:
OnManufacturersFetchComplete();
break;
case FT_PRINTERS:
OnPrintersFetchComplete();
break;
case FT_PPD_INDEX:
OnPpdIndexFetchComplete(fetcher_->GetFinalURL());
break;
case FT_PPD:
OnPpdFetchComplete();
break;
case FT_REVERSE_INDEX:
OnReverseIndexComplete();
break;
case FT_USB_DEVICES:
OnUsbFetchComplete();
break;
default:
LOG(DFATAL) << "Unknown fetch source";
}
fetch_inflight_ = false;
MaybeStartFetch();
}
private:
// Return the URL used to look up the supported locales list.
GURL GetLocalesURL() {
return GURL(options_.ppd_server_root + "/metadata_v2/locales.json");
}
GURL GetUsbURL(int vendor_id) {
DCHECK_GT(vendor_id, 0);
DCHECK_LE(vendor_id, 0xffff);
return GURL(base::StringPrintf("%s/metadata_v2/usb-%04x.json",
options_.ppd_server_root.c_str(),
vendor_id));
}
// Return the URL used to get the |ppd_index_shard| index.
GURL GetPpdIndexURL(int ppd_index_shard) {
return GURL(base::StringPrintf("%s/metadata_v2/index-%02d.json",
options_.ppd_server_root.c_str(),
ppd_index_shard));
}
// Return the ppd index shard number from its |url|.
int GetShardFromUrl(const GURL& url) {
auto url_str = url.spec();
if (url_str.empty()) {
return -1;
}
// Strip shard number from 2 digits following 'index'
int idx_pos = url_str.find_first_of("0123456789", url_str.find("index-"));
return std::stoi(url_str.substr(idx_pos, 2));
}
// Return the URL to get a localized manufacturers map.
GURL GetManufacturersURL(const std::string& locale) {
return GURL(base::StringPrintf("%s/metadata_v2/manufacturers-%s.json",
options_.ppd_server_root.c_str(),
locale.c_str()));
}
// Return the URL used to get a list of printers from the manufacturer |ref|.
GURL GetPrintersURL(const std::string& ref) {
return GURL(base::StringPrintf(
"%s/metadata_v2/%s", options_.ppd_server_root.c_str(), ref.c_str()));
}
// Return the URL used to get a ppd with the given filename.
GURL GetPpdURL(const std::string& filename) {
return GURL(base::StringPrintf(
"%s/ppds/%s", options_.ppd_server_root.c_str(), filename.c_str()));
}
// Return the URL to get a localized, shared manufacturers map.
GURL GetReverseIndexURL(const std::string& effective_make_and_model) {
return GURL(base::StringPrintf("%s/metadata_v2/reverse_index-%s-%02d.json",
options_.ppd_server_root.c_str(),
locale_.c_str(),
IndexShard(effective_make_and_model)));
}
// Create and return a fetcher that has the usual (for this class) flags set
// and calls back to OnURLFetchComplete in this class when it finishes.
void StartFetch(const GURL& url, FetcherTarget target) {
DCHECK(!fetch_inflight_);
DCHECK_EQ(fetcher_.get(), nullptr);
fetcher_target_ = target;
fetch_inflight_ = true;
if (url.SchemeIs("http") || url.SchemeIs("https")) {
auto resource_request = std::make_unique<network::ResourceRequest>();
resource_request->url = url;
resource_request->load_flags =
net::LOAD_BYPASS_CACHE | net::LOAD_DISABLE_CACHE |
net::LOAD_DO_NOT_SAVE_COOKIES | net::LOAD_DO_NOT_SEND_COOKIES |
net::LOAD_DO_NOT_SEND_AUTH_DATA;
// TODO(luum): confirm correct traffic annotation
fetcher_ = network::SimpleURLLoader::Create(std::move(resource_request),
MISSING_TRAFFIC_ANNOTATION);
// TODO(luum): consider using unbounded size
fetcher_->DownloadToString(
loader_factory_,
base::BindOnce(&PpdProviderImpl::OnURLFetchComplete, this),
network::SimpleURLLoader::kMaxBoundedStringDownloadSize);
} else if (url.SchemeIs("file")) {
auto file_contents = std::make_unique<std::string>();
std::string* content_ptr = file_contents.get();
base::PostTaskAndReplyWithResult(
disk_task_runner_.get(), FROM_HERE,
base::BindOnce(&FetchFile, url, content_ptr),
base::BindOnce(&PpdProviderImpl::OnFileFetchComplete, this,
std::move(file_contents)));
}
}
// Handle the result of a file fetch.
void OnFileFetchComplete(std::unique_ptr<std::string> file_contents,
bool success) {
file_fetch_success_ = success;
file_fetch_contents_ = success ? *file_contents : "";
OnURLFetchComplete(nullptr);
}
// Tidy up loose ends on an outstanding PPD resolution.
//
// If |ppd_contents| is non-empty, the request is resolved successfully
// using those contents. Otherwise |error_code| and an empty ppd
// is given to |cb|.
void FinishPpdResolution(ResolvePpdCallback cb,
const std::string& ppd_contents,
PpdProvider::CallbackResultCode error_code) {
if (!ppd_contents.empty()) {
base::SequencedTaskRunnerHandle::Get()->PostTask(
FROM_HERE,
base::BindOnce(std::move(cb), PpdProvider::SUCCESS, ppd_contents,
ExtractFiltersFromPpd(ppd_contents)));
} else {
DCHECK_NE(error_code, PpdProvider::SUCCESS);
base::SequencedTaskRunnerHandle::Get()->PostTask(
FROM_HERE, base::BindOnce(std::move(cb), error_code, std::string(),
std::vector<std::string>()));
}
}
// Callback when the cache lookup for a ppd request finishes. If we hit in
// the cache, satisfy the resolution, otherwise kick it over to the fetcher
// queue to be grabbed from a server.
void ResolvePpdCacheLookupDone(const Printer::PpdReference& reference,
ResolvePpdCallback cb,
const PpdCache::FindResult& result) {
// If all of the following are true, we use the cache result now:
//
// * It was a cache hit
// * The reference is not from a user-supplied ppd file
// * The cached data was fresh.
//
// In all other cases, we go through the full resolution flow (passing along
// the cached data, if we got any), even if we got something from the cache.
if (result.success && reference.user_supplied_ppd_url.empty() &&
result.age < options_.cache_staleness_age) {
DCHECK(!result.contents.empty());
FinishPpdResolution(std::move(cb), result.contents, PpdProvider::SUCCESS);
} else {
// Save the cache result (if any), and queue up for resolution.
ppd_resolution_queue_.push_back(
{reference, result.contents, std::move(cb)});
MaybeStartFetch();
}
}
// Handler for the completion of the locales fetch. This response should be a
// list of strings, each of which is a locale in which we can answer queries
// on the server. The server (should) guarantee that we get 'en' as an
// absolute minimum.
//
// Combine this information with the browser locale to figure out the best
// locale to use, and then start a fetch of the manufacturers map in that
// locale.
void OnLocalesFetchComplete() {
std::string contents;
if (ValidateAndGetResponseAsString(&contents) != PpdProvider::SUCCESS) {
FailQueuedMetadataResolutions(PpdProvider::SERVER_ERROR);
return;
}
auto top_list =
base::ListValue::From(base::JSONReader::ReadDeprecated(contents));
if (top_list.get() == nullptr) {
// We got something malformed back.
FailQueuedMetadataResolutions(PpdProvider::INTERNAL_ERROR);
return;
}
// This should just be a simple list of locale strings.
std::vector<std::string> available_locales;
bool found_en = false;
for (const base::Value& entry : *top_list) {
std::string tmp;
// Locales should have at *least* a two-character country code. 100 is an
// arbitrary upper bound for length to protect against extreme bogosity.
if (!entry.GetAsString(&tmp) || tmp.size() < 2 || tmp.size() > 100) {
FailQueuedMetadataResolutions(PpdProvider::INTERNAL_ERROR);
return;
}
if (tmp == "en") {
found_en = true;
}
available_locales.push_back(tmp);
}
if (available_locales.empty() || !found_en) {
// We have no locales, or we didn't get an english locale (which is our
// ultimate fallback)
FailQueuedMetadataResolutions(PpdProvider::INTERNAL_ERROR);
return;
}
// Everything checks out, set the locale, head back to fetch dispatch
// to start the manufacturer fetch.
locale_ = GetBestLocale(available_locales);
}
// Called when the |fetcher_| is expected have the results of a
// manufacturer map (which maps localized manufacturer names to keys for
// looking up printers from that manufacturer). Use this information to
// populate manufacturer_map_, and resolve all queued ResolveManufacturers()
// calls.
void OnManufacturersFetchComplete() {
DCHECK_EQ(nullptr, cached_metadata_.get());
std::vector<ManufacturersJSON> contents;
PpdProvider::CallbackResultCode code =
ValidateAndParseManufacturersJSON(&contents);
if (code != PpdProvider::SUCCESS) {
LOG(ERROR) << "Failed manufacturer parsing";
FailQueuedMetadataResolutions(code);
return;
}
cached_metadata_ = std::make_unique<
std::unordered_map<std::string, ManufacturerMetadata>>();
for (const auto& entry : contents) {
(*cached_metadata_)[entry.name].reference = entry.reference;
}
std::vector<std::string> manufacturer_list = GetManufacturerList();
// Complete any queued manufacturer resolutions.
for (auto& cb : manufacturers_resolution_queue_) {
base::SequencedTaskRunnerHandle::Get()->PostTask(
FROM_HERE, base::BindOnce(std::move(cb), PpdProvider::SUCCESS,
manufacturer_list));
}
manufacturers_resolution_queue_.clear();
}
// The outstanding fetch associated with the front of
// |printers_resolution_queue_| finished, use the response to satisfy that
// ResolvePrinters() call.
void OnPrintersFetchComplete() {
CHECK(cached_metadata_.get() != nullptr);
DCHECK(!printers_resolution_queue_.empty());
std::vector<PrintersJSON> contents;
PpdProvider::CallbackResultCode code =
ValidateAndParsePrintersJSON(&contents);
if (code != PpdProvider::SUCCESS) {
base::SequencedTaskRunnerHandle::Get()->PostTask(
FROM_HERE,
base::BindOnce(std::move(printers_resolution_queue_.front().cb), code,
ResolvedPrintersList()));
} else {
// This should be a list of lists of 2-element strings, where the first
// element is the localized name of the printer and the second element
// is the canonical name of the printer.
const std::string& manufacturer =
printers_resolution_queue_.front().manufacturer;
auto it = cached_metadata_->find(manufacturer);
// If we kicked off a resolution, the entry better have already been
// in the map.
CHECK(it != cached_metadata_->end());
// Create the printer map in the cache, and populate it.
auto& manufacturer_metadata = it->second;
CHECK(manufacturer_metadata.printers.get() == nullptr);
manufacturer_metadata.printers =
std::make_unique<std::unordered_map<std::string, PrintersJSON>>();
for (const auto& entry : contents) {
manufacturer_metadata.printers->insert({entry.name, entry});
}
base::SequencedTaskRunnerHandle::Get()->PostTask(
FROM_HERE,
base::BindOnce(std::move(printers_resolution_queue_.front().cb),
PpdProvider::SUCCESS,
GetManufacturerPrinterList(manufacturer_metadata)));
}
printers_resolution_queue_.pop_front();
}
// Called when |fetcher_| should have just received an index mapping
// ppd server keys to ppd filenames. Use this to populate
// |cached_ppd_idxs_|.
void OnPpdIndexFetchComplete(GURL url) {
std::vector<PpdIndexJSON> contents;
PpdProvider::CallbackResultCode code =
ValidateAndParsePpdIndexJSON(&contents);
if (code != PpdProvider::SUCCESS) {
FailQueuedServerPpdResolutions(code);
} else {
int ppd_index_shard = GetShardFromUrl(url);
if (ppd_index_shard < 0) {
FailQueuedServerPpdResolutions(PpdProvider::INTERNAL_ERROR);
return;
}
auto& cached_ppd_index = cached_ppd_idxs_[ppd_index_shard];
for (const auto& entry : contents) {
cached_ppd_index.insert(
{entry.effective_make_and_model, entry.ppd_filename});
}
}
}
// This is called when |fetcher_| should have just downloaded a ppd. If we
// downloaded something successfully, use it to satisfy the front of the ppd
// resolution queue, otherwise fail out that resolution.
void OnPpdFetchComplete() {
DCHECK(!ppd_resolution_queue_.empty());
std::string contents;
auto& entry = ppd_resolution_queue_.front();
if ((ValidateAndGetResponseAsString(&contents) != PpdProvider::SUCCESS)) {
FinishPpdResolution(std::move(entry.callback), entry.cached_contents,
PpdProvider::SERVER_ERROR);
} else if (contents.size() > kMaxPpdSizeBytes) {
FinishPpdResolution(std::move(entry.callback), entry.cached_contents,
PpdProvider::PPD_TOO_LARGE);
} else if (contents.empty()) {
FinishPpdResolution(std::move(entry.callback), entry.cached_contents,
PpdProvider::INTERNAL_ERROR);
} else {
// Success. Cache it and return it to the user.
ppd_cache_->Store(
PpdReferenceToCacheKey(ppd_resolution_queue_.front().reference),
contents);