Codebase list mozc / upstream/1.0.558.102 base / process.cc
upstream/1.0.558.102

Tree @upstream/1.0.558.102 (Download .tar.gz)

process.cc @upstream/1.0.558.102raw · history · blame

  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
// Copyright 2010, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
//     * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
//     * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

#include "base/process.h"

#include "base/const.h"

#ifdef OS_WINDOWS
#include <windows.h>
#include <shellapi.h>
#include <shlobj.h>
#include "base/util.h"
#include "third_party/mozc/sandbox/restricted_token_utils.h"
#else
#include <string.h>
#include <sys/stat.h>
#include <cerrno>
#endif  // WINDOWS

#ifdef OS_MACOSX
#include <cstdlib>
#include <fcntl.h>
#include <signal.h>
#include <spawn.h>  // for posix_spawn().
#include <sys/stat.h>
#include "base/mac_process.h"
#endif  // OS_MACOSX

#ifdef OS_LINUX
#include <fcntl.h>
#include <signal.h>
#include <spawn.h>  // for posix_spawn().
#include <sys/types.h>
#include <unistd.h>
#endif

#include <vector>
#include "base/util.h"

#ifndef OS_WINDOWS
// Defined somewhere in libc. We can't pass NULL as the 6th argument of
// posix_spawn() since Qt applications use (at least) DISPLAY and QT_IM_MODULE
// environment variables.
extern char **environ;
#endif

#ifdef OS_WINDOWS
namespace {
// ShellExecute to execute file in system dir.
// Since Windows does not allow rename or delete a directory which
// is set to the working directory by existing processes, we should
// avoid unexpected directory locking by background processes.
// System dir is expected to be more appropriate than tha directory
// where the executable exist, because installer can rename the
// executable to another directory and delete the application directory.
bool ShellExecuteInSystemDir(const wchar_t *verb,
                             const wchar_t *file,
                             const wchar_t *parameters,
                             INT show_command) {
  const int result =
      reinterpret_cast<int>(::ShellExecuteW(0, verb, file, parameters,
                                            mozc::Util::GetSystemDir(),
                                            show_command));
  LOG_IF(ERROR, result <= 32)
      << "ShellExecute failed."
      << ", error:" << result
      << ", verb: " << verb
      << ", file: " << file
      << ", parameters: " << parameters;
  return result > 32;
}

bool BeginBackgroundProcessModeWin32(
    mozc::ProsessPriorityClass *previous_mode) {
  // GetCurrentProcess returns a pseudo handle, which is currently (HANDLE)-1.
  // Unfortunately, (HANDLE)-1 is same to INVALID_HANDLE_VALUE so that we do
  // not use mozc::ScopedHandle to avoid confusion.
  const HANDLE current_process_handle = ::GetCurrentProcess();

  // If |previous_mode| is NULL, set dummy address to it.
  mozc::ProsessPriorityClass dummy;
  if (previous_mode == NULL) {
    previous_mode = &dummy;
  }

  bool succeeded = false;
  *previous_mode = ::GetPriorityClass(current_process_handle);
  if (*previous_mode == 0) {
    LOG(ERROR) << "GetPriorityClass failed. error = " << GetLastError();
    succeeded = false;
  } else {
    // Set process priority low
    if (mozc::Util::IsVistaOrLater()) {
      // Windows Vista introduced PROCESS_MODE_BACKGROUND_BEGIN, which can be
      // specified only if |hProcess| parameter is a handle to the current
      // process.
      const DWORD error = ::SetPriorityClass(current_process_handle,
                                             PROCESS_MODE_BACKGROUND_BEGIN);

      succeeded = (error != 0 &&
                   error != ERROR_PROCESS_MODE_ALREADY_BACKGROUND);
      DLOG_IF(INFO, error == ERROR_PROCESS_MODE_ALREADY_BACKGROUND)
          << "Already in background mode";
      LOG_IF(ERROR, !succeeded)
          << "SetPriorityClass failed. error = " << error;
    } else {
      const DWORD error = ::SetPriorityClass(current_process_handle,
                                             BELOW_NORMAL_PRIORITY_CLASS);
      succeeded = (error != 0);
      LOG_IF(ERROR, !succeeded) << "SetPriorityClass failed. error = " << error;
    }
  }

  // Actually CloseHandle with a pseudo handle has no effect.
  ::CloseHandle(current_process_handle);

  return succeeded;
}

bool EndBackgroundProcessModeWin32(
    const mozc::ProsessPriorityClass *previous_mode) {
  // GetCurrentProcess returns a pseudo handle, which is currently (HANDLE)-1.
  // Unfortunately, (HANDLE)-1 is same to INVALID_HANDLE_VALUE so that we do
  // not use mozc::ScopedHandle to avoid confusion.
  const HANDLE current_process_handle = ::GetCurrentProcess();
  bool succeeded = false;

  // Set process priority to the previous one
  if (mozc::Util::IsVistaOrLater()) {
    const DWORD error = ::SetPriorityClass(current_process_handle,
                                           PROCESS_MODE_BACKGROUND_END);
    succeeded = (error != 0);
    LOG_IF(ERROR, !succeeded) << "SetPriorityClass failed. error = " << error;
  } else {
    // Restore priority class
    if (previous_mode == NULL) {
      DLOG(INFO) << "previous_mode is NULL";
      succeeded = false;
    } else {
      const DWORD error = ::SetPriorityClass(current_process_handle,
                                             *previous_mode);
      succeeded = (error != 0);
      LOG_IF(ERROR, !succeeded) << "SetPriorityClass failed. error = " << error;
    }
  }

  // Actually CloseHandle with a pseudo handle has no effect.
  ::CloseHandle(current_process_handle);

  return succeeded;
}
}  // anonymous namespace
#endif  // OS_WINDOWS

namespace mozc {

bool Process::OpenBrowser(const string &url) {
  // url must start with http:// or https:// or file://
  if (url.find("http://") != 0 &&
      url.find("https://") != 0 &&
      url.find("file://") != 0) {
    return false;
  }

#ifdef OS_WINDOWS
  wstring wurl;
  Util::UTF8ToWide(url.c_str(), &wurl);
  return ShellExecuteInSystemDir(L"open", wurl.c_str(), NULL, SW_SHOW);
#endif

#ifdef OS_LINUX
  static const char kBrowserCommand[] = "/usr/bin/xdg-open";
  // xdg-open which uses kfmclient or gnome-open internally works both on KDE
  // and GNOME environments.
  return SpawnProcess(kBrowserCommand, url);
#endif  // LINUX

#ifdef OS_MACOSX
  return MacProcess::OpenBrowserForMac(url);
#endif  // OS_MACOSX
  return false;
}

bool Process::SpawnProcess(const string &path,
                           const string& arg, size_t *pid) {
#ifdef OS_WINDOWS
  wstring wpath;
  Util::UTF8ToWide(path.c_str(), &wpath);
  wpath = L"\"" + wpath + L"\"";
  if (!arg.empty()) {
    wstring warg;
    Util::UTF8ToWide(arg.c_str(), &warg);
    wpath += L" ";
    wpath += warg;
  }

  // The |lpCommandLine| parameter of CreateProcessW should be writable
  // so that we create a scoped_array here.
  scoped_array<wchar_t> wpath2(new wchar_t[wpath.size() + 1]);
  if (0 != wcscpy_s(wpath2.get(), wpath.size() + 1, wpath.c_str())) {
    return false;
  }

  STARTUPINFOW si = { 0 };
  si.cb = sizeof(si);
  si.dwFlags = STARTF_FORCEOFFFEEDBACK;
  PROCESS_INFORMATION pi = { 0 };

  // If both |lpApplicationName| and |lpCommandLine| are non-NULL,
  // the argument array of the process will be shifted.
  // http://support.microsoft.com/kb/175986
  const bool create_process_succeeded = ::CreateProcessW(
      NULL, wpath2.get(), NULL, NULL, FALSE,
      CREATE_DEFAULT_ERROR_MODE, NULL,
      // NOTE: Working directory will be locked by the system.
      // We use system directory to spawn process so that users will not
      // to be aware of any undeletable directory. (http://b/2017482)
      Util::GetSystemDir(),
      &si, &pi) != FALSE;

  if (create_process_succeeded) {
    ::CloseHandle(pi.hThread);
    ::CloseHandle(pi.hProcess);
  } else {
    LOG(ERROR) << "Create process failed: " << ::GetLastError();
  }

  return create_process_succeeded;
#else

  vector<string> arg_tmp;
  Util::SplitStringUsing(arg, " ", &arg_tmp);
  scoped_array<const char*> argv(new const char*[arg_tmp.size() + 2]);
  argv[0] = path.c_str();
  for (size_t i = 0; i < arg_tmp.size(); ++i) {
    argv[i + 1] = arg_tmp[i].c_str();
  }
  argv[arg_tmp.size() + 1] = NULL;

  struct stat statbuf;
  if (::stat(path.c_str(), &statbuf) != 0) {
    LOG(ERROR) << "Can't stat " << path << ": " << strerror(errno);
    return false;
  }
#ifdef OS_MACOSX
  // Check if the "path" is an application or not.  If it's an
  // application, do a special process using mac_process.mm.
  if (S_ISDIR(statbuf.st_mode) && path.size() > 4 &&
      path.substr(path.size() - 4) == ".app") {
    // In mac launchApplication cannot accept any arguments.
    return MacProcess::OpenApplication(path);
  }
#endif

#ifdef OS_LINUX
  // Do not call posix_spawn() for obviously bad path.
  if (!S_ISREG(statbuf.st_mode)) {
    LOG(ERROR) << "Not a regular file: " << path;
    return false;
  }
  if ((statbuf.st_mode & (S_IXUSR | S_IXGRP | S_IXOTH)) == 0) {
    LOG(ERROR) << "Not a executable file: " << path;
    return false;
  }

  // We don't want to execute setuid/gid binaries for security reasons.
  if ((statbuf.st_mode & (S_ISUID | S_ISGID)) != 0) {
    LOG(ERROR) << "Can't execute setuid or setgid binaries: " << path;
    return false;
  }

  // Use simple heap corruption checker in child processes. This setenv() does
  // not affect current process behavior since Glibc never check the variable
  // after main().
  // (www.gnu.org/software/libc/manual/html_node/Heap-Consistency-Checking.html)
  const int kOverwrite = 0;  // Do not overwrite.
  ::setenv("MALLOC_CHECK_", "2", kOverwrite);
#endif  // OS_LINUX
  pid_t tmp_pid = 0;

  // Spawn new process.
  // NOTE:
  // posix_spawn returns 0 even if kMozcServer doesn't exist, because
  // the return value of posix_spawn is basically determined
  // by the return value of fork().
  const int result = ::posix_spawn(
      &tmp_pid, path.c_str(), NULL, NULL, const_cast<char* const*>(argv.get()),
      environ);
  if (result == 0) {
    VLOG(1) << "posix_spawn: child pid is " << tmp_pid;
  } else {
    LOG(ERROR) << "posix_spawn failed: " << strerror(result);
  }

  if (pid != NULL) {
    *pid = tmp_pid;
  }
  return result == 0;
#endif  // OS_WINDOWS
}

bool Process::SpawnMozcProcess(
    const string &filename, const string &arg, size_t *pid) {
  return mozc::Process::SpawnProcess(
      mozc::Util::JoinPath(mozc::Util::GetServerDirectory(), filename),
      arg, pid);
}

#ifdef OS_WINDOWS
Process::SecurityInfo::SecurityInfo()
    : primary_level(sandbox::USER_LOCKDOWN),
      impersonation_level(sandbox::USER_LOCKDOWN),
      job_level(sandbox::JOB_LOCKDOWN),
      integrity_level(sandbox::INTEGRITY_LEVEL_SYSTEM),
      allow_ui_operation(false),
      in_system_dir(false),
      creation_flags(0) {}

bool Process::SpawnProcessAs(const string &path,
                             const string &arg,
                             const Process::SecurityInfo &info,
                             DWORD *pid) {
  wstring wpath;
  Util::UTF8ToWide(path.c_str(), &wpath);
  wpath = L"\"" + wpath + L"\"";
  if (!arg.empty()) {
    wstring warg;
    Util::UTF8ToWide(arg.c_str(), &warg);
    wpath += L" ";
    wpath += warg;
  }

  scoped_array<wchar_t> wpath2(new wchar_t[wpath.size() + 1]);
  if (0 != wcscpy_s(wpath2.get(), wpath.size() + 1, wpath.c_str())) {
    return false;
  }

  HANDLE job_handle = 0;
  // Create a Job inside restricted sandbox environment.
  // Child job inherits the environment of the caller.
  // (http://b/2048754)
  const DWORD err_code = sandbox::StartRestrictedProcessInJob(
      wpath2.get(),
      info.primary_level,
      info.impersonation_level,
      info.job_level,
      // If info.in_system_dir is true, we set the initial directory of the
      // process to system directory.
      info.in_system_dir ? Util::GetSystemDir() : NULL,
      info.integrity_level,
      info.allow_ui_operation ? JOB_OBJECT_UILIMIT_ALL : 0,
      info.creation_flags,
      &job_handle,
      pid);

  // Remove JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE to allow the
  // child process to continue running even after the parent is terminated
  // TODO(taku): better to add new paramenter to pass
  // JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE
  if (NULL != job_handle) {
    JOBOBJECT_EXTENDED_LIMIT_INFORMATION jeli;
    if (!::QueryInformationJobObject(job_handle,
                                     JobObjectExtendedLimitInformation,
                                     &jeli, sizeof(jeli), NULL)) {
      LOG(ERROR) << "QueryInformationJobObject failed: "
                 << ::GetLastError();
      ::CloseHandle(job_handle);
      return false;
    }

    jeli.BasicLimitInformation.LimitFlags
        &= ~JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE;
    if (!::SetInformationJobObject(job_handle,
                                   JobObjectExtendedLimitInformation,
                                   &jeli, sizeof(jeli))) {
      LOG(ERROR) << "SetQueryInformationJobObject failed: "
                 << ::GetLastError();
      ::CloseHandle(job_handle);
      return false;
    }
    ::CloseHandle(job_handle);
  }

  LOG_IF(ERROR, err_code != ERROR_SUCCESS) <<
      "sandbox::StartRestrictedProcessInJob failed: " << ::GetLastError();

  return ERROR_SUCCESS == err_code;
}
#endif  // OS_WINDOWS

bool Process::BeginBackgroundProcessMode(
    ProsessPriorityClass *previous_mode) {
#ifdef OS_WINDOWS
  return BeginBackgroundProcessModeWin32(previous_mode);
#else  // OS_WINDOWS
  // TODO(yukawa): Implement for MacOS and Linux
  return true;
#endif
}
bool Process::EndBackgroundProcessMode(
    const ProsessPriorityClass *previous_mode) {
#ifdef OS_WINDOWS
  return EndBackgroundProcessModeWin32(previous_mode);
#else  // OS_WINDOWS
  // TODO(yukawa): Implement for MacOS and Linux
  return true;
#endif
}

bool Process::WaitProcess(size_t pid, int timeout) {
  if (pid == 0) {
    LOG(WARNING) << "pid is 0. ignored";
    return true;
  }

  if (timeout == 0) {
    LOG(ERROR) << "timeout is 0";
    return false;
  }

#ifdef OS_WINDOWS
  DWORD processe_id = static_cast<DWORD>(pid);
  ScopedHandle handle(::OpenProcess(SYNCHRONIZE, FALSE, processe_id));
  if (handle.get() == NULL) {
    LOG(ERROR) << "Cannot get handle id";
    return true;
  }

  if (timeout < 0) {
    timeout = INFINITE;
  }

  const DWORD result = ::WaitForSingleObject(handle.get(), timeout);
  if (result == WAIT_TIMEOUT) {
    LOG(ERROR) << pid << " didn't terminate within " << timeout << " msec";
    return false;
  }

  return true;
#else
  pid_t processe_id = static_cast<pid_t>(pid);
  const int kPollingDuration = 250;
  int left_time = timeout < 0 ? 1 : timeout;
  while (left_time > 0) {
    Util::Sleep(kPollingDuration);
    if (::kill(processe_id, 0) != 0) {
      if (errno == EPERM) {
        return false;   // access defined
      }
      return true;   // process not found
    }
    if (timeout > 0) {
      left_time -= kPollingDuration;
    }
  }

  LOG(ERROR) << pid << " didn't terminate within " << timeout << " msec";
  return false;
#endif
}

bool Process::IsProcessAlive(size_t pid, bool default_result) {
  if (pid == 0) {
    return default_result;
  }

#ifdef OS_WINDOWS
  {
    ScopedHandle handle(::OpenProcess(SYNCHRONIZE, FALSE,
                                      static_cast<DWORD>(pid)));
    if (NULL == handle.get()) {
      const DWORD error = ::GetLastError();
      if (error == ERROR_ACCESS_DENIED) {
        LOG(ERROR) << "OpenProcess failed: " << error;
        return default_result;  // unknown
      }
      return false;  // not running
    }

    if (WAIT_TIMEOUT == ::WaitForSingleObject(handle.get(), 0)) {
      return true;  // running
    }
  }  // release handle

  return default_result;  // unknown

#else  // OS_WINDOWS
  const int kSig = 0;
  if (::kill(static_cast<pid_t>(pid), kSig) == -1) {
    if (errno == EPERM || errno == EINVAL) {
      // permission denied or invalid signal.
      return default_result;
    }
    return false;
  }

  return true;
#endif  // OS_WINDOWS
}

bool Process::IsThreadAlive(size_t thread_id, bool default_result) {
#ifdef OS_WINDOWS
  if (thread_id == 0) {
    return default_result;
  }

  {
    ScopedHandle handle(::OpenThread(SYNCHRONIZE, FALSE,
                                     static_cast<DWORD>(thread_id)));
    if (NULL == handle.get()) {
      const DWORD error = ::GetLastError();
      if (error == ERROR_ACCESS_DENIED) {
        LOG(ERROR) << "OpenThread failed: " << error;
        return default_result;  // unknown
      }
      return false;  // not running
    }

    if (WAIT_TIMEOUT == ::WaitForSingleObject(handle.get(), 0)) {
      return true;  // running
    }
  }  // release handle

  return default_result;  // unknown

#else   // OS_WINDOWS
  // On Linux/Mac, there is no way to check the status of thread id from
  // other process.
  return default_result;
#endif  // OS_WNIDOWS
}

bool Process::LaunchErrorMessageDialog(const string &error_type) {
#ifdef OS_MACOSX
  if (!MacProcess::LaunchErrorMessageDialog(error_type)) {
    LOG(ERROR) << "cannot error message dialog";
    return false;
  }
#endif  // OS_MACOSX

#ifdef OS_WINDOWS
  const string arg = "--mode=error_message_dialog --error_type=" + error_type;
  size_t pid = 0;
  if (!Process::SpawnProcess(
          Util::JoinPath(Util::GetServerDirectory(), kMozcTool), arg, &pid)) {
    LOG(ERROR) << "cannot launch " << kMozcTool;
    return false;
  }
#endif  // OS_WINDOWS

#ifdef OS_LINUX
  const char kMozcTool[] = "mozc_tool";
  const string arg = "--mode=error_message_dialog --error_type=" + error_type;
  size_t pid = 0;
  if (!Process::SpawnProcess(
          Util::JoinPath(Util::GetServerDirectory(), kMozcTool), arg, &pid)) {
    LOG(ERROR) << "cannot launch " << kMozcTool;
    return false;
  }
#endif  // OS_LINUX

  return true;
}
}  // namespace mozc