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>
55 #include "base/base_paths.h"
56 #include "base/basictypes.h"
57 #include "base/bind.h"
58 #include "base/command_line.h"
59 #include "base/files/file_path.h"
60 #include "base/files/file_util.h"
61 #include "base/location.h"
62 #include "base/logging.h"
63 #include "base/message_loop/message_loop.h"
64 #include "base/path_service.h"
65 #include "base/posix/eintr_wrapper.h"
66 #include "base/posix/safe_strerror.h"
67 #include "base/rand_util.h"
68 #include "base/sequenced_task_runner_helpers.h"
69 #include "base/single_thread_task_runner.h"
70 #include "base/stl_util.h"
71 #include "base/strings/string_number_conversions.h"
72 #include "base/strings/string_split.h"
73 #include "base/strings/string_util.h"
74 #include "base/strings/stringprintf.h"
75 #include "base/strings/sys_string_conversions.h"
76 #include "base/strings/utf_string_conversions.h"
77 #include "base/threading/platform_thread.h"
78 #include "base/time/time.h"
79 #include "base/timer/timer.h"
80 #include "chrome/common/chrome_constants.h"
81 #include "chrome/grit/chromium_strings.h"
82 #include "chrome/grit/generated_resources.h"
83 #include "content/public/browser/browser_thread.h"
84 #include "net/base/net_util.h"
85 #include "ui/base/l10n/l10n_util.h"
88 #include "chrome/browser/ui/process_singleton_dialog_linux.h"
91 #if defined(TOOLKIT_VIEWS) && defined(OS_LINUX) && !defined(OS_CHROMEOS)
92 #include "ui/views/linux_ui/linux_ui.h"
95 using content::BrowserThread
;
99 // Timeout for the current browser process to respond. 20 seconds should be
101 const int kTimeoutInSeconds
= 20;
102 // Number of retries to notify the browser. 20 retries over 20 seconds = 1 try
104 const int kRetryAttempts
= 20;
105 static bool g_disable_prompt
;
106 const char kStartToken
[] = "START";
107 const char kACKToken
[] = "ACK";
108 const char kShutdownToken
[] = "SHUTDOWN";
109 const char kTokenDelimiter
= '\0';
110 const int kMaxMessageLength
= 32 * 1024;
111 const int kMaxACKMessageLength
= arraysize(kShutdownToken
) - 1;
113 const char kLockDelimiter
= '-';
115 // Set the close-on-exec bit on a file descriptor.
116 // Returns 0 on success, -1 on failure.
117 int SetCloseOnExec(int fd
) {
118 int flags
= fcntl(fd
, F_GETFD
, 0);
121 if (flags
& FD_CLOEXEC
)
123 return fcntl(fd
, F_SETFD
, flags
| FD_CLOEXEC
);
126 // Close a socket and check return value.
127 void CloseSocket(int fd
) {
128 int rv
= IGNORE_EINTR(close(fd
));
129 DCHECK_EQ(0, rv
) << "Error closing socket: " << base::safe_strerror(errno
);
132 // Write a message to a socket fd.
133 bool WriteToSocket(int fd
, const char *message
, size_t length
) {
136 size_t bytes_written
= 0;
138 ssize_t rv
= HANDLE_EINTR(
139 write(fd
, message
+ bytes_written
, length
- bytes_written
));
141 if (errno
== EAGAIN
|| errno
== EWOULDBLOCK
) {
142 // The socket shouldn't block, we're sending so little data. Just give
143 // up here, since NotifyOtherProcess() doesn't have an asynchronous api.
144 LOG(ERROR
) << "ProcessSingleton would block on write(), so it gave up.";
147 PLOG(ERROR
) << "write() failed";
151 } while (bytes_written
< length
);
156 struct timeval
TimeDeltaToTimeVal(const base::TimeDelta
& delta
) {
157 struct timeval result
;
158 result
.tv_sec
= delta
.InSeconds();
159 result
.tv_usec
= delta
.InMicroseconds() % base::Time::kMicrosecondsPerSecond
;
163 // Wait a socket for read for a certain timeout.
164 // Returns -1 if error occurred, 0 if timeout reached, > 0 if the socket is
166 int WaitSocketForRead(int fd
, const base::TimeDelta
& timeout
) {
168 struct timeval tv
= TimeDeltaToTimeVal(timeout
);
171 FD_SET(fd
, &read_fds
);
173 return HANDLE_EINTR(select(fd
+ 1, &read_fds
, NULL
, NULL
, &tv
));
176 // Read a message from a socket fd, with an optional timeout.
177 // If |timeout| <= 0 then read immediately.
178 // Return number of bytes actually read, or -1 on error.
179 ssize_t
ReadFromSocket(int fd
,
182 const base::TimeDelta
& timeout
) {
183 if (timeout
> base::TimeDelta()) {
184 int rv
= WaitSocketForRead(fd
, timeout
);
189 size_t bytes_read
= 0;
191 ssize_t rv
= HANDLE_EINTR(read(fd
, buf
+ bytes_read
, bufsize
- bytes_read
));
193 if (errno
!= EAGAIN
&& errno
!= EWOULDBLOCK
) {
194 PLOG(ERROR
) << "read() failed";
197 // It would block, so we just return what has been read.
201 // No more data to read.
206 } while (bytes_read
< bufsize
);
211 // Set up a sockaddr appropriate for messaging.
212 void SetupSockAddr(const std::string
& path
, struct sockaddr_un
* addr
) {
213 addr
->sun_family
= AF_UNIX
;
214 CHECK(path
.length() < arraysize(addr
->sun_path
))
215 << "Socket path too long: " << path
;
216 base::strlcpy(addr
->sun_path
, path
.c_str(), arraysize(addr
->sun_path
));
219 // Set up a socket appropriate for messaging.
220 int SetupSocketOnly() {
221 int sock
= socket(PF_UNIX
, SOCK_STREAM
, 0);
222 PCHECK(sock
>= 0) << "socket() failed";
224 int rv
= net::SetNonBlocking(sock
);
225 DCHECK_EQ(0, rv
) << "Failed to make non-blocking socket.";
226 rv
= SetCloseOnExec(sock
);
227 DCHECK_EQ(0, rv
) << "Failed to set CLOEXEC on socket.";
232 // Set up a socket and sockaddr appropriate for messaging.
233 void SetupSocket(const std::string
& path
, int* sock
, struct sockaddr_un
* addr
) {
234 *sock
= SetupSocketOnly();
235 SetupSockAddr(path
, addr
);
238 // Read a symbolic link, return empty string if given path is not a symbol link.
239 base::FilePath
ReadLink(const base::FilePath
& path
) {
240 base::FilePath target
;
241 if (!base::ReadSymbolicLink(path
, &target
)) {
242 // The only errno that should occur is ENOENT.
243 if (errno
!= 0 && errno
!= ENOENT
)
244 PLOG(ERROR
) << "readlink(" << path
.value() << ") failed";
249 // Unlink a path. Return true on success.
250 bool UnlinkPath(const base::FilePath
& path
) {
251 int rv
= unlink(path
.value().c_str());
252 if (rv
< 0 && errno
!= ENOENT
)
253 PLOG(ERROR
) << "Failed to unlink " << path
.value();
258 // Create a symlink. Returns true on success.
259 bool SymlinkPath(const base::FilePath
& target
, const base::FilePath
& path
) {
260 if (!base::CreateSymbolicLink(target
, path
)) {
261 // Double check the value in case symlink suceeded but we got an incorrect
262 // failure due to NFS packet loss & retry.
263 int saved_errno
= errno
;
264 if (ReadLink(path
) != target
) {
265 // If we failed to create the lock, most likely another instance won the
268 PLOG(ERROR
) << "Failed to create " << path
.value();
275 // Extract the hostname and pid from the lock symlink.
276 // Returns true if the lock existed.
277 bool ParseLockPath(const base::FilePath
& path
,
278 std::string
* hostname
,
280 std::string real_path
= ReadLink(path
).value();
281 if (real_path
.empty())
284 std::string::size_type pos
= real_path
.rfind(kLockDelimiter
);
286 // If the path is not a symbolic link, or doesn't contain what we expect,
288 if (pos
== std::string::npos
) {
294 *hostname
= real_path
.substr(0, pos
);
296 const std::string
& pid_str
= real_path
.substr(pos
+ 1);
297 if (!base::StringToInt(pid_str
, pid
))
303 // Returns true if the user opted to unlock the profile.
304 bool DisplayProfileInUseError(const base::FilePath
& lock_path
,
305 const std::string
& hostname
,
307 base::string16 error
= l10n_util::GetStringFUTF16(
308 IDS_PROFILE_IN_USE_POSIX
,
309 base::IntToString16(pid
),
310 base::ASCIIToUTF16(hostname
));
313 if (g_disable_prompt
)
316 #if defined(OS_LINUX)
317 base::string16 relaunch_button_text
= l10n_util::GetStringUTF16(
318 IDS_PROFILE_IN_USE_LINUX_RELAUNCH
);
319 return ShowProcessSingletonDialog(error
, relaunch_button_text
);
320 #elif defined(OS_MACOSX)
321 // On Mac, always usurp the lock.
329 bool IsChromeProcess(pid_t pid
) {
330 base::FilePath
other_chrome_path(base::GetProcessExecutablePath(pid
));
331 return (!other_chrome_path
.empty() &&
332 other_chrome_path
.BaseName() ==
333 base::FilePath(chrome::kBrowserProcessExecutableName
));
336 // A helper class to hold onto a socket.
339 ScopedSocket() : fd_(-1) { Reset(); }
340 ~ScopedSocket() { Close(); }
341 int fd() { return fd_
; }
344 fd_
= SetupSocketOnly();
355 // Returns a random string for uniquifying profile connections.
356 std::string
GenerateCookie() {
357 return base::Uint64ToString(base::RandUint64());
360 bool CheckCookie(const base::FilePath
& path
, const base::FilePath
& cookie
) {
361 return (cookie
== ReadLink(path
));
364 bool ConnectSocket(ScopedSocket
* socket
,
365 const base::FilePath
& socket_path
,
366 const base::FilePath
& cookie_path
) {
367 base::FilePath socket_target
;
368 if (base::ReadSymbolicLink(socket_path
, &socket_target
)) {
369 // It's a symlink. Read the cookie.
370 base::FilePath cookie
= ReadLink(cookie_path
);
373 base::FilePath remote_cookie
= socket_target
.DirName().
374 Append(chrome::kSingletonCookieFilename
);
375 // Verify the cookie before connecting.
376 if (!CheckCookie(remote_cookie
, cookie
))
378 // Now we know the directory was (at that point) created by the profile
379 // owner. Try to connect.
381 SetupSockAddr(socket_target
.value(), &addr
);
382 int ret
= HANDLE_EINTR(connect(socket
->fd(),
383 reinterpret_cast<sockaddr
*>(&addr
),
387 // Check the cookie again. We only link in /tmp, which is sticky, so, if the
388 // directory is still correct, it must have been correct in-between when we
389 // connected. POSIX, sadly, lacks a connectat().
390 if (!CheckCookie(remote_cookie
, cookie
)) {
396 } else if (errno
== EINVAL
) {
397 // It exists, but is not a symlink (or some other error we detect
398 // later). Just connect to it directly; this is an older version of Chrome.
400 SetupSockAddr(socket_path
.value(), &addr
);
401 int ret
= HANDLE_EINTR(connect(socket
->fd(),
402 reinterpret_cast<sockaddr
*>(&addr
),
406 // File is missing, or other error.
408 PLOG(ERROR
) << "readlink failed";
413 #if defined(OS_MACOSX)
414 bool ReplaceOldSingletonLock(const base::FilePath
& symlink_content
,
415 const base::FilePath
& lock_path
) {
416 // Try taking an flock(2) on the file. Failure means the lock is taken so we
418 base::ScopedFD
lock_fd(HANDLE_EINTR(
419 open(lock_path
.value().c_str(), O_RDWR
| O_CREAT
| O_SYMLINK
, 0644)));
420 if (!lock_fd
.is_valid()) {
421 PLOG(ERROR
) << "Could not open singleton lock";
425 int rc
= HANDLE_EINTR(flock(lock_fd
.get(), LOCK_EX
| LOCK_NB
));
427 if (errno
== EWOULDBLOCK
) {
428 LOG(ERROR
) << "Singleton lock held by old process.";
430 PLOG(ERROR
) << "Error locking singleton lock";
435 // Successfully taking the lock means we can replace it with the a new symlink
436 // lock. We never flock() the lock file from now on. I.e. we assume that an
437 // old version of Chrome will not run with the same user data dir after this
439 if (!base::DeleteFile(lock_path
, false)) {
440 PLOG(ERROR
) << "Could not delete old singleton lock.";
444 return SymlinkPath(symlink_content
, lock_path
);
446 #endif // defined(OS_MACOSX)
450 ///////////////////////////////////////////////////////////////////////////////
451 // ProcessSingleton::LinuxWatcher
452 // A helper class for a Linux specific implementation of the process singleton.
453 // This class sets up a listener on the singleton socket and handles parsing
454 // messages that come in on the singleton socket.
455 class ProcessSingleton::LinuxWatcher
456 : public base::MessageLoopForIO::Watcher
,
457 public base::MessageLoop::DestructionObserver
,
458 public base::RefCountedThreadSafe
<ProcessSingleton::LinuxWatcher
,
459 BrowserThread::DeleteOnIOThread
> {
461 // A helper class to read message from an established socket.
462 class SocketReader
: public base::MessageLoopForIO::Watcher
{
464 SocketReader(ProcessSingleton::LinuxWatcher
* parent
,
465 base::MessageLoop
* ui_message_loop
,
468 ui_message_loop_(ui_message_loop
),
471 DCHECK_CURRENTLY_ON(BrowserThread::IO
);
473 base::MessageLoopForIO::current()->WatchFileDescriptor(
474 fd
, true, base::MessageLoopForIO::WATCH_READ
, &fd_reader_
, this);
475 // If we haven't completed in a reasonable amount of time, give up.
476 timer_
.Start(FROM_HERE
, base::TimeDelta::FromSeconds(kTimeoutInSeconds
),
477 this, &SocketReader::CleanupAndDeleteSelf
);
480 ~SocketReader() override
{ CloseSocket(fd_
); }
482 // MessageLoopForIO::Watcher impl.
483 void OnFileCanReadWithoutBlocking(int fd
) override
;
484 void OnFileCanWriteWithoutBlocking(int fd
) override
{
485 // SocketReader only watches for accept (read) events.
489 // Finish handling the incoming message by optionally sending back an ACK
490 // message and removing this SocketReader.
491 void FinishWithACK(const char *message
, size_t length
);
494 void CleanupAndDeleteSelf() {
495 DCHECK_CURRENTLY_ON(BrowserThread::IO
);
497 parent_
->RemoveSocketReader(this);
498 // We're deleted beyond this point.
501 base::MessageLoopForIO::FileDescriptorWatcher fd_reader_
;
503 // The ProcessSingleton::LinuxWatcher that owns us.
504 ProcessSingleton::LinuxWatcher
* const parent_
;
506 // A reference to the UI message loop.
507 base::MessageLoop
* const ui_message_loop_
;
509 // The file descriptor we're reading.
512 // Store the message in this buffer.
513 char buf_
[kMaxMessageLength
];
515 // Tracks the number of bytes we've read in case we're getting partial
519 base::OneShotTimer
<SocketReader
> timer_
;
521 DISALLOW_COPY_AND_ASSIGN(SocketReader
);
524 // We expect to only be constructed on the UI thread.
525 explicit LinuxWatcher(ProcessSingleton
* parent
)
526 : ui_message_loop_(base::MessageLoop::current()),
530 // Start listening for connections on the socket. This method should be
531 // called from the IO thread.
532 void StartListening(int socket
);
534 // This method determines if we should use the same process and if we should,
535 // opens a new browser tab. This runs on the UI thread.
536 // |reader| is for sending back ACK message.
537 void HandleMessage(const std::string
& current_dir
,
538 const std::vector
<std::string
>& argv
,
539 SocketReader
* reader
);
541 // MessageLoopForIO::Watcher impl. These run on the IO thread.
542 void OnFileCanReadWithoutBlocking(int fd
) override
;
543 void OnFileCanWriteWithoutBlocking(int fd
) override
{
544 // ProcessSingleton only watches for accept (read) events.
548 // MessageLoop::DestructionObserver
549 void WillDestroyCurrentMessageLoop() override
{
550 fd_watcher_
.StopWatchingFileDescriptor();
554 friend struct BrowserThread::DeleteOnThread
<BrowserThread::IO
>;
555 friend class base::DeleteHelper
<ProcessSingleton::LinuxWatcher
>;
557 ~LinuxWatcher() override
{
558 DCHECK_CURRENTLY_ON(BrowserThread::IO
);
559 STLDeleteElements(&readers_
);
561 base::MessageLoopForIO
* ml
= base::MessageLoopForIO::current();
562 ml
->RemoveDestructionObserver(this);
565 // Removes and deletes the SocketReader.
566 void RemoveSocketReader(SocketReader
* reader
);
568 base::MessageLoopForIO::FileDescriptorWatcher fd_watcher_
;
570 // A reference to the UI message loop (i.e., the message loop we were
572 base::MessageLoop
* ui_message_loop_
;
574 // The ProcessSingleton that owns us.
575 ProcessSingleton
* const parent_
;
577 std::set
<SocketReader
*> readers_
;
579 DISALLOW_COPY_AND_ASSIGN(LinuxWatcher
);
582 void ProcessSingleton::LinuxWatcher::OnFileCanReadWithoutBlocking(int fd
) {
583 DCHECK_CURRENTLY_ON(BrowserThread::IO
);
584 // Accepting incoming client.
586 socklen_t from_len
= sizeof(from
);
587 int connection_socket
= HANDLE_EINTR(accept(
588 fd
, reinterpret_cast<sockaddr
*>(&from
), &from_len
));
589 if (-1 == connection_socket
) {
590 PLOG(ERROR
) << "accept() failed";
593 int rv
= net::SetNonBlocking(connection_socket
);
594 DCHECK_EQ(0, rv
) << "Failed to make non-blocking socket.";
595 SocketReader
* reader
= new SocketReader(this,
598 readers_
.insert(reader
);
601 void ProcessSingleton::LinuxWatcher::StartListening(int socket
) {
602 DCHECK_CURRENTLY_ON(BrowserThread::IO
);
603 // Watch for client connections on this socket.
604 base::MessageLoopForIO
* ml
= base::MessageLoopForIO::current();
605 ml
->AddDestructionObserver(this);
606 ml
->WatchFileDescriptor(socket
, true, base::MessageLoopForIO::WATCH_READ
,
610 void ProcessSingleton::LinuxWatcher::HandleMessage(
611 const std::string
& current_dir
, const std::vector
<std::string
>& argv
,
612 SocketReader
* reader
) {
613 DCHECK(ui_message_loop_
== base::MessageLoop::current());
616 if (parent_
->notification_callback_
.Run(base::CommandLine(argv
),
617 base::FilePath(current_dir
))) {
618 // Send back "ACK" message to prevent the client process from starting up.
619 reader
->FinishWithACK(kACKToken
, arraysize(kACKToken
) - 1);
621 LOG(WARNING
) << "Not handling interprocess notification as browser"
623 // Send back "SHUTDOWN" message, so that the client process can start up
624 // without killing this process.
625 reader
->FinishWithACK(kShutdownToken
, arraysize(kShutdownToken
) - 1);
630 void ProcessSingleton::LinuxWatcher::RemoveSocketReader(SocketReader
* reader
) {
631 DCHECK_CURRENTLY_ON(BrowserThread::IO
);
633 readers_
.erase(reader
);
637 ///////////////////////////////////////////////////////////////////////////////
638 // ProcessSingleton::LinuxWatcher::SocketReader
641 void ProcessSingleton::LinuxWatcher::SocketReader::OnFileCanReadWithoutBlocking(
643 DCHECK_CURRENTLY_ON(BrowserThread::IO
);
645 while (bytes_read_
< sizeof(buf_
)) {
646 ssize_t rv
= HANDLE_EINTR(
647 read(fd
, buf_
+ bytes_read_
, sizeof(buf_
) - bytes_read_
));
649 if (errno
!= EAGAIN
&& errno
!= EWOULDBLOCK
) {
650 PLOG(ERROR
) << "read() failed";
654 // It would block, so we just return and continue to watch for the next
655 // opportunity to read.
659 // No more data to read. It's time to process the message.
666 // Validate the message. The shortest message is kStartToken\0x\0x
667 const size_t kMinMessageLength
= arraysize(kStartToken
) + 4;
668 if (bytes_read_
< kMinMessageLength
) {
669 buf_
[bytes_read_
] = 0;
670 LOG(ERROR
) << "Invalid socket message (wrong length):" << buf_
;
671 CleanupAndDeleteSelf();
675 std::string
str(buf_
, bytes_read_
);
676 std::vector
<std::string
> tokens
= base::SplitString(
677 str
, std::string(1, kTokenDelimiter
),
678 base::TRIM_WHITESPACE
, base::SPLIT_WANT_ALL
);
680 if (tokens
.size() < 3 || tokens
[0] != kStartToken
) {
681 LOG(ERROR
) << "Wrong message format: " << str
;
682 CleanupAndDeleteSelf();
686 // Stop the expiration timer to prevent this SocketReader object from being
687 // terminated unexpectly.
690 std::string current_dir
= tokens
[1];
691 // Remove the first two tokens. The remaining tokens should be the command
693 tokens
.erase(tokens
.begin());
694 tokens
.erase(tokens
.begin());
696 // Return to the UI thread to handle opening a new browser tab.
697 ui_message_loop_
->task_runner()->PostTask(
698 FROM_HERE
, base::Bind(&ProcessSingleton::LinuxWatcher::HandleMessage
,
699 parent_
, current_dir
, tokens
, this));
700 fd_reader_
.StopWatchingFileDescriptor();
702 // LinuxWatcher::HandleMessage() is in charge of destroying this SocketReader
703 // object by invoking SocketReader::FinishWithACK().
706 void ProcessSingleton::LinuxWatcher::SocketReader::FinishWithACK(
707 const char *message
, size_t length
) {
708 if (message
&& length
) {
709 // Not necessary to care about the return value.
710 WriteToSocket(fd_
, message
, length
);
713 if (shutdown(fd_
, SHUT_WR
) < 0)
714 PLOG(ERROR
) << "shutdown() failed";
716 BrowserThread::PostTask(
719 base::Bind(&ProcessSingleton::LinuxWatcher::RemoveSocketReader
,
722 // We will be deleted once the posted RemoveSocketReader task runs.
725 ///////////////////////////////////////////////////////////////////////////////
728 ProcessSingleton::ProcessSingleton(
729 const base::FilePath
& user_data_dir
,
730 const NotificationCallback
& notification_callback
)
731 : notification_callback_(notification_callback
),
732 current_pid_(base::GetCurrentProcId()),
733 watcher_(new LinuxWatcher(this)) {
734 socket_path_
= user_data_dir
.Append(chrome::kSingletonSocketFilename
);
735 lock_path_
= user_data_dir
.Append(chrome::kSingletonLockFilename
);
736 cookie_path_
= user_data_dir
.Append(chrome::kSingletonCookieFilename
);
738 kill_callback_
= base::Bind(&ProcessSingleton::KillProcess
,
739 base::Unretained(this));
742 ProcessSingleton::~ProcessSingleton() {
745 ProcessSingleton::NotifyResult
ProcessSingleton::NotifyOtherProcess() {
746 return NotifyOtherProcessWithTimeout(
747 *base::CommandLine::ForCurrentProcess(), kRetryAttempts
,
748 base::TimeDelta::FromSeconds(kTimeoutInSeconds
), true);
751 ProcessSingleton::NotifyResult
ProcessSingleton::NotifyOtherProcessWithTimeout(
752 const base::CommandLine
& cmd_line
,
754 const base::TimeDelta
& timeout
,
755 bool kill_unresponsive
) {
756 DCHECK_GE(retry_attempts
, 0);
757 DCHECK_GE(timeout
.InMicroseconds(), 0);
759 base::TimeDelta sleep_interval
= timeout
/ retry_attempts
;
762 for (int retries
= 0; retries
<= retry_attempts
; ++retries
) {
763 // Try to connect to the socket.
764 if (ConnectSocket(&socket
, socket_path_
, cookie_path_
))
767 // If we're in a race with another process, they may be in Create() and have
768 // created the lock but not attached to the socket. So we check if the
769 // process with the pid from the lockfile is currently running and is a
770 // chrome browser. If so, we loop and try again for |timeout|.
772 std::string hostname
;
774 if (!ParseLockPath(lock_path_
, &hostname
, &pid
)) {
775 // No lockfile exists.
779 if (hostname
.empty()) {
781 UnlinkPath(lock_path_
);
785 if (hostname
!= net::GetHostName() && !IsChromeProcess(pid
)) {
786 // Locked by process on another host. If the user selected to unlock
787 // the profile, try to continue; otherwise quit.
788 if (DisplayProfileInUseError(lock_path_
, hostname
, pid
)) {
789 UnlinkPath(lock_path_
);
792 return PROFILE_IN_USE
;
795 if (!IsChromeProcess(pid
)) {
796 // Orphaned lockfile (no process with pid, or non-chrome process.)
797 UnlinkPath(lock_path_
);
801 if (IsSameChromeInstance(pid
)) {
802 // Orphaned lockfile (pid is part of same chrome instance we are, even
803 // though we haven't tried to create a lockfile yet).
804 UnlinkPath(lock_path_
);
808 if (retries
== retry_attempts
) {
809 // Retries failed. Kill the unresponsive chrome process and continue.
810 if (!kill_unresponsive
|| !KillProcessByLockPath())
811 return PROFILE_IN_USE
;
815 base::PlatformThread::Sleep(sleep_interval
);
818 timeval socket_timeout
= TimeDeltaToTimeVal(timeout
);
819 setsockopt(socket
.fd(),
823 sizeof(socket_timeout
));
825 // Found another process, prepare our command line
826 // format is "START\0<current dir>\0<argv[0]>\0...\0<argv[n]>".
827 std::string
to_send(kStartToken
);
828 to_send
.push_back(kTokenDelimiter
);
830 base::FilePath current_dir
;
831 if (!PathService::Get(base::DIR_CURRENT
, ¤t_dir
))
833 to_send
.append(current_dir
.value());
835 const std::vector
<std::string
>& argv
= cmd_line
.argv();
836 for (std::vector
<std::string
>::const_iterator it
= argv
.begin();
837 it
!= argv
.end(); ++it
) {
838 to_send
.push_back(kTokenDelimiter
);
843 if (!WriteToSocket(socket
.fd(), to_send
.data(), to_send
.length())) {
844 // Try to kill the other process, because it might have been dead.
845 if (!kill_unresponsive
|| !KillProcessByLockPath())
846 return PROFILE_IN_USE
;
850 if (shutdown(socket
.fd(), SHUT_WR
) < 0)
851 PLOG(ERROR
) << "shutdown() failed";
853 // Read ACK message from the other process. It might be blocked for a certain
854 // timeout, to make sure the other process has enough time to return ACK.
855 char buf
[kMaxACKMessageLength
+ 1];
856 ssize_t len
= ReadFromSocket(socket
.fd(), buf
, kMaxACKMessageLength
, timeout
);
858 // Failed to read ACK, the other process might have been frozen.
860 if (!kill_unresponsive
|| !KillProcessByLockPath())
861 return PROFILE_IN_USE
;
866 if (strncmp(buf
, kShutdownToken
, arraysize(kShutdownToken
) - 1) == 0) {
867 // The other process is shutting down, it's safe to start a new process.
869 } else if (strncmp(buf
, kACKToken
, arraysize(kACKToken
) - 1) == 0) {
870 #if defined(TOOLKIT_VIEWS) && defined(OS_LINUX) && !defined(OS_CHROMEOS)
871 // Likely NULL in unit tests.
872 views::LinuxUI
* linux_ui
= views::LinuxUI::instance();
874 linux_ui
->NotifyWindowManagerStartupComplete();
877 // Assume the other process is handling the request.
878 return PROCESS_NOTIFIED
;
881 NOTREACHED() << "The other process returned unknown message: " << buf
;
882 return PROCESS_NOTIFIED
;
885 ProcessSingleton::NotifyResult
ProcessSingleton::NotifyOtherProcessOrCreate() {
886 return NotifyOtherProcessWithTimeoutOrCreate(
887 *base::CommandLine::ForCurrentProcess(), kRetryAttempts
,
888 base::TimeDelta::FromSeconds(kTimeoutInSeconds
));
891 ProcessSingleton::NotifyResult
892 ProcessSingleton::NotifyOtherProcessWithTimeoutOrCreate(
893 const base::CommandLine
& command_line
,
895 const base::TimeDelta
& timeout
) {
896 NotifyResult result
= NotifyOtherProcessWithTimeout(
897 command_line
, retry_attempts
, timeout
, true);
898 if (result
!= PROCESS_NONE
)
902 // If the Create() failed, try again to notify. (It could be that another
903 // instance was starting at the same time and managed to grab the lock before
905 // This time, we don't want to kill anything if we aren't successful, since we
906 // aren't going to try to take over the lock ourselves.
907 result
= NotifyOtherProcessWithTimeout(
908 command_line
, retry_attempts
, timeout
, false);
909 if (result
!= PROCESS_NONE
)
915 void ProcessSingleton::OverrideCurrentPidForTesting(base::ProcessId pid
) {
919 void ProcessSingleton::OverrideKillCallbackForTesting(
920 const base::Callback
<void(int)>& callback
) {
921 kill_callback_
= callback
;
924 void ProcessSingleton::DisablePromptForTesting() {
925 g_disable_prompt
= true;
928 bool ProcessSingleton::Create() {
932 // The symlink lock is pointed to the hostname and process id, so other
933 // processes can find it out.
934 base::FilePath
symlink_content(base::StringPrintf(
936 net::GetHostName().c_str(),
940 // Create symbol link before binding the socket, to ensure only one instance
941 // can have the socket open.
942 if (!SymlinkPath(symlink_content
, lock_path_
)) {
943 // TODO(jackhou): Remove this case once this code is stable on Mac.
944 // http://crbug.com/367612
945 #if defined(OS_MACOSX)
946 // On Mac, an existing non-symlink lock file means the lock could be held by
947 // the old process singleton code. If we can successfully replace the lock,
948 // continue as normal.
949 if (base::IsLink(lock_path_
) ||
950 !ReplaceOldSingletonLock(symlink_content
, lock_path_
)) {
954 // If we failed to create the lock, most likely another instance won the
960 // Create the socket file somewhere in /tmp which is usually mounted as a
961 // normal filesystem. Some network filesystems (notably AFS) are screwy and
962 // do not support Unix domain sockets.
963 if (!socket_dir_
.CreateUniqueTempDir()) {
964 LOG(ERROR
) << "Failed to create socket directory.";
968 // Check that the directory was created with the correct permissions.
970 CHECK(base::GetPosixFilePermissions(socket_dir_
.path(), &dir_mode
) &&
971 dir_mode
== base::FILE_PERMISSION_USER_MASK
)
972 << "Temp directory mode is not 700: " << std::oct
<< dir_mode
;
974 // Setup the socket symlink and the two cookies.
975 base::FilePath socket_target_path
=
976 socket_dir_
.path().Append(chrome::kSingletonSocketFilename
);
977 base::FilePath
cookie(GenerateCookie());
978 base::FilePath remote_cookie_path
=
979 socket_dir_
.path().Append(chrome::kSingletonCookieFilename
);
980 UnlinkPath(socket_path_
);
981 UnlinkPath(cookie_path_
);
982 if (!SymlinkPath(socket_target_path
, socket_path_
) ||
983 !SymlinkPath(cookie
, cookie_path_
) ||
984 !SymlinkPath(cookie
, remote_cookie_path
)) {
985 // We've already locked things, so we can't have lost the startup race,
986 // but something doesn't like us.
987 LOG(ERROR
) << "Failed to create symlinks.";
988 if (!socket_dir_
.Delete())
989 LOG(ERROR
) << "Encountered a problem when deleting socket directory.";
993 SetupSocket(socket_target_path
.value(), &sock
, &addr
);
995 if (bind(sock
, reinterpret_cast<sockaddr
*>(&addr
), sizeof(addr
)) < 0) {
996 PLOG(ERROR
) << "Failed to bind() " << socket_target_path
.value();
1001 if (listen(sock
, 5) < 0)
1002 NOTREACHED() << "listen failed: " << base::safe_strerror(errno
);
1004 DCHECK(BrowserThread::IsMessageLoopValid(BrowserThread::IO
));
1005 BrowserThread::PostTask(
1008 base::Bind(&ProcessSingleton::LinuxWatcher::StartListening
,
1015 void ProcessSingleton::Cleanup() {
1016 UnlinkPath(socket_path_
);
1017 UnlinkPath(cookie_path_
);
1018 UnlinkPath(lock_path_
);
1021 bool ProcessSingleton::IsSameChromeInstance(pid_t pid
) {
1022 pid_t cur_pid
= current_pid_
;
1023 while (pid
!= cur_pid
) {
1024 pid
= base::GetParentProcessId(pid
);
1027 if (!IsChromeProcess(pid
))
1033 bool ProcessSingleton::KillProcessByLockPath() {
1034 std::string hostname
;
1036 ParseLockPath(lock_path_
, &hostname
, &pid
);
1038 if (!hostname
.empty() && hostname
!= net::GetHostName()) {
1039 return DisplayProfileInUseError(lock_path_
, hostname
, pid
);
1041 UnlinkPath(lock_path_
);
1043 if (IsSameChromeInstance(pid
))
1047 kill_callback_
.Run(pid
);
1051 LOG(ERROR
) << "Failed to extract pid from path: " << lock_path_
.value();
1055 void ProcessSingleton::KillProcess(int pid
) {
1056 // TODO(james.su@gmail.com): Is SIGKILL ok?
1057 int rv
= kill(static_cast<base::ProcessHandle
>(pid
), SIGKILL
);
1058 // ESRCH = No Such Process (can happen if the other process is already in
1059 // progress of shutting down and finishes before we try to kill it).
1060 DCHECK(rv
== 0 || errno
== ESRCH
) << "Error killing process: "
1061 << base::safe_strerror(errno
);