[M94 Dev] Remove *.pyc files from git repositories
[platform/framework/web/chromium-efl.git] / chrome / browser / process_singleton_posix.cc
1 // Copyright 2014 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 <memory>
53 #include <set>
54 #include <string>
55
56 #include <stddef.h>
57
58 #include "base/base_paths.h"
59 #include "base/bind.h"
60 #include "base/command_line.h"
61 #include "base/containers/unique_ptr_adapters.h"
62 #include "base/cxx17_backports.h"
63 #include "base/files/file_descriptor_watcher_posix.h"
64 #include "base/files/file_path.h"
65 #include "base/files/file_util.h"
66 #include "base/location.h"
67 #include "base/logging.h"
68 #include "base/memory/ref_counted.h"
69 #include "base/metrics/histogram_functions.h"
70 #include "base/metrics/histogram_macros.h"
71 #include "base/path_service.h"
72 #include "base/posix/eintr_wrapper.h"
73 #include "base/posix/safe_strerror.h"
74 #include "base/rand_util.h"
75 #include "base/sequenced_task_runner_helpers.h"
76 #include "base/single_thread_task_runner.h"
77 #include "base/strings/string_number_conversions.h"
78 #include "base/strings/string_split.h"
79 #include "base/strings/string_util.h"
80 #include "base/strings/stringprintf.h"
81 #include "base/strings/sys_string_conversions.h"
82 #include "base/strings/utf_string_conversions.h"
83 #include "base/threading/platform_thread.h"
84 #include "base/threading/thread_task_runner_handle.h"
85 #include "base/time/time.h"
86 #include "base/timer/timer.h"
87 #include "build/build_config.h"
88 #include "build/chromeos_buildflags.h"
89 #include "chrome/common/chrome_constants.h"
90 #include "chrome/common/process_singleton_lock_posix.h"
91 #include "chrome/grit/chromium_strings.h"
92 #include "chrome/grit/generated_resources.h"
93 #include "content/public/browser/browser_task_traits.h"
94 #include "content/public/browser/browser_thread.h"
95 #include "net/base/network_interfaces.h"
96 #include "ui/base/l10n/l10n_util.h"
97
98 #if defined(OS_LINUX) || defined(OS_CHROMEOS)
99 #include "chrome/browser/ui/process_singleton_dialog_linux.h"
100 #endif
101
102 #if defined(TOOLKIT_VIEWS) && \
103     (defined(OS_LINUX) || BUILDFLAG(IS_CHROMEOS_LACROS))
104 #include "ui/views/linux_ui/linux_ui.h"
105 #endif
106
107 using content::BrowserThread;
108
109 namespace {
110
111 // Timeout for the current browser process to respond. 20 seconds should be
112 // enough.
113 const int kTimeoutInSeconds = 20;
114 // Number of retries to notify the browser. 20 retries over 20 seconds = 1 try
115 // per second.
116 const int kRetryAttempts = 20;
117 const char kStartToken[] = "START";
118 const char kACKToken[] = "ACK";
119 const char kShutdownToken[] = "SHUTDOWN";
120 const char kTokenDelimiter = '\0';
121 const int kMaxMessageLength = 32 * 1024;
122 const int kMaxACKMessageLength = base::size(kShutdownToken) - 1;
123
124 bool g_disable_prompt = false;
125 bool g_skip_is_chrome_process_check = false;
126 bool g_user_opted_unlock_in_use_profile = false;
127
128 // Set the close-on-exec bit on a file descriptor.
129 // Returns 0 on success, -1 on failure.
130 int SetCloseOnExec(int fd) {
131   int flags = fcntl(fd, F_GETFD, 0);
132   if (-1 == flags)
133     return flags;
134   if (flags & FD_CLOEXEC)
135     return 0;
136   return fcntl(fd, F_SETFD, flags | FD_CLOEXEC);
137 }
138
139 // Close a socket and check return value.
140 void CloseSocket(int fd) {
141   int rv = IGNORE_EINTR(close(fd));
142   DCHECK_EQ(0, rv) << "Error closing socket: " << base::safe_strerror(errno);
143 }
144
145 // Write a message to a socket fd.
146 bool WriteToSocket(int fd, const char *message, size_t length) {
147   DCHECK(message);
148   DCHECK(length);
149   size_t bytes_written = 0;
150   do {
151     ssize_t rv = HANDLE_EINTR(
152         write(fd, message + bytes_written, length - bytes_written));
153     if (rv < 0) {
154       if (errno == EAGAIN || errno == EWOULDBLOCK) {
155         // The socket shouldn't block, we're sending so little data.  Just give
156         // up here, since NotifyOtherProcess() doesn't have an asynchronous api.
157         LOG(ERROR) << "ProcessSingleton would block on write(), so it gave up.";
158         return false;
159       }
160       PLOG(ERROR) << "write() failed";
161       return false;
162     }
163     bytes_written += rv;
164   } while (bytes_written < length);
165
166   return true;
167 }
168
169 struct timeval TimeDeltaToTimeVal(const base::TimeDelta& delta) {
170   struct timeval result;
171   result.tv_sec = delta.InSeconds();
172   result.tv_usec = delta.InMicroseconds() % base::Time::kMicrosecondsPerSecond;
173   return result;
174 }
175
176 // Wait a socket for read for a certain timeout.
177 // Returns -1 if error occurred, 0 if timeout reached, > 0 if the socket is
178 // ready for read.
179 int WaitSocketForRead(int fd, const base::TimeDelta& timeout) {
180   fd_set read_fds;
181   struct timeval tv = TimeDeltaToTimeVal(timeout);
182
183   FD_ZERO(&read_fds);
184   FD_SET(fd, &read_fds);
185
186   return HANDLE_EINTR(select(fd + 1, &read_fds, NULL, NULL, &tv));
187 }
188
189 // Read a message from a socket fd, with an optional timeout.
190 // If |timeout| <= 0 then read immediately.
191 // Return number of bytes actually read, or -1 on error.
192 ssize_t ReadFromSocket(int fd,
193                        char* buf,
194                        size_t bufsize,
195                        const base::TimeDelta& timeout) {
196   if (timeout > base::TimeDelta()) {
197     int rv = WaitSocketForRead(fd, timeout);
198     if (rv <= 0)
199       return rv;
200   }
201
202   size_t bytes_read = 0;
203   do {
204     ssize_t rv = HANDLE_EINTR(read(fd, buf + bytes_read, bufsize - bytes_read));
205     if (rv < 0) {
206       if (errno != EAGAIN && errno != EWOULDBLOCK) {
207         PLOG(ERROR) << "read() failed";
208         return rv;
209       } else {
210         // It would block, so we just return what has been read.
211         return bytes_read;
212       }
213     } else if (!rv) {
214       // No more data to read.
215       return bytes_read;
216     } else {
217       bytes_read += rv;
218     }
219   } while (bytes_read < bufsize);
220
221   return bytes_read;
222 }
223
224 // Set up a sockaddr appropriate for messaging.
225 bool SetupSockAddr(const std::string& path, struct sockaddr_un* addr) {
226   addr->sun_family = AF_UNIX;
227   if (path.length() >= base::size(addr->sun_path))
228     return false;
229   base::strlcpy(addr->sun_path, path.c_str(), base::size(addr->sun_path));
230   return true;
231 }
232
233 // Set up a socket appropriate for messaging.
234 int SetupSocketOnly() {
235   int sock = socket(PF_UNIX, SOCK_STREAM, 0);
236   PCHECK(sock >= 0) << "socket() failed";
237
238   DCHECK(base::SetNonBlocking(sock)) << "Failed to make non-blocking socket.";
239   int rv = SetCloseOnExec(sock);
240   DCHECK_EQ(0, rv) << "Failed to set CLOEXEC on socket.";
241
242   return sock;
243 }
244
245 // Set up a socket and sockaddr appropriate for messaging.
246 void SetupSocket(const std::string& path, int* sock, struct sockaddr_un* addr) {
247   *sock = SetupSocketOnly();
248   CHECK(SetupSockAddr(path, addr)) << "Socket path too long: " << path;
249 }
250
251 // Read a symbolic link, return empty string if given path is not a symbol link.
252 base::FilePath ReadLink(const base::FilePath& path) {
253   base::FilePath target;
254   if (!base::ReadSymbolicLink(path, &target)) {
255     // The only errno that should occur is ENOENT.
256     if (errno != 0 && errno != ENOENT)
257       PLOG(ERROR) << "readlink(" << path.value() << ") failed";
258   }
259   return target;
260 }
261
262 // Unlink a path. Return true on success.
263 bool UnlinkPath(const base::FilePath& path) {
264   int rv = unlink(path.value().c_str());
265   if (rv < 0 && errno != ENOENT)
266     PLOG(ERROR) << "Failed to unlink " << path.value();
267
268   return rv == 0;
269 }
270
271 // Create a symlink. Returns true on success.
272 bool SymlinkPath(const base::FilePath& target, const base::FilePath& path) {
273   if (!base::CreateSymbolicLink(target, path)) {
274     // Double check the value in case symlink suceeded but we got an incorrect
275     // failure due to NFS packet loss & retry.
276     int saved_errno = errno;
277     if (ReadLink(path) != target) {
278       // If we failed to create the lock, most likely another instance won the
279       // startup race.
280       errno = saved_errno;
281       PLOG(ERROR) << "Failed to create " << path.value();
282       return false;
283     }
284   }
285   return true;
286 }
287
288 // Returns true if the user opted to unlock the profile.
289 bool DisplayProfileInUseError(const base::FilePath& lock_path,
290                               const std::string& hostname,
291                               int pid) {
292   std::u16string error = l10n_util::GetStringFUTF16(
293       IDS_PROFILE_IN_USE_POSIX, base::NumberToString16(pid),
294       base::ASCIIToUTF16(hostname));
295   LOG(ERROR) << error;
296
297   if (g_disable_prompt)
298     return g_user_opted_unlock_in_use_profile;
299
300 #if defined(OS_LINUX) || defined(OS_CHROMEOS)
301   std::u16string relaunch_button_text =
302       l10n_util::GetStringUTF16(IDS_PROFILE_IN_USE_LINUX_RELAUNCH);
303   return ShowProcessSingletonDialog(error, relaunch_button_text);
304 #elif defined(OS_MAC)
305   // On Mac, always usurp the lock.
306   return true;
307 #endif
308
309   NOTREACHED();
310   return false;
311 }
312
313 bool IsChromeProcess(pid_t pid) {
314   if (g_skip_is_chrome_process_check)
315     return true;
316
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::NumberToString(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 (base::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     if (!SetupSockAddr(socket_target.value(), &addr)) {
369       // If a sockaddr couldn't be initialized due to too long of a socket
370       // path, we can be sure there isn't already a Chrome running with this
371       // socket path, since it would have hit the CHECK() on the path length.
372       return false;
373     }
374     int ret = HANDLE_EINTR(connect(socket->fd(),
375                                    reinterpret_cast<sockaddr*>(&addr),
376                                    sizeof(addr)));
377     if (ret != 0)
378       return false;
379     // Check the cookie again. We only link in /tmp, which is sticky, so, if the
380     // directory is still correct, it must have been correct in-between when we
381     // connected. POSIX, sadly, lacks a connectat().
382     if (!CheckCookie(remote_cookie, cookie)) {
383       socket->Reset();
384       return false;
385     }
386     // Success!
387     return true;
388   } else if (errno == EINVAL) {
389     // It exists, but is not a symlink (or some other error we detect
390     // later). Just connect to it directly; this is an older version of Chrome.
391     sockaddr_un addr;
392     if (!SetupSockAddr(socket_path.value(), &addr)) {
393       // If a sockaddr couldn't be initialized due to too long of a socket
394       // path, we can be sure there isn't already a Chrome running with this
395       // socket path, since it would have hit the CHECK() on the path length.
396       return false;
397     }
398     int ret = HANDLE_EINTR(connect(socket->fd(),
399                                    reinterpret_cast<sockaddr*>(&addr),
400                                    sizeof(addr)));
401     return (ret == 0);
402   } else {
403     // File is missing, or other error.
404     if (errno != ENOENT)
405       PLOG(ERROR) << "readlink failed";
406     return false;
407   }
408 }
409
410 #if defined(OS_MAC)
411 bool ReplaceOldSingletonLock(const base::FilePath& symlink_content,
412                              const base::FilePath& lock_path) {
413   // Try taking an flock(2) on the file. Failure means the lock is taken so we
414   // should quit.
415   base::ScopedFD lock_fd(HANDLE_EINTR(
416       open(lock_path.value().c_str(), O_RDWR | O_CREAT | O_SYMLINK, 0644)));
417   if (!lock_fd.is_valid()) {
418     PLOG(ERROR) << "Could not open singleton lock";
419     return false;
420   }
421
422   int rc = HANDLE_EINTR(flock(lock_fd.get(), LOCK_EX | LOCK_NB));
423   if (rc == -1) {
424     if (errno == EWOULDBLOCK) {
425       LOG(ERROR) << "Singleton lock held by old process.";
426     } else {
427       PLOG(ERROR) << "Error locking singleton lock";
428     }
429     return false;
430   }
431
432   // Successfully taking the lock means we can replace it with the a new symlink
433   // lock. We never flock() the lock file from now on. I.e. we assume that an
434   // old version of Chrome will not run with the same user data dir after this
435   // version has run.
436   if (!base::DeleteFile(lock_path)) {
437     PLOG(ERROR) << "Could not delete old singleton lock.";
438     return false;
439   }
440
441   return SymlinkPath(symlink_content, lock_path);
442 }
443 #endif  // defined(OS_MAC)
444
445 void SendRemoteProcessInteractionResultHistogram(
446     ProcessSingleton::RemoteProcessInteractionResult result) {
447   UMA_HISTOGRAM_ENUMERATION(
448       "Chrome.ProcessSingleton.RemoteProcessInteractionResult", result,
449       ProcessSingleton::REMOTE_PROCESS_INTERACTION_RESULT_COUNT);
450 }
451
452 void SendRemoteHungProcessTerminateReasonHistogram(
453     ProcessSingleton::RemoteHungProcessTerminateReason reason) {
454   UMA_HISTOGRAM_ENUMERATION(
455       "Chrome.ProcessSingleton.RemoteHungProcessTerminateReason", reason,
456       ProcessSingleton::REMOTE_HUNG_PROCESS_TERMINATE_REASON_COUNT);
457 }
458
459 }  // namespace
460
461 ///////////////////////////////////////////////////////////////////////////////
462 // ProcessSingleton::LinuxWatcher
463 // A helper class for a Linux specific implementation of the process singleton.
464 // This class sets up a listener on the singleton socket and handles parsing
465 // messages that come in on the singleton socket.
466 class ProcessSingleton::LinuxWatcher
467     : public base::RefCountedThreadSafe<ProcessSingleton::LinuxWatcher,
468                                         BrowserThread::DeleteOnIOThread> {
469  public:
470   // A helper class to read message from an established socket.
471   class SocketReader {
472    public:
473     SocketReader(ProcessSingleton::LinuxWatcher* parent,
474                  scoped_refptr<base::SingleThreadTaskRunner> ui_task_runner,
475                  int fd)
476         : parent_(parent),
477           ui_task_runner_(ui_task_runner),
478           fd_(fd),
479           bytes_read_(0) {
480       DCHECK_CURRENTLY_ON(BrowserThread::IO);
481       // Wait for reads.
482       fd_watch_controller_ = base::FileDescriptorWatcher::WatchReadable(
483           fd, base::BindRepeating(&SocketReader::OnSocketCanReadWithoutBlocking,
484                                   base::Unretained(this)));
485       // If we haven't completed in a reasonable amount of time, give up.
486       timer_.Start(FROM_HERE, base::TimeDelta::FromSeconds(kTimeoutInSeconds),
487                    this, &SocketReader::CleanupAndDeleteSelf);
488     }
489
490     ~SocketReader() { CloseSocket(fd_); }
491
492     // Finish handling the incoming message by optionally sending back an ACK
493     // message and removing this SocketReader.
494     void FinishWithACK(const char *message, size_t length);
495
496    private:
497     void OnSocketCanReadWithoutBlocking();
498
499     void CleanupAndDeleteSelf() {
500       DCHECK_CURRENTLY_ON(BrowserThread::IO);
501
502       parent_->RemoveSocketReader(this);
503       // We're deleted beyond this point.
504     }
505
506     // Controls watching |fd_|.
507     std::unique_ptr<base::FileDescriptorWatcher::Controller>
508         fd_watch_controller_;
509
510     // The ProcessSingleton::LinuxWatcher that owns us.
511     ProcessSingleton::LinuxWatcher* const parent_;
512
513     // A reference to the UI task runner.
514     scoped_refptr<base::SingleThreadTaskRunner> ui_task_runner_;
515
516     // The file descriptor we're reading.
517     const int fd_;
518
519     // Store the message in this buffer.
520     char buf_[kMaxMessageLength];
521
522     // Tracks the number of bytes we've read in case we're getting partial
523     // reads.
524     size_t bytes_read_;
525
526     base::OneShotTimer timer_;
527
528     DISALLOW_COPY_AND_ASSIGN(SocketReader);
529   };
530
531   // We expect to only be constructed on the UI thread.
532   explicit LinuxWatcher(ProcessSingleton* parent)
533       : ui_task_runner_(base::ThreadTaskRunnerHandle::Get()), parent_(parent) {}
534
535   // Start listening for connections on the socket.  This method should be
536   // called from the IO thread.
537   void StartListening(int socket);
538
539   // This method determines if we should use the same process and if we should,
540   // opens a new browser tab.  This runs on the UI thread.
541   // |reader| is for sending back ACK message.
542   void HandleMessage(const std::string& current_dir,
543                      const std::vector<std::string>& argv,
544                      SocketReader* reader);
545
546  private:
547   friend struct BrowserThread::DeleteOnThread<BrowserThread::IO>;
548   friend class base::DeleteHelper<ProcessSingleton::LinuxWatcher>;
549
550   ~LinuxWatcher() {
551     DCHECK_CURRENTLY_ON(BrowserThread::IO);
552   }
553
554   void OnSocketCanReadWithoutBlocking(int socket);
555
556   // Removes and deletes the SocketReader.
557   void RemoveSocketReader(SocketReader* reader);
558
559   std::unique_ptr<base::FileDescriptorWatcher::Controller> socket_watcher_;
560
561   // A reference to the UI message loop (i.e., the message loop we were
562   // constructed on).
563   scoped_refptr<base::SingleThreadTaskRunner> ui_task_runner_;
564
565   // The ProcessSingleton that owns us.
566   ProcessSingleton* const parent_;
567
568   std::set<std::unique_ptr<SocketReader>, base::UniquePtrComparator> readers_;
569
570   DISALLOW_COPY_AND_ASSIGN(LinuxWatcher);
571 };
572
573 void ProcessSingleton::LinuxWatcher::OnSocketCanReadWithoutBlocking(
574     int socket) {
575   DCHECK_CURRENTLY_ON(BrowserThread::IO);
576   // Accepting incoming client.
577   sockaddr_un from;
578   socklen_t from_len = sizeof(from);
579   int connection_socket = HANDLE_EINTR(
580       accept(socket, reinterpret_cast<sockaddr*>(&from), &from_len));
581   if (-1 == connection_socket) {
582     PLOG(ERROR) << "accept() failed";
583     return;
584   }
585   DCHECK(base::SetNonBlocking(connection_socket))
586       << "Failed to make non-blocking socket.";
587   readers_.insert(
588       std::make_unique<SocketReader>(this, ui_task_runner_, connection_socket));
589 }
590
591 void ProcessSingleton::LinuxWatcher::StartListening(int socket) {
592   DCHECK_CURRENTLY_ON(BrowserThread::IO);
593   // Watch for client connections on this socket.
594   socket_watcher_ = base::FileDescriptorWatcher::WatchReadable(
595       socket, base::BindRepeating(&LinuxWatcher::OnSocketCanReadWithoutBlocking,
596                                   base::Unretained(this), socket));
597 }
598
599 void ProcessSingleton::LinuxWatcher::HandleMessage(
600     const std::string& current_dir, const std::vector<std::string>& argv,
601     SocketReader* reader) {
602   DCHECK(ui_task_runner_->BelongsToCurrentThread());
603   DCHECK(reader);
604
605   if (parent_->notification_callback_.Run(base::CommandLine(argv),
606                                           base::FilePath(current_dir))) {
607     // Send back "ACK" message to prevent the client process from starting up.
608     reader->FinishWithACK(kACKToken, base::size(kACKToken) - 1);
609   } else {
610     LOG(WARNING) << "Not handling interprocess notification as browser"
611                     " is shutting down";
612     // Send back "SHUTDOWN" message, so that the client process can start up
613     // without killing this process.
614     reader->FinishWithACK(kShutdownToken, base::size(kShutdownToken) - 1);
615     return;
616   }
617 }
618
619 void ProcessSingleton::LinuxWatcher::RemoveSocketReader(SocketReader* reader) {
620   DCHECK_CURRENTLY_ON(BrowserThread::IO);
621   DCHECK(reader);
622   auto it = readers_.find(reader);
623   readers_.erase(it);
624 }
625
626 ///////////////////////////////////////////////////////////////////////////////
627 // ProcessSingleton::LinuxWatcher::SocketReader
628 //
629
630 void ProcessSingleton::LinuxWatcher::SocketReader::
631     OnSocketCanReadWithoutBlocking() {
632   DCHECK_CURRENTLY_ON(BrowserThread::IO);
633   while (bytes_read_ < sizeof(buf_)) {
634     ssize_t rv =
635         HANDLE_EINTR(read(fd_, buf_ + bytes_read_, sizeof(buf_) - bytes_read_));
636     if (rv < 0) {
637       if (errno != EAGAIN && errno != EWOULDBLOCK) {
638         PLOG(ERROR) << "read() failed";
639         CloseSocket(fd_);
640         return;
641       } else {
642         // It would block, so we just return and continue to watch for the next
643         // opportunity to read.
644         return;
645       }
646     } else if (!rv) {
647       // No more data to read.  It's time to process the message.
648       break;
649     } else {
650       bytes_read_ += rv;
651     }
652   }
653
654   // Validate the message.  The shortest message is kStartToken\0x\0x
655   const size_t kMinMessageLength = base::size(kStartToken) + 4;
656   if (bytes_read_ < kMinMessageLength) {
657     buf_[bytes_read_] = 0;
658     LOG(ERROR) << "Invalid socket message (wrong length):" << buf_;
659     CleanupAndDeleteSelf();
660     return;
661   }
662
663   std::string str(buf_, bytes_read_);
664   std::vector<std::string> tokens = base::SplitString(
665       str, std::string(1, kTokenDelimiter),
666       base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
667
668   if (tokens.size() < 3 || tokens[0] != kStartToken) {
669     LOG(ERROR) << "Wrong message format: " << str;
670     CleanupAndDeleteSelf();
671     return;
672   }
673
674   // Stop the expiration timer to prevent this SocketReader object from being
675   // terminated unexpectly.
676   timer_.Stop();
677
678   std::string current_dir = tokens[1];
679   // Remove the first two tokens.  The remaining tokens should be the command
680   // line argv array.
681   tokens.erase(tokens.begin());
682   tokens.erase(tokens.begin());
683
684   // Return to the UI thread to handle opening a new browser tab.
685   ui_task_runner_->PostTask(
686       FROM_HERE, base::BindOnce(&ProcessSingleton::LinuxWatcher::HandleMessage,
687                                 parent_, current_dir, tokens, this));
688   fd_watch_controller_.reset();
689
690   // LinuxWatcher::HandleMessage() is in charge of destroying this SocketReader
691   // object by invoking SocketReader::FinishWithACK().
692 }
693
694 void ProcessSingleton::LinuxWatcher::SocketReader::FinishWithACK(
695     const char *message, size_t length) {
696   if (message && length) {
697     // Not necessary to care about the return value.
698     WriteToSocket(fd_, message, length);
699   }
700
701   if (shutdown(fd_, SHUT_WR) < 0)
702     PLOG(ERROR) << "shutdown() failed";
703
704   content::GetIOThreadTaskRunner({})->PostTask(
705       FROM_HERE,
706       base::BindOnce(&ProcessSingleton::LinuxWatcher::RemoveSocketReader,
707                      parent_, this));
708   // We will be deleted once the posted RemoveSocketReader task runs.
709 }
710
711 ///////////////////////////////////////////////////////////////////////////////
712 // ProcessSingleton
713 //
714 ProcessSingleton::ProcessSingleton(
715     const base::FilePath& user_data_dir,
716     const NotificationCallback& notification_callback)
717     : notification_callback_(notification_callback),
718       current_pid_(base::GetCurrentProcId()),
719       watcher_(new LinuxWatcher(this)) {
720   socket_path_ = user_data_dir.Append(chrome::kSingletonSocketFilename);
721   lock_path_ = user_data_dir.Append(chrome::kSingletonLockFilename);
722   cookie_path_ = user_data_dir.Append(chrome::kSingletonCookieFilename);
723
724   kill_callback_ = base::BindRepeating(&ProcessSingleton::KillProcess,
725                                        base::Unretained(this));
726 }
727
728 ProcessSingleton::~ProcessSingleton() {
729   DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
730 }
731
732 ProcessSingleton::NotifyResult ProcessSingleton::NotifyOtherProcess() {
733   return NotifyOtherProcessWithTimeout(
734       *base::CommandLine::ForCurrentProcess(), kRetryAttempts,
735       base::TimeDelta::FromSeconds(kTimeoutInSeconds), true);
736 }
737
738 ProcessSingleton::NotifyResult ProcessSingleton::NotifyOtherProcessWithTimeout(
739     const base::CommandLine& cmd_line,
740     int retry_attempts,
741     const base::TimeDelta& timeout,
742     bool kill_unresponsive) {
743   DCHECK_GE(retry_attempts, 0);
744   DCHECK_GE(timeout.InMicroseconds(), 0);
745
746   base::TimeDelta sleep_interval = timeout / retry_attempts;
747
748   ScopedSocket socket;
749   int pid = 0;
750   for (int retries = 0; retries <= retry_attempts; ++retries) {
751     // Try to connect to the socket.
752     if (ConnectSocket(&socket, socket_path_, cookie_path_)) {
753 #if defined(OS_MAC)
754       // On Mac, we want the open process' pid in case there are
755       // Apple Events to forward. See crbug.com/777863.
756       std::string hostname;
757       ParseProcessSingletonLock(lock_path_, &hostname, &pid);
758 #endif
759       break;
760     }
761
762     // If we're in a race with another process, they may be in Create() and have
763     // created the lock but not attached to the socket.  So we check if the
764     // process with the pid from the lockfile is currently running and is a
765     // chrome browser.  If so, we loop and try again for |timeout|.
766
767     std::string hostname;
768     if (!ParseProcessSingletonLock(lock_path_, &hostname, &pid)) {
769       // No lockfile exists.
770       return PROCESS_NONE;
771     }
772
773     if (hostname.empty()) {
774       // Invalid lockfile.
775       UnlinkPath(lock_path_);
776       SendRemoteProcessInteractionResultHistogram(INVALID_LOCK_FILE);
777       return PROCESS_NONE;
778     }
779
780     if (hostname != net::GetHostName() && !IsChromeProcess(pid)) {
781       // Locked by process on another host. If the user selected to unlock
782       // the profile, try to continue; otherwise quit.
783       if (DisplayProfileInUseError(lock_path_, hostname, pid)) {
784         UnlinkPath(lock_path_);
785         SendRemoteProcessInteractionResultHistogram(PROFILE_UNLOCKED);
786         return PROCESS_NONE;
787       }
788       return PROFILE_IN_USE;
789     }
790
791     if (!IsChromeProcess(pid)) {
792       // Orphaned lockfile (no process with pid, or non-chrome process.)
793       UnlinkPath(lock_path_);
794       SendRemoteProcessInteractionResultHistogram(ORPHANED_LOCK_FILE);
795       return PROCESS_NONE;
796     }
797
798     if (IsSameChromeInstance(pid)) {
799       // Orphaned lockfile (pid is part of same chrome instance we are, even
800       // though we haven't tried to create a lockfile yet).
801       UnlinkPath(lock_path_);
802       SendRemoteProcessInteractionResultHistogram(SAME_BROWSER_INSTANCE);
803       return PROCESS_NONE;
804     }
805
806     if (retries == retry_attempts) {
807       // Retries failed.  Kill the unresponsive chrome process and continue.
808       if (!kill_unresponsive || !KillProcessByLockPath(false))
809         return PROFILE_IN_USE;
810       SendRemoteHungProcessTerminateReasonHistogram(NOTIFY_ATTEMPTS_EXCEEDED);
811       return PROCESS_NONE;
812     }
813
814     base::PlatformThread::Sleep(sleep_interval);
815   }
816
817 #if defined(OS_MAC)
818   if (pid > 0 && WaitForAndForwardOpenURLEvent(pid)) {
819     return PROCESS_NOTIFIED;
820   }
821 #endif
822   timeval socket_timeout = TimeDeltaToTimeVal(timeout);
823   setsockopt(socket.fd(),
824              SOL_SOCKET,
825              SO_SNDTIMEO,
826              &socket_timeout,
827              sizeof(socket_timeout));
828
829   // Found another process, prepare our command line
830   // format is "START\0<current dir>\0<argv[0]>\0...\0<argv[n]>".
831   std::string to_send(kStartToken);
832   to_send.push_back(kTokenDelimiter);
833
834   base::FilePath current_dir;
835   if (!base::PathService::Get(base::DIR_CURRENT, &current_dir))
836     return PROCESS_NONE;
837   to_send.append(current_dir.value());
838
839   const std::vector<std::string>& argv = cmd_line.argv();
840   for (auto it = argv.begin(); it != argv.end(); ++it) {
841     to_send.push_back(kTokenDelimiter);
842     to_send.append(*it);
843   }
844
845   // Send the message
846   if (!WriteToSocket(socket.fd(), to_send.data(), to_send.length())) {
847     // Try to kill the other process, because it might have been dead.
848     if (!kill_unresponsive || !KillProcessByLockPath(true))
849       return PROFILE_IN_USE;
850     SendRemoteHungProcessTerminateReasonHistogram(SOCKET_WRITE_FAILED);
851     return PROCESS_NONE;
852   }
853
854   if (shutdown(socket.fd(), SHUT_WR) < 0)
855     PLOG(ERROR) << "shutdown() failed";
856
857   // Read ACK message from the other process. It might be blocked for a certain
858   // timeout, to make sure the other process has enough time to return ACK.
859   char buf[kMaxACKMessageLength + 1];
860   ssize_t len = ReadFromSocket(socket.fd(), buf, kMaxACKMessageLength, timeout);
861
862   // Failed to read ACK, the other process might have been frozen.
863   if (len <= 0) {
864     if (!kill_unresponsive || !KillProcessByLockPath(true))
865       return PROFILE_IN_USE;
866     SendRemoteHungProcessTerminateReasonHistogram(SOCKET_READ_FAILED);
867     return PROCESS_NONE;
868   }
869
870   buf[len] = '\0';
871   if (strncmp(buf, kShutdownToken, base::size(kShutdownToken) - 1) == 0) {
872     // The other process is shutting down, it's safe to start a new process.
873     SendRemoteProcessInteractionResultHistogram(REMOTE_PROCESS_SHUTTING_DOWN);
874     return PROCESS_NONE;
875   } else if (strncmp(buf, kACKToken, base::size(kACKToken) - 1) == 0) {
876 #if defined(TOOLKIT_VIEWS) && \
877     (defined(OS_LINUX) || BUILDFLAG(IS_CHROMEOS_LACROS))
878     // Likely NULL in unit tests.
879     views::LinuxUI* linux_ui = views::LinuxUI::instance();
880     if (linux_ui)
881       linux_ui->NotifyWindowManagerStartupComplete();
882 #endif
883
884     // Assume the other process is handling the request.
885     return PROCESS_NOTIFIED;
886   }
887
888   NOTREACHED() << "The other process returned unknown message: " << buf;
889   return PROCESS_NOTIFIED;
890 }
891
892 ProcessSingleton::NotifyResult ProcessSingleton::NotifyOtherProcessOrCreate() {
893   return NotifyOtherProcessWithTimeoutOrCreate(
894       *base::CommandLine::ForCurrentProcess(), kRetryAttempts,
895       base::TimeDelta::FromSeconds(kTimeoutInSeconds));
896 }
897
898 ProcessSingleton::NotifyResult
899 ProcessSingleton::NotifyOtherProcessWithTimeoutOrCreate(
900     const base::CommandLine& command_line,
901     int retry_attempts,
902     const base::TimeDelta& timeout) {
903   const base::TimeTicks begin_ticks = base::TimeTicks::Now();
904   NotifyResult result = NotifyOtherProcessWithTimeout(
905       command_line, retry_attempts, timeout, true);
906   if (result != PROCESS_NONE) {
907     if (result == PROCESS_NOTIFIED) {
908       UMA_HISTOGRAM_MEDIUM_TIMES("Chrome.ProcessSingleton.TimeToNotify",
909                                  base::TimeTicks::Now() - begin_ticks);
910     } else {
911       UMA_HISTOGRAM_MEDIUM_TIMES("Chrome.ProcessSingleton.TimeToFailure",
912                                  base::TimeTicks::Now() - begin_ticks);
913     }
914     return result;
915   }
916
917   if (Create()) {
918     UMA_HISTOGRAM_MEDIUM_TIMES("Chrome.ProcessSingleton.TimeToCreate",
919                                base::TimeTicks::Now() - begin_ticks);
920     return PROCESS_NONE;
921   }
922
923   // If the Create() failed, try again to notify. (It could be that another
924   // instance was starting at the same time and managed to grab the lock before
925   // we did.)
926   // This time, we don't want to kill anything if we aren't successful, since we
927   // aren't going to try to take over the lock ourselves.
928   result = NotifyOtherProcessWithTimeout(
929       command_line, retry_attempts, timeout, false);
930
931   if (result == PROCESS_NOTIFIED) {
932     UMA_HISTOGRAM_MEDIUM_TIMES("Chrome.ProcessSingleton.TimeToNotify",
933                                base::TimeTicks::Now() - begin_ticks);
934   } else {
935     UMA_HISTOGRAM_MEDIUM_TIMES("Chrome.ProcessSingleton.TimeToFailure",
936                                base::TimeTicks::Now() - begin_ticks);
937   }
938
939   if (result != PROCESS_NONE)
940     return result;
941
942   return LOCK_ERROR;
943 }
944
945 void ProcessSingleton::OverrideCurrentPidForTesting(base::ProcessId pid) {
946   current_pid_ = pid;
947 }
948
949 void ProcessSingleton::OverrideKillCallbackForTesting(
950     const base::RepeatingCallback<void(int)>& callback) {
951   kill_callback_ = callback;
952 }
953
954 // static
955 void ProcessSingleton::DisablePromptForTesting() {
956   g_disable_prompt = true;
957 }
958
959 // static
960 void ProcessSingleton::SkipIsChromeProcessCheckForTesting(bool skip) {
961   g_skip_is_chrome_process_check = skip;
962 }
963
964 // static
965 void ProcessSingleton::SetUserOptedUnlockInUseProfileForTesting(
966     bool set_unlock) {
967   g_user_opted_unlock_in_use_profile = set_unlock;
968 }
969
970 bool ProcessSingleton::Create() {
971   int sock;
972   sockaddr_un addr;
973
974   // The symlink lock is pointed to the hostname and process id, so other
975   // processes can find it out.
976   base::FilePath symlink_content(
977       base::StringPrintf("%s%c%u", net::GetHostName().c_str(),
978                          kProcessSingletonLockDelimiter, current_pid_));
979
980   // Create symbol link before binding the socket, to ensure only one instance
981   // can have the socket open.
982   if (!SymlinkPath(symlink_content, lock_path_)) {
983     // TODO(jackhou): Remove this case once this code is stable on Mac.
984     // http://crbug.com/367612
985 #if defined(OS_MAC)
986     // On Mac, an existing non-symlink lock file means the lock could be held by
987     // the old process singleton code. If we can successfully replace the lock,
988     // continue as normal.
989     if (base::IsLink(lock_path_) ||
990         !ReplaceOldSingletonLock(symlink_content, lock_path_)) {
991       return false;
992     }
993 #else
994     // If we failed to create the lock, most likely another instance won the
995     // startup race.
996     return false;
997 #endif
998   }
999
1000   // Create the socket file somewhere in /tmp which is usually mounted as a
1001   // normal filesystem. Some network filesystems (notably AFS) are screwy and
1002   // do not support Unix domain sockets.
1003   if (!socket_dir_.CreateUniqueTempDir()) {
1004     LOG(ERROR) << "Failed to create socket directory.";
1005     return false;
1006   }
1007
1008   // Check that the directory was created with the correct permissions.
1009   int dir_mode = 0;
1010   CHECK(base::GetPosixFilePermissions(socket_dir_.GetPath(), &dir_mode) &&
1011         dir_mode == base::FILE_PERMISSION_USER_MASK)
1012       << "Temp directory mode is not 700: " << std::oct << dir_mode;
1013
1014   // Try to create the socket before creating the symlink, as SetupSocket may
1015   // fail on a CHECK if the |socket_target_path| is too long, and this avoids
1016   // leaving a dangling symlink.
1017   base::FilePath socket_target_path =
1018       socket_dir_.GetPath().Append(chrome::kSingletonSocketFilename);
1019   SetupSocket(socket_target_path.value(), &sock, &addr);
1020
1021   // Setup the socket symlink and the two cookies.
1022   base::FilePath cookie(GenerateCookie());
1023   base::FilePath remote_cookie_path =
1024       socket_dir_.GetPath().Append(chrome::kSingletonCookieFilename);
1025   UnlinkPath(socket_path_);
1026   UnlinkPath(cookie_path_);
1027   if (!SymlinkPath(socket_target_path, socket_path_) ||
1028       !SymlinkPath(cookie, cookie_path_) ||
1029       !SymlinkPath(cookie, remote_cookie_path)) {
1030     // We've already locked things, so we can't have lost the startup race,
1031     // but something doesn't like us.
1032     LOG(ERROR) << "Failed to create symlinks.";
1033     if (!socket_dir_.Delete())
1034       LOG(ERROR) << "Encountered a problem when deleting socket directory.";
1035     return false;
1036   }
1037
1038   if (bind(sock, reinterpret_cast<sockaddr*>(&addr), sizeof(addr)) < 0) {
1039     PLOG(ERROR) << "Failed to bind() " << socket_target_path.value();
1040     CloseSocket(sock);
1041     return false;
1042   }
1043
1044   if (listen(sock, 5) < 0)
1045     NOTREACHED() << "listen failed: " << base::safe_strerror(errno);
1046
1047   DCHECK(BrowserThread::IsThreadInitialized(BrowserThread::IO));
1048   content::GetIOThreadTaskRunner({})->PostTask(
1049       FROM_HERE, base::BindOnce(&ProcessSingleton::LinuxWatcher::StartListening,
1050                                 watcher_, sock));
1051
1052   return true;
1053 }
1054
1055 void ProcessSingleton::Cleanup() {
1056   UnlinkPath(socket_path_);
1057   UnlinkPath(cookie_path_);
1058   UnlinkPath(lock_path_);
1059 }
1060
1061 bool ProcessSingleton::IsSameChromeInstance(pid_t pid) {
1062   pid_t cur_pid = current_pid_;
1063   while (pid != cur_pid) {
1064     pid = base::GetParentProcessId(pid);
1065     if (pid <= 0)
1066       return false;
1067     if (!IsChromeProcess(pid))
1068       return false;
1069   }
1070   return true;
1071 }
1072
1073 bool ProcessSingleton::KillProcessByLockPath(bool is_connected_to_socket) {
1074   std::string hostname;
1075   int pid;
1076   ParseProcessSingletonLock(lock_path_, &hostname, &pid);
1077
1078   if (!hostname.empty() && hostname != net::GetHostName() &&
1079       !is_connected_to_socket) {
1080     bool res = DisplayProfileInUseError(lock_path_, hostname, pid);
1081     if (res) {
1082       UnlinkPath(lock_path_);
1083       SendRemoteProcessInteractionResultHistogram(PROFILE_UNLOCKED_BEFORE_KILL);
1084     }
1085     return res;
1086   }
1087   UnlinkPath(lock_path_);
1088
1089   if (IsSameChromeInstance(pid)) {
1090     SendRemoteProcessInteractionResultHistogram(
1091         SAME_BROWSER_INSTANCE_BEFORE_KILL);
1092     return true;
1093   }
1094
1095   if (pid > 0) {
1096     kill_callback_.Run(pid);
1097     return true;
1098   }
1099
1100   SendRemoteProcessInteractionResultHistogram(FAILED_TO_EXTRACT_PID);
1101
1102   LOG(ERROR) << "Failed to extract pid from path: " << lock_path_.value();
1103   return true;
1104 }
1105
1106 void ProcessSingleton::KillProcess(int pid) {
1107   // TODO(james.su@gmail.com): Is SIGKILL ok?
1108   int rv = kill(static_cast<base::ProcessHandle>(pid), SIGKILL);
1109   // ESRCH = No Such Process (can happen if the other process is already in
1110   // progress of shutting down and finishes before we try to kill it).
1111   DCHECK(rv == 0 || errno == ESRCH) << "Error killing process: "
1112                                     << base::safe_strerror(errno);
1113
1114   int error_code = (rv == 0) ? 0 : errno;
1115   base::UmaHistogramSparse(
1116       "Chrome.ProcessSingleton.TerminateProcessErrorCode.Posix", error_code);
1117
1118   RemoteProcessInteractionResult action = TERMINATE_SUCCEEDED;
1119   if (rv != 0) {
1120     switch (error_code) {
1121       case ESRCH:
1122         action = REMOTE_PROCESS_NOT_FOUND;
1123         break;
1124       case EPERM:
1125         action = TERMINATE_NOT_ENOUGH_PERMISSIONS;
1126         break;
1127       default:
1128         action = TERMINATE_FAILED;
1129         break;
1130     }
1131   }
1132   SendRemoteProcessInteractionResultHistogram(action);
1133 }