File: cups_printer.cc

package info (click to toggle)
chromium 139.0.7258.127-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 6,122,156 kB
  • sloc: cpp: 35,100,771; ansic: 7,163,530; javascript: 4,103,002; python: 1,436,920; asm: 946,517; xml: 746,709; pascal: 187,653; perl: 88,691; sh: 88,436; objc: 79,953; sql: 51,488; cs: 44,583; fortran: 24,137; makefile: 22,147; tcl: 15,277; php: 13,980; yacc: 8,984; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (380 lines) | stat: -rw-r--r-- 12,976 bytes parent folder | download | duplicates (5)
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
// Copyright 2016 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/cups_printer.h"

#include <cups/cups.h>

#include <cstring>
#include <string>
#include <string_view>
#include <utility>

#include "base/compiler_specific.h"
#include "base/memory/raw_ptr.h"
#include "base/strings/string_number_conversions.h"
#include "build/build_config.h"
#include "printing/backend/cups_connection.h"
#include "printing/backend/cups_ipp_constants.h"
#include "printing/backend/cups_ipp_helper.h"
#include "printing/backend/cups_weak_functions.h"
#include "printing/backend/print_backend.h"
#include "printing/backend/print_backend_consts.h"
#include "printing/backend/print_backend_utils.h"
#include "printing/print_job_constants.h"
#include "url/gurl.h"

namespace printing {

class CupsPrinterImpl : public CupsPrinter {
 public:
  CupsPrinterImpl(http_t* http, ScopedDestination dest)
      : cups_http_(http),
        destination_(std::move(dest)),
        printer_attributes_(WrapIpp(nullptr)) {
    DCHECK(cups_http_);
    DCHECK(destination_);

    const char* printer_uri = cupsGetOption(kCUPSOptPrinterUriSupported,
                                            destination_.get()->num_options,
                                            destination_.get()->options);

    // crbug.com/1418564: Every printer *should* have a "printer-uri-supported"
    // attribute, but make sure Chromium doesn't crash if one doesn't for
    // whatever reason. The printer in question won't actually work, but
    // that's a better outcome than crashing here.
    // TODO(crbug.com/40894807): filter such printers out before reaching this
    // point
    if (printer_uri) {
      printer_uri_ = printer_uri;
      resource_path_ = std::string(GURL(printer_uri_).path_piece());
    }
  }

  CupsPrinterImpl(const CupsPrinterImpl&) = delete;
  CupsPrinterImpl& operator=(const CupsPrinterImpl&) = delete;

  ~CupsPrinterImpl() override = default;

  bool is_default() const override { return destination_->is_default; }

  // CupsOptionProvider
  ipp_attribute_t* GetSupportedOptionValues(
      const char* option_name) const override {
    if (!EnsureDestInfo())
      return nullptr;

    return cupsFindDestSupported(cups_http_, destination_.get(),
                                 dest_info_.get(), option_name);
  }

  // CupsOptionProvider
  std::vector<std::string_view> GetSupportedOptionValueStrings(
      const char* option_name) const override {
    std::vector<std::string_view> values;
    ipp_attribute_t* attr = GetSupportedOptionValues(option_name);
    if (!attr)
      return values;

    int num_options = ippGetCount(attr);
    for (int i = 0; i < num_options; ++i) {
      const char* const value = ippGetString(attr, i, nullptr);
      if (!value) {
        continue;
      }
      values.push_back(value);
    }

    return values;
  }

  // CupsOptionProvider
  ipp_attribute_t* GetDefaultOptionValue(
      const char* option_name) const override {
    if (!EnsureDestInfo())
      return nullptr;

    return cupsFindDestDefault(cups_http_, destination_.get(), dest_info_.get(),
                               option_name);
  }

  // CupsOptionProvider
  bool CheckOptionSupported(const char* name,
                            const char* value) const override {
    if (!EnsureDestInfo())
      return false;

#if BUILDFLAG(IS_CHROMEOS)
    // OAuth token passed to CUPS as IPP attribute, see b/200086039.
    if (name &&
        UNSAFE_TODO(strcmp(name, kSettingChromeOSAccessOAuthToken)) == 0) {
      return true;
    }

    // Special case for the IPP 'client-info' collection because
    // cupsCheckDestSupported will not report it as supported even when it is.
    // See http://b/238761330.
    if (name && UNSAFE_TODO(strcmp(name, kIppClientInfo)) == 0) {
      return true;
    }
#endif

    int supported = cupsCheckDestSupported(cups_http_, destination_.get(),
                                           dest_info_.get(), name, value);
    return supported == 1;
  }

  // CupsOptionProvider
  ipp_attribute_t* GetMediaColDatabase() const override {
    if (!EnsurePrinterAttributes()) {
      return nullptr;
    }

    return ippFindAttribute(printer_attributes_.get(), kIppMediaColDatabase,
                            IPP_TAG_BEGIN_COLLECTION);
  }

  // CupsOptionProvider
  const char* GetLocalizedOptionValueName(const char* option_name,
                                          const char* value) const override {
    if (!EnsureDestInfo()) {
      return nullptr;
    }

    return cupsLocalizeDestValue(cups_http_, destination_.get(),
                                 dest_info_.get(), option_name, value);
  }

  bool ToPrinterInfo(PrinterBasicInfo* printer_info) const override {
    const cups_dest_t* printer = destination_.get();

    printer_info->printer_name = printer->name;

    const std::string info = GetInfo();
    const std::string make_and_model = GetMakeAndModel();

    printer_info->display_name = GetDisplayName(printer->name, info);
    printer_info->printer_description =
        GetPrinterDescription(make_and_model, info);

    printer_info->options[kDriverInfoTagName] = make_and_model;

    // Store printer options.
    if (printer->num_options > 0) {
      // SAFETY: Required from CUPS.
      auto options = UNSAFE_BUFFERS(base::span<const cups_option_t>(
          printer->options, static_cast<size_t>(printer->num_options)));
      for (const auto& option : options) {
        printer_info->options[option.name] = option.value;
      }
    }

    return true;
  }

  std::string GetName() const override {
    return std::string(destination_->name);
  }

  std::string GetMakeAndModel() const override {
    const char* make_and_model =
        cupsGetOption(kCUPSOptPrinterMakeAndModel, destination_->num_options,
                      destination_->options);

    return make_and_model ? std::string(make_and_model) : std::string();
  }

  std::string GetInfo() const override {
    const char* info = cupsGetOption(
        kCUPSOptPrinterInfo, destination_->num_options, destination_->options);

    return info ? std::string(info) : std::string();
  }

  std::string GetUri() const override {
    const char* uri = cupsGetOption(
        kCUPSOptDeviceUri, destination_->num_options, destination_->options);
    return uri ? std::string(uri) : std::string();
  }

  bool EnsureDestInfo() const override {
    if (dest_info_)
      return true;

    dest_info_.reset(cupsCopyDestInfo(cups_http_, destination_.get()));
    return !!dest_info_;
  }

  ipp_status_t CreateJob(int* job_id,
                         const std::string& title,
                         const std::string& username,
                         ipp_t* attributes) override {
    ScopedIppPtr request = CreateRequest(IPP_OP_CREATE_JOB, username);

    if (!title.empty()) {
      ippAddString(request.get(), IPP_TAG_OPERATION, IPP_TAG_NAME, kIppJobName,
                   nullptr, title.c_str());
    }

    CopyAttributeGroup(request.get(), attributes, IPP_TAG_OPERATION);
    CopyAttributeGroup(request.get(), attributes, IPP_TAG_JOB);
    // We would also copy subscription attributes here if we actually used
    // any. We don't, though.

    // cupsDoRequest() takes ownership of the request and frees it for us.
    ScopedIppPtr response = WrapIpp(
        cupsDoRequest(cups_http_, request.release(), resource_path_.c_str()));

    ipp_attribute_t* attr =
        ippFindAttribute(response.get(), kIppJobId, IPP_TAG_INTEGER);
    *job_id = ippGetInteger(attr, 0);

    return ippGetStatusCode(response.get());
  }

  bool StartDocument(int job_id,
                     const std::string& docname,
                     bool last_document,
                     const std::string& username,
                     ipp_t* attributes) override {
    DCHECK(job_id);
    ScopedIppPtr request = CreateRequest(IPP_OP_SEND_DOCUMENT, username);

    ippAddInteger(request.get(), IPP_TAG_OPERATION, IPP_TAG_INTEGER, kIppJobId,
                  job_id);
    ippAddBoolean(request.get(), IPP_TAG_OPERATION, kIppLastDocument,
                  static_cast<char>(last_document));
    ippAddString(request.get(), IPP_TAG_OPERATION, IPP_TAG_MIMETYPE,
                 kIppDocumentFormat, nullptr, CUPS_FORMAT_PDF);
    if (!docname.empty()) {
      ippAddString(request.get(), IPP_TAG_OPERATION, IPP_TAG_NAME,
                   kIppDocumentName, nullptr, docname.c_str());
    }

    CopyAttributeGroup(request.get(), attributes, IPP_TAG_OPERATION);
    CopyAttributeGroup(request.get(), attributes, IPP_TAG_DOCUMENT);

    http_status_t status =
        cupsSendRequest(cups_http_, request.get(), resource_path_.c_str(),
                        CUPS_LENGTH_VARIABLE);
    return status == HTTP_CONTINUE;
  }

  bool StreamData(const std::vector<char>& buffer) override {
    http_status_t status =
        cupsWriteRequestData(cups_http_, buffer.data(), buffer.size());
    return status == HTTP_STATUS_CONTINUE;
  }

  bool FinishDocument() override {
    ScopedIppPtr response =
        WrapIpp(cupsGetResponse(cups_http_, resource_path_.c_str()));
    ipp_status_t status = ippGetStatusCode(response.get());
    return status == IPP_STATUS_OK;
  }

  ipp_status_t CloseJob(int job_id, const std::string& username) override {
    DCHECK(job_id);
    ScopedIppPtr request = CreateRequest(IPP_OP_CLOSE_JOB, username);

    ippAddInteger(request.get(), IPP_TAG_OPERATION, IPP_TAG_INTEGER, kIppJobId,
                  job_id);

    ScopedIppPtr response = WrapIpp(
        cupsDoRequest(cups_http_, request.release(), resource_path_.c_str()));
    return ippGetStatusCode(response.get());
  }

  bool CancelJob(int job_id) override {
    DCHECK(job_id);

    // TODO(skau): Try to change back to cupsCancelDestJob().
    ipp_status_t status =
        cupsCancelJob2(cups_http_, destination_->name, job_id, 0 /*cancel*/);
    return status == IPP_STATUS_OK;
  }

 private:
  // Sends the request to populate `printer_attributes_` if it's not already
  // populated.
  bool EnsurePrinterAttributes() const {
    if (printer_attributes_) {
      return true;
    }

    ScopedIppPtr request = CreateRequest(IPP_OP_GET_PRINTER_ATTRIBUTES, "");
    // The requested attributes can be changed to "all","media-col-database" if
    // we want to directly query printer attributes other than
    // media-col-database in the future.
    constexpr const char* kRequestedAttributes[] = {kIppMediaColDatabase};
    ippAddStrings(request.get(), IPP_TAG_OPERATION, IPP_TAG_KEYWORD,
                  kIppRequestedAttributes, std::size(kRequestedAttributes),
                  nullptr, kRequestedAttributes);

    // cupsDoRequest() takes ownership of the request and frees it for us.
    printer_attributes_.reset(
        cupsDoRequest(cups_http_, request.release(), resource_path_.c_str()));

    if (ippGetStatusCode(printer_attributes_.get()) != IPP_STATUS_OK) {
      printer_attributes_.reset();
      return false;
    }

    // Go through all of our media-col-database entries and consolidate any that
    // have custom size ranges.
    FilterMediaColSizes(printer_attributes_);

    return true;
  }

  // internal helper function to initialize an IPP request
  ScopedIppPtr CreateRequest(ipp_op_t op, const std::string& username) const {
    const char* c_username = username.empty() ? cupsUser() : username.c_str();

    ipp_t* request = ippNewRequest(op);
    ippAddString(request, IPP_TAG_OPERATION, IPP_TAG_URI, kIppPrinterUri,
                 nullptr, printer_uri_.c_str());
    ippAddString(request, IPP_TAG_OPERATION, IPP_TAG_NAME,
                 kIppRequestingUserName, nullptr, c_username);

    return WrapIpp(request);
  }

  // internal helper function to copy attributes to an IPP request
  void CopyAttributeGroup(ipp_t* request,
                          ipp_t* attributes,
                          ipp_tag_t group) const {
    for (ipp_attribute_t* attr = ippFirstAttribute(attributes); attr;
         attr = ippNextAttribute(attributes)) {
      if (ippGetGroupTag(attr) == group) {
        ippCopyAttribute(request, attr, 0);
      }
    }
  }

  // http connection owned by the CupsConnection which created this object
  const raw_ptr<http_t> cups_http_;

  // information to identify a printer
  ScopedDestination destination_;

  // opaque object containing printer attributes and options
  mutable ScopedDestInfo dest_info_;

  // uri used to connect to this printer
  std::string printer_uri_;

  // resource path used to connect to this printer
  std::string resource_path_;

  // printer attributes that describe the supported options
  mutable ScopedIppPtr printer_attributes_;
};

std::unique_ptr<CupsPrinter> CupsPrinter::Create(http_t* http,
                                                 ScopedDestination dest) {
  return std::make_unique<CupsPrinterImpl>(http, std::move(dest));
}

}  // namespace printing