process_singleton_posix.cc 37 KB

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