Componentize HistoryURLProvider/ScoredHistoryMatch.
[chromium-blink-merge.git] / chrome / browser / process_singleton_posix.cc
blob6ccc2659d75ee8079721fa21477e4c8b1d943733
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;
688 base::SplitString(str, kTokenDelimiter, &tokens);
690 if (tokens.size() < 3 || tokens[0] != kStartToken) {
691 LOG(ERROR) << "Wrong message format: " << str;
692 CleanupAndDeleteSelf();
693 return;
696 // Stop the expiration timer to prevent this SocketReader object from being
697 // terminated unexpectly.
698 timer_.Stop();
700 std::string current_dir = tokens[1];
701 // Remove the first two tokens. The remaining tokens should be the command
702 // line argv array.
703 tokens.erase(tokens.begin());
704 tokens.erase(tokens.begin());
706 // Return to the UI thread to handle opening a new browser tab.
707 ui_message_loop_->task_runner()->PostTask(
708 FROM_HERE, base::Bind(&ProcessSingleton::LinuxWatcher::HandleMessage,
709 parent_, current_dir, tokens, this));
710 fd_reader_.StopWatchingFileDescriptor();
712 // LinuxWatcher::HandleMessage() is in charge of destroying this SocketReader
713 // object by invoking SocketReader::FinishWithACK().
716 void ProcessSingleton::LinuxWatcher::SocketReader::FinishWithACK(
717 const char *message, size_t length) {
718 if (message && length) {
719 // Not necessary to care about the return value.
720 WriteToSocket(fd_, message, length);
723 if (shutdown(fd_, SHUT_WR) < 0)
724 PLOG(ERROR) << "shutdown() failed";
726 BrowserThread::PostTask(
727 BrowserThread::IO,
728 FROM_HERE,
729 base::Bind(&ProcessSingleton::LinuxWatcher::RemoveSocketReader,
730 parent_,
731 this));
732 // We will be deleted once the posted RemoveSocketReader task runs.
735 ///////////////////////////////////////////////////////////////////////////////
736 // ProcessSingleton
738 ProcessSingleton::ProcessSingleton(
739 const base::FilePath& user_data_dir,
740 const NotificationCallback& notification_callback)
741 : notification_callback_(notification_callback),
742 current_pid_(base::GetCurrentProcId()),
743 watcher_(new LinuxWatcher(this)) {
744 socket_path_ = user_data_dir.Append(chrome::kSingletonSocketFilename);
745 lock_path_ = user_data_dir.Append(chrome::kSingletonLockFilename);
746 cookie_path_ = user_data_dir.Append(chrome::kSingletonCookieFilename);
748 kill_callback_ = base::Bind(&ProcessSingleton::KillProcess,
749 base::Unretained(this));
752 ProcessSingleton::~ProcessSingleton() {
755 ProcessSingleton::NotifyResult ProcessSingleton::NotifyOtherProcess() {
756 return NotifyOtherProcessWithTimeout(
757 *base::CommandLine::ForCurrentProcess(), kRetryAttempts,
758 base::TimeDelta::FromSeconds(kTimeoutInSeconds), true);
761 ProcessSingleton::NotifyResult ProcessSingleton::NotifyOtherProcessWithTimeout(
762 const base::CommandLine& cmd_line,
763 int retry_attempts,
764 const base::TimeDelta& timeout,
765 bool kill_unresponsive) {
766 DCHECK_GE(retry_attempts, 0);
767 DCHECK_GE(timeout.InMicroseconds(), 0);
769 base::TimeDelta sleep_interval = timeout / retry_attempts;
771 ScopedSocket socket;
772 for (int retries = 0; retries <= retry_attempts; ++retries) {
773 // Try to connect to the socket.
774 if (ConnectSocket(&socket, socket_path_, cookie_path_))
775 break;
777 // If we're in a race with another process, they may be in Create() and have
778 // created the lock but not attached to the socket. So we check if the
779 // process with the pid from the lockfile is currently running and is a
780 // chrome browser. If so, we loop and try again for |timeout|.
782 std::string hostname;
783 int pid;
784 if (!ParseLockPath(lock_path_, &hostname, &pid)) {
785 // No lockfile exists.
786 return PROCESS_NONE;
789 if (hostname.empty()) {
790 // Invalid lockfile.
791 UnlinkPath(lock_path_);
792 return PROCESS_NONE;
795 if (hostname != net::GetHostName() && !IsChromeProcess(pid)) {
796 // Locked by process on another host. If the user selected to unlock
797 // the profile, try to continue; otherwise quit.
798 if (DisplayProfileInUseError(lock_path_, hostname, pid)) {
799 UnlinkPath(lock_path_);
800 return PROCESS_NONE;
802 return PROFILE_IN_USE;
805 if (!IsChromeProcess(pid)) {
806 // Orphaned lockfile (no process with pid, or non-chrome process.)
807 UnlinkPath(lock_path_);
808 return PROCESS_NONE;
811 if (IsSameChromeInstance(pid)) {
812 // Orphaned lockfile (pid is part of same chrome instance we are, even
813 // though we haven't tried to create a lockfile yet).
814 UnlinkPath(lock_path_);
815 return PROCESS_NONE;
818 if (retries == retry_attempts) {
819 // Retries failed. Kill the unresponsive chrome process and continue.
820 if (!kill_unresponsive || !KillProcessByLockPath())
821 return PROFILE_IN_USE;
822 return PROCESS_NONE;
825 base::PlatformThread::Sleep(sleep_interval);
828 timeval socket_timeout = TimeDeltaToTimeVal(timeout);
829 setsockopt(socket.fd(),
830 SOL_SOCKET,
831 SO_SNDTIMEO,
832 &socket_timeout,
833 sizeof(socket_timeout));
835 // Found another process, prepare our command line
836 // format is "START\0<current dir>\0<argv[0]>\0...\0<argv[n]>".
837 std::string to_send(kStartToken);
838 to_send.push_back(kTokenDelimiter);
840 base::FilePath current_dir;
841 if (!PathService::Get(base::DIR_CURRENT, &current_dir))
842 return PROCESS_NONE;
843 to_send.append(current_dir.value());
845 const std::vector<std::string>& argv = cmd_line.argv();
846 for (std::vector<std::string>::const_iterator it = argv.begin();
847 it != argv.end(); ++it) {
848 to_send.push_back(kTokenDelimiter);
849 to_send.append(*it);
852 // Send the message
853 if (!WriteToSocket(socket.fd(), to_send.data(), to_send.length())) {
854 // Try to kill the other process, because it might have been dead.
855 if (!kill_unresponsive || !KillProcessByLockPath())
856 return PROFILE_IN_USE;
857 return PROCESS_NONE;
860 if (shutdown(socket.fd(), SHUT_WR) < 0)
861 PLOG(ERROR) << "shutdown() failed";
863 // Read ACK message from the other process. It might be blocked for a certain
864 // timeout, to make sure the other process has enough time to return ACK.
865 char buf[kMaxACKMessageLength + 1];
866 ssize_t len = ReadFromSocket(socket.fd(), buf, kMaxACKMessageLength, timeout);
868 // Failed to read ACK, the other process might have been frozen.
869 if (len <= 0) {
870 if (!kill_unresponsive || !KillProcessByLockPath())
871 return PROFILE_IN_USE;
872 return PROCESS_NONE;
875 buf[len] = '\0';
876 if (strncmp(buf, kShutdownToken, arraysize(kShutdownToken) - 1) == 0) {
877 // The other process is shutting down, it's safe to start a new process.
878 return PROCESS_NONE;
879 } else if (strncmp(buf, kACKToken, arraysize(kACKToken) - 1) == 0) {
880 #if defined(TOOLKIT_VIEWS) && defined(OS_LINUX) && !defined(OS_CHROMEOS)
881 // Likely NULL in unit tests.
882 views::LinuxUI* linux_ui = views::LinuxUI::instance();
883 if (linux_ui)
884 linux_ui->NotifyWindowManagerStartupComplete();
885 #endif
887 // Assume the other process is handling the request.
888 return PROCESS_NOTIFIED;
891 NOTREACHED() << "The other process returned unknown message: " << buf;
892 return PROCESS_NOTIFIED;
895 ProcessSingleton::NotifyResult ProcessSingleton::NotifyOtherProcessOrCreate() {
896 return NotifyOtherProcessWithTimeoutOrCreate(
897 *base::CommandLine::ForCurrentProcess(), kRetryAttempts,
898 base::TimeDelta::FromSeconds(kTimeoutInSeconds));
901 ProcessSingleton::NotifyResult
902 ProcessSingleton::NotifyOtherProcessWithTimeoutOrCreate(
903 const base::CommandLine& command_line,
904 int retry_attempts,
905 const base::TimeDelta& timeout) {
906 NotifyResult result = NotifyOtherProcessWithTimeout(
907 command_line, retry_attempts, timeout, true);
908 if (result != PROCESS_NONE)
909 return result;
910 if (Create())
911 return PROCESS_NONE;
912 // If the Create() failed, try again to notify. (It could be that another
913 // instance was starting at the same time and managed to grab the lock before
914 // we did.)
915 // This time, we don't want to kill anything if we aren't successful, since we
916 // aren't going to try to take over the lock ourselves.
917 result = NotifyOtherProcessWithTimeout(
918 command_line, retry_attempts, timeout, false);
919 if (result != PROCESS_NONE)
920 return result;
922 return LOCK_ERROR;
925 void ProcessSingleton::OverrideCurrentPidForTesting(base::ProcessId pid) {
926 current_pid_ = pid;
929 void ProcessSingleton::OverrideKillCallbackForTesting(
930 const base::Callback<void(int)>& callback) {
931 kill_callback_ = callback;
934 void ProcessSingleton::DisablePromptForTesting() {
935 g_disable_prompt = true;
938 bool ProcessSingleton::Create() {
939 int sock;
940 sockaddr_un addr;
942 // The symlink lock is pointed to the hostname and process id, so other
943 // processes can find it out.
944 base::FilePath symlink_content(base::StringPrintf(
945 "%s%c%u",
946 net::GetHostName().c_str(),
947 kLockDelimiter,
948 current_pid_));
950 // Create symbol link before binding the socket, to ensure only one instance
951 // can have the socket open.
952 if (!SymlinkPath(symlink_content, lock_path_)) {
953 // TODO(jackhou): Remove this case once this code is stable on Mac.
954 // http://crbug.com/367612
955 #if defined(OS_MACOSX)
956 // On Mac, an existing non-symlink lock file means the lock could be held by
957 // the old process singleton code. If we can successfully replace the lock,
958 // continue as normal.
959 if (base::IsLink(lock_path_) ||
960 !ReplaceOldSingletonLock(symlink_content, lock_path_)) {
961 return false;
963 #else
964 // If we failed to create the lock, most likely another instance won the
965 // startup race.
966 return false;
967 #endif
970 // Create the socket file somewhere in /tmp which is usually mounted as a
971 // normal filesystem. Some network filesystems (notably AFS) are screwy and
972 // do not support Unix domain sockets.
973 if (!socket_dir_.CreateUniqueTempDir()) {
974 LOG(ERROR) << "Failed to create socket directory.";
975 return false;
978 // Check that the directory was created with the correct permissions.
979 int dir_mode = 0;
980 CHECK(base::GetPosixFilePermissions(socket_dir_.path(), &dir_mode) &&
981 dir_mode == base::FILE_PERMISSION_USER_MASK)
982 << "Temp directory mode is not 700: " << std::oct << dir_mode;
984 // Setup the socket symlink and the two cookies.
985 base::FilePath socket_target_path =
986 socket_dir_.path().Append(chrome::kSingletonSocketFilename);
987 base::FilePath cookie(GenerateCookie());
988 base::FilePath remote_cookie_path =
989 socket_dir_.path().Append(chrome::kSingletonCookieFilename);
990 UnlinkPath(socket_path_);
991 UnlinkPath(cookie_path_);
992 if (!SymlinkPath(socket_target_path, socket_path_) ||
993 !SymlinkPath(cookie, cookie_path_) ||
994 !SymlinkPath(cookie, remote_cookie_path)) {
995 // We've already locked things, so we can't have lost the startup race,
996 // but something doesn't like us.
997 LOG(ERROR) << "Failed to create symlinks.";
998 if (!socket_dir_.Delete())
999 LOG(ERROR) << "Encountered a problem when deleting socket directory.";
1000 return false;
1003 SetupSocket(socket_target_path.value(), &sock, &addr);
1005 if (bind(sock, reinterpret_cast<sockaddr*>(&addr), sizeof(addr)) < 0) {
1006 PLOG(ERROR) << "Failed to bind() " << socket_target_path.value();
1007 CloseSocket(sock);
1008 return false;
1011 if (listen(sock, 5) < 0)
1012 NOTREACHED() << "listen failed: " << base::safe_strerror(errno);
1014 DCHECK(BrowserThread::IsMessageLoopValid(BrowserThread::IO));
1015 BrowserThread::PostTask(
1016 BrowserThread::IO,
1017 FROM_HERE,
1018 base::Bind(&ProcessSingleton::LinuxWatcher::StartListening,
1019 watcher_.get(),
1020 sock));
1022 return true;
1025 void ProcessSingleton::Cleanup() {
1026 UnlinkPath(socket_path_);
1027 UnlinkPath(cookie_path_);
1028 UnlinkPath(lock_path_);
1031 bool ProcessSingleton::IsSameChromeInstance(pid_t pid) {
1032 pid_t cur_pid = current_pid_;
1033 while (pid != cur_pid) {
1034 pid = base::GetParentProcessId(pid);
1035 if (pid < 0)
1036 return false;
1037 if (!IsChromeProcess(pid))
1038 return false;
1040 return true;
1043 bool ProcessSingleton::KillProcessByLockPath() {
1044 std::string hostname;
1045 int pid;
1046 ParseLockPath(lock_path_, &hostname, &pid);
1048 if (!hostname.empty() && hostname != net::GetHostName()) {
1049 return DisplayProfileInUseError(lock_path_, hostname, pid);
1051 UnlinkPath(lock_path_);
1053 if (IsSameChromeInstance(pid))
1054 return true;
1056 if (pid > 0) {
1057 kill_callback_.Run(pid);
1058 return true;
1061 LOG(ERROR) << "Failed to extract pid from path: " << lock_path_.value();
1062 return true;
1065 void ProcessSingleton::KillProcess(int pid) {
1066 // TODO(james.su@gmail.com): Is SIGKILL ok?
1067 int rv = kill(static_cast<base::ProcessHandle>(pid), SIGKILL);
1068 // ESRCH = No Such Process (can happen if the other process is already in
1069 // progress of shutting down and finishes before we try to kill it).
1070 DCHECK(rv == 0 || errno == ESRCH) << "Error killing process: "
1071 << base::safe_strerror(errno);