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