base::Time multiplicative operator overloading
[chromium-blink-merge.git] / chrome / browser / process_singleton_posix.cc
blob05e149951d70cd723cffb792c089b064c6273145
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/logging.h"
62 #include "base/message_loop/message_loop.h"
63 #include "base/path_service.h"
64 #include "base/posix/eintr_wrapper.h"
65 #include "base/rand_util.h"
66 #include "base/safe_strerror_posix.h"
67 #include "base/sequenced_task_runner_helpers.h"
68 #include "base/stl_util.h"
69 #include "base/strings/string_number_conversions.h"
70 #include "base/strings/string_split.h"
71 #include "base/strings/string_util.h"
72 #include "base/strings/stringprintf.h"
73 #include "base/strings/sys_string_conversions.h"
74 #include "base/strings/utf_string_conversions.h"
75 #include "base/threading/platform_thread.h"
76 #include "base/time/time.h"
77 #include "base/timer/timer.h"
78 #include "chrome/common/chrome_constants.h"
79 #include "chrome/grit/chromium_strings.h"
80 #include "chrome/grit/generated_resources.h"
81 #include "content/public/browser/browser_thread.h"
82 #include "net/base/net_util.h"
83 #include "ui/base/l10n/l10n_util.h"
85 #if defined(OS_LINUX)
86 #include "chrome/browser/ui/process_singleton_dialog_linux.h"
87 #endif
89 #if defined(TOOLKIT_VIEWS) && defined(OS_LINUX) && !defined(OS_CHROMEOS)
90 #include "ui/views/linux_ui/linux_ui.h"
91 #endif
93 using content::BrowserThread;
95 namespace {
97 // Timeout for the current browser process to respond. 20 seconds should be
98 // enough.
99 const int kTimeoutInSeconds = 20;
100 // Number of retries to notify the browser. 20 retries over 20 seconds = 1 try
101 // per second.
102 const int kRetryAttempts = 20;
103 static bool g_disable_prompt;
104 const char kStartToken[] = "START";
105 const char kACKToken[] = "ACK";
106 const char kShutdownToken[] = "SHUTDOWN";
107 const char kTokenDelimiter = '\0';
108 const int kMaxMessageLength = 32 * 1024;
109 const int kMaxACKMessageLength = arraysize(kShutdownToken) - 1;
111 const char kLockDelimiter = '-';
113 // Set a file descriptor to be non-blocking.
114 // Return 0 on success, -1 on failure.
115 int SetNonBlocking(int fd) {
116 int flags = fcntl(fd, F_GETFL, 0);
117 if (-1 == flags)
118 return flags;
119 if (flags & O_NONBLOCK)
120 return 0;
121 return fcntl(fd, F_SETFL, flags | O_NONBLOCK);
124 // Set the close-on-exec bit on a file descriptor.
125 // Returns 0 on success, -1 on failure.
126 int SetCloseOnExec(int fd) {
127 int flags = fcntl(fd, F_GETFD, 0);
128 if (-1 == flags)
129 return flags;
130 if (flags & FD_CLOEXEC)
131 return 0;
132 return fcntl(fd, F_SETFD, flags | FD_CLOEXEC);
135 // Close a socket and check return value.
136 void CloseSocket(int fd) {
137 int rv = IGNORE_EINTR(close(fd));
138 DCHECK_EQ(0, rv) << "Error closing socket: " << safe_strerror(errno);
141 // Write a message to a socket fd.
142 bool WriteToSocket(int fd, const char *message, size_t length) {
143 DCHECK(message);
144 DCHECK(length);
145 size_t bytes_written = 0;
146 do {
147 ssize_t rv = HANDLE_EINTR(
148 write(fd, message + bytes_written, length - bytes_written));
149 if (rv < 0) {
150 if (errno == EAGAIN || errno == EWOULDBLOCK) {
151 // The socket shouldn't block, we're sending so little data. Just give
152 // up here, since NotifyOtherProcess() doesn't have an asynchronous api.
153 LOG(ERROR) << "ProcessSingleton would block on write(), so it gave up.";
154 return false;
156 PLOG(ERROR) << "write() failed";
157 return false;
159 bytes_written += rv;
160 } while (bytes_written < length);
162 return true;
165 struct timeval TimeDeltaToTimeVal(const base::TimeDelta& delta) {
166 struct timeval result;
167 result.tv_sec = delta.InSeconds();
168 result.tv_usec = delta.InMicroseconds() % base::Time::kMicrosecondsPerSecond;
169 return result;
172 // Wait a socket for read for a certain timeout.
173 // Returns -1 if error occurred, 0 if timeout reached, > 0 if the socket is
174 // ready for read.
175 int WaitSocketForRead(int fd, const base::TimeDelta& timeout) {
176 fd_set read_fds;
177 struct timeval tv = TimeDeltaToTimeVal(timeout);
179 FD_ZERO(&read_fds);
180 FD_SET(fd, &read_fds);
182 return HANDLE_EINTR(select(fd + 1, &read_fds, NULL, NULL, &tv));
185 // Read a message from a socket fd, with an optional timeout.
186 // If |timeout| <= 0 then read immediately.
187 // Return number of bytes actually read, or -1 on error.
188 ssize_t ReadFromSocket(int fd,
189 char* buf,
190 size_t bufsize,
191 const base::TimeDelta& timeout) {
192 if (timeout > base::TimeDelta()) {
193 int rv = WaitSocketForRead(fd, timeout);
194 if (rv <= 0)
195 return rv;
198 size_t bytes_read = 0;
199 do {
200 ssize_t rv = HANDLE_EINTR(read(fd, buf + bytes_read, bufsize - bytes_read));
201 if (rv < 0) {
202 if (errno != EAGAIN && errno != EWOULDBLOCK) {
203 PLOG(ERROR) << "read() failed";
204 return rv;
205 } else {
206 // It would block, so we just return what has been read.
207 return bytes_read;
209 } else if (!rv) {
210 // No more data to read.
211 return bytes_read;
212 } else {
213 bytes_read += rv;
215 } while (bytes_read < bufsize);
217 return bytes_read;
220 // Set up a sockaddr appropriate for messaging.
221 void SetupSockAddr(const std::string& path, struct sockaddr_un* addr) {
222 addr->sun_family = AF_UNIX;
223 CHECK(path.length() < arraysize(addr->sun_path))
224 << "Socket path too long: " << path;
225 base::strlcpy(addr->sun_path, path.c_str(), arraysize(addr->sun_path));
228 // Set up a socket appropriate for messaging.
229 int SetupSocketOnly() {
230 int sock = socket(PF_UNIX, SOCK_STREAM, 0);
231 PCHECK(sock >= 0) << "socket() failed";
233 int rv = SetNonBlocking(sock);
234 DCHECK_EQ(0, rv) << "Failed to make non-blocking socket.";
235 rv = SetCloseOnExec(sock);
236 DCHECK_EQ(0, rv) << "Failed to set CLOEXEC on socket.";
238 return sock;
241 // Set up a socket and sockaddr appropriate for messaging.
242 void SetupSocket(const std::string& path, int* sock, struct sockaddr_un* addr) {
243 *sock = SetupSocketOnly();
244 SetupSockAddr(path, addr);
247 // Read a symbolic link, return empty string if given path is not a symbol link.
248 base::FilePath ReadLink(const base::FilePath& path) {
249 base::FilePath target;
250 if (!base::ReadSymbolicLink(path, &target)) {
251 // The only errno that should occur is ENOENT.
252 if (errno != 0 && errno != ENOENT)
253 PLOG(ERROR) << "readlink(" << path.value() << ") failed";
255 return target;
258 // Unlink a path. Return true on success.
259 bool UnlinkPath(const base::FilePath& path) {
260 int rv = unlink(path.value().c_str());
261 if (rv < 0 && errno != ENOENT)
262 PLOG(ERROR) << "Failed to unlink " << path.value();
264 return rv == 0;
267 // Create a symlink. Returns true on success.
268 bool SymlinkPath(const base::FilePath& target, const base::FilePath& path) {
269 if (!base::CreateSymbolicLink(target, path)) {
270 // Double check the value in case symlink suceeded but we got an incorrect
271 // failure due to NFS packet loss & retry.
272 int saved_errno = errno;
273 if (ReadLink(path) != target) {
274 // If we failed to create the lock, most likely another instance won the
275 // startup race.
276 errno = saved_errno;
277 PLOG(ERROR) << "Failed to create " << path.value();
278 return false;
281 return true;
284 // Extract the hostname and pid from the lock symlink.
285 // Returns true if the lock existed.
286 bool ParseLockPath(const base::FilePath& path,
287 std::string* hostname,
288 int* pid) {
289 std::string real_path = ReadLink(path).value();
290 if (real_path.empty())
291 return false;
293 std::string::size_type pos = real_path.rfind(kLockDelimiter);
295 // If the path is not a symbolic link, or doesn't contain what we expect,
296 // bail.
297 if (pos == std::string::npos) {
298 *hostname = "";
299 *pid = -1;
300 return true;
303 *hostname = real_path.substr(0, pos);
305 const std::string& pid_str = real_path.substr(pos + 1);
306 if (!base::StringToInt(pid_str, pid))
307 *pid = -1;
309 return true;
312 // Returns true if the user opted to unlock the profile.
313 bool DisplayProfileInUseError(const base::FilePath& lock_path,
314 const std::string& hostname,
315 int pid) {
316 base::string16 error = l10n_util::GetStringFUTF16(
317 IDS_PROFILE_IN_USE_POSIX,
318 base::IntToString16(pid),
319 base::ASCIIToUTF16(hostname));
320 LOG(ERROR) << error;
322 if (g_disable_prompt)
323 return false;
325 #if defined(OS_LINUX)
326 base::string16 relaunch_button_text = l10n_util::GetStringUTF16(
327 IDS_PROFILE_IN_USE_LINUX_RELAUNCH);
328 return ShowProcessSingletonDialog(error, relaunch_button_text);
329 #elif defined(OS_MACOSX)
330 // On Mac, always usurp the lock.
331 return true;
332 #endif
334 NOTREACHED();
335 return false;
338 bool IsChromeProcess(pid_t pid) {
339 base::FilePath other_chrome_path(base::GetProcessExecutablePath(pid));
340 return (!other_chrome_path.empty() &&
341 other_chrome_path.BaseName() ==
342 base::FilePath(chrome::kBrowserProcessExecutableName));
345 // A helper class to hold onto a socket.
346 class ScopedSocket {
347 public:
348 ScopedSocket() : fd_(-1) { Reset(); }
349 ~ScopedSocket() { Close(); }
350 int fd() { return fd_; }
351 void Reset() {
352 Close();
353 fd_ = SetupSocketOnly();
355 void Close() {
356 if (fd_ >= 0)
357 CloseSocket(fd_);
358 fd_ = -1;
360 private:
361 int fd_;
364 // Returns a random string for uniquifying profile connections.
365 std::string GenerateCookie() {
366 return base::Uint64ToString(base::RandUint64());
369 bool CheckCookie(const base::FilePath& path, const base::FilePath& cookie) {
370 return (cookie == ReadLink(path));
373 bool ConnectSocket(ScopedSocket* socket,
374 const base::FilePath& socket_path,
375 const base::FilePath& cookie_path) {
376 base::FilePath socket_target;
377 if (base::ReadSymbolicLink(socket_path, &socket_target)) {
378 // It's a symlink. Read the cookie.
379 base::FilePath cookie = ReadLink(cookie_path);
380 if (cookie.empty())
381 return false;
382 base::FilePath remote_cookie = socket_target.DirName().
383 Append(chrome::kSingletonCookieFilename);
384 // Verify the cookie before connecting.
385 if (!CheckCookie(remote_cookie, cookie))
386 return false;
387 // Now we know the directory was (at that point) created by the profile
388 // owner. Try to connect.
389 sockaddr_un addr;
390 SetupSockAddr(socket_target.value(), &addr);
391 int ret = HANDLE_EINTR(connect(socket->fd(),
392 reinterpret_cast<sockaddr*>(&addr),
393 sizeof(addr)));
394 if (ret != 0)
395 return false;
396 // Check the cookie again. We only link in /tmp, which is sticky, so, if the
397 // directory is still correct, it must have been correct in-between when we
398 // connected. POSIX, sadly, lacks a connectat().
399 if (!CheckCookie(remote_cookie, cookie)) {
400 socket->Reset();
401 return false;
403 // Success!
404 return true;
405 } else if (errno == EINVAL) {
406 // It exists, but is not a symlink (or some other error we detect
407 // later). Just connect to it directly; this is an older version of Chrome.
408 sockaddr_un addr;
409 SetupSockAddr(socket_path.value(), &addr);
410 int ret = HANDLE_EINTR(connect(socket->fd(),
411 reinterpret_cast<sockaddr*>(&addr),
412 sizeof(addr)));
413 return (ret == 0);
414 } else {
415 // File is missing, or other error.
416 if (errno != ENOENT)
417 PLOG(ERROR) << "readlink failed";
418 return false;
422 #if defined(OS_MACOSX)
423 bool ReplaceOldSingletonLock(const base::FilePath& symlink_content,
424 const base::FilePath& lock_path) {
425 // Try taking an flock(2) on the file. Failure means the lock is taken so we
426 // should quit.
427 base::ScopedFD lock_fd(HANDLE_EINTR(
428 open(lock_path.value().c_str(), O_RDWR | O_CREAT | O_SYMLINK, 0644)));
429 if (!lock_fd.is_valid()) {
430 PLOG(ERROR) << "Could not open singleton lock";
431 return false;
434 int rc = HANDLE_EINTR(flock(lock_fd.get(), LOCK_EX | LOCK_NB));
435 if (rc == -1) {
436 if (errno == EWOULDBLOCK) {
437 LOG(ERROR) << "Singleton lock held by old process.";
438 } else {
439 PLOG(ERROR) << "Error locking singleton lock";
441 return false;
444 // Successfully taking the lock means we can replace it with the a new symlink
445 // lock. We never flock() the lock file from now on. I.e. we assume that an
446 // old version of Chrome will not run with the same user data dir after this
447 // version has run.
448 if (!base::DeleteFile(lock_path, false)) {
449 PLOG(ERROR) << "Could not delete old singleton lock.";
450 return false;
453 return SymlinkPath(symlink_content, lock_path);
455 #endif // defined(OS_MACOSX)
457 } // namespace
459 ///////////////////////////////////////////////////////////////////////////////
460 // ProcessSingleton::LinuxWatcher
461 // A helper class for a Linux specific implementation of the process singleton.
462 // This class sets up a listener on the singleton socket and handles parsing
463 // messages that come in on the singleton socket.
464 class ProcessSingleton::LinuxWatcher
465 : public base::MessageLoopForIO::Watcher,
466 public base::MessageLoop::DestructionObserver,
467 public base::RefCountedThreadSafe<ProcessSingleton::LinuxWatcher,
468 BrowserThread::DeleteOnIOThread> {
469 public:
470 // A helper class to read message from an established socket.
471 class SocketReader : public base::MessageLoopForIO::Watcher {
472 public:
473 SocketReader(ProcessSingleton::LinuxWatcher* parent,
474 base::MessageLoop* ui_message_loop,
475 int fd)
476 : parent_(parent),
477 ui_message_loop_(ui_message_loop),
478 fd_(fd),
479 bytes_read_(0) {
480 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
481 // Wait for reads.
482 base::MessageLoopForIO::current()->WatchFileDescriptor(
483 fd, true, base::MessageLoopForIO::WATCH_READ, &fd_reader_, this);
484 // If we haven't completed in a reasonable amount of time, give up.
485 timer_.Start(FROM_HERE, base::TimeDelta::FromSeconds(kTimeoutInSeconds),
486 this, &SocketReader::CleanupAndDeleteSelf);
489 ~SocketReader() override { CloseSocket(fd_); }
491 // MessageLoopForIO::Watcher impl.
492 void OnFileCanReadWithoutBlocking(int fd) override;
493 void OnFileCanWriteWithoutBlocking(int fd) override {
494 // SocketReader only watches for accept (read) events.
495 NOTREACHED();
498 // Finish handling the incoming message by optionally sending back an ACK
499 // message and removing this SocketReader.
500 void FinishWithACK(const char *message, size_t length);
502 private:
503 void CleanupAndDeleteSelf() {
504 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
506 parent_->RemoveSocketReader(this);
507 // We're deleted beyond this point.
510 base::MessageLoopForIO::FileDescriptorWatcher fd_reader_;
512 // The ProcessSingleton::LinuxWatcher that owns us.
513 ProcessSingleton::LinuxWatcher* const parent_;
515 // A reference to the UI message loop.
516 base::MessageLoop* const ui_message_loop_;
518 // The file descriptor we're reading.
519 const int fd_;
521 // Store the message in this buffer.
522 char buf_[kMaxMessageLength];
524 // Tracks the number of bytes we've read in case we're getting partial
525 // reads.
526 size_t bytes_read_;
528 base::OneShotTimer<SocketReader> timer_;
530 DISALLOW_COPY_AND_ASSIGN(SocketReader);
533 // We expect to only be constructed on the UI thread.
534 explicit LinuxWatcher(ProcessSingleton* parent)
535 : ui_message_loop_(base::MessageLoop::current()),
536 parent_(parent) {
539 // Start listening for connections on the socket. This method should be
540 // called from the IO thread.
541 void StartListening(int socket);
543 // This method determines if we should use the same process and if we should,
544 // opens a new browser tab. This runs on the UI thread.
545 // |reader| is for sending back ACK message.
546 void HandleMessage(const std::string& current_dir,
547 const std::vector<std::string>& argv,
548 SocketReader* reader);
550 // MessageLoopForIO::Watcher impl. These run on the IO thread.
551 void OnFileCanReadWithoutBlocking(int fd) override;
552 void OnFileCanWriteWithoutBlocking(int fd) override {
553 // ProcessSingleton only watches for accept (read) events.
554 NOTREACHED();
557 // MessageLoop::DestructionObserver
558 void WillDestroyCurrentMessageLoop() override {
559 fd_watcher_.StopWatchingFileDescriptor();
562 private:
563 friend struct BrowserThread::DeleteOnThread<BrowserThread::IO>;
564 friend class base::DeleteHelper<ProcessSingleton::LinuxWatcher>;
566 ~LinuxWatcher() override {
567 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
568 STLDeleteElements(&readers_);
570 base::MessageLoopForIO* ml = base::MessageLoopForIO::current();
571 ml->RemoveDestructionObserver(this);
574 // Removes and deletes the SocketReader.
575 void RemoveSocketReader(SocketReader* reader);
577 base::MessageLoopForIO::FileDescriptorWatcher fd_watcher_;
579 // A reference to the UI message loop (i.e., the message loop we were
580 // constructed on).
581 base::MessageLoop* ui_message_loop_;
583 // The ProcessSingleton that owns us.
584 ProcessSingleton* const parent_;
586 std::set<SocketReader*> readers_;
588 DISALLOW_COPY_AND_ASSIGN(LinuxWatcher);
591 void ProcessSingleton::LinuxWatcher::OnFileCanReadWithoutBlocking(int fd) {
592 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
593 // Accepting incoming client.
594 sockaddr_un from;
595 socklen_t from_len = sizeof(from);
596 int connection_socket = HANDLE_EINTR(accept(
597 fd, reinterpret_cast<sockaddr*>(&from), &from_len));
598 if (-1 == connection_socket) {
599 PLOG(ERROR) << "accept() failed";
600 return;
602 int rv = SetNonBlocking(connection_socket);
603 DCHECK_EQ(0, rv) << "Failed to make non-blocking socket.";
604 SocketReader* reader = new SocketReader(this,
605 ui_message_loop_,
606 connection_socket);
607 readers_.insert(reader);
610 void ProcessSingleton::LinuxWatcher::StartListening(int socket) {
611 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
612 // Watch for client connections on this socket.
613 base::MessageLoopForIO* ml = base::MessageLoopForIO::current();
614 ml->AddDestructionObserver(this);
615 ml->WatchFileDescriptor(socket, true, base::MessageLoopForIO::WATCH_READ,
616 &fd_watcher_, this);
619 void ProcessSingleton::LinuxWatcher::HandleMessage(
620 const std::string& current_dir, const std::vector<std::string>& argv,
621 SocketReader* reader) {
622 DCHECK(ui_message_loop_ == base::MessageLoop::current());
623 DCHECK(reader);
625 if (parent_->notification_callback_.Run(base::CommandLine(argv),
626 base::FilePath(current_dir))) {
627 // Send back "ACK" message to prevent the client process from starting up.
628 reader->FinishWithACK(kACKToken, arraysize(kACKToken) - 1);
629 } else {
630 LOG(WARNING) << "Not handling interprocess notification as browser"
631 " is shutting down";
632 // Send back "SHUTDOWN" message, so that the client process can start up
633 // without killing this process.
634 reader->FinishWithACK(kShutdownToken, arraysize(kShutdownToken) - 1);
635 return;
639 void ProcessSingleton::LinuxWatcher::RemoveSocketReader(SocketReader* reader) {
640 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
641 DCHECK(reader);
642 readers_.erase(reader);
643 delete reader;
646 ///////////////////////////////////////////////////////////////////////////////
647 // ProcessSingleton::LinuxWatcher::SocketReader
650 void ProcessSingleton::LinuxWatcher::SocketReader::OnFileCanReadWithoutBlocking(
651 int fd) {
652 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
653 DCHECK_EQ(fd, fd_);
654 while (bytes_read_ < sizeof(buf_)) {
655 ssize_t rv = HANDLE_EINTR(
656 read(fd, buf_ + bytes_read_, sizeof(buf_) - bytes_read_));
657 if (rv < 0) {
658 if (errno != EAGAIN && errno != EWOULDBLOCK) {
659 PLOG(ERROR) << "read() failed";
660 CloseSocket(fd);
661 return;
662 } else {
663 // It would block, so we just return and continue to watch for the next
664 // opportunity to read.
665 return;
667 } else if (!rv) {
668 // No more data to read. It's time to process the message.
669 break;
670 } else {
671 bytes_read_ += rv;
675 // Validate the message. The shortest message is kStartToken\0x\0x
676 const size_t kMinMessageLength = arraysize(kStartToken) + 4;
677 if (bytes_read_ < kMinMessageLength) {
678 buf_[bytes_read_] = 0;
679 LOG(ERROR) << "Invalid socket message (wrong length):" << buf_;
680 CleanupAndDeleteSelf();
681 return;
684 std::string str(buf_, bytes_read_);
685 std::vector<std::string> tokens;
686 base::SplitString(str, kTokenDelimiter, &tokens);
688 if (tokens.size() < 3 || tokens[0] != kStartToken) {
689 LOG(ERROR) << "Wrong message format: " << str;
690 CleanupAndDeleteSelf();
691 return;
694 // Stop the expiration timer to prevent this SocketReader object from being
695 // terminated unexpectly.
696 timer_.Stop();
698 std::string current_dir = tokens[1];
699 // Remove the first two tokens. The remaining tokens should be the command
700 // line argv array.
701 tokens.erase(tokens.begin());
702 tokens.erase(tokens.begin());
704 // Return to the UI thread to handle opening a new browser tab.
705 ui_message_loop_->PostTask(FROM_HERE, base::Bind(
706 &ProcessSingleton::LinuxWatcher::HandleMessage,
707 parent_,
708 current_dir,
709 tokens,
710 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(
728 BrowserThread::IO,
729 FROM_HERE,
730 base::Bind(&ProcessSingleton::LinuxWatcher::RemoveSocketReader,
731 parent_,
732 this));
733 // We will be deleted once the posted RemoveSocketReader task runs.
736 ///////////////////////////////////////////////////////////////////////////////
737 // ProcessSingleton
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,
764 int retry_attempts,
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;
772 ScopedSocket socket;
773 for (int retries = 0; retries <= retry_attempts; ++retries) {
774 // Try to connect to the socket.
775 if (ConnectSocket(&socket, socket_path_, cookie_path_))
776 break;
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;
784 int pid;
785 if (!ParseLockPath(lock_path_, &hostname, &pid)) {
786 // No lockfile exists.
787 return PROCESS_NONE;
790 if (hostname.empty()) {
791 // Invalid lockfile.
792 UnlinkPath(lock_path_);
793 return PROCESS_NONE;
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_);
801 return PROCESS_NONE;
803 return PROFILE_IN_USE;
806 if (!IsChromeProcess(pid)) {
807 // Orphaned lockfile (no process with pid, or non-chrome process.)
808 UnlinkPath(lock_path_);
809 return PROCESS_NONE;
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_);
816 return PROCESS_NONE;
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;
823 return PROCESS_NONE;
826 base::PlatformThread::Sleep(sleep_interval);
829 timeval socket_timeout = TimeDeltaToTimeVal(timeout);
830 setsockopt(socket.fd(),
831 SOL_SOCKET,
832 SO_SNDTIMEO,
833 &socket_timeout,
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, &current_dir))
843 return PROCESS_NONE;
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);
850 to_send.append(*it);
853 // Send the message
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;
858 return PROCESS_NONE;
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.
870 if (len <= 0) {
871 if (!kill_unresponsive || !KillProcessByLockPath())
872 return PROFILE_IN_USE;
873 return PROCESS_NONE;
876 buf[len] = '\0';
877 if (strncmp(buf, kShutdownToken, arraysize(kShutdownToken) - 1) == 0) {
878 // The other process is shutting down, it's safe to start a new process.
879 return PROCESS_NONE;
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();
884 if (linux_ui)
885 linux_ui->NotifyWindowManagerStartupComplete();
886 #endif
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,
905 int retry_attempts,
906 const base::TimeDelta& timeout) {
907 NotifyResult result = NotifyOtherProcessWithTimeout(
908 command_line, retry_attempts, timeout, true);
909 if (result != PROCESS_NONE)
910 return result;
911 if (Create())
912 return 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
915 // we did.)
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)
921 return result;
923 return LOCK_ERROR;
926 void ProcessSingleton::OverrideCurrentPidForTesting(base::ProcessId pid) {
927 current_pid_ = 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() {
940 int sock;
941 sockaddr_un addr;
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(
946 "%s%c%u",
947 net::GetHostName().c_str(),
948 kLockDelimiter,
949 current_pid_));
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_)) {
962 return false;
964 #else
965 // If we failed to create the lock, most likely another instance won the
966 // startup race.
967 return false;
968 #endif
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.";
976 return false;
979 // Check that the directory was created with the correct permissions.
980 int dir_mode = 0;
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.";
1001 return false;
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();
1008 CloseSocket(sock);
1009 return false;
1012 if (listen(sock, 5) < 0)
1013 NOTREACHED() << "listen failed: " << safe_strerror(errno);
1015 DCHECK(BrowserThread::IsMessageLoopValid(BrowserThread::IO));
1016 BrowserThread::PostTask(
1017 BrowserThread::IO,
1018 FROM_HERE,
1019 base::Bind(&ProcessSingleton::LinuxWatcher::StartListening,
1020 watcher_.get(),
1021 sock));
1023 return true;
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);
1036 if (pid < 0)
1037 return false;
1038 if (!IsChromeProcess(pid))
1039 return false;
1041 return true;
1044 bool ProcessSingleton::KillProcessByLockPath() {
1045 std::string hostname;
1046 int pid;
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))
1055 return true;
1057 if (pid > 0) {
1058 kill_callback_.Run(pid);
1059 return true;
1062 LOG(ERROR) << "Failed to extract pid from path: " << lock_path_.value();
1063 return true;
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 << safe_strerror(errno);