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