Roll src/third_party/WebKit eac3800:0237a66 (svn 202606:202607)
[chromium-blink-merge.git] / chrome / browser / process_singleton_posix.cc
blob5e2635e29cb49a4131972b1ad9033785ea1a8338
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
9 // exits.
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
31 // starts as normal.
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"
42 #include <errno.h>
43 #include <fcntl.h>
44 #include <signal.h>
45 #include <sys/socket.h>
46 #include <sys/stat.h>
47 #include <sys/types.h>
48 #include <sys/un.h>
49 #include <unistd.h>
51 #include <cstring>
52 #include <set>
53 #include <string>
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"
87 #if defined(OS_LINUX)
88 #include "chrome/browser/ui/process_singleton_dialog_linux.h"
89 #endif
91 #if defined(TOOLKIT_VIEWS) && defined(OS_LINUX) && !defined(OS_CHROMEOS)
92 #include "ui/views/linux_ui/linux_ui.h"
93 #endif
95 using content::BrowserThread;
97 namespace {
99 // Timeout for the current browser process to respond. 20 seconds should be
100 // enough.
101 const int kTimeoutInSeconds = 20;
102 // Number of retries to notify the browser. 20 retries over 20 seconds = 1 try
103 // per second.
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);
119 if (-1 == flags)
120 return flags;
121 if (flags & FD_CLOEXEC)
122 return 0;
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) {
134 DCHECK(message);
135 DCHECK(length);
136 size_t bytes_written = 0;
137 do {
138 ssize_t rv = HANDLE_EINTR(
139 write(fd, message + bytes_written, length - bytes_written));
140 if (rv < 0) {
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.";
145 return false;
147 PLOG(ERROR) << "write() failed";
148 return false;
150 bytes_written += rv;
151 } while (bytes_written < length);
153 return true;
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;
160 return result;
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
165 // ready for read.
166 int WaitSocketForRead(int fd, const base::TimeDelta& timeout) {
167 fd_set read_fds;
168 struct timeval tv = TimeDeltaToTimeVal(timeout);
170 FD_ZERO(&read_fds);
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,
180 char* buf,
181 size_t bufsize,
182 const base::TimeDelta& timeout) {
183 if (timeout > base::TimeDelta()) {
184 int rv = WaitSocketForRead(fd, timeout);
185 if (rv <= 0)
186 return rv;
189 size_t bytes_read = 0;
190 do {
191 ssize_t rv = HANDLE_EINTR(read(fd, buf + bytes_read, bufsize - bytes_read));
192 if (rv < 0) {
193 if (errno != EAGAIN && errno != EWOULDBLOCK) {
194 PLOG(ERROR) << "read() failed";
195 return rv;
196 } else {
197 // It would block, so we just return what has been read.
198 return bytes_read;
200 } else if (!rv) {
201 // No more data to read.
202 return bytes_read;
203 } else {
204 bytes_read += rv;
206 } while (bytes_read < bufsize);
208 return bytes_read;
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.";
229 return sock;
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";
246 return target;
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();
255 return rv == 0;
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
266 // startup race.
267 errno = saved_errno;
268 PLOG(ERROR) << "Failed to create " << path.value();
269 return false;
272 return true;
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,
279 int* pid) {
280 std::string real_path = ReadLink(path).value();
281 if (real_path.empty())
282 return false;
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,
287 // bail.
288 if (pos == std::string::npos) {
289 *hostname = "";
290 *pid = -1;
291 return true;
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))
298 *pid = -1;
300 return true;
303 // Returns true if the user opted to unlock the profile.
304 bool DisplayProfileInUseError(const base::FilePath& lock_path,
305 const std::string& hostname,
306 int pid) {
307 base::string16 error = l10n_util::GetStringFUTF16(
308 IDS_PROFILE_IN_USE_POSIX,
309 base::IntToString16(pid),
310 base::ASCIIToUTF16(hostname));
311 LOG(ERROR) << error;
313 if (g_disable_prompt)
314 return false;
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.
322 return true;
323 #endif
325 NOTREACHED();
326 return false;
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.
337 class ScopedSocket {
338 public:
339 ScopedSocket() : fd_(-1) { Reset(); }
340 ~ScopedSocket() { Close(); }
341 int fd() { return fd_; }
342 void Reset() {
343 Close();
344 fd_ = SetupSocketOnly();
346 void Close() {
347 if (fd_ >= 0)
348 CloseSocket(fd_);
349 fd_ = -1;
351 private:
352 int fd_;
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);
371 if (cookie.empty())
372 return false;
373 base::FilePath remote_cookie = socket_target.DirName().
374 Append(chrome::kSingletonCookieFilename);
375 // Verify the cookie before connecting.
376 if (!CheckCookie(remote_cookie, cookie))
377 return false;
378 // Now we know the directory was (at that point) created by the profile
379 // owner. Try to connect.
380 sockaddr_un addr;
381 SetupSockAddr(socket_target.value(), &addr);
382 int ret = HANDLE_EINTR(connect(socket->fd(),
383 reinterpret_cast<sockaddr*>(&addr),
384 sizeof(addr)));
385 if (ret != 0)
386 return false;
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)) {
391 socket->Reset();
392 return false;
394 // Success!
395 return true;
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.
399 sockaddr_un addr;
400 SetupSockAddr(socket_path.value(), &addr);
401 int ret = HANDLE_EINTR(connect(socket->fd(),
402 reinterpret_cast<sockaddr*>(&addr),
403 sizeof(addr)));
404 return (ret == 0);
405 } else {
406 // File is missing, or other error.
407 if (errno != ENOENT)
408 PLOG(ERROR) << "readlink failed";
409 return false;
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
417 // should quit.
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";
422 return false;
425 int rc = HANDLE_EINTR(flock(lock_fd.get(), LOCK_EX | LOCK_NB));
426 if (rc == -1) {
427 if (errno == EWOULDBLOCK) {
428 LOG(ERROR) << "Singleton lock held by old process.";
429 } else {
430 PLOG(ERROR) << "Error locking singleton lock";
432 return false;
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
438 // version has run.
439 if (!base::DeleteFile(lock_path, false)) {
440 PLOG(ERROR) << "Could not delete old singleton lock.";
441 return false;
444 return SymlinkPath(symlink_content, lock_path);
446 #endif // defined(OS_MACOSX)
448 } // namespace
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> {
460 public:
461 // A helper class to read message from an established socket.
462 class SocketReader : public base::MessageLoopForIO::Watcher {
463 public:
464 SocketReader(ProcessSingleton::LinuxWatcher* parent,
465 base::MessageLoop* ui_message_loop,
466 int fd)
467 : parent_(parent),
468 ui_message_loop_(ui_message_loop),
469 fd_(fd),
470 bytes_read_(0) {
471 DCHECK_CURRENTLY_ON(BrowserThread::IO);
472 // Wait for reads.
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.
486 NOTREACHED();
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);
493 private:
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.
510 const int fd_;
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
516 // reads.
517 size_t bytes_read_;
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()),
527 parent_(parent) {
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.
545 NOTREACHED();
548 // MessageLoop::DestructionObserver
549 void WillDestroyCurrentMessageLoop() override {
550 fd_watcher_.StopWatchingFileDescriptor();
553 private:
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
571 // constructed on).
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.
585 sockaddr_un from;
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";
591 return;
593 int rv = net::SetNonBlocking(connection_socket);
594 DCHECK_EQ(0, rv) << "Failed to make non-blocking socket.";
595 SocketReader* reader = new SocketReader(this,
596 ui_message_loop_,
597 connection_socket);
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,
607 &fd_watcher_, this);
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());
614 DCHECK(reader);
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);
620 } else {
621 LOG(WARNING) << "Not handling interprocess notification as browser"
622 " is shutting down";
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);
626 return;
630 void ProcessSingleton::LinuxWatcher::RemoveSocketReader(SocketReader* reader) {
631 DCHECK_CURRENTLY_ON(BrowserThread::IO);
632 DCHECK(reader);
633 readers_.erase(reader);
634 delete reader;
637 ///////////////////////////////////////////////////////////////////////////////
638 // ProcessSingleton::LinuxWatcher::SocketReader
641 void ProcessSingleton::LinuxWatcher::SocketReader::OnFileCanReadWithoutBlocking(
642 int fd) {
643 DCHECK_CURRENTLY_ON(BrowserThread::IO);
644 DCHECK_EQ(fd, fd_);
645 while (bytes_read_ < sizeof(buf_)) {
646 ssize_t rv = HANDLE_EINTR(
647 read(fd, buf_ + bytes_read_, sizeof(buf_) - bytes_read_));
648 if (rv < 0) {
649 if (errno != EAGAIN && errno != EWOULDBLOCK) {
650 PLOG(ERROR) << "read() failed";
651 CloseSocket(fd);
652 return;
653 } else {
654 // It would block, so we just return and continue to watch for the next
655 // opportunity to read.
656 return;
658 } else if (!rv) {
659 // No more data to read. It's time to process the message.
660 break;
661 } else {
662 bytes_read_ += rv;
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();
672 return;
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();
683 return;
686 // Stop the expiration timer to prevent this SocketReader object from being
687 // terminated unexpectly.
688 timer_.Stop();
690 std::string current_dir = tokens[1];
691 // Remove the first two tokens. The remaining tokens should be the command
692 // line argv array.
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(
717 BrowserThread::IO,
718 FROM_HERE,
719 base::Bind(&ProcessSingleton::LinuxWatcher::RemoveSocketReader,
720 parent_,
721 this));
722 // We will be deleted once the posted RemoveSocketReader task runs.
725 ///////////////////////////////////////////////////////////////////////////////
726 // ProcessSingleton
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,
753 int retry_attempts,
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;
761 ScopedSocket socket;
762 for (int retries = 0; retries <= retry_attempts; ++retries) {
763 // Try to connect to the socket.
764 if (ConnectSocket(&socket, socket_path_, cookie_path_))
765 break;
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;
773 int pid;
774 if (!ParseLockPath(lock_path_, &hostname, &pid)) {
775 // No lockfile exists.
776 return PROCESS_NONE;
779 if (hostname.empty()) {
780 // Invalid lockfile.
781 UnlinkPath(lock_path_);
782 return PROCESS_NONE;
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_);
790 return PROCESS_NONE;
792 return PROFILE_IN_USE;
795 if (!IsChromeProcess(pid)) {
796 // Orphaned lockfile (no process with pid, or non-chrome process.)
797 UnlinkPath(lock_path_);
798 return PROCESS_NONE;
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_);
805 return PROCESS_NONE;
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;
812 return PROCESS_NONE;
815 base::PlatformThread::Sleep(sleep_interval);
818 timeval socket_timeout = TimeDeltaToTimeVal(timeout);
819 setsockopt(socket.fd(),
820 SOL_SOCKET,
821 SO_SNDTIMEO,
822 &socket_timeout,
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, &current_dir))
832 return PROCESS_NONE;
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);
839 to_send.append(*it);
842 // Send the message
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;
847 return PROCESS_NONE;
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.
859 if (len <= 0) {
860 if (!kill_unresponsive || !KillProcessByLockPath())
861 return PROFILE_IN_USE;
862 return PROCESS_NONE;
865 buf[len] = '\0';
866 if (strncmp(buf, kShutdownToken, arraysize(kShutdownToken) - 1) == 0) {
867 // The other process is shutting down, it's safe to start a new process.
868 return PROCESS_NONE;
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();
873 if (linux_ui)
874 linux_ui->NotifyWindowManagerStartupComplete();
875 #endif
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,
894 int retry_attempts,
895 const base::TimeDelta& timeout) {
896 NotifyResult result = NotifyOtherProcessWithTimeout(
897 command_line, retry_attempts, timeout, true);
898 if (result != PROCESS_NONE)
899 return result;
900 if (Create())
901 return 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
904 // we did.)
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)
910 return result;
912 return LOCK_ERROR;
915 void ProcessSingleton::OverrideCurrentPidForTesting(base::ProcessId pid) {
916 current_pid_ = 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() {
929 int sock;
930 sockaddr_un addr;
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(
935 "%s%c%u",
936 net::GetHostName().c_str(),
937 kLockDelimiter,
938 current_pid_));
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_)) {
951 return false;
953 #else
954 // If we failed to create the lock, most likely another instance won the
955 // startup race.
956 return false;
957 #endif
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.";
965 return false;
968 // Check that the directory was created with the correct permissions.
969 int dir_mode = 0;
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.";
990 return false;
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();
997 CloseSocket(sock);
998 return false;
1001 if (listen(sock, 5) < 0)
1002 NOTREACHED() << "listen failed: " << base::safe_strerror(errno);
1004 DCHECK(BrowserThread::IsMessageLoopValid(BrowserThread::IO));
1005 BrowserThread::PostTask(
1006 BrowserThread::IO,
1007 FROM_HERE,
1008 base::Bind(&ProcessSingleton::LinuxWatcher::StartListening,
1009 watcher_.get(),
1010 sock));
1012 return true;
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);
1025 if (pid < 0)
1026 return false;
1027 if (!IsChromeProcess(pid))
1028 return false;
1030 return true;
1033 bool ProcessSingleton::KillProcessByLockPath() {
1034 std::string hostname;
1035 int pid;
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))
1044 return true;
1046 if (pid > 0) {
1047 kill_callback_.Run(pid);
1048 return true;
1051 LOG(ERROR) << "Failed to extract pid from path: " << lock_path_.value();
1052 return true;
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);