Fix build break
[chromium-blink-merge.git] / chrome / browser / process_singleton_linux.cc
blobe96cf96f5b4ce8b639b0ed65a1d1c04e9f8c0df8
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 #if defined(TOOLKIT_GTK)
45 #include <gdk/gdk.h>
46 #endif
47 #include <signal.h>
48 #include <sys/socket.h>
49 #include <sys/stat.h>
50 #include <sys/types.h>
51 #include <sys/un.h>
52 #include <unistd.h>
54 #include <cstring>
55 #include <set>
56 #include <string>
58 #include "base/base_paths.h"
59 #include "base/basictypes.h"
60 #include "base/bind.h"
61 #include "base/command_line.h"
62 #include "base/file_util.h"
63 #include "base/files/file_path.h"
64 #include "base/logging.h"
65 #include "base/message_loop.h"
66 #include "base/path_service.h"
67 #include "base/posix/eintr_wrapper.h"
68 #include "base/process_util.h"
69 #include "base/rand_util.h"
70 #include "base/safe_strerror_posix.h"
71 #include "base/sequenced_task_runner_helpers.h"
72 #include "base/stl_util.h"
73 #include "base/stringprintf.h"
74 #include "base/strings/string_number_conversions.h"
75 #include "base/strings/string_split.h"
76 #include "base/strings/sys_string_conversions.h"
77 #include "base/threading/platform_thread.h"
78 #include "base/time.h"
79 #include "base/timer.h"
80 #include "base/utf_string_conversions.h"
81 #if defined(TOOLKIT_GTK)
82 #include "chrome/browser/ui/gtk/process_singleton_dialog.h"
83 #endif
84 #include "chrome/common/chrome_constants.h"
85 #include "content/public/browser/browser_thread.h"
86 #include "grit/chromium_strings.h"
87 #include "grit/generated_resources.h"
88 #include "net/base/net_util.h"
89 #include "ui/base/l10n/l10n_util.h"
91 using content::BrowserThread;
93 const int ProcessSingleton::kTimeoutInSeconds;
95 namespace {
97 static bool g_disable_prompt;
98 const char kStartToken[] = "START";
99 const char kACKToken[] = "ACK";
100 const char kShutdownToken[] = "SHUTDOWN";
101 const char kTokenDelimiter = '\0';
102 const int kMaxMessageLength = 32 * 1024;
103 const int kMaxACKMessageLength = arraysize(kShutdownToken) - 1;
105 const char kLockDelimiter = '-';
107 // Set a file descriptor to be non-blocking.
108 // Return 0 on success, -1 on failure.
109 int SetNonBlocking(int fd) {
110 int flags = fcntl(fd, F_GETFL, 0);
111 if (-1 == flags)
112 return flags;
113 if (flags & O_NONBLOCK)
114 return 0;
115 return fcntl(fd, F_SETFL, flags | O_NONBLOCK);
118 // Set the close-on-exec bit on a file descriptor.
119 // Returns 0 on success, -1 on failure.
120 int SetCloseOnExec(int fd) {
121 int flags = fcntl(fd, F_GETFD, 0);
122 if (-1 == flags)
123 return flags;
124 if (flags & FD_CLOEXEC)
125 return 0;
126 return fcntl(fd, F_SETFD, flags | FD_CLOEXEC);
129 // Close a socket and check return value.
130 void CloseSocket(int fd) {
131 int rv = HANDLE_EINTR(close(fd));
132 DCHECK_EQ(0, rv) << "Error closing socket: " << safe_strerror(errno);
135 // Write a message to a socket fd.
136 bool WriteToSocket(int fd, const char *message, size_t length) {
137 DCHECK(message);
138 DCHECK(length);
139 size_t bytes_written = 0;
140 do {
141 ssize_t rv = HANDLE_EINTR(
142 write(fd, message + bytes_written, length - bytes_written));
143 if (rv < 0) {
144 if (errno == EAGAIN || errno == EWOULDBLOCK) {
145 // The socket shouldn't block, we're sending so little data. Just give
146 // up here, since NotifyOtherProcess() doesn't have an asynchronous api.
147 LOG(ERROR) << "ProcessSingleton would block on write(), so it gave up.";
148 return false;
150 PLOG(ERROR) << "write() failed";
151 return false;
153 bytes_written += rv;
154 } while (bytes_written < length);
156 return true;
159 // Wait a socket for read for a certain timeout in seconds.
160 // Returns -1 if error occurred, 0 if timeout reached, > 0 if the socket is
161 // ready for read.
162 int WaitSocketForRead(int fd, int timeout) {
163 fd_set read_fds;
164 struct timeval tv;
166 FD_ZERO(&read_fds);
167 FD_SET(fd, &read_fds);
168 tv.tv_sec = timeout;
169 tv.tv_usec = 0;
171 return HANDLE_EINTR(select(fd + 1, &read_fds, NULL, NULL, &tv));
174 // Read a message from a socket fd, with an optional timeout in seconds.
175 // If |timeout| <= 0 then read immediately.
176 // Return number of bytes actually read, or -1 on error.
177 ssize_t ReadFromSocket(int fd, char *buf, size_t bufsize, int timeout) {
178 if (timeout > 0) {
179 int rv = WaitSocketForRead(fd, timeout);
180 if (rv <= 0)
181 return rv;
184 size_t bytes_read = 0;
185 do {
186 ssize_t rv = HANDLE_EINTR(read(fd, buf + bytes_read, bufsize - bytes_read));
187 if (rv < 0) {
188 if (errno != EAGAIN && errno != EWOULDBLOCK) {
189 PLOG(ERROR) << "read() failed";
190 return rv;
191 } else {
192 // It would block, so we just return what has been read.
193 return bytes_read;
195 } else if (!rv) {
196 // No more data to read.
197 return bytes_read;
198 } else {
199 bytes_read += rv;
201 } while (bytes_read < bufsize);
203 return bytes_read;
206 // Set up a sockaddr appropriate for messaging.
207 void SetupSockAddr(const std::string& path, struct sockaddr_un* addr) {
208 addr->sun_family = AF_UNIX;
209 CHECK(path.length() < arraysize(addr->sun_path))
210 << "Socket path too long: " << path;
211 base::strlcpy(addr->sun_path, path.c_str(), arraysize(addr->sun_path));
214 // Set up a socket appropriate for messaging.
215 int SetupSocketOnly() {
216 int sock = socket(PF_UNIX, SOCK_STREAM, 0);
217 PCHECK(sock >= 0) << "socket() failed";
219 int rv = SetNonBlocking(sock);
220 DCHECK_EQ(0, rv) << "Failed to make non-blocking socket.";
221 rv = SetCloseOnExec(sock);
222 DCHECK_EQ(0, rv) << "Failed to set CLOEXEC on socket.";
224 return sock;
227 // Set up a socket and sockaddr appropriate for messaging.
228 void SetupSocket(const std::string& path, int* sock, struct sockaddr_un* addr) {
229 *sock = SetupSocketOnly();
230 SetupSockAddr(path, addr);
233 // Read a symbolic link, return empty string if given path is not a symbol link.
234 base::FilePath ReadLink(const base::FilePath& path) {
235 base::FilePath target;
236 if (!file_util::ReadSymbolicLink(path, &target)) {
237 // The only errno that should occur is ENOENT.
238 if (errno != 0 && errno != ENOENT)
239 PLOG(ERROR) << "readlink(" << path.value() << ") failed";
241 return target;
244 // Unlink a path. Return true on success.
245 bool UnlinkPath(const base::FilePath& path) {
246 int rv = unlink(path.value().c_str());
247 if (rv < 0 && errno != ENOENT)
248 PLOG(ERROR) << "Failed to unlink " << path.value();
250 return rv == 0;
253 // Create a symlink. Returns true on success.
254 bool SymlinkPath(const base::FilePath& target, const base::FilePath& path) {
255 if (!file_util::CreateSymbolicLink(target, path)) {
256 // Double check the value in case symlink suceeded but we got an incorrect
257 // failure due to NFS packet loss & retry.
258 int saved_errno = errno;
259 if (ReadLink(path) != target) {
260 // If we failed to create the lock, most likely another instance won the
261 // startup race.
262 errno = saved_errno;
263 PLOG(ERROR) << "Failed to create " << path.value();
264 return false;
267 return true;
270 // Extract the hostname and pid from the lock symlink.
271 // Returns true if the lock existed.
272 bool ParseLockPath(const base::FilePath& path,
273 std::string* hostname,
274 int* pid) {
275 std::string real_path = ReadLink(path).value();
276 if (real_path.empty())
277 return false;
279 std::string::size_type pos = real_path.rfind(kLockDelimiter);
281 // If the path is not a symbolic link, or doesn't contain what we expect,
282 // bail.
283 if (pos == std::string::npos) {
284 *hostname = "";
285 *pid = -1;
286 return true;
289 *hostname = real_path.substr(0, pos);
291 const std::string& pid_str = real_path.substr(pos + 1);
292 if (!base::StringToInt(pid_str, pid))
293 *pid = -1;
295 return true;
298 void DisplayProfileInUseError(const std::string& lock_path,
299 const std::string& hostname,
300 int pid) {
301 string16 error = l10n_util::GetStringFUTF16(
302 IDS_PROFILE_IN_USE_LINUX,
303 base::IntToString16(pid),
304 ASCIIToUTF16(hostname),
305 WideToUTF16(base::SysNativeMBToWide(lock_path)),
306 l10n_util::GetStringUTF16(IDS_PRODUCT_NAME));
307 LOG(ERROR) << base::SysWideToNativeMB(UTF16ToWide(error)).c_str();
308 if (!g_disable_prompt) {
309 #if defined(TOOLKIT_GTK)
310 ProcessSingletonDialog::ShowAndRun(UTF16ToUTF8(error));
311 #else
312 NOTIMPLEMENTED();
313 #endif
317 bool IsChromeProcess(pid_t pid) {
318 base::FilePath other_chrome_path(base::GetProcessExecutablePath(pid));
319 return (!other_chrome_path.empty() &&
320 other_chrome_path.BaseName() ==
321 base::FilePath(chrome::kBrowserProcessExecutableName));
324 // A helper class to hold onto a socket.
325 class ScopedSocket {
326 public:
327 ScopedSocket() : fd_(-1) { Reset(); }
328 ~ScopedSocket() { Close(); }
329 int fd() { return fd_; }
330 void Reset() {
331 Close();
332 fd_ = SetupSocketOnly();
334 void Close() {
335 if (fd_ >= 0)
336 CloseSocket(fd_);
337 fd_ = -1;
339 private:
340 int fd_;
343 // Returns a random string for uniquifying profile connections.
344 std::string GenerateCookie() {
345 return base::Uint64ToString(base::RandUint64());
348 bool CheckCookie(const base::FilePath& path, const base::FilePath& cookie) {
349 return (cookie == ReadLink(path));
352 bool ConnectSocket(ScopedSocket* socket,
353 const base::FilePath& socket_path,
354 const base::FilePath& cookie_path) {
355 base::FilePath socket_target;
356 if (file_util::ReadSymbolicLink(socket_path, &socket_target)) {
357 // It's a symlink. Read the cookie.
358 base::FilePath cookie = ReadLink(cookie_path);
359 if (cookie.empty())
360 return false;
361 base::FilePath remote_cookie = socket_target.DirName().
362 Append(chrome::kSingletonCookieFilename);
363 // Verify the cookie before connecting.
364 if (!CheckCookie(remote_cookie, cookie))
365 return false;
366 // Now we know the directory was (at that point) created by the profile
367 // owner. Try to connect.
368 sockaddr_un addr;
369 SetupSockAddr(socket_path.value(), &addr);
370 int ret = HANDLE_EINTR(connect(socket->fd(),
371 reinterpret_cast<sockaddr*>(&addr),
372 sizeof(addr)));
373 if (ret != 0)
374 return false;
375 // Check the cookie again. We only link in /tmp, which is sticky, so, if the
376 // directory is still correct, it must have been correct in-between when we
377 // connected. POSIX, sadly, lacks a connectat().
378 if (!CheckCookie(remote_cookie, cookie)) {
379 socket->Reset();
380 return false;
382 // Success!
383 return true;
384 } else if (errno == EINVAL) {
385 // It exists, but is not a symlink (or some other error we detect
386 // later). Just connect to it directly; this is an older version of Chrome.
387 sockaddr_un addr;
388 SetupSockAddr(socket_path.value(), &addr);
389 int ret = HANDLE_EINTR(connect(socket->fd(),
390 reinterpret_cast<sockaddr*>(&addr),
391 sizeof(addr)));
392 return (ret == 0);
393 } else {
394 // File is missing, or other error.
395 if (errno != ENOENT)
396 PLOG(ERROR) << "readlink failed";
397 return false;
401 } // namespace
403 ///////////////////////////////////////////////////////////////////////////////
404 // ProcessSingleton::LinuxWatcher
405 // A helper class for a Linux specific implementation of the process singleton.
406 // This class sets up a listener on the singleton socket and handles parsing
407 // messages that come in on the singleton socket.
408 class ProcessSingleton::LinuxWatcher
409 : public MessageLoopForIO::Watcher,
410 public MessageLoop::DestructionObserver,
411 public base::RefCountedThreadSafe<ProcessSingleton::LinuxWatcher,
412 BrowserThread::DeleteOnIOThread> {
413 public:
414 // A helper class to read message from an established socket.
415 class SocketReader : public MessageLoopForIO::Watcher {
416 public:
417 SocketReader(ProcessSingleton::LinuxWatcher* parent,
418 MessageLoop* ui_message_loop,
419 int fd)
420 : parent_(parent),
421 ui_message_loop_(ui_message_loop),
422 fd_(fd),
423 bytes_read_(0) {
424 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
425 // Wait for reads.
426 MessageLoopForIO::current()->WatchFileDescriptor(
427 fd, true, MessageLoopForIO::WATCH_READ, &fd_reader_, this);
428 // If we haven't completed in a reasonable amount of time, give up.
429 timer_.Start(FROM_HERE, base::TimeDelta::FromSeconds(kTimeoutInSeconds),
430 this, &SocketReader::CleanupAndDeleteSelf);
433 virtual ~SocketReader() {
434 CloseSocket(fd_);
437 // MessageLoopForIO::Watcher impl.
438 virtual void OnFileCanReadWithoutBlocking(int fd) OVERRIDE;
439 virtual void OnFileCanWriteWithoutBlocking(int fd) OVERRIDE {
440 // SocketReader only watches for accept (read) events.
441 NOTREACHED();
444 // Finish handling the incoming message by optionally sending back an ACK
445 // message and removing this SocketReader.
446 void FinishWithACK(const char *message, size_t length);
448 private:
449 void CleanupAndDeleteSelf() {
450 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
452 parent_->RemoveSocketReader(this);
453 // We're deleted beyond this point.
456 MessageLoopForIO::FileDescriptorWatcher fd_reader_;
458 // The ProcessSingleton::LinuxWatcher that owns us.
459 ProcessSingleton::LinuxWatcher* const parent_;
461 // A reference to the UI message loop.
462 MessageLoop* const ui_message_loop_;
464 // The file descriptor we're reading.
465 const int fd_;
467 // Store the message in this buffer.
468 char buf_[kMaxMessageLength];
470 // Tracks the number of bytes we've read in case we're getting partial
471 // reads.
472 size_t bytes_read_;
474 base::OneShotTimer<SocketReader> timer_;
476 DISALLOW_COPY_AND_ASSIGN(SocketReader);
479 // We expect to only be constructed on the UI thread.
480 explicit LinuxWatcher(ProcessSingleton* parent)
481 : ui_message_loop_(MessageLoop::current()),
482 parent_(parent) {
485 // Start listening for connections on the socket. This method should be
486 // called from the IO thread.
487 void StartListening(int socket);
489 // This method determines if we should use the same process and if we should,
490 // opens a new browser tab. This runs on the UI thread.
491 // |reader| is for sending back ACK message.
492 void HandleMessage(const std::string& current_dir,
493 const std::vector<std::string>& argv,
494 SocketReader* reader);
496 // MessageLoopForIO::Watcher impl. These run on the IO thread.
497 virtual void OnFileCanReadWithoutBlocking(int fd) OVERRIDE;
498 virtual void OnFileCanWriteWithoutBlocking(int fd) OVERRIDE {
499 // ProcessSingleton only watches for accept (read) events.
500 NOTREACHED();
503 // MessageLoop::DestructionObserver
504 virtual void WillDestroyCurrentMessageLoop() OVERRIDE {
505 fd_watcher_.StopWatchingFileDescriptor();
508 private:
509 friend struct BrowserThread::DeleteOnThread<BrowserThread::IO>;
510 friend class base::DeleteHelper<ProcessSingleton::LinuxWatcher>;
512 virtual ~LinuxWatcher() {
513 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
514 STLDeleteElements(&readers_);
516 MessageLoopForIO* ml = MessageLoopForIO::current();
517 ml->RemoveDestructionObserver(this);
520 // Removes and deletes the SocketReader.
521 void RemoveSocketReader(SocketReader* reader);
523 MessageLoopForIO::FileDescriptorWatcher fd_watcher_;
525 // A reference to the UI message loop (i.e., the message loop we were
526 // constructed on).
527 MessageLoop* ui_message_loop_;
529 // The ProcessSingleton that owns us.
530 ProcessSingleton* const parent_;
532 std::set<SocketReader*> readers_;
534 DISALLOW_COPY_AND_ASSIGN(LinuxWatcher);
537 void ProcessSingleton::LinuxWatcher::OnFileCanReadWithoutBlocking(int fd) {
538 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
539 // Accepting incoming client.
540 sockaddr_un from;
541 socklen_t from_len = sizeof(from);
542 int connection_socket = HANDLE_EINTR(accept(
543 fd, reinterpret_cast<sockaddr*>(&from), &from_len));
544 if (-1 == connection_socket) {
545 PLOG(ERROR) << "accept() failed";
546 return;
548 int rv = SetNonBlocking(connection_socket);
549 DCHECK_EQ(0, rv) << "Failed to make non-blocking socket.";
550 SocketReader* reader = new SocketReader(this,
551 ui_message_loop_,
552 connection_socket);
553 readers_.insert(reader);
556 void ProcessSingleton::LinuxWatcher::StartListening(int socket) {
557 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
558 // Watch for client connections on this socket.
559 MessageLoopForIO* ml = MessageLoopForIO::current();
560 ml->AddDestructionObserver(this);
561 ml->WatchFileDescriptor(socket, true, MessageLoopForIO::WATCH_READ,
562 &fd_watcher_, this);
565 void ProcessSingleton::LinuxWatcher::HandleMessage(
566 const std::string& current_dir, const std::vector<std::string>& argv,
567 SocketReader* reader) {
568 DCHECK(ui_message_loop_ == MessageLoop::current());
569 DCHECK(reader);
570 // If locked, it means we are not ready to process this message because
571 // we are probably in a first run critical phase.
572 if (parent_->locked()) {
573 DLOG(WARNING) << "Browser is locked";
574 parent_->saved_startup_messages_.push_back(
575 std::make_pair(argv, base::FilePath(current_dir)));
576 // Send back "ACK" message to prevent the client process from starting up.
577 reader->FinishWithACK(kACKToken, arraysize(kACKToken) - 1);
578 return;
581 if (parent_->notification_callback_.Run(CommandLine(argv),
582 base::FilePath(current_dir))) {
583 // Send back "ACK" message to prevent the client process from starting up.
584 reader->FinishWithACK(kACKToken, arraysize(kACKToken) - 1);
585 } else {
586 LOG(WARNING) << "Not handling interprocess notification as browser"
587 " is shutting down";
588 // Send back "SHUTDOWN" message, so that the client process can start up
589 // without killing this process.
590 reader->FinishWithACK(kShutdownToken, arraysize(kShutdownToken) - 1);
591 return;
595 void ProcessSingleton::LinuxWatcher::RemoveSocketReader(SocketReader* reader) {
596 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
597 DCHECK(reader);
598 readers_.erase(reader);
599 delete reader;
602 ///////////////////////////////////////////////////////////////////////////////
603 // ProcessSingleton::LinuxWatcher::SocketReader
606 void ProcessSingleton::LinuxWatcher::SocketReader::OnFileCanReadWithoutBlocking(
607 int fd) {
608 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
609 DCHECK_EQ(fd, fd_);
610 while (bytes_read_ < sizeof(buf_)) {
611 ssize_t rv = HANDLE_EINTR(
612 read(fd, buf_ + bytes_read_, sizeof(buf_) - bytes_read_));
613 if (rv < 0) {
614 if (errno != EAGAIN && errno != EWOULDBLOCK) {
615 PLOG(ERROR) << "read() failed";
616 CloseSocket(fd);
617 return;
618 } else {
619 // It would block, so we just return and continue to watch for the next
620 // opportunity to read.
621 return;
623 } else if (!rv) {
624 // No more data to read. It's time to process the message.
625 break;
626 } else {
627 bytes_read_ += rv;
631 // Validate the message. The shortest message is kStartToken\0x\0x
632 const size_t kMinMessageLength = arraysize(kStartToken) + 4;
633 if (bytes_read_ < kMinMessageLength) {
634 buf_[bytes_read_] = 0;
635 LOG(ERROR) << "Invalid socket message (wrong length):" << buf_;
636 CleanupAndDeleteSelf();
637 return;
640 std::string str(buf_, bytes_read_);
641 std::vector<std::string> tokens;
642 base::SplitString(str, kTokenDelimiter, &tokens);
644 if (tokens.size() < 3 || tokens[0] != kStartToken) {
645 LOG(ERROR) << "Wrong message format: " << str;
646 CleanupAndDeleteSelf();
647 return;
650 // Stop the expiration timer to prevent this SocketReader object from being
651 // terminated unexpectly.
652 timer_.Stop();
654 std::string current_dir = tokens[1];
655 // Remove the first two tokens. The remaining tokens should be the command
656 // line argv array.
657 tokens.erase(tokens.begin());
658 tokens.erase(tokens.begin());
660 // Return to the UI thread to handle opening a new browser tab.
661 ui_message_loop_->PostTask(FROM_HERE, base::Bind(
662 &ProcessSingleton::LinuxWatcher::HandleMessage,
663 parent_,
664 current_dir,
665 tokens,
666 this));
667 fd_reader_.StopWatchingFileDescriptor();
669 // LinuxWatcher::HandleMessage() is in charge of destroying this SocketReader
670 // object by invoking SocketReader::FinishWithACK().
673 void ProcessSingleton::LinuxWatcher::SocketReader::FinishWithACK(
674 const char *message, size_t length) {
675 if (message && length) {
676 // Not necessary to care about the return value.
677 WriteToSocket(fd_, message, length);
680 if (shutdown(fd_, SHUT_WR) < 0)
681 PLOG(ERROR) << "shutdown() failed";
683 BrowserThread::PostTask(
684 BrowserThread::IO,
685 FROM_HERE,
686 base::Bind(&ProcessSingleton::LinuxWatcher::RemoveSocketReader,
687 parent_,
688 this));
689 // We will be deleted once the posted RemoveSocketReader task runs.
692 ///////////////////////////////////////////////////////////////////////////////
693 // ProcessSingleton
695 ProcessSingleton::ProcessSingleton(
696 const base::FilePath& user_data_dir,
697 const NotificationCallback& notification_callback)
698 : locked_(false),
699 foreground_window_(NULL),
700 notification_callback_(notification_callback),
701 current_pid_(base::GetCurrentProcId()),
702 ALLOW_THIS_IN_INITIALIZER_LIST(watcher_(new LinuxWatcher(this))) {
703 socket_path_ = user_data_dir.Append(chrome::kSingletonSocketFilename);
704 lock_path_ = user_data_dir.Append(chrome::kSingletonLockFilename);
705 cookie_path_ = user_data_dir.Append(chrome::kSingletonCookieFilename);
707 kill_callback_ = base::Bind(&ProcessSingleton::KillProcess,
708 base::Unretained(this));
711 ProcessSingleton::~ProcessSingleton() {
714 ProcessSingleton::NotifyResult ProcessSingleton::NotifyOtherProcess() {
715 return NotifyOtherProcessWithTimeout(*CommandLine::ForCurrentProcess(),
716 kTimeoutInSeconds,
717 true);
720 ProcessSingleton::NotifyResult ProcessSingleton::NotifyOtherProcessWithTimeout(
721 const CommandLine& cmd_line,
722 int timeout_seconds,
723 bool kill_unresponsive) {
724 DCHECK_GE(timeout_seconds, 0);
726 ScopedSocket socket;
727 for (int retries = 0; retries <= timeout_seconds; ++retries) {
728 // Try to connect to the socket.
729 if (ConnectSocket(&socket, socket_path_, cookie_path_))
730 break;
732 // If we're in a race with another process, they may be in Create() and have
733 // created the lock but not attached to the socket. So we check if the
734 // process with the pid from the lockfile is currently running and is a
735 // chrome browser. If so, we loop and try again for |timeout_seconds|.
737 std::string hostname;
738 int pid;
739 if (!ParseLockPath(lock_path_, &hostname, &pid)) {
740 // No lockfile exists.
741 return PROCESS_NONE;
744 if (hostname.empty()) {
745 // Invalid lockfile.
746 UnlinkPath(lock_path_);
747 return PROCESS_NONE;
750 if (hostname != net::GetHostName()) {
751 // Locked by process on another host.
752 DisplayProfileInUseError(lock_path_.value(), hostname, pid);
753 return PROFILE_IN_USE;
756 if (!IsChromeProcess(pid)) {
757 // Orphaned lockfile (no process with pid, or non-chrome process.)
758 UnlinkPath(lock_path_);
759 return PROCESS_NONE;
762 if (IsSameChromeInstance(pid)) {
763 // Orphaned lockfile (pid is part of same chrome instance we are, even
764 // though we haven't tried to create a lockfile yet).
765 UnlinkPath(lock_path_);
766 return PROCESS_NONE;
769 if (retries == timeout_seconds) {
770 // Retries failed. Kill the unresponsive chrome process and continue.
771 if (!kill_unresponsive || !KillProcessByLockPath())
772 return PROFILE_IN_USE;
773 return PROCESS_NONE;
776 base::PlatformThread::Sleep(base::TimeDelta::FromSeconds(1));
779 timeval timeout = {timeout_seconds, 0};
780 setsockopt(socket.fd(), SOL_SOCKET, SO_SNDTIMEO, &timeout, sizeof(timeout));
782 // Found another process, prepare our command line
783 // format is "START\0<current dir>\0<argv[0]>\0...\0<argv[n]>".
784 std::string to_send(kStartToken);
785 to_send.push_back(kTokenDelimiter);
787 base::FilePath current_dir;
788 if (!PathService::Get(base::DIR_CURRENT, &current_dir))
789 return PROCESS_NONE;
790 to_send.append(current_dir.value());
792 const std::vector<std::string>& argv = cmd_line.argv();
793 for (std::vector<std::string>::const_iterator it = argv.begin();
794 it != argv.end(); ++it) {
795 to_send.push_back(kTokenDelimiter);
796 to_send.append(*it);
799 // Send the message
800 if (!WriteToSocket(socket.fd(), to_send.data(), to_send.length())) {
801 // Try to kill the other process, because it might have been dead.
802 if (!kill_unresponsive || !KillProcessByLockPath())
803 return PROFILE_IN_USE;
804 return PROCESS_NONE;
807 if (shutdown(socket.fd(), SHUT_WR) < 0)
808 PLOG(ERROR) << "shutdown() failed";
810 // Read ACK message from the other process. It might be blocked for a certain
811 // timeout, to make sure the other process has enough time to return ACK.
812 char buf[kMaxACKMessageLength + 1];
813 ssize_t len =
814 ReadFromSocket(socket.fd(), buf, kMaxACKMessageLength, timeout_seconds);
816 // Failed to read ACK, the other process might have been frozen.
817 if (len <= 0) {
818 if (!kill_unresponsive || !KillProcessByLockPath())
819 return PROFILE_IN_USE;
820 return PROCESS_NONE;
823 buf[len] = '\0';
824 if (strncmp(buf, kShutdownToken, arraysize(kShutdownToken) - 1) == 0) {
825 // The other process is shutting down, it's safe to start a new process.
826 return PROCESS_NONE;
827 } else if (strncmp(buf, kACKToken, arraysize(kACKToken) - 1) == 0) {
828 #if defined(TOOLKIT_GTK)
829 // Notify the window manager that we've started up; if we do not open a
830 // window, GTK will not automatically call this for us.
831 gdk_notify_startup_complete();
832 #endif
833 // Assume the other process is handling the request.
834 return PROCESS_NOTIFIED;
837 NOTREACHED() << "The other process returned unknown message: " << buf;
838 return PROCESS_NOTIFIED;
841 ProcessSingleton::NotifyResult ProcessSingleton::NotifyOtherProcessOrCreate() {
842 return NotifyOtherProcessWithTimeoutOrCreate(
843 *CommandLine::ForCurrentProcess(),
844 kTimeoutInSeconds);
847 ProcessSingleton::NotifyResult
848 ProcessSingleton::NotifyOtherProcessWithTimeoutOrCreate(
849 const CommandLine& command_line,
850 int timeout_seconds) {
851 NotifyResult result = NotifyOtherProcessWithTimeout(command_line,
852 timeout_seconds, true);
853 if (result != PROCESS_NONE)
854 return result;
855 if (Create())
856 return PROCESS_NONE;
857 // If the Create() failed, try again to notify. (It could be that another
858 // instance was starting at the same time and managed to grab the lock before
859 // we did.)
860 // This time, we don't want to kill anything if we aren't successful, since we
861 // aren't going to try to take over the lock ourselves.
862 result = NotifyOtherProcessWithTimeout(command_line, timeout_seconds, false);
863 if (result != PROCESS_NONE)
864 return result;
866 return LOCK_ERROR;
869 void ProcessSingleton::OverrideCurrentPidForTesting(base::ProcessId pid) {
870 current_pid_ = pid;
873 void ProcessSingleton::OverrideKillCallbackForTesting(
874 const base::Callback<void(int)>& callback) {
875 kill_callback_ = callback;
878 void ProcessSingleton::DisablePromptForTesting() {
879 g_disable_prompt = true;
882 bool ProcessSingleton::Create() {
883 int sock;
884 sockaddr_un addr;
886 // The symlink lock is pointed to the hostname and process id, so other
887 // processes can find it out.
888 base::FilePath symlink_content(base::StringPrintf(
889 "%s%c%u",
890 net::GetHostName().c_str(),
891 kLockDelimiter,
892 current_pid_));
894 // Create symbol link before binding the socket, to ensure only one instance
895 // can have the socket open.
896 if (!SymlinkPath(symlink_content, lock_path_)) {
897 // If we failed to create the lock, most likely another instance won the
898 // startup race.
899 return false;
902 // Create the socket file somewhere in /tmp which is usually mounted as a
903 // normal filesystem. Some network filesystems (notably AFS) are screwy and
904 // do not support Unix domain sockets.
905 if (!socket_dir_.CreateUniqueTempDir()) {
906 LOG(ERROR) << "Failed to create socket directory.";
907 return false;
909 // Setup the socket symlink and the two cookies.
910 base::FilePath socket_target_path =
911 socket_dir_.path().Append(chrome::kSingletonSocketFilename);
912 base::FilePath cookie(GenerateCookie());
913 base::FilePath remote_cookie_path =
914 socket_dir_.path().Append(chrome::kSingletonCookieFilename);
915 UnlinkPath(socket_path_);
916 UnlinkPath(cookie_path_);
917 if (!SymlinkPath(socket_target_path, socket_path_) ||
918 !SymlinkPath(cookie, cookie_path_) ||
919 !SymlinkPath(cookie, remote_cookie_path)) {
920 // We've already locked things, so we can't have lost the startup race,
921 // but something doesn't like us.
922 LOG(ERROR) << "Failed to create symlinks.";
923 if (!socket_dir_.Delete())
924 LOG(ERROR) << "Encountered a problem when deleting socket directory.";
925 return false;
928 SetupSocket(socket_target_path.value(), &sock, &addr);
930 if (bind(sock, reinterpret_cast<sockaddr*>(&addr), sizeof(addr)) < 0) {
931 PLOG(ERROR) << "Failed to bind() " << socket_target_path.value();
932 CloseSocket(sock);
933 return false;
936 if (listen(sock, 5) < 0)
937 NOTREACHED() << "listen failed: " << safe_strerror(errno);
939 DCHECK(BrowserThread::IsMessageLoopValid(BrowserThread::IO));
940 BrowserThread::PostTask(
941 BrowserThread::IO,
942 FROM_HERE,
943 base::Bind(&ProcessSingleton::LinuxWatcher::StartListening,
944 watcher_.get(),
945 sock));
947 return true;
950 void ProcessSingleton::Cleanup() {
951 UnlinkPath(socket_path_);
952 UnlinkPath(cookie_path_);
953 UnlinkPath(lock_path_);
956 bool ProcessSingleton::IsSameChromeInstance(pid_t pid) {
957 pid_t cur_pid = current_pid_;
958 while (pid != cur_pid) {
959 pid = base::GetParentProcessId(pid);
960 if (pid < 0)
961 return false;
962 if (!IsChromeProcess(pid))
963 return false;
965 return true;
968 bool ProcessSingleton::KillProcessByLockPath() {
969 std::string hostname;
970 int pid;
971 ParseLockPath(lock_path_, &hostname, &pid);
973 if (!hostname.empty() && hostname != net::GetHostName()) {
974 DisplayProfileInUseError(lock_path_.value(), hostname, pid);
975 return false;
977 UnlinkPath(lock_path_);
979 if (IsSameChromeInstance(pid))
980 return true;
982 if (pid > 0) {
983 kill_callback_.Run(pid);
984 return true;
987 LOG(ERROR) << "Failed to extract pid from path: " << lock_path_.value();
988 return true;
991 void ProcessSingleton::KillProcess(int pid) {
992 // TODO(james.su@gmail.com): Is SIGKILL ok?
993 int rv = kill(static_cast<base::ProcessHandle>(pid), SIGKILL);
994 // ESRCH = No Such Process (can happen if the other process is already in
995 // progress of shutting down and finishes before we try to kill it).
996 DCHECK(rv == 0 || errno == ESRCH) << "Error killing process: "
997 << safe_strerror(errno);