Changes for start_with_ext Telemetry test to work on Windows.
[chromium-blink-merge.git] / chrome / browser / process_singleton_posix.cc
blob25e9eca031d66b6a01e9ad91830a5ec838e48e48
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 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);
119 if (-1 == flags)
120 return flags;
121 if (flags & O_NONBLOCK)
122 return 0;
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);
130 if (-1 == flags)
131 return flags;
132 if (flags & FD_CLOEXEC)
133 return 0;
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) {
145 DCHECK(message);
146 DCHECK(length);
147 size_t bytes_written = 0;
148 do {
149 ssize_t rv = HANDLE_EINTR(
150 write(fd, message + bytes_written, length - bytes_written));
151 if (rv < 0) {
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.";
156 return false;
158 PLOG(ERROR) << "write() failed";
159 return false;
161 bytes_written += rv;
162 } while (bytes_written < length);
164 return true;
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;
171 return result;
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
176 // ready for read.
177 int WaitSocketForRead(int fd, const base::TimeDelta& timeout) {
178 fd_set read_fds;
179 struct timeval tv = TimeDeltaToTimeVal(timeout);
181 FD_ZERO(&read_fds);
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,
191 char* buf,
192 size_t bufsize,
193 const base::TimeDelta& timeout) {
194 if (timeout > base::TimeDelta()) {
195 int rv = WaitSocketForRead(fd, timeout);
196 if (rv <= 0)
197 return rv;
200 size_t bytes_read = 0;
201 do {
202 ssize_t rv = HANDLE_EINTR(read(fd, buf + bytes_read, bufsize - bytes_read));
203 if (rv < 0) {
204 if (errno != EAGAIN && errno != EWOULDBLOCK) {
205 PLOG(ERROR) << "read() failed";
206 return rv;
207 } else {
208 // It would block, so we just return what has been read.
209 return bytes_read;
211 } else if (!rv) {
212 // No more data to read.
213 return bytes_read;
214 } else {
215 bytes_read += rv;
217 } while (bytes_read < bufsize);
219 return bytes_read;
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.";
240 return sock;
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";
257 return target;
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();
266 return rv == 0;
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
277 // startup race.
278 errno = saved_errno;
279 PLOG(ERROR) << "Failed to create " << path.value();
280 return false;
283 return true;
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,
290 int* pid) {
291 std::string real_path = ReadLink(path).value();
292 if (real_path.empty())
293 return false;
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,
298 // bail.
299 if (pos == std::string::npos) {
300 *hostname = "";
301 *pid = -1;
302 return true;
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))
309 *pid = -1;
311 return true;
314 // Returns true if the user opted to unlock the profile.
315 bool DisplayProfileInUseError(const base::FilePath& lock_path,
316 const std::string& hostname,
317 int pid) {
318 base::string16 error = l10n_util::GetStringFUTF16(
319 IDS_PROFILE_IN_USE_POSIX,
320 base::IntToString16(pid),
321 base::ASCIIToUTF16(hostname));
322 LOG(ERROR) << error;
324 if (g_disable_prompt)
325 return false;
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.
333 return true;
334 #endif
336 NOTREACHED();
337 return false;
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.
348 class ScopedSocket {
349 public:
350 ScopedSocket() : fd_(-1) { Reset(); }
351 ~ScopedSocket() { Close(); }
352 int fd() { return fd_; }
353 void Reset() {
354 Close();
355 fd_ = SetupSocketOnly();
357 void Close() {
358 if (fd_ >= 0)
359 CloseSocket(fd_);
360 fd_ = -1;
362 private:
363 int fd_;
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);
382 if (cookie.empty())
383 return false;
384 base::FilePath remote_cookie = socket_target.DirName().
385 Append(chrome::kSingletonCookieFilename);
386 // Verify the cookie before connecting.
387 if (!CheckCookie(remote_cookie, cookie))
388 return false;
389 // Now we know the directory was (at that point) created by the profile
390 // owner. Try to connect.
391 sockaddr_un addr;
392 SetupSockAddr(socket_target.value(), &addr);
393 int ret = HANDLE_EINTR(connect(socket->fd(),
394 reinterpret_cast<sockaddr*>(&addr),
395 sizeof(addr)));
396 if (ret != 0)
397 return false;
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)) {
402 socket->Reset();
403 return false;
405 // Success!
406 return true;
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.
410 sockaddr_un addr;
411 SetupSockAddr(socket_path.value(), &addr);
412 int ret = HANDLE_EINTR(connect(socket->fd(),
413 reinterpret_cast<sockaddr*>(&addr),
414 sizeof(addr)));
415 return (ret == 0);
416 } else {
417 // File is missing, or other error.
418 if (errno != ENOENT)
419 PLOG(ERROR) << "readlink failed";
420 return false;
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
428 // should quit.
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";
433 return false;
436 int rc = HANDLE_EINTR(flock(lock_fd.get(), LOCK_EX | LOCK_NB));
437 if (rc == -1) {
438 if (errno == EWOULDBLOCK) {
439 LOG(ERROR) << "Singleton lock held by old process.";
440 } else {
441 PLOG(ERROR) << "Error locking singleton lock";
443 return false;
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
449 // version has run.
450 if (!base::DeleteFile(lock_path, false)) {
451 PLOG(ERROR) << "Could not delete old singleton lock.";
452 return false;
455 return SymlinkPath(symlink_content, lock_path);
457 #endif // defined(OS_MACOSX)
459 } // namespace
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> {
471 public:
472 // A helper class to read message from an established socket.
473 class SocketReader : public base::MessageLoopForIO::Watcher {
474 public:
475 SocketReader(ProcessSingleton::LinuxWatcher* parent,
476 base::MessageLoop* ui_message_loop,
477 int fd)
478 : parent_(parent),
479 ui_message_loop_(ui_message_loop),
480 fd_(fd),
481 bytes_read_(0) {
482 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
483 // Wait for reads.
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.
497 NOTREACHED();
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);
504 private:
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.
521 const int fd_;
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
527 // reads.
528 size_t bytes_read_;
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()),
538 parent_(parent) {
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.
556 NOTREACHED();
559 // MessageLoop::DestructionObserver
560 void WillDestroyCurrentMessageLoop() override {
561 fd_watcher_.StopWatchingFileDescriptor();
564 private:
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
582 // constructed on).
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.
596 sockaddr_un from;
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";
602 return;
604 int rv = SetNonBlocking(connection_socket);
605 DCHECK_EQ(0, rv) << "Failed to make non-blocking socket.";
606 SocketReader* reader = new SocketReader(this,
607 ui_message_loop_,
608 connection_socket);
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,
618 &fd_watcher_, this);
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());
625 DCHECK(reader);
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);
631 } else {
632 LOG(WARNING) << "Not handling interprocess notification as browser"
633 " is shutting down";
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);
637 return;
641 void ProcessSingleton::LinuxWatcher::RemoveSocketReader(SocketReader* reader) {
642 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
643 DCHECK(reader);
644 readers_.erase(reader);
645 delete reader;
648 ///////////////////////////////////////////////////////////////////////////////
649 // ProcessSingleton::LinuxWatcher::SocketReader
652 void ProcessSingleton::LinuxWatcher::SocketReader::OnFileCanReadWithoutBlocking(
653 int fd) {
654 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
655 DCHECK_EQ(fd, fd_);
656 while (bytes_read_ < sizeof(buf_)) {
657 ssize_t rv = HANDLE_EINTR(
658 read(fd, buf_ + bytes_read_, sizeof(buf_) - bytes_read_));
659 if (rv < 0) {
660 if (errno != EAGAIN && errno != EWOULDBLOCK) {
661 PLOG(ERROR) << "read() failed";
662 CloseSocket(fd);
663 return;
664 } else {
665 // It would block, so we just return and continue to watch for the next
666 // opportunity to read.
667 return;
669 } else if (!rv) {
670 // No more data to read. It's time to process the message.
671 break;
672 } else {
673 bytes_read_ += rv;
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();
683 return;
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();
694 return;
697 // Stop the expiration timer to prevent this SocketReader object from being
698 // terminated unexpectly.
699 timer_.Stop();
701 std::string current_dir = tokens[1];
702 // Remove the first two tokens. The remaining tokens should be the command
703 // line argv array.
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(
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: " << base::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 << base::safe_strerror(errno);