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