[safe-browsing] Database full hash matches like prefix match.
[chromium-blink-merge.git] / chrome / browser / process_singleton_linux.cc
blob54d7db296f329d29016c8f5ba35d64bbefadd778
1 // Copyright (c) 2012 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/file_util.h"
60 #include "base/files/file_path.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/stringprintf.h"
72 #include "base/strings/sys_string_conversions.h"
73 #include "base/strings/utf_string_conversions.h"
74 #include "base/threading/platform_thread.h"
75 #include "base/time/time.h"
76 #include "base/timer/timer.h"
77 #include "chrome/browser/ui/process_singleton_dialog_linux.h"
78 #include "chrome/common/chrome_constants.h"
79 #include "content/public/browser/browser_thread.h"
80 #include "grit/chromium_strings.h"
81 #include "grit/generated_resources.h"
82 #include "net/base/net_util.h"
83 #include "ui/base/l10n/l10n_util.h"
85 #if defined(TOOLKIT_VIEWS) && !defined(OS_CHROMEOS)
86 #include "ui/views/linux_ui/linux_ui.h"
87 #endif
89 using content::BrowserThread;
91 const int ProcessSingleton::kTimeoutInSeconds;
93 namespace {
95 static bool g_disable_prompt;
96 const char kStartToken[] = "START";
97 const char kACKToken[] = "ACK";
98 const char kShutdownToken[] = "SHUTDOWN";
99 const char kTokenDelimiter = '\0';
100 const int kMaxMessageLength = 32 * 1024;
101 const int kMaxACKMessageLength = arraysize(kShutdownToken) - 1;
103 const char kLockDelimiter = '-';
105 // Set a file descriptor to be non-blocking.
106 // Return 0 on success, -1 on failure.
107 int SetNonBlocking(int fd) {
108 int flags = fcntl(fd, F_GETFL, 0);
109 if (-1 == flags)
110 return flags;
111 if (flags & O_NONBLOCK)
112 return 0;
113 return fcntl(fd, F_SETFL, flags | O_NONBLOCK);
116 // Set the close-on-exec bit on a file descriptor.
117 // Returns 0 on success, -1 on failure.
118 int SetCloseOnExec(int fd) {
119 int flags = fcntl(fd, F_GETFD, 0);
120 if (-1 == flags)
121 return flags;
122 if (flags & FD_CLOEXEC)
123 return 0;
124 return fcntl(fd, F_SETFD, flags | FD_CLOEXEC);
127 // Close a socket and check return value.
128 void CloseSocket(int fd) {
129 int rv = IGNORE_EINTR(close(fd));
130 DCHECK_EQ(0, rv) << "Error closing socket: " << safe_strerror(errno);
133 // Write a message to a socket fd.
134 bool WriteToSocket(int fd, const char *message, size_t length) {
135 DCHECK(message);
136 DCHECK(length);
137 size_t bytes_written = 0;
138 do {
139 ssize_t rv = HANDLE_EINTR(
140 write(fd, message + bytes_written, length - bytes_written));
141 if (rv < 0) {
142 if (errno == EAGAIN || errno == EWOULDBLOCK) {
143 // The socket shouldn't block, we're sending so little data. Just give
144 // up here, since NotifyOtherProcess() doesn't have an asynchronous api.
145 LOG(ERROR) << "ProcessSingleton would block on write(), so it gave up.";
146 return false;
148 PLOG(ERROR) << "write() failed";
149 return false;
151 bytes_written += rv;
152 } while (bytes_written < length);
154 return true;
157 // Wait a socket for read for a certain timeout in seconds.
158 // Returns -1 if error occurred, 0 if timeout reached, > 0 if the socket is
159 // ready for read.
160 int WaitSocketForRead(int fd, int timeout) {
161 fd_set read_fds;
162 struct timeval tv;
164 FD_ZERO(&read_fds);
165 FD_SET(fd, &read_fds);
166 tv.tv_sec = timeout;
167 tv.tv_usec = 0;
169 return HANDLE_EINTR(select(fd + 1, &read_fds, NULL, NULL, &tv));
172 // Read a message from a socket fd, with an optional timeout in seconds.
173 // If |timeout| <= 0 then read immediately.
174 // Return number of bytes actually read, or -1 on error.
175 ssize_t ReadFromSocket(int fd, char *buf, size_t bufsize, int timeout) {
176 if (timeout > 0) {
177 int rv = WaitSocketForRead(fd, timeout);
178 if (rv <= 0)
179 return rv;
182 size_t bytes_read = 0;
183 do {
184 ssize_t rv = HANDLE_EINTR(read(fd, buf + bytes_read, bufsize - bytes_read));
185 if (rv < 0) {
186 if (errno != EAGAIN && errno != EWOULDBLOCK) {
187 PLOG(ERROR) << "read() failed";
188 return rv;
189 } else {
190 // It would block, so we just return what has been read.
191 return bytes_read;
193 } else if (!rv) {
194 // No more data to read.
195 return bytes_read;
196 } else {
197 bytes_read += rv;
199 } while (bytes_read < bufsize);
201 return bytes_read;
204 // Set up a sockaddr appropriate for messaging.
205 void SetupSockAddr(const std::string& path, struct sockaddr_un* addr) {
206 addr->sun_family = AF_UNIX;
207 CHECK(path.length() < arraysize(addr->sun_path))
208 << "Socket path too long: " << path;
209 base::strlcpy(addr->sun_path, path.c_str(), arraysize(addr->sun_path));
212 // Set up a socket appropriate for messaging.
213 int SetupSocketOnly() {
214 int sock = socket(PF_UNIX, SOCK_STREAM, 0);
215 PCHECK(sock >= 0) << "socket() failed";
217 int rv = SetNonBlocking(sock);
218 DCHECK_EQ(0, rv) << "Failed to make non-blocking socket.";
219 rv = SetCloseOnExec(sock);
220 DCHECK_EQ(0, rv) << "Failed to set CLOEXEC on socket.";
222 return sock;
225 // Set up a socket and sockaddr appropriate for messaging.
226 void SetupSocket(const std::string& path, int* sock, struct sockaddr_un* addr) {
227 *sock = SetupSocketOnly();
228 SetupSockAddr(path, addr);
231 // Read a symbolic link, return empty string if given path is not a symbol link.
232 base::FilePath ReadLink(const base::FilePath& path) {
233 base::FilePath target;
234 if (!base::ReadSymbolicLink(path, &target)) {
235 // The only errno that should occur is ENOENT.
236 if (errno != 0 && errno != ENOENT)
237 PLOG(ERROR) << "readlink(" << path.value() << ") failed";
239 return target;
242 // Unlink a path. Return true on success.
243 bool UnlinkPath(const base::FilePath& path) {
244 int rv = unlink(path.value().c_str());
245 if (rv < 0 && errno != ENOENT)
246 PLOG(ERROR) << "Failed to unlink " << path.value();
248 return rv == 0;
251 // Create a symlink. Returns true on success.
252 bool SymlinkPath(const base::FilePath& target, const base::FilePath& path) {
253 if (!base::CreateSymbolicLink(target, path)) {
254 // Double check the value in case symlink suceeded but we got an incorrect
255 // failure due to NFS packet loss & retry.
256 int saved_errno = errno;
257 if (ReadLink(path) != target) {
258 // If we failed to create the lock, most likely another instance won the
259 // startup race.
260 errno = saved_errno;
261 PLOG(ERROR) << "Failed to create " << path.value();
262 return false;
265 return true;
268 // Extract the hostname and pid from the lock symlink.
269 // Returns true if the lock existed.
270 bool ParseLockPath(const base::FilePath& path,
271 std::string* hostname,
272 int* pid) {
273 std::string real_path = ReadLink(path).value();
274 if (real_path.empty())
275 return false;
277 std::string::size_type pos = real_path.rfind(kLockDelimiter);
279 // If the path is not a symbolic link, or doesn't contain what we expect,
280 // bail.
281 if (pos == std::string::npos) {
282 *hostname = "";
283 *pid = -1;
284 return true;
287 *hostname = real_path.substr(0, pos);
289 const std::string& pid_str = real_path.substr(pos + 1);
290 if (!base::StringToInt(pid_str, pid))
291 *pid = -1;
293 return true;
296 // Returns true if the user opted to unlock the profile.
297 bool DisplayProfileInUseError(const base::FilePath& lock_path,
298 const std::string& hostname,
299 int pid) {
300 base::string16 error = l10n_util::GetStringFUTF16(
301 IDS_PROFILE_IN_USE_LINUX,
302 base::IntToString16(pid),
303 base::ASCIIToUTF16(hostname));
304 base::string16 relaunch_button_text = l10n_util::GetStringUTF16(
305 IDS_PROFILE_IN_USE_LINUX_RELAUNCH);
306 LOG(ERROR) << base::SysWideToNativeMB(base::UTF16ToWide(error)).c_str();
307 if (!g_disable_prompt)
308 return ShowProcessSingletonDialog(error, relaunch_button_text);
309 return false;
312 bool IsChromeProcess(pid_t pid) {
313 base::FilePath other_chrome_path(base::GetProcessExecutablePath(pid));
314 return (!other_chrome_path.empty() &&
315 other_chrome_path.BaseName() ==
316 base::FilePath(chrome::kBrowserProcessExecutableName));
319 // A helper class to hold onto a socket.
320 class ScopedSocket {
321 public:
322 ScopedSocket() : fd_(-1) { Reset(); }
323 ~ScopedSocket() { Close(); }
324 int fd() { return fd_; }
325 void Reset() {
326 Close();
327 fd_ = SetupSocketOnly();
329 void Close() {
330 if (fd_ >= 0)
331 CloseSocket(fd_);
332 fd_ = -1;
334 private:
335 int fd_;
338 // Returns a random string for uniquifying profile connections.
339 std::string GenerateCookie() {
340 return base::Uint64ToString(base::RandUint64());
343 bool CheckCookie(const base::FilePath& path, const base::FilePath& cookie) {
344 return (cookie == ReadLink(path));
347 bool ConnectSocket(ScopedSocket* socket,
348 const base::FilePath& socket_path,
349 const base::FilePath& cookie_path) {
350 base::FilePath socket_target;
351 if (base::ReadSymbolicLink(socket_path, &socket_target)) {
352 // It's a symlink. Read the cookie.
353 base::FilePath cookie = ReadLink(cookie_path);
354 if (cookie.empty())
355 return false;
356 base::FilePath remote_cookie = socket_target.DirName().
357 Append(chrome::kSingletonCookieFilename);
358 // Verify the cookie before connecting.
359 if (!CheckCookie(remote_cookie, cookie))
360 return false;
361 // Now we know the directory was (at that point) created by the profile
362 // owner. Try to connect.
363 sockaddr_un addr;
364 SetupSockAddr(socket_path.value(), &addr);
365 int ret = HANDLE_EINTR(connect(socket->fd(),
366 reinterpret_cast<sockaddr*>(&addr),
367 sizeof(addr)));
368 if (ret != 0)
369 return false;
370 // Check the cookie again. We only link in /tmp, which is sticky, so, if the
371 // directory is still correct, it must have been correct in-between when we
372 // connected. POSIX, sadly, lacks a connectat().
373 if (!CheckCookie(remote_cookie, cookie)) {
374 socket->Reset();
375 return false;
377 // Success!
378 return true;
379 } else if (errno == EINVAL) {
380 // It exists, but is not a symlink (or some other error we detect
381 // later). Just connect to it directly; this is an older version of Chrome.
382 sockaddr_un addr;
383 SetupSockAddr(socket_path.value(), &addr);
384 int ret = HANDLE_EINTR(connect(socket->fd(),
385 reinterpret_cast<sockaddr*>(&addr),
386 sizeof(addr)));
387 return (ret == 0);
388 } else {
389 // File is missing, or other error.
390 if (errno != ENOENT)
391 PLOG(ERROR) << "readlink failed";
392 return false;
396 } // namespace
398 ///////////////////////////////////////////////////////////////////////////////
399 // ProcessSingleton::LinuxWatcher
400 // A helper class for a Linux specific implementation of the process singleton.
401 // This class sets up a listener on the singleton socket and handles parsing
402 // messages that come in on the singleton socket.
403 class ProcessSingleton::LinuxWatcher
404 : public base::MessageLoopForIO::Watcher,
405 public base::MessageLoop::DestructionObserver,
406 public base::RefCountedThreadSafe<ProcessSingleton::LinuxWatcher,
407 BrowserThread::DeleteOnIOThread> {
408 public:
409 // A helper class to read message from an established socket.
410 class SocketReader : public base::MessageLoopForIO::Watcher {
411 public:
412 SocketReader(ProcessSingleton::LinuxWatcher* parent,
413 base::MessageLoop* ui_message_loop,
414 int fd)
415 : parent_(parent),
416 ui_message_loop_(ui_message_loop),
417 fd_(fd),
418 bytes_read_(0) {
419 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
420 // Wait for reads.
421 base::MessageLoopForIO::current()->WatchFileDescriptor(
422 fd, true, base::MessageLoopForIO::WATCH_READ, &fd_reader_, this);
423 // If we haven't completed in a reasonable amount of time, give up.
424 timer_.Start(FROM_HERE, base::TimeDelta::FromSeconds(kTimeoutInSeconds),
425 this, &SocketReader::CleanupAndDeleteSelf);
428 virtual ~SocketReader() {
429 CloseSocket(fd_);
432 // MessageLoopForIO::Watcher impl.
433 virtual void OnFileCanReadWithoutBlocking(int fd) OVERRIDE;
434 virtual void OnFileCanWriteWithoutBlocking(int fd) OVERRIDE {
435 // SocketReader only watches for accept (read) events.
436 NOTREACHED();
439 // Finish handling the incoming message by optionally sending back an ACK
440 // message and removing this SocketReader.
441 void FinishWithACK(const char *message, size_t length);
443 private:
444 void CleanupAndDeleteSelf() {
445 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
447 parent_->RemoveSocketReader(this);
448 // We're deleted beyond this point.
451 base::MessageLoopForIO::FileDescriptorWatcher fd_reader_;
453 // The ProcessSingleton::LinuxWatcher that owns us.
454 ProcessSingleton::LinuxWatcher* const parent_;
456 // A reference to the UI message loop.
457 base::MessageLoop* const ui_message_loop_;
459 // The file descriptor we're reading.
460 const int fd_;
462 // Store the message in this buffer.
463 char buf_[kMaxMessageLength];
465 // Tracks the number of bytes we've read in case we're getting partial
466 // reads.
467 size_t bytes_read_;
469 base::OneShotTimer<SocketReader> timer_;
471 DISALLOW_COPY_AND_ASSIGN(SocketReader);
474 // We expect to only be constructed on the UI thread.
475 explicit LinuxWatcher(ProcessSingleton* parent)
476 : ui_message_loop_(base::MessageLoop::current()),
477 parent_(parent) {
480 // Start listening for connections on the socket. This method should be
481 // called from the IO thread.
482 void StartListening(int socket);
484 // This method determines if we should use the same process and if we should,
485 // opens a new browser tab. This runs on the UI thread.
486 // |reader| is for sending back ACK message.
487 void HandleMessage(const std::string& current_dir,
488 const std::vector<std::string>& argv,
489 SocketReader* reader);
491 // MessageLoopForIO::Watcher impl. These run on the IO thread.
492 virtual void OnFileCanReadWithoutBlocking(int fd) OVERRIDE;
493 virtual void OnFileCanWriteWithoutBlocking(int fd) OVERRIDE {
494 // ProcessSingleton only watches for accept (read) events.
495 NOTREACHED();
498 // MessageLoop::DestructionObserver
499 virtual void WillDestroyCurrentMessageLoop() OVERRIDE {
500 fd_watcher_.StopWatchingFileDescriptor();
503 private:
504 friend struct BrowserThread::DeleteOnThread<BrowserThread::IO>;
505 friend class base::DeleteHelper<ProcessSingleton::LinuxWatcher>;
507 virtual ~LinuxWatcher() {
508 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
509 STLDeleteElements(&readers_);
511 base::MessageLoopForIO* ml = base::MessageLoopForIO::current();
512 ml->RemoveDestructionObserver(this);
515 // Removes and deletes the SocketReader.
516 void RemoveSocketReader(SocketReader* reader);
518 base::MessageLoopForIO::FileDescriptorWatcher fd_watcher_;
520 // A reference to the UI message loop (i.e., the message loop we were
521 // constructed on).
522 base::MessageLoop* ui_message_loop_;
524 // The ProcessSingleton that owns us.
525 ProcessSingleton* const parent_;
527 std::set<SocketReader*> readers_;
529 DISALLOW_COPY_AND_ASSIGN(LinuxWatcher);
532 void ProcessSingleton::LinuxWatcher::OnFileCanReadWithoutBlocking(int fd) {
533 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
534 // Accepting incoming client.
535 sockaddr_un from;
536 socklen_t from_len = sizeof(from);
537 int connection_socket = HANDLE_EINTR(accept(
538 fd, reinterpret_cast<sockaddr*>(&from), &from_len));
539 if (-1 == connection_socket) {
540 PLOG(ERROR) << "accept() failed";
541 return;
543 int rv = SetNonBlocking(connection_socket);
544 DCHECK_EQ(0, rv) << "Failed to make non-blocking socket.";
545 SocketReader* reader = new SocketReader(this,
546 ui_message_loop_,
547 connection_socket);
548 readers_.insert(reader);
551 void ProcessSingleton::LinuxWatcher::StartListening(int socket) {
552 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
553 // Watch for client connections on this socket.
554 base::MessageLoopForIO* ml = base::MessageLoopForIO::current();
555 ml->AddDestructionObserver(this);
556 ml->WatchFileDescriptor(socket, true, base::MessageLoopForIO::WATCH_READ,
557 &fd_watcher_, this);
560 void ProcessSingleton::LinuxWatcher::HandleMessage(
561 const std::string& current_dir, const std::vector<std::string>& argv,
562 SocketReader* reader) {
563 DCHECK(ui_message_loop_ == base::MessageLoop::current());
564 DCHECK(reader);
566 if (parent_->notification_callback_.Run(CommandLine(argv),
567 base::FilePath(current_dir))) {
568 // Send back "ACK" message to prevent the client process from starting up.
569 reader->FinishWithACK(kACKToken, arraysize(kACKToken) - 1);
570 } else {
571 LOG(WARNING) << "Not handling interprocess notification as browser"
572 " is shutting down";
573 // Send back "SHUTDOWN" message, so that the client process can start up
574 // without killing this process.
575 reader->FinishWithACK(kShutdownToken, arraysize(kShutdownToken) - 1);
576 return;
580 void ProcessSingleton::LinuxWatcher::RemoveSocketReader(SocketReader* reader) {
581 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
582 DCHECK(reader);
583 readers_.erase(reader);
584 delete reader;
587 ///////////////////////////////////////////////////////////////////////////////
588 // ProcessSingleton::LinuxWatcher::SocketReader
591 void ProcessSingleton::LinuxWatcher::SocketReader::OnFileCanReadWithoutBlocking(
592 int fd) {
593 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
594 DCHECK_EQ(fd, fd_);
595 while (bytes_read_ < sizeof(buf_)) {
596 ssize_t rv = HANDLE_EINTR(
597 read(fd, buf_ + bytes_read_, sizeof(buf_) - bytes_read_));
598 if (rv < 0) {
599 if (errno != EAGAIN && errno != EWOULDBLOCK) {
600 PLOG(ERROR) << "read() failed";
601 CloseSocket(fd);
602 return;
603 } else {
604 // It would block, so we just return and continue to watch for the next
605 // opportunity to read.
606 return;
608 } else if (!rv) {
609 // No more data to read. It's time to process the message.
610 break;
611 } else {
612 bytes_read_ += rv;
616 // Validate the message. The shortest message is kStartToken\0x\0x
617 const size_t kMinMessageLength = arraysize(kStartToken) + 4;
618 if (bytes_read_ < kMinMessageLength) {
619 buf_[bytes_read_] = 0;
620 LOG(ERROR) << "Invalid socket message (wrong length):" << buf_;
621 CleanupAndDeleteSelf();
622 return;
625 std::string str(buf_, bytes_read_);
626 std::vector<std::string> tokens;
627 base::SplitString(str, kTokenDelimiter, &tokens);
629 if (tokens.size() < 3 || tokens[0] != kStartToken) {
630 LOG(ERROR) << "Wrong message format: " << str;
631 CleanupAndDeleteSelf();
632 return;
635 // Stop the expiration timer to prevent this SocketReader object from being
636 // terminated unexpectly.
637 timer_.Stop();
639 std::string current_dir = tokens[1];
640 // Remove the first two tokens. The remaining tokens should be the command
641 // line argv array.
642 tokens.erase(tokens.begin());
643 tokens.erase(tokens.begin());
645 // Return to the UI thread to handle opening a new browser tab.
646 ui_message_loop_->PostTask(FROM_HERE, base::Bind(
647 &ProcessSingleton::LinuxWatcher::HandleMessage,
648 parent_,
649 current_dir,
650 tokens,
651 this));
652 fd_reader_.StopWatchingFileDescriptor();
654 // LinuxWatcher::HandleMessage() is in charge of destroying this SocketReader
655 // object by invoking SocketReader::FinishWithACK().
658 void ProcessSingleton::LinuxWatcher::SocketReader::FinishWithACK(
659 const char *message, size_t length) {
660 if (message && length) {
661 // Not necessary to care about the return value.
662 WriteToSocket(fd_, message, length);
665 if (shutdown(fd_, SHUT_WR) < 0)
666 PLOG(ERROR) << "shutdown() failed";
668 BrowserThread::PostTask(
669 BrowserThread::IO,
670 FROM_HERE,
671 base::Bind(&ProcessSingleton::LinuxWatcher::RemoveSocketReader,
672 parent_,
673 this));
674 // We will be deleted once the posted RemoveSocketReader task runs.
677 ///////////////////////////////////////////////////////////////////////////////
678 // ProcessSingleton
680 ProcessSingleton::ProcessSingleton(
681 const base::FilePath& user_data_dir,
682 const NotificationCallback& notification_callback)
683 : notification_callback_(notification_callback),
684 current_pid_(base::GetCurrentProcId()),
685 watcher_(new LinuxWatcher(this)) {
686 socket_path_ = user_data_dir.Append(chrome::kSingletonSocketFilename);
687 lock_path_ = user_data_dir.Append(chrome::kSingletonLockFilename);
688 cookie_path_ = user_data_dir.Append(chrome::kSingletonCookieFilename);
690 kill_callback_ = base::Bind(&ProcessSingleton::KillProcess,
691 base::Unretained(this));
694 ProcessSingleton::~ProcessSingleton() {
697 ProcessSingleton::NotifyResult ProcessSingleton::NotifyOtherProcess() {
698 return NotifyOtherProcessWithTimeout(*CommandLine::ForCurrentProcess(),
699 kTimeoutInSeconds,
700 true);
703 ProcessSingleton::NotifyResult ProcessSingleton::NotifyOtherProcessWithTimeout(
704 const CommandLine& cmd_line,
705 int timeout_seconds,
706 bool kill_unresponsive) {
707 DCHECK_GE(timeout_seconds, 0);
709 ScopedSocket socket;
710 for (int retries = 0; retries <= timeout_seconds; ++retries) {
711 // Try to connect to the socket.
712 if (ConnectSocket(&socket, socket_path_, cookie_path_))
713 break;
715 // If we're in a race with another process, they may be in Create() and have
716 // created the lock but not attached to the socket. So we check if the
717 // process with the pid from the lockfile is currently running and is a
718 // chrome browser. If so, we loop and try again for |timeout_seconds|.
720 std::string hostname;
721 int pid;
722 if (!ParseLockPath(lock_path_, &hostname, &pid)) {
723 // No lockfile exists.
724 return PROCESS_NONE;
727 if (hostname.empty()) {
728 // Invalid lockfile.
729 UnlinkPath(lock_path_);
730 return PROCESS_NONE;
733 if (hostname != net::GetHostName() && !IsChromeProcess(pid)) {
734 // Locked by process on another host. If the user selected to unlock
735 // the profile, try to continue; otherwise quit.
736 if (DisplayProfileInUseError(lock_path_, hostname, pid)) {
737 UnlinkPath(lock_path_);
738 return PROCESS_NONE;
740 return PROFILE_IN_USE;
743 if (!IsChromeProcess(pid)) {
744 // Orphaned lockfile (no process with pid, or non-chrome process.)
745 UnlinkPath(lock_path_);
746 return PROCESS_NONE;
749 if (IsSameChromeInstance(pid)) {
750 // Orphaned lockfile (pid is part of same chrome instance we are, even
751 // though we haven't tried to create a lockfile yet).
752 UnlinkPath(lock_path_);
753 return PROCESS_NONE;
756 if (retries == timeout_seconds) {
757 // Retries failed. Kill the unresponsive chrome process and continue.
758 if (!kill_unresponsive || !KillProcessByLockPath())
759 return PROFILE_IN_USE;
760 return PROCESS_NONE;
763 base::PlatformThread::Sleep(base::TimeDelta::FromSeconds(1));
766 timeval timeout = {timeout_seconds, 0};
767 setsockopt(socket.fd(), SOL_SOCKET, SO_SNDTIMEO, &timeout, sizeof(timeout));
769 // Found another process, prepare our command line
770 // format is "START\0<current dir>\0<argv[0]>\0...\0<argv[n]>".
771 std::string to_send(kStartToken);
772 to_send.push_back(kTokenDelimiter);
774 base::FilePath current_dir;
775 if (!PathService::Get(base::DIR_CURRENT, &current_dir))
776 return PROCESS_NONE;
777 to_send.append(current_dir.value());
779 const std::vector<std::string>& argv = cmd_line.argv();
780 for (std::vector<std::string>::const_iterator it = argv.begin();
781 it != argv.end(); ++it) {
782 to_send.push_back(kTokenDelimiter);
783 to_send.append(*it);
786 // Send the message
787 if (!WriteToSocket(socket.fd(), to_send.data(), to_send.length())) {
788 // Try to kill the other process, because it might have been dead.
789 if (!kill_unresponsive || !KillProcessByLockPath())
790 return PROFILE_IN_USE;
791 return PROCESS_NONE;
794 if (shutdown(socket.fd(), SHUT_WR) < 0)
795 PLOG(ERROR) << "shutdown() failed";
797 // Read ACK message from the other process. It might be blocked for a certain
798 // timeout, to make sure the other process has enough time to return ACK.
799 char buf[kMaxACKMessageLength + 1];
800 ssize_t len =
801 ReadFromSocket(socket.fd(), buf, kMaxACKMessageLength, timeout_seconds);
803 // Failed to read ACK, the other process might have been frozen.
804 if (len <= 0) {
805 if (!kill_unresponsive || !KillProcessByLockPath())
806 return PROFILE_IN_USE;
807 return PROCESS_NONE;
810 buf[len] = '\0';
811 if (strncmp(buf, kShutdownToken, arraysize(kShutdownToken) - 1) == 0) {
812 // The other process is shutting down, it's safe to start a new process.
813 return PROCESS_NONE;
814 } else if (strncmp(buf, kACKToken, arraysize(kACKToken) - 1) == 0) {
815 #if defined(TOOLKIT_VIEWS) && !defined(OS_CHROMEOS)
816 // Likely NULL in unit tests.
817 views::LinuxUI* linux_ui = views::LinuxUI::instance();
818 if (linux_ui)
819 linux_ui->NotifyWindowManagerStartupComplete();
820 #endif
822 // Assume the other process is handling the request.
823 return PROCESS_NOTIFIED;
826 NOTREACHED() << "The other process returned unknown message: " << buf;
827 return PROCESS_NOTIFIED;
830 ProcessSingleton::NotifyResult ProcessSingleton::NotifyOtherProcessOrCreate() {
831 return NotifyOtherProcessWithTimeoutOrCreate(
832 *CommandLine::ForCurrentProcess(),
833 kTimeoutInSeconds);
836 ProcessSingleton::NotifyResult
837 ProcessSingleton::NotifyOtherProcessWithTimeoutOrCreate(
838 const CommandLine& command_line,
839 int timeout_seconds) {
840 NotifyResult result = NotifyOtherProcessWithTimeout(command_line,
841 timeout_seconds, true);
842 if (result != PROCESS_NONE)
843 return result;
844 if (Create())
845 return PROCESS_NONE;
846 // If the Create() failed, try again to notify. (It could be that another
847 // instance was starting at the same time and managed to grab the lock before
848 // we did.)
849 // This time, we don't want to kill anything if we aren't successful, since we
850 // aren't going to try to take over the lock ourselves.
851 result = NotifyOtherProcessWithTimeout(command_line, timeout_seconds, false);
852 if (result != PROCESS_NONE)
853 return result;
855 return LOCK_ERROR;
858 void ProcessSingleton::OverrideCurrentPidForTesting(base::ProcessId pid) {
859 current_pid_ = pid;
862 void ProcessSingleton::OverrideKillCallbackForTesting(
863 const base::Callback<void(int)>& callback) {
864 kill_callback_ = callback;
867 void ProcessSingleton::DisablePromptForTesting() {
868 g_disable_prompt = true;
871 bool ProcessSingleton::Create() {
872 int sock;
873 sockaddr_un addr;
875 // The symlink lock is pointed to the hostname and process id, so other
876 // processes can find it out.
877 base::FilePath symlink_content(base::StringPrintf(
878 "%s%c%u",
879 net::GetHostName().c_str(),
880 kLockDelimiter,
881 current_pid_));
883 // Create symbol link before binding the socket, to ensure only one instance
884 // can have the socket open.
885 if (!SymlinkPath(symlink_content, lock_path_)) {
886 // If we failed to create the lock, most likely another instance won the
887 // startup race.
888 return false;
891 // Create the socket file somewhere in /tmp which is usually mounted as a
892 // normal filesystem. Some network filesystems (notably AFS) are screwy and
893 // do not support Unix domain sockets.
894 if (!socket_dir_.CreateUniqueTempDir()) {
895 LOG(ERROR) << "Failed to create socket directory.";
896 return false;
898 // Setup the socket symlink and the two cookies.
899 base::FilePath socket_target_path =
900 socket_dir_.path().Append(chrome::kSingletonSocketFilename);
901 base::FilePath cookie(GenerateCookie());
902 base::FilePath remote_cookie_path =
903 socket_dir_.path().Append(chrome::kSingletonCookieFilename);
904 UnlinkPath(socket_path_);
905 UnlinkPath(cookie_path_);
906 if (!SymlinkPath(socket_target_path, socket_path_) ||
907 !SymlinkPath(cookie, cookie_path_) ||
908 !SymlinkPath(cookie, remote_cookie_path)) {
909 // We've already locked things, so we can't have lost the startup race,
910 // but something doesn't like us.
911 LOG(ERROR) << "Failed to create symlinks.";
912 if (!socket_dir_.Delete())
913 LOG(ERROR) << "Encountered a problem when deleting socket directory.";
914 return false;
917 SetupSocket(socket_target_path.value(), &sock, &addr);
919 if (bind(sock, reinterpret_cast<sockaddr*>(&addr), sizeof(addr)) < 0) {
920 PLOG(ERROR) << "Failed to bind() " << socket_target_path.value();
921 CloseSocket(sock);
922 return false;
925 if (listen(sock, 5) < 0)
926 NOTREACHED() << "listen failed: " << safe_strerror(errno);
928 DCHECK(BrowserThread::IsMessageLoopValid(BrowserThread::IO));
929 BrowserThread::PostTask(
930 BrowserThread::IO,
931 FROM_HERE,
932 base::Bind(&ProcessSingleton::LinuxWatcher::StartListening,
933 watcher_.get(),
934 sock));
936 return true;
939 void ProcessSingleton::Cleanup() {
940 UnlinkPath(socket_path_);
941 UnlinkPath(cookie_path_);
942 UnlinkPath(lock_path_);
945 bool ProcessSingleton::IsSameChromeInstance(pid_t pid) {
946 pid_t cur_pid = current_pid_;
947 while (pid != cur_pid) {
948 pid = base::GetParentProcessId(pid);
949 if (pid < 0)
950 return false;
951 if (!IsChromeProcess(pid))
952 return false;
954 return true;
957 bool ProcessSingleton::KillProcessByLockPath() {
958 std::string hostname;
959 int pid;
960 ParseLockPath(lock_path_, &hostname, &pid);
962 if (!hostname.empty() && hostname != net::GetHostName()) {
963 return DisplayProfileInUseError(lock_path_, hostname, pid);
965 UnlinkPath(lock_path_);
967 if (IsSameChromeInstance(pid))
968 return true;
970 if (pid > 0) {
971 kill_callback_.Run(pid);
972 return true;
975 LOG(ERROR) << "Failed to extract pid from path: " << lock_path_.value();
976 return true;
979 void ProcessSingleton::KillProcess(int pid) {
980 // TODO(james.su@gmail.com): Is SIGKILL ok?
981 int rv = kill(static_cast<base::ProcessHandle>(pid), SIGKILL);
982 // ESRCH = No Such Process (can happen if the other process is already in
983 // progress of shutting down and finishes before we try to kill it).
984 DCHECK(rv == 0 || errno == ESRCH) << "Error killing process: "
985 << safe_strerror(errno);