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