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