1 // Copyright 2014 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 // On Linux, when the user tries to launch a second copy of chrome, we check
6 // for a socket in the user's profile directory. If the socket file is open we
7 // send a message to the first chrome browser process with the current
8 // directory and second process command line flags. The second process then
11 // Because many networked filesystem implementations do not support unix domain
12 // sockets, we create the socket in a temporary directory and create a symlink
13 // in the profile. This temporary directory is no longer bound to the profile,
14 // and may disappear across a reboot or login to a separate session. To bind
15 // them, we store a unique cookie in the profile directory, which must also be
16 // present in the remote directory to connect. The cookie is checked both before
17 // and after the connection. /tmp is sticky, and different Chrome sessions use
18 // different cookies. Thus, a matching cookie before and after means the
19 // connection was to a directory with a valid cookie.
21 // We also have a lock file, which is a symlink to a non-existent destination.
22 // The destination is a string containing the hostname and process id of
23 // chrome's browser process, eg. "SingletonLock -> example.com-9156". When the
24 // first copy of chrome exits it will delete the lock file on shutdown, so that
25 // a different instance on a different host may then use the profile directory.
27 // If writing to the socket fails, the hostname in the lock is checked to see if
28 // another instance is running a different host using a shared filesystem (nfs,
29 // etc.) If the hostname differs an error is displayed and the second process
30 // exits. Otherwise the first process (if any) is killed and the second process
33 // When the second process sends the current directory and command line flags to
34 // the first process, it waits for an ACK message back from the first process
35 // for a certain time. If there is no ACK message back in time, then the first
36 // process will be considered as hung for some reason. The second process then
37 // retrieves the process id from the symbol link and kills it by sending
38 // SIGKILL. Then the second process starts as normal.
40 #include "chrome/browser/process_singleton.h"
45 #include <sys/socket.h>
47 #include <sys/types.h>
58 #include "base/base_paths.h"
59 #include "base/bind.h"
60 #include "base/command_line.h"
61 #include "base/containers/unique_ptr_adapters.h"
62 #include "base/cxx17_backports.h"
63 #include "base/files/file_descriptor_watcher_posix.h"
64 #include "base/files/file_path.h"
65 #include "base/files/file_util.h"
66 #include "base/location.h"
67 #include "base/logging.h"
68 #include "base/memory/ref_counted.h"
69 #include "base/metrics/histogram_functions.h"
70 #include "base/metrics/histogram_macros.h"
71 #include "base/path_service.h"
72 #include "base/posix/eintr_wrapper.h"
73 #include "base/posix/safe_strerror.h"
74 #include "base/rand_util.h"
75 #include "base/sequenced_task_runner_helpers.h"
76 #include "base/single_thread_task_runner.h"
77 #include "base/strings/string_number_conversions.h"
78 #include "base/strings/string_split.h"
79 #include "base/strings/string_util.h"
80 #include "base/strings/stringprintf.h"
81 #include "base/strings/sys_string_conversions.h"
82 #include "base/strings/utf_string_conversions.h"
83 #include "base/threading/platform_thread.h"
84 #include "base/threading/thread_task_runner_handle.h"
85 #include "base/time/time.h"
86 #include "base/timer/timer.h"
87 #include "build/build_config.h"
88 #include "build/chromeos_buildflags.h"
89 #include "chrome/common/chrome_constants.h"
90 #include "chrome/common/process_singleton_lock_posix.h"
91 #include "chrome/grit/chromium_strings.h"
92 #include "chrome/grit/generated_resources.h"
93 #include "content/public/browser/browser_task_traits.h"
94 #include "content/public/browser/browser_thread.h"
95 #include "net/base/network_interfaces.h"
96 #include "ui/base/l10n/l10n_util.h"
98 #if defined(OS_LINUX) || defined(OS_CHROMEOS)
99 #include "chrome/browser/ui/process_singleton_dialog_linux.h"
102 #if defined(TOOLKIT_VIEWS) && \
103 (defined(OS_LINUX) || BUILDFLAG(IS_CHROMEOS_LACROS))
104 #include "ui/views/linux_ui/linux_ui.h"
107 using content::BrowserThread;
111 // Timeout for the current browser process to respond. 20 seconds should be
113 const int kTimeoutInSeconds = 20;
114 // Number of retries to notify the browser. 20 retries over 20 seconds = 1 try
116 const int kRetryAttempts = 20;
117 const char kStartToken[] = "START";
118 const char kACKToken[] = "ACK";
119 const char kShutdownToken[] = "SHUTDOWN";
120 const char kTokenDelimiter = '\0';
121 const int kMaxMessageLength = 32 * 1024;
122 const int kMaxACKMessageLength = base::size(kShutdownToken) - 1;
124 bool g_disable_prompt = false;
125 bool g_skip_is_chrome_process_check = false;
126 bool g_user_opted_unlock_in_use_profile = false;
128 // Set the close-on-exec bit on a file descriptor.
129 // Returns 0 on success, -1 on failure.
130 int SetCloseOnExec(int fd) {
131 int flags = fcntl(fd, F_GETFD, 0);
134 if (flags & FD_CLOEXEC)
136 return fcntl(fd, F_SETFD, flags | FD_CLOEXEC);
139 // Close a socket and check return value.
140 void CloseSocket(int fd) {
141 int rv = IGNORE_EINTR(close(fd));
142 DCHECK_EQ(0, rv) << "Error closing socket: " << base::safe_strerror(errno);
145 // Write a message to a socket fd.
146 bool WriteToSocket(int fd, const char *message, size_t length) {
149 size_t bytes_written = 0;
151 ssize_t rv = HANDLE_EINTR(
152 write(fd, message + bytes_written, length - bytes_written));
154 if (errno == EAGAIN || errno == EWOULDBLOCK) {
155 // The socket shouldn't block, we're sending so little data. Just give
156 // up here, since NotifyOtherProcess() doesn't have an asynchronous api.
157 LOG(ERROR) << "ProcessSingleton would block on write(), so it gave up.";
160 PLOG(ERROR) << "write() failed";
164 } while (bytes_written < length);
169 struct timeval TimeDeltaToTimeVal(const base::TimeDelta& delta) {
170 struct timeval result;
171 result.tv_sec = delta.InSeconds();
172 result.tv_usec = delta.InMicroseconds() % base::Time::kMicrosecondsPerSecond;
176 // Wait a socket for read for a certain timeout.
177 // Returns -1 if error occurred, 0 if timeout reached, > 0 if the socket is
179 int WaitSocketForRead(int fd, const base::TimeDelta& timeout) {
181 struct timeval tv = TimeDeltaToTimeVal(timeout);
184 FD_SET(fd, &read_fds);
186 return HANDLE_EINTR(select(fd + 1, &read_fds, NULL, NULL, &tv));
189 // Read a message from a socket fd, with an optional timeout.
190 // If |timeout| <= 0 then read immediately.
191 // Return number of bytes actually read, or -1 on error.
192 ssize_t ReadFromSocket(int fd,
195 const base::TimeDelta& timeout) {
196 if (timeout > base::TimeDelta()) {
197 int rv = WaitSocketForRead(fd, timeout);
202 size_t bytes_read = 0;
204 ssize_t rv = HANDLE_EINTR(read(fd, buf + bytes_read, bufsize - bytes_read));
206 if (errno != EAGAIN && errno != EWOULDBLOCK) {
207 PLOG(ERROR) << "read() failed";
210 // It would block, so we just return what has been read.
214 // No more data to read.
219 } while (bytes_read < bufsize);
224 // Set up a sockaddr appropriate for messaging.
225 bool SetupSockAddr(const std::string& path, struct sockaddr_un* addr) {
226 addr->sun_family = AF_UNIX;
227 if (path.length() >= base::size(addr->sun_path))
229 base::strlcpy(addr->sun_path, path.c_str(), base::size(addr->sun_path));
233 // Set up a socket appropriate for messaging.
234 int SetupSocketOnly() {
235 int sock = socket(PF_UNIX, SOCK_STREAM, 0);
236 PCHECK(sock >= 0) << "socket() failed";
238 DCHECK(base::SetNonBlocking(sock)) << "Failed to make non-blocking socket.";
239 int rv = SetCloseOnExec(sock);
240 DCHECK_EQ(0, rv) << "Failed to set CLOEXEC on socket.";
245 // Set up a socket and sockaddr appropriate for messaging.
246 void SetupSocket(const std::string& path, int* sock, struct sockaddr_un* addr) {
247 *sock = SetupSocketOnly();
248 CHECK(SetupSockAddr(path, addr)) << "Socket path too long: " << path;
251 // Read a symbolic link, return empty string if given path is not a symbol link.
252 base::FilePath ReadLink(const base::FilePath& path) {
253 base::FilePath target;
254 if (!base::ReadSymbolicLink(path, &target)) {
255 // The only errno that should occur is ENOENT.
256 if (errno != 0 && errno != ENOENT)
257 PLOG(ERROR) << "readlink(" << path.value() << ") failed";
262 // Unlink a path. Return true on success.
263 bool UnlinkPath(const base::FilePath& path) {
264 int rv = unlink(path.value().c_str());
265 if (rv < 0 && errno != ENOENT)
266 PLOG(ERROR) << "Failed to unlink " << path.value();
271 // Create a symlink. Returns true on success.
272 bool SymlinkPath(const base::FilePath& target, const base::FilePath& path) {
273 if (!base::CreateSymbolicLink(target, path)) {
274 // Double check the value in case symlink suceeded but we got an incorrect
275 // failure due to NFS packet loss & retry.
276 int saved_errno = errno;
277 if (ReadLink(path) != target) {
278 // If we failed to create the lock, most likely another instance won the
281 PLOG(ERROR) << "Failed to create " << path.value();
288 // Returns true if the user opted to unlock the profile.
289 bool DisplayProfileInUseError(const base::FilePath& lock_path,
290 const std::string& hostname,
292 std::u16string error = l10n_util::GetStringFUTF16(
293 IDS_PROFILE_IN_USE_POSIX, base::NumberToString16(pid),
294 base::ASCIIToUTF16(hostname));
297 if (g_disable_prompt)
298 return g_user_opted_unlock_in_use_profile;
300 #if defined(OS_LINUX) || defined(OS_CHROMEOS)
301 std::u16string relaunch_button_text =
302 l10n_util::GetStringUTF16(IDS_PROFILE_IN_USE_LINUX_RELAUNCH);
303 return ShowProcessSingletonDialog(error, relaunch_button_text);
304 #elif defined(OS_MAC)
305 // On Mac, always usurp the lock.
313 bool IsChromeProcess(pid_t pid) {
314 if (g_skip_is_chrome_process_check)
317 base::FilePath other_chrome_path(base::GetProcessExecutablePath(pid));
318 return (!other_chrome_path.empty() &&
319 other_chrome_path.BaseName() ==
320 base::FilePath(chrome::kBrowserProcessExecutableName));
323 // A helper class to hold onto a socket.
326 ScopedSocket() : fd_(-1) { Reset(); }
327 ~ScopedSocket() { Close(); }
328 int fd() { return fd_; }
331 fd_ = SetupSocketOnly();
342 // Returns a random string for uniquifying profile connections.
343 std::string GenerateCookie() {
344 return base::NumberToString(base::RandUint64());
347 bool CheckCookie(const base::FilePath& path, const base::FilePath& cookie) {
348 return (cookie == ReadLink(path));
351 bool ConnectSocket(ScopedSocket* socket,
352 const base::FilePath& socket_path,
353 const base::FilePath& cookie_path) {
354 base::FilePath socket_target;
355 if (base::ReadSymbolicLink(socket_path, &socket_target)) {
356 // It's a symlink. Read the cookie.
357 base::FilePath cookie = ReadLink(cookie_path);
360 base::FilePath remote_cookie = socket_target.DirName().
361 Append(chrome::kSingletonCookieFilename);
362 // Verify the cookie before connecting.
363 if (!CheckCookie(remote_cookie, cookie))
365 // Now we know the directory was (at that point) created by the profile
366 // owner. Try to connect.
368 if (!SetupSockAddr(socket_target.value(), &addr)) {
369 // If a sockaddr couldn't be initialized due to too long of a socket
370 // path, we can be sure there isn't already a Chrome running with this
371 // socket path, since it would have hit the CHECK() on the path length.
374 int ret = HANDLE_EINTR(connect(socket->fd(),
375 reinterpret_cast<sockaddr*>(&addr),
379 // Check the cookie again. We only link in /tmp, which is sticky, so, if the
380 // directory is still correct, it must have been correct in-between when we
381 // connected. POSIX, sadly, lacks a connectat().
382 if (!CheckCookie(remote_cookie, cookie)) {
388 } else if (errno == EINVAL) {
389 // It exists, but is not a symlink (or some other error we detect
390 // later). Just connect to it directly; this is an older version of Chrome.
392 if (!SetupSockAddr(socket_path.value(), &addr)) {
393 // If a sockaddr couldn't be initialized due to too long of a socket
394 // path, we can be sure there isn't already a Chrome running with this
395 // socket path, since it would have hit the CHECK() on the path length.
398 int ret = HANDLE_EINTR(connect(socket->fd(),
399 reinterpret_cast<sockaddr*>(&addr),
403 // File is missing, or other error.
405 PLOG(ERROR) << "readlink failed";
411 bool ReplaceOldSingletonLock(const base::FilePath& symlink_content,
412 const base::FilePath& lock_path) {
413 // Try taking an flock(2) on the file. Failure means the lock is taken so we
415 base::ScopedFD lock_fd(HANDLE_EINTR(
416 open(lock_path.value().c_str(), O_RDWR | O_CREAT | O_SYMLINK, 0644)));
417 if (!lock_fd.is_valid()) {
418 PLOG(ERROR) << "Could not open singleton lock";
422 int rc = HANDLE_EINTR(flock(lock_fd.get(), LOCK_EX | LOCK_NB));
424 if (errno == EWOULDBLOCK) {
425 LOG(ERROR) << "Singleton lock held by old process.";
427 PLOG(ERROR) << "Error locking singleton lock";
432 // Successfully taking the lock means we can replace it with the a new symlink
433 // lock. We never flock() the lock file from now on. I.e. we assume that an
434 // old version of Chrome will not run with the same user data dir after this
436 if (!base::DeleteFile(lock_path)) {
437 PLOG(ERROR) << "Could not delete old singleton lock.";
441 return SymlinkPath(symlink_content, lock_path);
443 #endif // defined(OS_MAC)
445 void SendRemoteProcessInteractionResultHistogram(
446 ProcessSingleton::RemoteProcessInteractionResult result) {
447 UMA_HISTOGRAM_ENUMERATION(
448 "Chrome.ProcessSingleton.RemoteProcessInteractionResult", result,
449 ProcessSingleton::REMOTE_PROCESS_INTERACTION_RESULT_COUNT);
452 void SendRemoteHungProcessTerminateReasonHistogram(
453 ProcessSingleton::RemoteHungProcessTerminateReason reason) {
454 UMA_HISTOGRAM_ENUMERATION(
455 "Chrome.ProcessSingleton.RemoteHungProcessTerminateReason", reason,
456 ProcessSingleton::REMOTE_HUNG_PROCESS_TERMINATE_REASON_COUNT);
461 ///////////////////////////////////////////////////////////////////////////////
462 // ProcessSingleton::LinuxWatcher
463 // A helper class for a Linux specific implementation of the process singleton.
464 // This class sets up a listener on the singleton socket and handles parsing
465 // messages that come in on the singleton socket.
466 class ProcessSingleton::LinuxWatcher
467 : public base::RefCountedThreadSafe<ProcessSingleton::LinuxWatcher,
468 BrowserThread::DeleteOnIOThread> {
470 // A helper class to read message from an established socket.
473 SocketReader(ProcessSingleton::LinuxWatcher* parent,
474 scoped_refptr<base::SingleThreadTaskRunner> ui_task_runner,
477 ui_task_runner_(ui_task_runner),
480 DCHECK_CURRENTLY_ON(BrowserThread::IO);
482 fd_watch_controller_ = base::FileDescriptorWatcher::WatchReadable(
483 fd, base::BindRepeating(&SocketReader::OnSocketCanReadWithoutBlocking,
484 base::Unretained(this)));
485 // If we haven't completed in a reasonable amount of time, give up.
486 timer_.Start(FROM_HERE, base::TimeDelta::FromSeconds(kTimeoutInSeconds),
487 this, &SocketReader::CleanupAndDeleteSelf);
490 ~SocketReader() { CloseSocket(fd_); }
492 // Finish handling the incoming message by optionally sending back an ACK
493 // message and removing this SocketReader.
494 void FinishWithACK(const char *message, size_t length);
497 void OnSocketCanReadWithoutBlocking();
499 void CleanupAndDeleteSelf() {
500 DCHECK_CURRENTLY_ON(BrowserThread::IO);
502 parent_->RemoveSocketReader(this);
503 // We're deleted beyond this point.
506 // Controls watching |fd_|.
507 std::unique_ptr<base::FileDescriptorWatcher::Controller>
508 fd_watch_controller_;
510 // The ProcessSingleton::LinuxWatcher that owns us.
511 ProcessSingleton::LinuxWatcher* const parent_;
513 // A reference to the UI task runner.
514 scoped_refptr<base::SingleThreadTaskRunner> ui_task_runner_;
516 // The file descriptor we're reading.
519 // Store the message in this buffer.
520 char buf_[kMaxMessageLength];
522 // Tracks the number of bytes we've read in case we're getting partial
526 base::OneShotTimer timer_;
528 DISALLOW_COPY_AND_ASSIGN(SocketReader);
531 // We expect to only be constructed on the UI thread.
532 explicit LinuxWatcher(ProcessSingleton* parent)
533 : ui_task_runner_(base::ThreadTaskRunnerHandle::Get()), parent_(parent) {}
535 // Start listening for connections on the socket. This method should be
536 // called from the IO thread.
537 void StartListening(int socket);
539 // This method determines if we should use the same process and if we should,
540 // opens a new browser tab. This runs on the UI thread.
541 // |reader| is for sending back ACK message.
542 void HandleMessage(const std::string& current_dir,
543 const std::vector<std::string>& argv,
544 SocketReader* reader);
547 friend struct BrowserThread::DeleteOnThread<BrowserThread::IO>;
548 friend class base::DeleteHelper<ProcessSingleton::LinuxWatcher>;
551 DCHECK_CURRENTLY_ON(BrowserThread::IO);
554 void OnSocketCanReadWithoutBlocking(int socket);
556 // Removes and deletes the SocketReader.
557 void RemoveSocketReader(SocketReader* reader);
559 std::unique_ptr<base::FileDescriptorWatcher::Controller> socket_watcher_;
561 // A reference to the UI message loop (i.e., the message loop we were
563 scoped_refptr<base::SingleThreadTaskRunner> ui_task_runner_;
565 // The ProcessSingleton that owns us.
566 ProcessSingleton* const parent_;
568 std::set<std::unique_ptr<SocketReader>, base::UniquePtrComparator> readers_;
570 DISALLOW_COPY_AND_ASSIGN(LinuxWatcher);
573 void ProcessSingleton::LinuxWatcher::OnSocketCanReadWithoutBlocking(
575 DCHECK_CURRENTLY_ON(BrowserThread::IO);
576 // Accepting incoming client.
578 socklen_t from_len = sizeof(from);
579 int connection_socket = HANDLE_EINTR(
580 accept(socket, reinterpret_cast<sockaddr*>(&from), &from_len));
581 if (-1 == connection_socket) {
582 PLOG(ERROR) << "accept() failed";
585 DCHECK(base::SetNonBlocking(connection_socket))
586 << "Failed to make non-blocking socket.";
588 std::make_unique<SocketReader>(this, ui_task_runner_, connection_socket));
591 void ProcessSingleton::LinuxWatcher::StartListening(int socket) {
592 DCHECK_CURRENTLY_ON(BrowserThread::IO);
593 // Watch for client connections on this socket.
594 socket_watcher_ = base::FileDescriptorWatcher::WatchReadable(
595 socket, base::BindRepeating(&LinuxWatcher::OnSocketCanReadWithoutBlocking,
596 base::Unretained(this), socket));
599 void ProcessSingleton::LinuxWatcher::HandleMessage(
600 const std::string& current_dir, const std::vector<std::string>& argv,
601 SocketReader* reader) {
602 DCHECK(ui_task_runner_->BelongsToCurrentThread());
605 if (parent_->notification_callback_.Run(base::CommandLine(argv),
606 base::FilePath(current_dir))) {
607 // Send back "ACK" message to prevent the client process from starting up.
608 reader->FinishWithACK(kACKToken, base::size(kACKToken) - 1);
610 LOG(WARNING) << "Not handling interprocess notification as browser"
612 // Send back "SHUTDOWN" message, so that the client process can start up
613 // without killing this process.
614 reader->FinishWithACK(kShutdownToken, base::size(kShutdownToken) - 1);
619 void ProcessSingleton::LinuxWatcher::RemoveSocketReader(SocketReader* reader) {
620 DCHECK_CURRENTLY_ON(BrowserThread::IO);
622 auto it = readers_.find(reader);
626 ///////////////////////////////////////////////////////////////////////////////
627 // ProcessSingleton::LinuxWatcher::SocketReader
630 void ProcessSingleton::LinuxWatcher::SocketReader::
631 OnSocketCanReadWithoutBlocking() {
632 DCHECK_CURRENTLY_ON(BrowserThread::IO);
633 while (bytes_read_ < sizeof(buf_)) {
635 HANDLE_EINTR(read(fd_, buf_ + bytes_read_, sizeof(buf_) - bytes_read_));
637 if (errno != EAGAIN && errno != EWOULDBLOCK) {
638 PLOG(ERROR) << "read() failed";
642 // It would block, so we just return and continue to watch for the next
643 // opportunity to read.
647 // No more data to read. It's time to process the message.
654 // Validate the message. The shortest message is kStartToken\0x\0x
655 const size_t kMinMessageLength = base::size(kStartToken) + 4;
656 if (bytes_read_ < kMinMessageLength) {
657 buf_[bytes_read_] = 0;
658 LOG(ERROR) << "Invalid socket message (wrong length):" << buf_;
659 CleanupAndDeleteSelf();
663 std::string str(buf_, bytes_read_);
664 std::vector<std::string> tokens = base::SplitString(
665 str, std::string(1, kTokenDelimiter),
666 base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
668 if (tokens.size() < 3 || tokens[0] != kStartToken) {
669 LOG(ERROR) << "Wrong message format: " << str;
670 CleanupAndDeleteSelf();
674 // Stop the expiration timer to prevent this SocketReader object from being
675 // terminated unexpectly.
678 std::string current_dir = tokens[1];
679 // Remove the first two tokens. The remaining tokens should be the command
681 tokens.erase(tokens.begin());
682 tokens.erase(tokens.begin());
684 // Return to the UI thread to handle opening a new browser tab.
685 ui_task_runner_->PostTask(
686 FROM_HERE, base::BindOnce(&ProcessSingleton::LinuxWatcher::HandleMessage,
687 parent_, current_dir, tokens, this));
688 fd_watch_controller_.reset();
690 // LinuxWatcher::HandleMessage() is in charge of destroying this SocketReader
691 // object by invoking SocketReader::FinishWithACK().
694 void ProcessSingleton::LinuxWatcher::SocketReader::FinishWithACK(
695 const char *message, size_t length) {
696 if (message && length) {
697 // Not necessary to care about the return value.
698 WriteToSocket(fd_, message, length);
701 if (shutdown(fd_, SHUT_WR) < 0)
702 PLOG(ERROR) << "shutdown() failed";
704 content::GetIOThreadTaskRunner({})->PostTask(
706 base::BindOnce(&ProcessSingleton::LinuxWatcher::RemoveSocketReader,
708 // We will be deleted once the posted RemoveSocketReader task runs.
711 ///////////////////////////////////////////////////////////////////////////////
714 ProcessSingleton::ProcessSingleton(
715 const base::FilePath& user_data_dir,
716 const NotificationCallback& notification_callback)
717 : notification_callback_(notification_callback),
718 current_pid_(base::GetCurrentProcId()),
719 watcher_(new LinuxWatcher(this)) {
720 socket_path_ = user_data_dir.Append(chrome::kSingletonSocketFilename);
721 lock_path_ = user_data_dir.Append(chrome::kSingletonLockFilename);
722 cookie_path_ = user_data_dir.Append(chrome::kSingletonCookieFilename);
724 kill_callback_ = base::BindRepeating(&ProcessSingleton::KillProcess,
725 base::Unretained(this));
728 ProcessSingleton::~ProcessSingleton() {
729 DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
732 ProcessSingleton::NotifyResult ProcessSingleton::NotifyOtherProcess() {
733 return NotifyOtherProcessWithTimeout(
734 *base::CommandLine::ForCurrentProcess(), kRetryAttempts,
735 base::TimeDelta::FromSeconds(kTimeoutInSeconds), true);
738 ProcessSingleton::NotifyResult ProcessSingleton::NotifyOtherProcessWithTimeout(
739 const base::CommandLine& cmd_line,
741 const base::TimeDelta& timeout,
742 bool kill_unresponsive) {
743 DCHECK_GE(retry_attempts, 0);
744 DCHECK_GE(timeout.InMicroseconds(), 0);
746 base::TimeDelta sleep_interval = timeout / retry_attempts;
750 for (int retries = 0; retries <= retry_attempts; ++retries) {
751 // Try to connect to the socket.
752 if (ConnectSocket(&socket, socket_path_, cookie_path_)) {
754 // On Mac, we want the open process' pid in case there are
755 // Apple Events to forward. See crbug.com/777863.
756 std::string hostname;
757 ParseProcessSingletonLock(lock_path_, &hostname, &pid);
762 // If we're in a race with another process, they may be in Create() and have
763 // created the lock but not attached to the socket. So we check if the
764 // process with the pid from the lockfile is currently running and is a
765 // chrome browser. If so, we loop and try again for |timeout|.
767 std::string hostname;
768 if (!ParseProcessSingletonLock(lock_path_, &hostname, &pid)) {
769 // No lockfile exists.
773 if (hostname.empty()) {
775 UnlinkPath(lock_path_);
776 SendRemoteProcessInteractionResultHistogram(INVALID_LOCK_FILE);
780 if (hostname != net::GetHostName() && !IsChromeProcess(pid)) {
781 // Locked by process on another host. If the user selected to unlock
782 // the profile, try to continue; otherwise quit.
783 if (DisplayProfileInUseError(lock_path_, hostname, pid)) {
784 UnlinkPath(lock_path_);
785 SendRemoteProcessInteractionResultHistogram(PROFILE_UNLOCKED);
788 return PROFILE_IN_USE;
791 if (!IsChromeProcess(pid)) {
792 // Orphaned lockfile (no process with pid, or non-chrome process.)
793 UnlinkPath(lock_path_);
794 SendRemoteProcessInteractionResultHistogram(ORPHANED_LOCK_FILE);
798 if (IsSameChromeInstance(pid)) {
799 // Orphaned lockfile (pid is part of same chrome instance we are, even
800 // though we haven't tried to create a lockfile yet).
801 UnlinkPath(lock_path_);
802 SendRemoteProcessInteractionResultHistogram(SAME_BROWSER_INSTANCE);
806 if (retries == retry_attempts) {
807 // Retries failed. Kill the unresponsive chrome process and continue.
808 if (!kill_unresponsive || !KillProcessByLockPath(false))
809 return PROFILE_IN_USE;
810 SendRemoteHungProcessTerminateReasonHistogram(NOTIFY_ATTEMPTS_EXCEEDED);
814 base::PlatformThread::Sleep(sleep_interval);
818 if (pid > 0 && WaitForAndForwardOpenURLEvent(pid)) {
819 return PROCESS_NOTIFIED;
822 timeval socket_timeout = TimeDeltaToTimeVal(timeout);
823 setsockopt(socket.fd(),
827 sizeof(socket_timeout));
829 // Found another process, prepare our command line
830 // format is "START\0<current dir>\0<argv[0]>\0...\0<argv[n]>".
831 std::string to_send(kStartToken);
832 to_send.push_back(kTokenDelimiter);
834 base::FilePath current_dir;
835 if (!base::PathService::Get(base::DIR_CURRENT, ¤t_dir))
837 to_send.append(current_dir.value());
839 const std::vector<std::string>& argv = cmd_line.argv();
840 for (auto it = argv.begin(); it != argv.end(); ++it) {
841 to_send.push_back(kTokenDelimiter);
846 if (!WriteToSocket(socket.fd(), to_send.data(), to_send.length())) {
847 // Try to kill the other process, because it might have been dead.
848 if (!kill_unresponsive || !KillProcessByLockPath(true))
849 return PROFILE_IN_USE;
850 SendRemoteHungProcessTerminateReasonHistogram(SOCKET_WRITE_FAILED);
854 if (shutdown(socket.fd(), SHUT_WR) < 0)
855 PLOG(ERROR) << "shutdown() failed";
857 // Read ACK message from the other process. It might be blocked for a certain
858 // timeout, to make sure the other process has enough time to return ACK.
859 char buf[kMaxACKMessageLength + 1];
860 ssize_t len = ReadFromSocket(socket.fd(), buf, kMaxACKMessageLength, timeout);
862 // Failed to read ACK, the other process might have been frozen.
864 if (!kill_unresponsive || !KillProcessByLockPath(true))
865 return PROFILE_IN_USE;
866 SendRemoteHungProcessTerminateReasonHistogram(SOCKET_READ_FAILED);
871 if (strncmp(buf, kShutdownToken, base::size(kShutdownToken) - 1) == 0) {
872 // The other process is shutting down, it's safe to start a new process.
873 SendRemoteProcessInteractionResultHistogram(REMOTE_PROCESS_SHUTTING_DOWN);
875 } else if (strncmp(buf, kACKToken, base::size(kACKToken) - 1) == 0) {
876 #if defined(TOOLKIT_VIEWS) && \
877 (defined(OS_LINUX) || BUILDFLAG(IS_CHROMEOS_LACROS))
878 // Likely NULL in unit tests.
879 views::LinuxUI* linux_ui = views::LinuxUI::instance();
881 linux_ui->NotifyWindowManagerStartupComplete();
884 // Assume the other process is handling the request.
885 return PROCESS_NOTIFIED;
888 NOTREACHED() << "The other process returned unknown message: " << buf;
889 return PROCESS_NOTIFIED;
892 ProcessSingleton::NotifyResult ProcessSingleton::NotifyOtherProcessOrCreate() {
893 return NotifyOtherProcessWithTimeoutOrCreate(
894 *base::CommandLine::ForCurrentProcess(), kRetryAttempts,
895 base::TimeDelta::FromSeconds(kTimeoutInSeconds));
898 ProcessSingleton::NotifyResult
899 ProcessSingleton::NotifyOtherProcessWithTimeoutOrCreate(
900 const base::CommandLine& command_line,
902 const base::TimeDelta& timeout) {
903 const base::TimeTicks begin_ticks = base::TimeTicks::Now();
904 NotifyResult result = NotifyOtherProcessWithTimeout(
905 command_line, retry_attempts, timeout, true);
906 if (result != PROCESS_NONE) {
907 if (result == PROCESS_NOTIFIED) {
908 UMA_HISTOGRAM_MEDIUM_TIMES("Chrome.ProcessSingleton.TimeToNotify",
909 base::TimeTicks::Now() - begin_ticks);
911 UMA_HISTOGRAM_MEDIUM_TIMES("Chrome.ProcessSingleton.TimeToFailure",
912 base::TimeTicks::Now() - begin_ticks);
918 UMA_HISTOGRAM_MEDIUM_TIMES("Chrome.ProcessSingleton.TimeToCreate",
919 base::TimeTicks::Now() - begin_ticks);
923 // If the Create() failed, try again to notify. (It could be that another
924 // instance was starting at the same time and managed to grab the lock before
926 // This time, we don't want to kill anything if we aren't successful, since we
927 // aren't going to try to take over the lock ourselves.
928 result = NotifyOtherProcessWithTimeout(
929 command_line, retry_attempts, timeout, false);
931 if (result == PROCESS_NOTIFIED) {
932 UMA_HISTOGRAM_MEDIUM_TIMES("Chrome.ProcessSingleton.TimeToNotify",
933 base::TimeTicks::Now() - begin_ticks);
935 UMA_HISTOGRAM_MEDIUM_TIMES("Chrome.ProcessSingleton.TimeToFailure",
936 base::TimeTicks::Now() - begin_ticks);
939 if (result != PROCESS_NONE)
945 void ProcessSingleton::OverrideCurrentPidForTesting(base::ProcessId pid) {
949 void ProcessSingleton::OverrideKillCallbackForTesting(
950 const base::RepeatingCallback<void(int)>& callback) {
951 kill_callback_ = callback;
955 void ProcessSingleton::DisablePromptForTesting() {
956 g_disable_prompt = true;
960 void ProcessSingleton::SkipIsChromeProcessCheckForTesting(bool skip) {
961 g_skip_is_chrome_process_check = skip;
965 void ProcessSingleton::SetUserOptedUnlockInUseProfileForTesting(
967 g_user_opted_unlock_in_use_profile = set_unlock;
970 bool ProcessSingleton::Create() {
974 // The symlink lock is pointed to the hostname and process id, so other
975 // processes can find it out.
976 base::FilePath symlink_content(
977 base::StringPrintf("%s%c%u", net::GetHostName().c_str(),
978 kProcessSingletonLockDelimiter, current_pid_));
980 // Create symbol link before binding the socket, to ensure only one instance
981 // can have the socket open.
982 if (!SymlinkPath(symlink_content, lock_path_)) {
983 // TODO(jackhou): Remove this case once this code is stable on Mac.
984 // http://crbug.com/367612
986 // On Mac, an existing non-symlink lock file means the lock could be held by
987 // the old process singleton code. If we can successfully replace the lock,
988 // continue as normal.
989 if (base::IsLink(lock_path_) ||
990 !ReplaceOldSingletonLock(symlink_content, lock_path_)) {
994 // If we failed to create the lock, most likely another instance won the
1000 // Create the socket file somewhere in /tmp which is usually mounted as a
1001 // normal filesystem. Some network filesystems (notably AFS) are screwy and
1002 // do not support Unix domain sockets.
1003 if (!socket_dir_.CreateUniqueTempDir()) {
1004 LOG(ERROR) << "Failed to create socket directory.";
1008 // Check that the directory was created with the correct permissions.
1010 CHECK(base::GetPosixFilePermissions(socket_dir_.GetPath(), &dir_mode) &&
1011 dir_mode == base::FILE_PERMISSION_USER_MASK)
1012 << "Temp directory mode is not 700: " << std::oct << dir_mode;
1014 // Try to create the socket before creating the symlink, as SetupSocket may
1015 // fail on a CHECK if the |socket_target_path| is too long, and this avoids
1016 // leaving a dangling symlink.
1017 base::FilePath socket_target_path =
1018 socket_dir_.GetPath().Append(chrome::kSingletonSocketFilename);
1019 SetupSocket(socket_target_path.value(), &sock, &addr);
1021 // Setup the socket symlink and the two cookies.
1022 base::FilePath cookie(GenerateCookie());
1023 base::FilePath remote_cookie_path =
1024 socket_dir_.GetPath().Append(chrome::kSingletonCookieFilename);
1025 UnlinkPath(socket_path_);
1026 UnlinkPath(cookie_path_);
1027 if (!SymlinkPath(socket_target_path, socket_path_) ||
1028 !SymlinkPath(cookie, cookie_path_) ||
1029 !SymlinkPath(cookie, remote_cookie_path)) {
1030 // We've already locked things, so we can't have lost the startup race,
1031 // but something doesn't like us.
1032 LOG(ERROR) << "Failed to create symlinks.";
1033 if (!socket_dir_.Delete())
1034 LOG(ERROR) << "Encountered a problem when deleting socket directory.";
1038 if (bind(sock, reinterpret_cast<sockaddr*>(&addr), sizeof(addr)) < 0) {
1039 PLOG(ERROR) << "Failed to bind() " << socket_target_path.value();
1044 if (listen(sock, 5) < 0)
1045 NOTREACHED() << "listen failed: " << base::safe_strerror(errno);
1047 DCHECK(BrowserThread::IsThreadInitialized(BrowserThread::IO));
1048 content::GetIOThreadTaskRunner({})->PostTask(
1049 FROM_HERE, base::BindOnce(&ProcessSingleton::LinuxWatcher::StartListening,
1055 void ProcessSingleton::Cleanup() {
1056 UnlinkPath(socket_path_);
1057 UnlinkPath(cookie_path_);
1058 UnlinkPath(lock_path_);
1061 bool ProcessSingleton::IsSameChromeInstance(pid_t pid) {
1062 pid_t cur_pid = current_pid_;
1063 while (pid != cur_pid) {
1064 pid = base::GetParentProcessId(pid);
1067 if (!IsChromeProcess(pid))
1073 bool ProcessSingleton::KillProcessByLockPath(bool is_connected_to_socket) {
1074 std::string hostname;
1076 ParseProcessSingletonLock(lock_path_, &hostname, &pid);
1078 if (!hostname.empty() && hostname != net::GetHostName() &&
1079 !is_connected_to_socket) {
1080 bool res = DisplayProfileInUseError(lock_path_, hostname, pid);
1082 UnlinkPath(lock_path_);
1083 SendRemoteProcessInteractionResultHistogram(PROFILE_UNLOCKED_BEFORE_KILL);
1087 UnlinkPath(lock_path_);
1089 if (IsSameChromeInstance(pid)) {
1090 SendRemoteProcessInteractionResultHistogram(
1091 SAME_BROWSER_INSTANCE_BEFORE_KILL);
1096 kill_callback_.Run(pid);
1100 SendRemoteProcessInteractionResultHistogram(FAILED_TO_EXTRACT_PID);
1102 LOG(ERROR) << "Failed to extract pid from path: " << lock_path_.value();
1106 void ProcessSingleton::KillProcess(int pid) {
1107 // TODO(james.su@gmail.com): Is SIGKILL ok?
1108 int rv = kill(static_cast<base::ProcessHandle>(pid), SIGKILL);
1109 // ESRCH = No Such Process (can happen if the other process is already in
1110 // progress of shutting down and finishes before we try to kill it).
1111 DCHECK(rv == 0 || errno == ESRCH) << "Error killing process: "
1112 << base::safe_strerror(errno);
1114 int error_code = (rv == 0) ? 0 : errno;
1115 base::UmaHistogramSparse(
1116 "Chrome.ProcessSingleton.TerminateProcessErrorCode.Posix", error_code);
1118 RemoteProcessInteractionResult action = TERMINATE_SUCCEEDED;
1120 switch (error_code) {
1122 action = REMOTE_PROCESS_NOT_FOUND;
1125 action = TERMINATE_NOT_ENOUGH_PERMISSIONS;
1128 action = TERMINATE_FAILED;
1132 SendRemoteProcessInteractionResultHistogram(action);