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