summaryrefslogtreecommitdiffstats
path: root/printing/backend/print_backend_cups.cc
blob: 3b38c3fbbf35780283dfc9b042fc0ace09f29596 (plain)
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
// Copyright (c) 2010 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 "printing/backend/print_backend.h"

#include <dlfcn.h>
#include <errno.h>
#if !defined(OS_MACOSX)
#include <gcrypt.h>
#endif
#include <pthread.h>

#include "base/file_util.h"
#include "base/lazy_instance.h"
#include "base/logging.h"
#include "base/string_number_conversions.h"
#include "base/synchronization/lock.h"
#include "base/values.h"
#include "googleurl/src/gurl.h"
#include "printing/backend/cups_helper.h"
#include "printing/backend/print_backend_consts.h"

#if !defined(OS_MACOSX)
GCRY_THREAD_OPTION_PTHREAD_IMPL;

namespace {

// Init GCrypt library (needed for CUPS) using pthreads.
// There exists a bug in CUPS library, where it crashed with: "ath.c:184:
// _gcry_ath_mutex_lock: Assertion `*lock == ((ath_mutex_t) 0)' failed."
// It happened when multiple threads tried printing simultaneously.
// Google search for 'gnutls thread safety' provided a solution that
// initialized gcrypt and gnutls.

// Initially, we linked with -lgnutls and simply called gnutls_global_init(),
// but this did not work well since we build one binary on Ubuntu Hardy and
// expect it to run on many Linux distros. (See http://crbug.com/46954)
// So instead we use dlopen() and dlsym() to dynamically load and call
// gnutls_global_init().

class GcryptInitializer {
 public:
  GcryptInitializer() {
    Init();
  }

 private:
  void Init() {
    gcry_control(GCRYCTL_SET_THREAD_CBS, &gcry_threads_pthread);
    const char* kGnuTlsFile = "libgnutls.so";
    void* gnutls_lib = dlopen(kGnuTlsFile, RTLD_NOW);
    if (!gnutls_lib) {
      LOG(ERROR) << "Cannot load " << kGnuTlsFile;
      return;
    }
    const char* kGnuTlsInitFuncName = "gnutls_global_init";
    int (*pgnutls_global_init)(void) = reinterpret_cast<int(*)()>(
        dlsym(gnutls_lib, kGnuTlsInitFuncName));
    if (!pgnutls_global_init) {
      LOG(ERROR) << "Could not find " << kGnuTlsInitFuncName
                 << " in " << kGnuTlsFile;
      return;
    }
    if ((*pgnutls_global_init)() != 0)
      LOG(ERROR) << "Gnutls initialization failed";
  }
};

static base::LazyInstance<GcryptInitializer> g_gcrypt_initializer(
    base::LINKER_INITIALIZED);

}  // namespace
#endif

namespace printing {

static const char kCUPSPrinterInfoOpt[] = "printer-info";
static const char kCUPSPrinterStateOpt[] = "printer-state";

class PrintBackendCUPS : public PrintBackend {
 public:
  PrintBackendCUPS(const GURL& print_server_url, bool blocking);
  virtual ~PrintBackendCUPS() {}

  // PrintBackend implementation.
  virtual bool EnumeratePrinters(PrinterList* printer_list);

  virtual bool GetPrinterCapsAndDefaults(const std::string& printer_name,
                                         PrinterCapsAndDefaults* printer_info);

  virtual bool IsValidPrinter(const std::string& printer_name);

 private:
  // Following functions are wrappers around corresponding CUPS functions.
  // <functions>2()  are called when print server is specified, and plain
  // version in another case. There is an issue specifing CUPS_HTTP_DEFAULT
  // in the <functions>2(), it does not work in CUPS prior to 1.4.
  int GetDests(cups_dest_t** dests);
  FilePath GetPPD(const char* name);

  GURL print_server_url_;
  bool blocking_;
};

PrintBackendCUPS::PrintBackendCUPS(const GURL& print_server_url, bool blocking)
    : print_server_url_(print_server_url), blocking_(blocking) {
}

bool PrintBackendCUPS::EnumeratePrinters(PrinterList* printer_list) {
  DCHECK(printer_list);
  printer_list->clear();

  cups_dest_t* destinations = NULL;
  int num_dests = GetDests(&destinations);
  // TODO(gene): Figure out how to get an error code from cupsGetDests so we can
  // differentiate between the enumeration failing and there being 0 printers.

  for (int printer_index = 0; printer_index < num_dests; printer_index++) {
    const cups_dest_t& printer = destinations[printer_index];

    PrinterBasicInfo printer_info;
    printer_info.printer_name = printer.name;

    const char* info = cupsGetOption(kCUPSPrinterInfoOpt,
        printer.num_options, printer.options);
    if (info != NULL)
      printer_info.printer_description = info;

    const char* state = cupsGetOption(kCUPSPrinterStateOpt,
        printer.num_options, printer.options);
    if (state != NULL)
      base::StringToInt(state, &printer_info.printer_status);

    // Store printer options.
    for (int opt_index = 0; opt_index < printer.num_options; opt_index++) {
      printer_info.options[printer.options[opt_index].name] =
          printer.options[opt_index].value;
    }

    printer_list->push_back(printer_info);
  }

  cupsFreeDests(num_dests, destinations);

  VLOG(1) << "CUPS: Enumerated " << printer_list->size() << " printers.";
  return true;
}

bool PrintBackendCUPS::GetPrinterCapsAndDefaults(
    const std::string& printer_name,
    PrinterCapsAndDefaults* printer_info) {
  DCHECK(printer_info);

  VLOG(1) << "CUPS: Getting Caps and Defaults for: " << printer_name;

  FilePath ppd_path(GetPPD(printer_name.c_str()));
  // In some cases CUPS failed to get ppd file.
  if (ppd_path.empty()) {
    LOG(ERROR) << "CUPS: Failed to get PPD for: " << printer_name;
    return false;
  }

  std::string content;
  bool res = file_util::ReadFileToString(ppd_path, &content);

  file_util::Delete(ppd_path, false);

  if (res) {
    printer_info->printer_capabilities.swap(content);
    printer_info->caps_mime_type = "application/pagemaker";
    // In CUPS, printer defaults is a part of PPD file. Nothing to upload here.
    printer_info->printer_defaults.clear();
    printer_info->defaults_mime_type.clear();
  }

  return res;
}

bool PrintBackendCUPS::IsValidPrinter(const std::string& printer_name) {
  // This is not very efficient way to get specific printer info. CUPS 1.4
  // supports cupsGetNamedDest() function. However, CUPS 1.4 is not available
  // everywhere (for example, it supported from Mac OS 10.6 only).
  PrinterList printer_list;
  EnumeratePrinters(&printer_list);

  PrinterList::iterator it;
  for (it = printer_list.begin(); it != printer_list.end(); ++it)
    if (it->printer_name == printer_name)
      return true;
  return false;
}

scoped_refptr<PrintBackend> PrintBackend::CreateInstance(
    const DictionaryValue* print_backend_settings) {
#if !defined(OS_MACOSX)
  // Initialize gcrypt library.
  g_gcrypt_initializer.Get();
#endif

  std::string print_server_url_str, cups_blocking;
  if (print_backend_settings) {
    print_backend_settings->GetString(kCUPSPrintServerURL,
                                      &print_server_url_str);

    print_backend_settings->GetString(kCUPSBlocking,
                                      &cups_blocking);
  }
  GURL print_server_url(print_server_url_str.c_str());
  return new PrintBackendCUPS(print_server_url, cups_blocking == kValueTrue);
}

int PrintBackendCUPS::GetDests(cups_dest_t** dests) {
  if (print_server_url_.is_empty()) {  // Use default (local) print server.
    return cupsGetDests(dests);
  } else {
    HttpConnectionCUPS http(print_server_url_);
    http.SetBlocking(blocking_);
    return cupsGetDests2(http.http(), dests);
  }
}

FilePath PrintBackendCUPS::GetPPD(const char* name) {
  // cupsGetPPD returns a filename stored in a static buffer in CUPS.
  // Protect this code with lock.
  static base::Lock ppd_lock;
  base::AutoLock ppd_autolock(ppd_lock);
  FilePath ppd_path;
  const char* ppd_file_path = NULL;
  if (print_server_url_.is_empty()) {  // Use default (local) print server.
    ppd_file_path = cupsGetPPD(name);
    if (ppd_file_path)
      ppd_path = FilePath(ppd_file_path);
  } else {
    // cupsGetPPD2 gets stuck sometimes in an infinite time due to network
    // configuration/issues. To prevent that, use non-blocking http connection
    // here.
    // Note: After looking at CUPS sources, it looks like non-blocking
    // connection will timeout after 10 seconds of no data period. And it will
    // return the same way as if data was completely and sucessfully downloaded.
    // To distinguish error case from the normal return, will check result file
    // size agains content length.
    HttpConnectionCUPS http(print_server_url_);
    http.SetBlocking(blocking_);
    ppd_file_path = cupsGetPPD2(http.http(), name);
    // Check if the get full PPD, since non-blocking call may simply return
    // normally after timeout expired.
    if (ppd_file_path) {
      ppd_path = FilePath(ppd_file_path);
      off_t content_len = httpGetLength2(http.http());
      int64 ppd_size = 0;
      // This is a heuristic to detect if we reached timeout. If we see content
      // length is larger that the actual file we downloaded it means timeout
      // reached. Sometimes http can be compressed, and in that case the
      // the content length will be smaller than the actual payload (not sure
      // if CUPS support such responses).
      if (!file_util::GetFileSize(ppd_path, &ppd_size) ||
          content_len > ppd_size) {
        LOG(ERROR) << "Error downloading PPD file for: " << name
                   << ", file size: "  << ppd_size
                   << ", content length: " << content_len;
        file_util::Delete(ppd_path, false);
        ppd_path.clear();
      }
    }
  }
  return ppd_path;
}

}  // namespace printing