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 a file descriptor to be non-blocking.
116 // Return 0 on success, -1 on failure.
117 int SetNonBlocking(int fd
) {
118 int flags
= fcntl(fd
, F_GETFL
, 0);
121 if (flags
& O_NONBLOCK
)
123 return fcntl(fd
, F_SETFL
, flags
| O_NONBLOCK
);
126 // Set the close-on-exec bit on a file descriptor.
127 // Returns 0 on success, -1 on failure.
128 int SetCloseOnExec(int fd
) {
129 int flags
= fcntl(fd
, F_GETFD
, 0);
132 if (flags
& FD_CLOEXEC
)
134 return fcntl(fd
, F_SETFD
, flags
| FD_CLOEXEC
);
137 // Close a socket and check return value.
138 void CloseSocket(int fd
) {
139 int rv
= IGNORE_EINTR(close(fd
));
140 DCHECK_EQ(0, rv
) << "Error closing socket: " << base::safe_strerror(errno
);
143 // Write a message to a socket fd.
144 bool WriteToSocket(int fd
, const char *message
, size_t length
) {
147 size_t bytes_written
= 0;
149 ssize_t rv
= HANDLE_EINTR(
150 write(fd
, message
+ bytes_written
, length
- bytes_written
));
152 if (errno
== EAGAIN
|| errno
== EWOULDBLOCK
) {
153 // The socket shouldn't block, we're sending so little data. Just give
154 // up here, since NotifyOtherProcess() doesn't have an asynchronous api.
155 LOG(ERROR
) << "ProcessSingleton would block on write(), so it gave up.";
158 PLOG(ERROR
) << "write() failed";
162 } while (bytes_written
< length
);
167 struct timeval
TimeDeltaToTimeVal(const base::TimeDelta
& delta
) {
168 struct timeval result
;
169 result
.tv_sec
= delta
.InSeconds();
170 result
.tv_usec
= delta
.InMicroseconds() % base::Time::kMicrosecondsPerSecond
;
174 // Wait a socket for read for a certain timeout.
175 // Returns -1 if error occurred, 0 if timeout reached, > 0 if the socket is
177 int WaitSocketForRead(int fd
, const base::TimeDelta
& timeout
) {
179 struct timeval tv
= TimeDeltaToTimeVal(timeout
);
182 FD_SET(fd
, &read_fds
);
184 return HANDLE_EINTR(select(fd
+ 1, &read_fds
, NULL
, NULL
, &tv
));
187 // Read a message from a socket fd, with an optional timeout.
188 // If |timeout| <= 0 then read immediately.
189 // Return number of bytes actually read, or -1 on error.
190 ssize_t
ReadFromSocket(int fd
,
193 const base::TimeDelta
& timeout
) {
194 if (timeout
> base::TimeDelta()) {
195 int rv
= WaitSocketForRead(fd
, timeout
);
200 size_t bytes_read
= 0;
202 ssize_t rv
= HANDLE_EINTR(read(fd
, buf
+ bytes_read
, bufsize
- bytes_read
));
204 if (errno
!= EAGAIN
&& errno
!= EWOULDBLOCK
) {
205 PLOG(ERROR
) << "read() failed";
208 // It would block, so we just return what has been read.
212 // No more data to read.
217 } while (bytes_read
< bufsize
);
222 // Set up a sockaddr appropriate for messaging.
223 void SetupSockAddr(const std::string
& path
, struct sockaddr_un
* addr
) {
224 addr
->sun_family
= AF_UNIX
;
225 CHECK(path
.length() < arraysize(addr
->sun_path
))
226 << "Socket path too long: " << path
;
227 base::strlcpy(addr
->sun_path
, path
.c_str(), arraysize(addr
->sun_path
));
230 // Set up a socket appropriate for messaging.
231 int SetupSocketOnly() {
232 int sock
= socket(PF_UNIX
, SOCK_STREAM
, 0);
233 PCHECK(sock
>= 0) << "socket() failed";
235 int rv
= SetNonBlocking(sock
);
236 DCHECK_EQ(0, rv
) << "Failed to make non-blocking socket.";
237 rv
= SetCloseOnExec(sock
);
238 DCHECK_EQ(0, rv
) << "Failed to set CLOEXEC on socket.";
243 // Set up a socket and sockaddr appropriate for messaging.
244 void SetupSocket(const std::string
& path
, int* sock
, struct sockaddr_un
* addr
) {
245 *sock
= SetupSocketOnly();
246 SetupSockAddr(path
, addr
);
249 // Read a symbolic link, return empty string if given path is not a symbol link.
250 base::FilePath
ReadLink(const base::FilePath
& path
) {
251 base::FilePath target
;
252 if (!base::ReadSymbolicLink(path
, &target
)) {
253 // The only errno that should occur is ENOENT.
254 if (errno
!= 0 && errno
!= ENOENT
)
255 PLOG(ERROR
) << "readlink(" << path
.value() << ") failed";
260 // Unlink a path. Return true on success.
261 bool UnlinkPath(const base::FilePath
& path
) {
262 int rv
= unlink(path
.value().c_str());
263 if (rv
< 0 && errno
!= ENOENT
)
264 PLOG(ERROR
) << "Failed to unlink " << path
.value();
269 // Create a symlink. Returns true on success.
270 bool SymlinkPath(const base::FilePath
& target
, const base::FilePath
& path
) {
271 if (!base::CreateSymbolicLink(target
, path
)) {
272 // Double check the value in case symlink suceeded but we got an incorrect
273 // failure due to NFS packet loss & retry.
274 int saved_errno
= errno
;
275 if (ReadLink(path
) != target
) {
276 // If we failed to create the lock, most likely another instance won the
279 PLOG(ERROR
) << "Failed to create " << path
.value();
286 // Extract the hostname and pid from the lock symlink.
287 // Returns true if the lock existed.
288 bool ParseLockPath(const base::FilePath
& path
,
289 std::string
* hostname
,
291 std::string real_path
= ReadLink(path
).value();
292 if (real_path
.empty())
295 std::string::size_type pos
= real_path
.rfind(kLockDelimiter
);
297 // If the path is not a symbolic link, or doesn't contain what we expect,
299 if (pos
== std::string::npos
) {
305 *hostname
= real_path
.substr(0, pos
);
307 const std::string
& pid_str
= real_path
.substr(pos
+ 1);
308 if (!base::StringToInt(pid_str
, pid
))
314 // Returns true if the user opted to unlock the profile.
315 bool DisplayProfileInUseError(const base::FilePath
& lock_path
,
316 const std::string
& hostname
,
318 base::string16 error
= l10n_util::GetStringFUTF16(
319 IDS_PROFILE_IN_USE_POSIX
,
320 base::IntToString16(pid
),
321 base::ASCIIToUTF16(hostname
));
324 if (g_disable_prompt
)
327 #if defined(OS_LINUX)
328 base::string16 relaunch_button_text
= l10n_util::GetStringUTF16(
329 IDS_PROFILE_IN_USE_LINUX_RELAUNCH
);
330 return ShowProcessSingletonDialog(error
, relaunch_button_text
);
331 #elif defined(OS_MACOSX)
332 // On Mac, always usurp the lock.
340 bool IsChromeProcess(pid_t pid
) {
341 base::FilePath
other_chrome_path(base::GetProcessExecutablePath(pid
));
342 return (!other_chrome_path
.empty() &&
343 other_chrome_path
.BaseName() ==
344 base::FilePath(chrome::kBrowserProcessExecutableName
));
347 // A helper class to hold onto a socket.
350 ScopedSocket() : fd_(-1) { Reset(); }
351 ~ScopedSocket() { Close(); }
352 int fd() { return fd_
; }
355 fd_
= SetupSocketOnly();
366 // Returns a random string for uniquifying profile connections.
367 std::string
GenerateCookie() {
368 return base::Uint64ToString(base::RandUint64());
371 bool CheckCookie(const base::FilePath
& path
, const base::FilePath
& cookie
) {
372 return (cookie
== ReadLink(path
));
375 bool ConnectSocket(ScopedSocket
* socket
,
376 const base::FilePath
& socket_path
,
377 const base::FilePath
& cookie_path
) {
378 base::FilePath socket_target
;
379 if (base::ReadSymbolicLink(socket_path
, &socket_target
)) {
380 // It's a symlink. Read the cookie.
381 base::FilePath cookie
= ReadLink(cookie_path
);
384 base::FilePath remote_cookie
= socket_target
.DirName().
385 Append(chrome::kSingletonCookieFilename
);
386 // Verify the cookie before connecting.
387 if (!CheckCookie(remote_cookie
, cookie
))
389 // Now we know the directory was (at that point) created by the profile
390 // owner. Try to connect.
392 SetupSockAddr(socket_target
.value(), &addr
);
393 int ret
= HANDLE_EINTR(connect(socket
->fd(),
394 reinterpret_cast<sockaddr
*>(&addr
),
398 // Check the cookie again. We only link in /tmp, which is sticky, so, if the
399 // directory is still correct, it must have been correct in-between when we
400 // connected. POSIX, sadly, lacks a connectat().
401 if (!CheckCookie(remote_cookie
, cookie
)) {
407 } else if (errno
== EINVAL
) {
408 // It exists, but is not a symlink (or some other error we detect
409 // later). Just connect to it directly; this is an older version of Chrome.
411 SetupSockAddr(socket_path
.value(), &addr
);
412 int ret
= HANDLE_EINTR(connect(socket
->fd(),
413 reinterpret_cast<sockaddr
*>(&addr
),
417 // File is missing, or other error.
419 PLOG(ERROR
) << "readlink failed";
424 #if defined(OS_MACOSX)
425 bool ReplaceOldSingletonLock(const base::FilePath
& symlink_content
,
426 const base::FilePath
& lock_path
) {
427 // Try taking an flock(2) on the file. Failure means the lock is taken so we
429 base::ScopedFD
lock_fd(HANDLE_EINTR(
430 open(lock_path
.value().c_str(), O_RDWR
| O_CREAT
| O_SYMLINK
, 0644)));
431 if (!lock_fd
.is_valid()) {
432 PLOG(ERROR
) << "Could not open singleton lock";
436 int rc
= HANDLE_EINTR(flock(lock_fd
.get(), LOCK_EX
| LOCK_NB
));
438 if (errno
== EWOULDBLOCK
) {
439 LOG(ERROR
) << "Singleton lock held by old process.";
441 PLOG(ERROR
) << "Error locking singleton lock";
446 // Successfully taking the lock means we can replace it with the a new symlink
447 // lock. We never flock() the lock file from now on. I.e. we assume that an
448 // old version of Chrome will not run with the same user data dir after this
450 if (!base::DeleteFile(lock_path
, false)) {
451 PLOG(ERROR
) << "Could not delete old singleton lock.";
455 return SymlinkPath(symlink_content
, lock_path
);
457 #endif // defined(OS_MACOSX)
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::MessageLoopForIO::Watcher
,
468 public base::MessageLoop::DestructionObserver
,
469 public base::RefCountedThreadSafe
<ProcessSingleton::LinuxWatcher
,
470 BrowserThread::DeleteOnIOThread
> {
472 // A helper class to read message from an established socket.
473 class SocketReader
: public base::MessageLoopForIO::Watcher
{
475 SocketReader(ProcessSingleton::LinuxWatcher
* parent
,
476 base::MessageLoop
* ui_message_loop
,
479 ui_message_loop_(ui_message_loop
),
482 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO
));
484 base::MessageLoopForIO::current()->WatchFileDescriptor(
485 fd
, true, base::MessageLoopForIO::WATCH_READ
, &fd_reader_
, this);
486 // If we haven't completed in a reasonable amount of time, give up.
487 timer_
.Start(FROM_HERE
, base::TimeDelta::FromSeconds(kTimeoutInSeconds
),
488 this, &SocketReader::CleanupAndDeleteSelf
);
491 ~SocketReader() override
{ CloseSocket(fd_
); }
493 // MessageLoopForIO::Watcher impl.
494 void OnFileCanReadWithoutBlocking(int fd
) override
;
495 void OnFileCanWriteWithoutBlocking(int fd
) override
{
496 // SocketReader only watches for accept (read) events.
500 // Finish handling the incoming message by optionally sending back an ACK
501 // message and removing this SocketReader.
502 void FinishWithACK(const char *message
, size_t length
);
505 void CleanupAndDeleteSelf() {
506 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO
));
508 parent_
->RemoveSocketReader(this);
509 // We're deleted beyond this point.
512 base::MessageLoopForIO::FileDescriptorWatcher fd_reader_
;
514 // The ProcessSingleton::LinuxWatcher that owns us.
515 ProcessSingleton::LinuxWatcher
* const parent_
;
517 // A reference to the UI message loop.
518 base::MessageLoop
* const ui_message_loop_
;
520 // The file descriptor we're reading.
523 // Store the message in this buffer.
524 char buf_
[kMaxMessageLength
];
526 // Tracks the number of bytes we've read in case we're getting partial
530 base::OneShotTimer
<SocketReader
> timer_
;
532 DISALLOW_COPY_AND_ASSIGN(SocketReader
);
535 // We expect to only be constructed on the UI thread.
536 explicit LinuxWatcher(ProcessSingleton
* parent
)
537 : ui_message_loop_(base::MessageLoop::current()),
541 // Start listening for connections on the socket. This method should be
542 // called from the IO thread.
543 void StartListening(int socket
);
545 // This method determines if we should use the same process and if we should,
546 // opens a new browser tab. This runs on the UI thread.
547 // |reader| is for sending back ACK message.
548 void HandleMessage(const std::string
& current_dir
,
549 const std::vector
<std::string
>& argv
,
550 SocketReader
* reader
);
552 // MessageLoopForIO::Watcher impl. These run on the IO thread.
553 void OnFileCanReadWithoutBlocking(int fd
) override
;
554 void OnFileCanWriteWithoutBlocking(int fd
) override
{
555 // ProcessSingleton only watches for accept (read) events.
559 // MessageLoop::DestructionObserver
560 void WillDestroyCurrentMessageLoop() override
{
561 fd_watcher_
.StopWatchingFileDescriptor();
565 friend struct BrowserThread::DeleteOnThread
<BrowserThread::IO
>;
566 friend class base::DeleteHelper
<ProcessSingleton::LinuxWatcher
>;
568 ~LinuxWatcher() override
{
569 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO
));
570 STLDeleteElements(&readers_
);
572 base::MessageLoopForIO
* ml
= base::MessageLoopForIO::current();
573 ml
->RemoveDestructionObserver(this);
576 // Removes and deletes the SocketReader.
577 void RemoveSocketReader(SocketReader
* reader
);
579 base::MessageLoopForIO::FileDescriptorWatcher fd_watcher_
;
581 // A reference to the UI message loop (i.e., the message loop we were
583 base::MessageLoop
* ui_message_loop_
;
585 // The ProcessSingleton that owns us.
586 ProcessSingleton
* const parent_
;
588 std::set
<SocketReader
*> readers_
;
590 DISALLOW_COPY_AND_ASSIGN(LinuxWatcher
);
593 void ProcessSingleton::LinuxWatcher::OnFileCanReadWithoutBlocking(int fd
) {
594 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO
));
595 // Accepting incoming client.
597 socklen_t from_len
= sizeof(from
);
598 int connection_socket
= HANDLE_EINTR(accept(
599 fd
, reinterpret_cast<sockaddr
*>(&from
), &from_len
));
600 if (-1 == connection_socket
) {
601 PLOG(ERROR
) << "accept() failed";
604 int rv
= SetNonBlocking(connection_socket
);
605 DCHECK_EQ(0, rv
) << "Failed to make non-blocking socket.";
606 SocketReader
* reader
= new SocketReader(this,
609 readers_
.insert(reader
);
612 void ProcessSingleton::LinuxWatcher::StartListening(int socket
) {
613 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO
));
614 // Watch for client connections on this socket.
615 base::MessageLoopForIO
* ml
= base::MessageLoopForIO::current();
616 ml
->AddDestructionObserver(this);
617 ml
->WatchFileDescriptor(socket
, true, base::MessageLoopForIO::WATCH_READ
,
621 void ProcessSingleton::LinuxWatcher::HandleMessage(
622 const std::string
& current_dir
, const std::vector
<std::string
>& argv
,
623 SocketReader
* reader
) {
624 DCHECK(ui_message_loop_
== base::MessageLoop::current());
627 if (parent_
->notification_callback_
.Run(base::CommandLine(argv
),
628 base::FilePath(current_dir
))) {
629 // Send back "ACK" message to prevent the client process from starting up.
630 reader
->FinishWithACK(kACKToken
, arraysize(kACKToken
) - 1);
632 LOG(WARNING
) << "Not handling interprocess notification as browser"
634 // Send back "SHUTDOWN" message, so that the client process can start up
635 // without killing this process.
636 reader
->FinishWithACK(kShutdownToken
, arraysize(kShutdownToken
) - 1);
641 void ProcessSingleton::LinuxWatcher::RemoveSocketReader(SocketReader
* reader
) {
642 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO
));
644 readers_
.erase(reader
);
648 ///////////////////////////////////////////////////////////////////////////////
649 // ProcessSingleton::LinuxWatcher::SocketReader
652 void ProcessSingleton::LinuxWatcher::SocketReader::OnFileCanReadWithoutBlocking(
654 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO
));
656 while (bytes_read_
< sizeof(buf_
)) {
657 ssize_t rv
= HANDLE_EINTR(
658 read(fd
, buf_
+ bytes_read_
, sizeof(buf_
) - bytes_read_
));
660 if (errno
!= EAGAIN
&& errno
!= EWOULDBLOCK
) {
661 PLOG(ERROR
) << "read() failed";
665 // It would block, so we just return and continue to watch for the next
666 // opportunity to read.
670 // No more data to read. It's time to process the message.
677 // Validate the message. The shortest message is kStartToken\0x\0x
678 const size_t kMinMessageLength
= arraysize(kStartToken
) + 4;
679 if (bytes_read_
< kMinMessageLength
) {
680 buf_
[bytes_read_
] = 0;
681 LOG(ERROR
) << "Invalid socket message (wrong length):" << buf_
;
682 CleanupAndDeleteSelf();
686 std::string
str(buf_
, bytes_read_
);
687 std::vector
<std::string
> tokens
= base::SplitString(
688 str
, std::string(1, kTokenDelimiter
),
689 base::TRIM_WHITESPACE
, base::SPLIT_WANT_ALL
);
691 if (tokens
.size() < 3 || tokens
[0] != kStartToken
) {
692 LOG(ERROR
) << "Wrong message format: " << str
;
693 CleanupAndDeleteSelf();
697 // Stop the expiration timer to prevent this SocketReader object from being
698 // terminated unexpectly.
701 std::string current_dir
= tokens
[1];
702 // Remove the first two tokens. The remaining tokens should be the command
704 tokens
.erase(tokens
.begin());
705 tokens
.erase(tokens
.begin());
707 // Return to the UI thread to handle opening a new browser tab.
708 ui_message_loop_
->task_runner()->PostTask(
709 FROM_HERE
, base::Bind(&ProcessSingleton::LinuxWatcher::HandleMessage
,
710 parent_
, current_dir
, tokens
, this));
711 fd_reader_
.StopWatchingFileDescriptor();
713 // LinuxWatcher::HandleMessage() is in charge of destroying this SocketReader
714 // object by invoking SocketReader::FinishWithACK().
717 void ProcessSingleton::LinuxWatcher::SocketReader::FinishWithACK(
718 const char *message
, size_t length
) {
719 if (message
&& length
) {
720 // Not necessary to care about the return value.
721 WriteToSocket(fd_
, message
, length
);
724 if (shutdown(fd_
, SHUT_WR
) < 0)
725 PLOG(ERROR
) << "shutdown() failed";
727 BrowserThread::PostTask(
730 base::Bind(&ProcessSingleton::LinuxWatcher::RemoveSocketReader
,
733 // We will be deleted once the posted RemoveSocketReader task runs.
736 ///////////////////////////////////////////////////////////////////////////////
739 ProcessSingleton::ProcessSingleton(
740 const base::FilePath
& user_data_dir
,
741 const NotificationCallback
& notification_callback
)
742 : notification_callback_(notification_callback
),
743 current_pid_(base::GetCurrentProcId()),
744 watcher_(new LinuxWatcher(this)) {
745 socket_path_
= user_data_dir
.Append(chrome::kSingletonSocketFilename
);
746 lock_path_
= user_data_dir
.Append(chrome::kSingletonLockFilename
);
747 cookie_path_
= user_data_dir
.Append(chrome::kSingletonCookieFilename
);
749 kill_callback_
= base::Bind(&ProcessSingleton::KillProcess
,
750 base::Unretained(this));
753 ProcessSingleton::~ProcessSingleton() {
756 ProcessSingleton::NotifyResult
ProcessSingleton::NotifyOtherProcess() {
757 return NotifyOtherProcessWithTimeout(
758 *base::CommandLine::ForCurrentProcess(), kRetryAttempts
,
759 base::TimeDelta::FromSeconds(kTimeoutInSeconds
), true);
762 ProcessSingleton::NotifyResult
ProcessSingleton::NotifyOtherProcessWithTimeout(
763 const base::CommandLine
& cmd_line
,
765 const base::TimeDelta
& timeout
,
766 bool kill_unresponsive
) {
767 DCHECK_GE(retry_attempts
, 0);
768 DCHECK_GE(timeout
.InMicroseconds(), 0);
770 base::TimeDelta sleep_interval
= timeout
/ retry_attempts
;
773 for (int retries
= 0; retries
<= retry_attempts
; ++retries
) {
774 // Try to connect to the socket.
775 if (ConnectSocket(&socket
, socket_path_
, cookie_path_
))
778 // If we're in a race with another process, they may be in Create() and have
779 // created the lock but not attached to the socket. So we check if the
780 // process with the pid from the lockfile is currently running and is a
781 // chrome browser. If so, we loop and try again for |timeout|.
783 std::string hostname
;
785 if (!ParseLockPath(lock_path_
, &hostname
, &pid
)) {
786 // No lockfile exists.
790 if (hostname
.empty()) {
792 UnlinkPath(lock_path_
);
796 if (hostname
!= net::GetHostName() && !IsChromeProcess(pid
)) {
797 // Locked by process on another host. If the user selected to unlock
798 // the profile, try to continue; otherwise quit.
799 if (DisplayProfileInUseError(lock_path_
, hostname
, pid
)) {
800 UnlinkPath(lock_path_
);
803 return PROFILE_IN_USE
;
806 if (!IsChromeProcess(pid
)) {
807 // Orphaned lockfile (no process with pid, or non-chrome process.)
808 UnlinkPath(lock_path_
);
812 if (IsSameChromeInstance(pid
)) {
813 // Orphaned lockfile (pid is part of same chrome instance we are, even
814 // though we haven't tried to create a lockfile yet).
815 UnlinkPath(lock_path_
);
819 if (retries
== retry_attempts
) {
820 // Retries failed. Kill the unresponsive chrome process and continue.
821 if (!kill_unresponsive
|| !KillProcessByLockPath())
822 return PROFILE_IN_USE
;
826 base::PlatformThread::Sleep(sleep_interval
);
829 timeval socket_timeout
= TimeDeltaToTimeVal(timeout
);
830 setsockopt(socket
.fd(),
834 sizeof(socket_timeout
));
836 // Found another process, prepare our command line
837 // format is "START\0<current dir>\0<argv[0]>\0...\0<argv[n]>".
838 std::string
to_send(kStartToken
);
839 to_send
.push_back(kTokenDelimiter
);
841 base::FilePath current_dir
;
842 if (!PathService::Get(base::DIR_CURRENT
, ¤t_dir
))
844 to_send
.append(current_dir
.value());
846 const std::vector
<std::string
>& argv
= cmd_line
.argv();
847 for (std::vector
<std::string
>::const_iterator it
= argv
.begin();
848 it
!= argv
.end(); ++it
) {
849 to_send
.push_back(kTokenDelimiter
);
854 if (!WriteToSocket(socket
.fd(), to_send
.data(), to_send
.length())) {
855 // Try to kill the other process, because it might have been dead.
856 if (!kill_unresponsive
|| !KillProcessByLockPath())
857 return PROFILE_IN_USE
;
861 if (shutdown(socket
.fd(), SHUT_WR
) < 0)
862 PLOG(ERROR
) << "shutdown() failed";
864 // Read ACK message from the other process. It might be blocked for a certain
865 // timeout, to make sure the other process has enough time to return ACK.
866 char buf
[kMaxACKMessageLength
+ 1];
867 ssize_t len
= ReadFromSocket(socket
.fd(), buf
, kMaxACKMessageLength
, timeout
);
869 // Failed to read ACK, the other process might have been frozen.
871 if (!kill_unresponsive
|| !KillProcessByLockPath())
872 return PROFILE_IN_USE
;
877 if (strncmp(buf
, kShutdownToken
, arraysize(kShutdownToken
) - 1) == 0) {
878 // The other process is shutting down, it's safe to start a new process.
880 } else if (strncmp(buf
, kACKToken
, arraysize(kACKToken
) - 1) == 0) {
881 #if defined(TOOLKIT_VIEWS) && defined(OS_LINUX) && !defined(OS_CHROMEOS)
882 // Likely NULL in unit tests.
883 views::LinuxUI
* linux_ui
= views::LinuxUI::instance();
885 linux_ui
->NotifyWindowManagerStartupComplete();
888 // Assume the other process is handling the request.
889 return PROCESS_NOTIFIED
;
892 NOTREACHED() << "The other process returned unknown message: " << buf
;
893 return PROCESS_NOTIFIED
;
896 ProcessSingleton::NotifyResult
ProcessSingleton::NotifyOtherProcessOrCreate() {
897 return NotifyOtherProcessWithTimeoutOrCreate(
898 *base::CommandLine::ForCurrentProcess(), kRetryAttempts
,
899 base::TimeDelta::FromSeconds(kTimeoutInSeconds
));
902 ProcessSingleton::NotifyResult
903 ProcessSingleton::NotifyOtherProcessWithTimeoutOrCreate(
904 const base::CommandLine
& command_line
,
906 const base::TimeDelta
& timeout
) {
907 NotifyResult result
= NotifyOtherProcessWithTimeout(
908 command_line
, retry_attempts
, timeout
, true);
909 if (result
!= PROCESS_NONE
)
913 // If the Create() failed, try again to notify. (It could be that another
914 // instance was starting at the same time and managed to grab the lock before
916 // This time, we don't want to kill anything if we aren't successful, since we
917 // aren't going to try to take over the lock ourselves.
918 result
= NotifyOtherProcessWithTimeout(
919 command_line
, retry_attempts
, timeout
, false);
920 if (result
!= PROCESS_NONE
)
926 void ProcessSingleton::OverrideCurrentPidForTesting(base::ProcessId pid
) {
930 void ProcessSingleton::OverrideKillCallbackForTesting(
931 const base::Callback
<void(int)>& callback
) {
932 kill_callback_
= callback
;
935 void ProcessSingleton::DisablePromptForTesting() {
936 g_disable_prompt
= true;
939 bool ProcessSingleton::Create() {
943 // The symlink lock is pointed to the hostname and process id, so other
944 // processes can find it out.
945 base::FilePath
symlink_content(base::StringPrintf(
947 net::GetHostName().c_str(),
951 // Create symbol link before binding the socket, to ensure only one instance
952 // can have the socket open.
953 if (!SymlinkPath(symlink_content
, lock_path_
)) {
954 // TODO(jackhou): Remove this case once this code is stable on Mac.
955 // http://crbug.com/367612
956 #if defined(OS_MACOSX)
957 // On Mac, an existing non-symlink lock file means the lock could be held by
958 // the old process singleton code. If we can successfully replace the lock,
959 // continue as normal.
960 if (base::IsLink(lock_path_
) ||
961 !ReplaceOldSingletonLock(symlink_content
, lock_path_
)) {
965 // If we failed to create the lock, most likely another instance won the
971 // Create the socket file somewhere in /tmp which is usually mounted as a
972 // normal filesystem. Some network filesystems (notably AFS) are screwy and
973 // do not support Unix domain sockets.
974 if (!socket_dir_
.CreateUniqueTempDir()) {
975 LOG(ERROR
) << "Failed to create socket directory.";
979 // Check that the directory was created with the correct permissions.
981 CHECK(base::GetPosixFilePermissions(socket_dir_
.path(), &dir_mode
) &&
982 dir_mode
== base::FILE_PERMISSION_USER_MASK
)
983 << "Temp directory mode is not 700: " << std::oct
<< dir_mode
;
985 // Setup the socket symlink and the two cookies.
986 base::FilePath socket_target_path
=
987 socket_dir_
.path().Append(chrome::kSingletonSocketFilename
);
988 base::FilePath
cookie(GenerateCookie());
989 base::FilePath remote_cookie_path
=
990 socket_dir_
.path().Append(chrome::kSingletonCookieFilename
);
991 UnlinkPath(socket_path_
);
992 UnlinkPath(cookie_path_
);
993 if (!SymlinkPath(socket_target_path
, socket_path_
) ||
994 !SymlinkPath(cookie
, cookie_path_
) ||
995 !SymlinkPath(cookie
, remote_cookie_path
)) {
996 // We've already locked things, so we can't have lost the startup race,
997 // but something doesn't like us.
998 LOG(ERROR
) << "Failed to create symlinks.";
999 if (!socket_dir_
.Delete())
1000 LOG(ERROR
) << "Encountered a problem when deleting socket directory.";
1004 SetupSocket(socket_target_path
.value(), &sock
, &addr
);
1006 if (bind(sock
, reinterpret_cast<sockaddr
*>(&addr
), sizeof(addr
)) < 0) {
1007 PLOG(ERROR
) << "Failed to bind() " << socket_target_path
.value();
1012 if (listen(sock
, 5) < 0)
1013 NOTREACHED() << "listen failed: " << base::safe_strerror(errno
);
1015 DCHECK(BrowserThread::IsMessageLoopValid(BrowserThread::IO
));
1016 BrowserThread::PostTask(
1019 base::Bind(&ProcessSingleton::LinuxWatcher::StartListening
,
1026 void ProcessSingleton::Cleanup() {
1027 UnlinkPath(socket_path_
);
1028 UnlinkPath(cookie_path_
);
1029 UnlinkPath(lock_path_
);
1032 bool ProcessSingleton::IsSameChromeInstance(pid_t pid
) {
1033 pid_t cur_pid
= current_pid_
;
1034 while (pid
!= cur_pid
) {
1035 pid
= base::GetParentProcessId(pid
);
1038 if (!IsChromeProcess(pid
))
1044 bool ProcessSingleton::KillProcessByLockPath() {
1045 std::string hostname
;
1047 ParseLockPath(lock_path_
, &hostname
, &pid
);
1049 if (!hostname
.empty() && hostname
!= net::GetHostName()) {
1050 return DisplayProfileInUseError(lock_path_
, hostname
, pid
);
1052 UnlinkPath(lock_path_
);
1054 if (IsSameChromeInstance(pid
))
1058 kill_callback_
.Run(pid
);
1062 LOG(ERROR
) << "Failed to extract pid from path: " << lock_path_
.value();
1066 void ProcessSingleton::KillProcess(int pid
) {
1067 // TODO(james.su@gmail.com): Is SIGKILL ok?
1068 int rv
= kill(static_cast<base::ProcessHandle
>(pid
), SIGKILL
);
1069 // ESRCH = No Such Process (can happen if the other process is already in
1070 // progress of shutting down and finishes before we try to kill it).
1071 DCHECK(rv
== 0 || errno
== ESRCH
) << "Error killing process: "
1072 << base::safe_strerror(errno
);