summaryrefslogtreecommitdiffstats
path: root/cloud_print/virtual_driver/win/install/setup.cc
blob: 1b83cbb35205a8fd8349a7f1232a608d919de40b (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
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
// Copyright (c) 2011 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 <windows.h>
#include <winspool.h>

#include "base/at_exit.h"
#include "base/command_line.h"
#include "base/file_util.h"
#include "base/file_version_info_win.h"
#include "base/logging.h"
#include "base/path_service.h"
#include "base/process_util.h"
#include "base/string16.h"
#include "base/win/registry.h"
#include "base/win/scoped_handle.h"
#include "cloud_print/virtual_driver/win/virtual_driver_consts.h"
#include "cloud_print/virtual_driver/win/virtual_driver_helpers.h"
#include "grit/virtual_driver_setup_resources.h"

namespace {
const wchar_t kVersionKey[] = L"pv";
const wchar_t kNameKey[] = L"name";
const wchar_t kLangKey[] = L"lang";
const wchar_t kNameValue[] = L"GCP Virtual Driver";
const wchar_t kLangValue[] = L"rn";

void SetRegistryKeys() {
  base::win::RegKey key;
  if (key.Create(HKEY_LOCAL_MACHINE, cloud_print::kKeyLocation,
                 KEY_SET_VALUE) != ERROR_SUCCESS) {
    LOG(ERROR) << "Unable to open key";
  }

  // Get the version from the resource file.
  std::wstring version_string;
  scoped_ptr<FileVersionInfo> version_info(
      FileVersionInfo::CreateFileVersionInfoForCurrentModule());

  if (version_info.get()) {
    FileVersionInfoWin* version_info_win =
        static_cast<FileVersionInfoWin*>(version_info.get());
    version_string = version_info_win->product_version();
  } else {
    LOG(ERROR) << "Unable to get version string";
    // Use a random version string so that Omaha has something to go by.
    version_string = L"0.0.0.99";
  }

  if (key.WriteValue(kVersionKey, version_string.c_str()) != ERROR_SUCCESS ||
      key.WriteValue(kNameKey, kNameValue) != ERROR_SUCCESS ||
      key.WriteValue(kLangKey, kLangValue) != ERROR_SUCCESS) {
    LOG(ERROR) << "Unable to set registry keys";
  }
}

void DeleteRegistryKeys() {
  base::win::RegKey key;
  if (key.Open(HKEY_LOCAL_MACHINE, cloud_print::kKeyLocation,
               DELETE) != ERROR_SUCCESS) {
    LOG(ERROR) << "Unable to open key to delete";
  }
  if (key.DeleteKey(L"") != ERROR_SUCCESS) {
    LOG(ERROR) << "Unable to delete key";
  }
}

HRESULT GetPpdPath(FilePath* path) {
  if (!PathService::Get(base::DIR_EXE, path)) {
    LOG(ERROR) << "Unable to get install path.";
    return ERROR_PATH_NOT_FOUND;
  }
  *path = path->Append(L"GCP-driver.ppd");
  return S_OK;
}

HRESULT GetPortMonitorDllPath(FilePath* path) {
  if (!PathService::Get(base::DIR_EXE, path)) {
    LOG(ERROR) << "Unable to get install path.";
    return ERROR_PATH_NOT_FOUND;
  }
  *path = path->Append(cloud_print::GetPortMonitorDllName());
  return S_OK;
}

HRESULT GetPortMonitorInstallPath(FilePath* path) {
  if (cloud_print::IsSystem64Bit()) {
    if (!PathService::Get(base::DIR_WINDOWS, path)) {
      return ERROR_PATH_NOT_FOUND;
    }
    // Sysnative will bypass filesystem redirection and give us
    // the location of the 64bit system32 from a 32 bit process.
    *path = path->Append(L"sysnative");
  } else {
    if (!PathService::Get(base::DIR_SYSTEM, path)) {
      LOG(ERROR) << "Unable to get system path.";
      return ERROR_PATH_NOT_FOUND;
    }
  }
  *path = path->Append(cloud_print::GetPortMonitorDllName());
  return S_OK;
}

HRESULT GetRegsvr32Path(FilePath* path) {
  if (!PathService::Get(base::DIR_SYSTEM, path)) {
    LOG(ERROR) << "Unable to get system path.";
    return ERROR_PATH_NOT_FOUND;
  }
  *path = path->Append(FilePath(L"regsvr32.exe"));
  return S_OK;
}

HRESULT RegisterPortMonitor(bool install) {
  FilePath target_path;
  HRESULT result = S_OK;
  result = GetPortMonitorInstallPath(&target_path);
  if (!SUCCEEDED(result)) {
    LOG(ERROR) << "Unable to get port monitor target path.";
    return result;
  }
  FilePath source_path;
  result = GetPortMonitorDllPath(&source_path);
  if (!SUCCEEDED(result)) {
    LOG(ERROR) << "Unable to get dll source path.";
    return result;
  }
  if (install) {
    if (!file_util::CopyFileW(source_path, target_path)) {
      LOG(ERROR) << "Unable copy port monitor dll from " <<
          source_path.value() << " to " << target_path.value();
      return ERROR_ACCESS_DENIED;
    }
  }
  FilePath regsvr32_path;
  result = GetRegsvr32Path(&regsvr32_path);
  if (!SUCCEEDED(result)) {
    LOG(ERROR) << "Can't find regsvr32.exe.";
    return result;
  }

  CommandLine command_line(regsvr32_path);
  command_line.AppendArg("/s");
  if (!install) {
    command_line.AppendArg("/u");
  }
  command_line.AppendArgPath(source_path);

  base::LaunchOptions options;
  HANDLE process_handle;
  options.wait = true;
  if (!base::LaunchProcess(command_line, options, &process_handle)) {
    LOG(ERROR) << "Unable to launch regsvr32.exe.";
    return ERROR_NOT_SUPPORTED;
  }
  base::win::ScopedHandle scoped_process_handle(process_handle);

  DWORD exit_code = S_OK;
  if (!GetExitCodeProcess(scoped_process_handle, &exit_code)) {
    HRESULT result = cloud_print::GetLastHResult();
    LOG(ERROR) << "Unable to get regsvr32.exe exit code.";
    return result;
  }
  if (exit_code != 0) {
    LOG(ERROR) << "Regsvr32.exe failed with " << exit_code;
    return HRESULT_FROM_WIN32(exit_code);
  }
  if (!install) {
    if (!file_util::Delete(target_path, false)) {
      LOG(ERROR) << "Unable to delete " << target_path.value();
      return ERROR_ACCESS_DENIED;
    }
  }
  return S_OK;
}

DWORDLONG GetVersionNumber() {
  DWORDLONG retval = 0;
  scoped_ptr<FileVersionInfo> version_info(
      FileVersionInfo::CreateFileVersionInfoForCurrentModule());
  if (version_info.get()) {
    FileVersionInfoWin* version_info_win =
        static_cast<FileVersionInfoWin*>(version_info.get());
    VS_FIXEDFILEINFO* fixed_file_info = version_info_win->fixed_file_info();
    retval = fixed_file_info->dwFileVersionMS;
    retval <<= 32;
    retval |= fixed_file_info->dwFileVersionMS;
  }
  return retval;
}

HRESULT InstallPpd() {
  DRIVER_INFO_6 driver_info = {0};
  HRESULT result = S_OK;

  // Set up paths for the files we depend on.
  FilePath source_path;
  FilePath driver_dir;
  cloud_print::GetPrinterDriverDir(&driver_dir);
  FilePath xps_path = driver_dir.Append(L"mxdwdrv.dll");
  FilePath ui_path = driver_dir.Append(L"ps5ui.dll");
  FilePath ui_help_path = driver_dir.Append(L"unidrv.hlp");
  result = GetPpdPath(&source_path);
  if (!SUCCEEDED(result)) {
    return result;
  }
  // None of the print API structures likes constant strings even though they
  // don't modify the string.  const_casting is the cleanest option.
  driver_info.pDataFile = const_cast<LPWSTR>(source_path.value().c_str());
  driver_info.pHelpFile = const_cast<LPWSTR>(ui_help_path.value().c_str());
  driver_info.pDriverPath = const_cast<LPWSTR>(xps_path.value().c_str());
  driver_info.pConfigFile = const_cast<LPWSTR>(ui_path.value().c_str());

  // Set up user visible strings.
  string16 manufacturer = cloud_print::LoadLocalString(IDS_GOOGLE);
  driver_info.pszMfgName = const_cast<LPWSTR>(manufacturer.c_str());
  driver_info.pszProvider = const_cast<LPWSTR>(manufacturer.c_str());
  driver_info.pszOEMUrl = L"http://www.google.com/cloudprint";
  driver_info.dwlDriverVersion = GetVersionNumber();
  string16 driver_name = cloud_print::LoadLocalString(IDS_DRIVER_NAME);
  driver_info.pName = const_cast<LPWSTR>(driver_name.c_str());

  // Set up supported print system version.  Must be 3.
  driver_info.cVersion = 3;

  // TODO(abodenha@chromium.org) Properly handle dependencies.
  // GPD files are often dependent on various Windows core drivers.
  // I haven't found a reliable way to express those dependencies
  // other than using an INF for installation.
  if (!AddPrinterDriverEx(NULL,
                          6,
                          reinterpret_cast<BYTE*>(&driver_info),
                          APD_COPY_NEW_FILES|APD_COPY_FROM_DIRECTORY)) {
    result = cloud_print::GetLastHResult();
    LOG(ERROR) << "Unable to add printer driver";
    return result;
  }
  return S_OK;
}

HRESULT UninstallPpd() {
  int tries = 10;
  string16 driver_name = cloud_print::LoadLocalString(IDS_DRIVER_NAME);
  while (!DeletePrinterDriverEx(NULL,
                                NULL,
                                const_cast<LPWSTR>(driver_name.c_str()),
                                DPD_DELETE_UNUSED_FILES,
                                0) && tries > 0) {
    if (GetLastError() == ERROR_UNKNOWN_PRINTER_DRIVER) {
      LOG(WARNING) << "Print driver is already uninstalled.";
      return S_OK;
    }
    // After deleting the printer it can take a few seconds before
    // the driver is free for deletion.  Retry a few times before giving up.
    LOG(WARNING) << "Attempt to delete printer driver failed.  Retrying.";
    tries--;
    Sleep(2000);
  }
  if (tries <= 0) {
    HRESULT result = cloud_print::GetLastHResult();
    LOG(ERROR) << "Unable to delete printer driver.";
    return result;
  }
  return S_OK;
}

HRESULT InstallPrinter(void) {
  PRINTER_INFO_2 printer_info = {0};

  // None of the print API structures likes constant strings even though they
  // don't modify the string.  const_casting is the cleanest option.
  string16 driver_name = cloud_print::LoadLocalString(IDS_DRIVER_NAME);
  printer_info.pDriverName = const_cast<LPWSTR>(driver_name.c_str());
  printer_info.pPrinterName = const_cast<LPWSTR>(driver_name.c_str());
  printer_info.pComment =  const_cast<LPWSTR>(driver_name.c_str());
  string16 port_name;
  printer_info.pPortName = const_cast<LPWSTR>(cloud_print::kPortName);
  printer_info.Attributes = PRINTER_ATTRIBUTE_DIRECT|PRINTER_ATTRIBUTE_LOCAL;
  printer_info.pPrintProcessor = L"winprint";
  HANDLE handle = AddPrinter(NULL, 2, reinterpret_cast<BYTE*>(&printer_info));
  if (handle == NULL) {
    HRESULT result = cloud_print::GetLastHResult();
    LOG(ERROR) << "Unable to add printer";
    return result;
  }
  ClosePrinter(handle);
  return S_OK;
}

HRESULT UninstallPrinter(void) {
  HANDLE handle = NULL;
  PRINTER_DEFAULTS printer_defaults = {0};
  printer_defaults.DesiredAccess = PRINTER_ALL_ACCESS;
  string16 driver_name = cloud_print::LoadLocalString(IDS_DRIVER_NAME);
  if (!OpenPrinter(const_cast<LPWSTR>(driver_name.c_str()),
                   &handle,
                   &printer_defaults)) {
    // If we can't open the printer, it was probably already removed.
    LOG(WARNING) << "Unable to open printer";
    return S_OK;
  }
  if (!DeletePrinter(handle)) {
    HRESULT result = cloud_print::GetLastHResult();
    LOG(ERROR) << "Unable to delete printer";
    ClosePrinter(handle);
    return result;
  }
  ClosePrinter(handle);
  return S_OK;
}

HRESULT InstallVirtualDriver(void) {
  HRESULT result = S_OK;
  result = RegisterPortMonitor(true);
  if (!SUCCEEDED(result)) {
    LOG(ERROR) << "Unable to register port monitor.";
    return result;
  }
  result = InstallPpd();
  if (!SUCCEEDED(result)) {
    LOG(ERROR) << "Unable to install Ppd.";
    return result;
  }
  result = InstallPrinter();
  if (!SUCCEEDED(result)) {
    LOG(ERROR) << "Unable to install printer.";
    return result;
  }
  SetRegistryKeys();
  return S_OK;
}

HRESULT UninstallVirtualDriver(void) {
  HRESULT result = S_OK;
  result = UninstallPrinter();
  if (!SUCCEEDED(result)) {
    LOG(ERROR) << "Unable to uninstall Ppd.";
    return result;
  }
  result = UninstallPpd();
  if (!SUCCEEDED(result)) {
    LOG(ERROR) << "Unable to remove Ppd.";
    return result;
  }
  result = RegisterPortMonitor(false);
  if (!SUCCEEDED(result)) {
    LOG(ERROR) << "Unable to remove port monitor.";
    return result;
  }
  DeleteRegistryKeys();
  return S_OK;
}

}  // namespace

int WINAPI WinMain(__in  HINSTANCE hInstance,
            __in  HINSTANCE hPrevInstance,
            __in  LPSTR lpCmdLine,
            __in  int nCmdShow) {
  base::AtExitManager at_exit_manager;
  CommandLine::Init(0, NULL);
  HRESULT retval = S_OK;
  if (CommandLine::ForCurrentProcess()->HasSwitch("uninstall")) {
    retval = UninstallVirtualDriver();
  } else {
    retval = InstallVirtualDriver();
  }
  // Installer is silent by default as required by Omaha.
  if (CommandLine::ForCurrentProcess()->HasSwitch("verbose")) {
    cloud_print::DisplayWindowsMessage(NULL, retval,
        cloud_print::LoadLocalString(IDS_DRIVER_NAME));
  }
  return retval;
}