process_singleton_posix.cc 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104
  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 "shell/browser/browser.h"
  53. #include "shell/common/electron_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/metrics/histogram_macros.h"
  65. #include "base/path_service.h"
  66. #include "base/posix/eintr_wrapper.h"
  67. #include "base/posix/safe_strerror.h"
  68. #include "base/rand_util.h"
  69. #include "base/sequenced_task_runner_helpers.h"
  70. #include "base/single_thread_task_runner.h"
  71. #include "base/stl_util.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/task/post_task.h"
  79. #include "base/threading/platform_thread.h"
  80. #include "base/threading/thread_restrictions.h"
  81. #include "base/threading/thread_task_runner_handle.h"
  82. #include "base/time/time.h"
  83. #include "base/timer/timer.h"
  84. #include "build/build_config.h"
  85. #include "content/public/browser/browser_task_traits.h"
  86. #include "content/public/browser/browser_thread.h"
  87. #include "net/base/network_interfaces.h"
  88. #if defined(TOOLKIT_VIEWS) && defined(OS_LINUX) && !defined(OS_CHROMEOS)
  89. #include "ui/views/linux_ui/linux_ui.h"
  90. #endif
  91. using content::BrowserThread;
  92. namespace {
  93. // Timeout for the current browser process to respond. 20 seconds should be
  94. // enough.
  95. const int kTimeoutInSeconds = 20;
  96. // Number of retries to notify the browser. 20 retries over 20 seconds = 1 try
  97. // per second.
  98. const int kRetryAttempts = 20;
  99. static bool g_disable_prompt;
  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 = base::size(kShutdownToken) - 1;
  106. const char kLockDelimiter = '-';
  107. const base::FilePath::CharType kSingletonCookieFilename[] =
  108. FILE_PATH_LITERAL("SingletonCookie");
  109. const base::FilePath::CharType kSingletonLockFilename[] =
  110. FILE_PATH_LITERAL("SingletonLock");
  111. const base::FilePath::CharType kSingletonSocketFilename[] =
  112. FILE_PATH_LITERAL("SS");
  113. // Set the close-on-exec bit on a file descriptor.
  114. // Returns 0 on success, -1 on failure.
  115. int SetCloseOnExec(int fd) {
  116. int flags = fcntl(fd, F_GETFD, 0);
  117. if (-1 == flags)
  118. return flags;
  119. if (flags & FD_CLOEXEC)
  120. return 0;
  121. return fcntl(fd, F_SETFD, flags | FD_CLOEXEC);
  122. }
  123. // Close a socket and check return value.
  124. void CloseSocket(int fd) {
  125. int rv = IGNORE_EINTR(close(fd));
  126. DCHECK_EQ(0, rv) << "Error closing socket: " << base::safe_strerror(errno);
  127. }
  128. // Write a message to a socket fd.
  129. bool WriteToSocket(int fd, const char* message, size_t length) {
  130. DCHECK(message);
  131. DCHECK(length);
  132. size_t bytes_written = 0;
  133. do {
  134. ssize_t rv = HANDLE_EINTR(
  135. write(fd, message + bytes_written, length - bytes_written));
  136. if (rv < 0) {
  137. if (errno == EAGAIN || errno == EWOULDBLOCK) {
  138. // The socket shouldn't block, we're sending so little data. Just give
  139. // up here, since NotifyOtherProcess() doesn't have an asynchronous api.
  140. LOG(ERROR) << "ProcessSingleton would block on write(), so it gave up.";
  141. return false;
  142. }
  143. PLOG(ERROR) << "write() failed";
  144. return false;
  145. }
  146. bytes_written += rv;
  147. } while (bytes_written < length);
  148. return true;
  149. }
  150. struct timeval TimeDeltaToTimeVal(const base::TimeDelta& delta) {
  151. struct timeval result;
  152. result.tv_sec = delta.InSeconds();
  153. result.tv_usec = delta.InMicroseconds() % base::Time::kMicrosecondsPerSecond;
  154. return result;
  155. }
  156. // Wait a socket for read for a certain timeout.
  157. // Returns -1 if error occurred, 0 if timeout reached, > 0 if the socket is
  158. // ready for read.
  159. int WaitSocketForRead(int fd, const base::TimeDelta& timeout) {
  160. fd_set read_fds;
  161. struct timeval tv = TimeDeltaToTimeVal(timeout);
  162. FD_ZERO(&read_fds);
  163. FD_SET(fd, &read_fds);
  164. return HANDLE_EINTR(select(fd + 1, &read_fds, nullptr, nullptr, &tv));
  165. }
  166. // Read a message from a socket fd, with an optional timeout.
  167. // If |timeout| <= 0 then read immediately.
  168. // Return number of bytes actually read, or -1 on error.
  169. ssize_t ReadFromSocket(int fd,
  170. char* buf,
  171. size_t bufsize,
  172. const base::TimeDelta& timeout) {
  173. if (timeout > base::TimeDelta()) {
  174. int rv = WaitSocketForRead(fd, timeout);
  175. if (rv <= 0)
  176. return rv;
  177. }
  178. size_t bytes_read = 0;
  179. do {
  180. ssize_t rv = HANDLE_EINTR(read(fd, buf + bytes_read, bufsize - bytes_read));
  181. if (rv < 0) {
  182. if (errno != EAGAIN && errno != EWOULDBLOCK) {
  183. PLOG(ERROR) << "read() failed";
  184. return rv;
  185. } else {
  186. // It would block, so we just return what has been read.
  187. return bytes_read;
  188. }
  189. } else if (!rv) {
  190. // No more data to read.
  191. return bytes_read;
  192. } else {
  193. bytes_read += rv;
  194. }
  195. } while (bytes_read < bufsize);
  196. return bytes_read;
  197. }
  198. // Set up a sockaddr appropriate for messaging.
  199. void SetupSockAddr(const std::string& path, struct sockaddr_un* addr) {
  200. addr->sun_family = AF_UNIX;
  201. CHECK(path.length() < base::size(addr->sun_path))
  202. << "Socket path too long: " << path;
  203. base::strlcpy(addr->sun_path, path.c_str(), base::size(addr->sun_path));
  204. }
  205. // Set up a socket appropriate for messaging.
  206. int SetupSocketOnly() {
  207. int sock = socket(PF_UNIX, SOCK_STREAM, 0);
  208. PCHECK(sock >= 0) << "socket() failed";
  209. DCHECK(base::SetNonBlocking(sock)) << "Failed to make non-blocking socket.";
  210. int rv = SetCloseOnExec(sock);
  211. DCHECK_EQ(0, rv) << "Failed to set CLOEXEC on socket.";
  212. return sock;
  213. }
  214. // Set up a socket and sockaddr appropriate for messaging.
  215. void SetupSocket(const std::string& path, int* sock, struct sockaddr_un* addr) {
  216. *sock = SetupSocketOnly();
  217. SetupSockAddr(path, addr);
  218. }
  219. // Read a symbolic link, return empty string if given path is not a symbol link.
  220. base::FilePath ReadLink(const base::FilePath& path) {
  221. base::FilePath target;
  222. if (!base::ReadSymbolicLink(path, &target)) {
  223. // The only errno that should occur is ENOENT.
  224. if (errno != 0 && errno != ENOENT)
  225. PLOG(ERROR) << "readlink(" << path.value() << ") failed";
  226. }
  227. return target;
  228. }
  229. // Unlink a path. Return true on success.
  230. bool UnlinkPath(const base::FilePath& path) {
  231. int rv = unlink(path.value().c_str());
  232. if (rv < 0 && errno != ENOENT)
  233. PLOG(ERROR) << "Failed to unlink " << path.value();
  234. return rv == 0;
  235. }
  236. // Create a symlink. Returns true on success.
  237. bool SymlinkPath(const base::FilePath& target, const base::FilePath& path) {
  238. if (!base::CreateSymbolicLink(target, path)) {
  239. // Double check the value in case symlink suceeded but we got an incorrect
  240. // failure due to NFS packet loss & retry.
  241. int saved_errno = errno;
  242. if (ReadLink(path) != target) {
  243. // If we failed to create the lock, most likely another instance won the
  244. // startup race.
  245. errno = saved_errno;
  246. PLOG(ERROR) << "Failed to create " << path.value();
  247. return false;
  248. }
  249. }
  250. return true;
  251. }
  252. // Extract the hostname and pid from the lock symlink.
  253. // Returns true if the lock existed.
  254. bool ParseLockPath(const base::FilePath& path,
  255. std::string* hostname,
  256. int* pid) {
  257. std::string real_path = ReadLink(path).value();
  258. if (real_path.empty())
  259. return false;
  260. std::string::size_type pos = real_path.rfind(kLockDelimiter);
  261. // If the path is not a symbolic link, or doesn't contain what we expect,
  262. // bail.
  263. if (pos == std::string::npos) {
  264. *hostname = "";
  265. *pid = -1;
  266. return true;
  267. }
  268. *hostname = real_path.substr(0, pos);
  269. const std::string& pid_str = real_path.substr(pos + 1);
  270. if (!base::StringToInt(pid_str, pid))
  271. *pid = -1;
  272. return true;
  273. }
  274. // Returns true if the user opted to unlock the profile.
  275. bool DisplayProfileInUseError(const base::FilePath& lock_path,
  276. const std::string& hostname,
  277. int pid) {
  278. return true;
  279. }
  280. bool IsChromeProcess(pid_t pid) {
  281. base::FilePath other_chrome_path(base::GetProcessExecutablePath(pid));
  282. auto* command_line = base::CommandLine::ForCurrentProcess();
  283. base::FilePath exec_path(command_line->GetProgram());
  284. base::PathService::Get(base::FILE_EXE, &exec_path);
  285. return (!other_chrome_path.empty() &&
  286. other_chrome_path.BaseName() == exec_path.BaseName());
  287. }
  288. // A helper class to hold onto a socket.
  289. class ScopedSocket {
  290. public:
  291. ScopedSocket() : fd_(-1) { Reset(); }
  292. ~ScopedSocket() { Close(); }
  293. int fd() { return fd_; }
  294. void Reset() {
  295. Close();
  296. fd_ = SetupSocketOnly();
  297. }
  298. void Close() {
  299. if (fd_ >= 0)
  300. CloseSocket(fd_);
  301. fd_ = -1;
  302. }
  303. private:
  304. int fd_;
  305. };
  306. // Returns a random string for uniquifying profile connections.
  307. std::string GenerateCookie() {
  308. return base::NumberToString(base::RandUint64());
  309. }
  310. bool CheckCookie(const base::FilePath& path, const base::FilePath& cookie) {
  311. return (cookie == ReadLink(path));
  312. }
  313. bool IsAppSandboxed() {
  314. #if defined(OS_MACOSX)
  315. // NB: There is no sane API for this, we have to just guess by
  316. // reading tea leaves
  317. base::FilePath home_dir;
  318. if (!base::PathService::Get(base::DIR_HOME, &home_dir)) {
  319. return false;
  320. }
  321. return home_dir.value().find("Library/Containers") != std::string::npos;
  322. #else
  323. return false;
  324. #endif // defined(OS_MACOSX)
  325. }
  326. bool ConnectSocket(ScopedSocket* socket,
  327. const base::FilePath& socket_path,
  328. const base::FilePath& cookie_path) {
  329. base::FilePath socket_target;
  330. if (base::ReadSymbolicLink(socket_path, &socket_target)) {
  331. // It's a symlink. Read the cookie.
  332. base::FilePath cookie = ReadLink(cookie_path);
  333. if (cookie.empty())
  334. return false;
  335. base::FilePath remote_cookie =
  336. socket_target.DirName().Append(kSingletonCookieFilename);
  337. // Verify the cookie before connecting.
  338. if (!CheckCookie(remote_cookie, cookie))
  339. return false;
  340. // Now we know the directory was (at that point) created by the profile
  341. // owner. Try to connect.
  342. sockaddr_un addr;
  343. SetupSockAddr(socket_target.value(), &addr);
  344. int ret = HANDLE_EINTR(connect(
  345. socket->fd(), reinterpret_cast<sockaddr*>(&addr), sizeof(addr)));
  346. if (ret != 0)
  347. return false;
  348. // Check the cookie again. We only link in /tmp, which is sticky, so, if the
  349. // directory is still correct, it must have been correct in-between when we
  350. // connected. POSIX, sadly, lacks a connectat().
  351. if (!CheckCookie(remote_cookie, cookie)) {
  352. socket->Reset();
  353. return false;
  354. }
  355. // Success!
  356. return true;
  357. } else if (errno == EINVAL) {
  358. // It exists, but is not a symlink (or some other error we detect
  359. // later). Just connect to it directly; this is an older version of Chrome.
  360. sockaddr_un addr;
  361. SetupSockAddr(socket_path.value(), &addr);
  362. int ret = HANDLE_EINTR(connect(
  363. socket->fd(), reinterpret_cast<sockaddr*>(&addr), sizeof(addr)));
  364. return (ret == 0);
  365. } else {
  366. // File is missing, or other error.
  367. if (errno != ENOENT)
  368. PLOG(ERROR) << "readlink failed";
  369. return false;
  370. }
  371. }
  372. #if defined(OS_MACOSX)
  373. bool ReplaceOldSingletonLock(const base::FilePath& symlink_content,
  374. const base::FilePath& lock_path) {
  375. // Try taking an flock(2) on the file. Failure means the lock is taken so we
  376. // should quit.
  377. base::ScopedFD lock_fd(HANDLE_EINTR(
  378. open(lock_path.value().c_str(), O_RDWR | O_CREAT | O_SYMLINK, 0644)));
  379. if (!lock_fd.is_valid()) {
  380. PLOG(ERROR) << "Could not open singleton lock";
  381. return false;
  382. }
  383. int rc = HANDLE_EINTR(flock(lock_fd.get(), LOCK_EX | LOCK_NB));
  384. if (rc == -1) {
  385. if (errno == EWOULDBLOCK) {
  386. LOG(ERROR) << "Singleton lock held by old process.";
  387. } else {
  388. PLOG(ERROR) << "Error locking singleton lock";
  389. }
  390. return false;
  391. }
  392. // Successfully taking the lock means we can replace it with the a new symlink
  393. // lock. We never flock() the lock file from now on. I.e. we assume that an
  394. // old version of Chrome will not run with the same user data dir after this
  395. // version has run.
  396. if (!base::DeleteFile(lock_path, false)) {
  397. PLOG(ERROR) << "Could not delete old singleton lock.";
  398. return false;
  399. }
  400. return SymlinkPath(symlink_content, lock_path);
  401. }
  402. #endif // defined(OS_MACOSX)
  403. } // namespace
  404. ///////////////////////////////////////////////////////////////////////////////
  405. // ProcessSingleton::LinuxWatcher
  406. // A helper class for a Linux specific implementation of the process singleton.
  407. // This class sets up a listener on the singleton socket and handles parsing
  408. // messages that come in on the singleton socket.
  409. class ProcessSingleton::LinuxWatcher
  410. : public base::RefCountedThreadSafe<ProcessSingleton::LinuxWatcher,
  411. BrowserThread::DeleteOnIOThread> {
  412. public:
  413. // A helper class to read message from an established socket.
  414. class SocketReader {
  415. public:
  416. SocketReader(ProcessSingleton::LinuxWatcher* parent,
  417. scoped_refptr<base::SingleThreadTaskRunner> ui_task_runner,
  418. int fd)
  419. : parent_(parent),
  420. ui_task_runner_(ui_task_runner),
  421. fd_(fd),
  422. bytes_read_(0) {
  423. DCHECK_CURRENTLY_ON(BrowserThread::IO);
  424. // Wait for reads.
  425. fd_watch_controller_ = base::FileDescriptorWatcher::WatchReadable(
  426. fd, base::BindRepeating(&SocketReader::OnSocketCanReadWithoutBlocking,
  427. base::Unretained(this)));
  428. // If we haven't completed in a reasonable amount of time, give up.
  429. timer_.Start(FROM_HERE, base::TimeDelta::FromSeconds(kTimeoutInSeconds),
  430. this, &SocketReader::CleanupAndDeleteSelf);
  431. }
  432. ~SocketReader() { CloseSocket(fd_); }
  433. // Finish handling the incoming message by optionally sending back an ACK
  434. // message and removing this SocketReader.
  435. void FinishWithACK(const char* message, size_t length);
  436. private:
  437. void OnSocketCanReadWithoutBlocking();
  438. void CleanupAndDeleteSelf() {
  439. DCHECK_CURRENTLY_ON(BrowserThread::IO);
  440. parent_->RemoveSocketReader(this);
  441. // We're deleted beyond this point.
  442. }
  443. // Controls watching |fd_|.
  444. std::unique_ptr<base::FileDescriptorWatcher::Controller>
  445. fd_watch_controller_;
  446. // The ProcessSingleton::LinuxWatcher that owns us.
  447. ProcessSingleton::LinuxWatcher* const parent_;
  448. // A reference to the UI task runner.
  449. scoped_refptr<base::SingleThreadTaskRunner> ui_task_runner_;
  450. // The file descriptor we're reading.
  451. const int fd_;
  452. // Store the message in this buffer.
  453. char buf_[kMaxMessageLength];
  454. // Tracks the number of bytes we've read in case we're getting partial
  455. // reads.
  456. size_t bytes_read_;
  457. base::OneShotTimer timer_;
  458. DISALLOW_COPY_AND_ASSIGN(SocketReader);
  459. };
  460. // We expect to only be constructed on the UI thread.
  461. explicit LinuxWatcher(ProcessSingleton* parent)
  462. : ui_task_runner_(base::ThreadTaskRunnerHandle::Get()), parent_(parent) {}
  463. // Start listening for connections on the socket. This method should be
  464. // called from the IO thread.
  465. void StartListening(int socket);
  466. // This method determines if we should use the same process and if we should,
  467. // opens a new browser tab. This runs on the UI thread.
  468. // |reader| is for sending back ACK message.
  469. void HandleMessage(const std::string& current_dir,
  470. const std::vector<std::string>& argv,
  471. SocketReader* reader);
  472. private:
  473. friend struct BrowserThread::DeleteOnThread<BrowserThread::IO>;
  474. friend class base::DeleteHelper<ProcessSingleton::LinuxWatcher>;
  475. ~LinuxWatcher() { DCHECK_CURRENTLY_ON(BrowserThread::IO); }
  476. void OnSocketCanReadWithoutBlocking(int socket);
  477. // Removes and deletes the SocketReader.
  478. void RemoveSocketReader(SocketReader* reader);
  479. std::unique_ptr<base::FileDescriptorWatcher::Controller> socket_watcher_;
  480. // A reference to the UI message loop (i.e., the message loop we were
  481. // constructed on).
  482. scoped_refptr<base::SingleThreadTaskRunner> ui_task_runner_;
  483. // The ProcessSingleton that owns us.
  484. ProcessSingleton* const parent_;
  485. std::set<std::unique_ptr<SocketReader>> readers_;
  486. DISALLOW_COPY_AND_ASSIGN(LinuxWatcher);
  487. };
  488. void ProcessSingleton::LinuxWatcher::OnSocketCanReadWithoutBlocking(
  489. int socket) {
  490. DCHECK_CURRENTLY_ON(BrowserThread::IO);
  491. // Accepting incoming client.
  492. sockaddr_un from;
  493. socklen_t from_len = sizeof(from);
  494. int connection_socket = HANDLE_EINTR(
  495. accept(socket, reinterpret_cast<sockaddr*>(&from), &from_len));
  496. if (-1 == connection_socket) {
  497. PLOG(ERROR) << "accept() failed";
  498. return;
  499. }
  500. DCHECK(base::SetNonBlocking(connection_socket))
  501. << "Failed to make non-blocking socket.";
  502. readers_.insert(
  503. std::make_unique<SocketReader>(this, ui_task_runner_, connection_socket));
  504. }
  505. void ProcessSingleton::LinuxWatcher::StartListening(int socket) {
  506. DCHECK_CURRENTLY_ON(BrowserThread::IO);
  507. // Watch for client connections on this socket.
  508. socket_watcher_ = base::FileDescriptorWatcher::WatchReadable(
  509. socket, base::BindRepeating(&LinuxWatcher::OnSocketCanReadWithoutBlocking,
  510. base::Unretained(this), socket));
  511. }
  512. void ProcessSingleton::LinuxWatcher::HandleMessage(
  513. const std::string& current_dir,
  514. const std::vector<std::string>& argv,
  515. SocketReader* reader) {
  516. DCHECK(ui_task_runner_->BelongsToCurrentThread());
  517. DCHECK(reader);
  518. if (parent_->notification_callback_.Run(argv, base::FilePath(current_dir))) {
  519. // Send back "ACK" message to prevent the client process from starting up.
  520. reader->FinishWithACK(kACKToken, base::size(kACKToken) - 1);
  521. } else {
  522. LOG(WARNING) << "Not handling interprocess notification as browser"
  523. " is shutting down";
  524. // Send back "SHUTDOWN" message, so that the client process can start up
  525. // without killing this process.
  526. reader->FinishWithACK(kShutdownToken, base::size(kShutdownToken) - 1);
  527. return;
  528. }
  529. }
  530. void ProcessSingleton::LinuxWatcher::RemoveSocketReader(SocketReader* reader) {
  531. DCHECK_CURRENTLY_ON(BrowserThread::IO);
  532. DCHECK(reader);
  533. auto it = std::find_if(readers_.begin(), readers_.end(),
  534. [reader](const std::unique_ptr<SocketReader>& ptr) {
  535. return ptr.get() == reader;
  536. });
  537. readers_.erase(it);
  538. }
  539. ///////////////////////////////////////////////////////////////////////////////
  540. // ProcessSingleton::LinuxWatcher::SocketReader
  541. //
  542. void ProcessSingleton::LinuxWatcher::SocketReader::
  543. OnSocketCanReadWithoutBlocking() {
  544. DCHECK_CURRENTLY_ON(BrowserThread::IO);
  545. while (bytes_read_ < sizeof(buf_)) {
  546. ssize_t rv =
  547. HANDLE_EINTR(read(fd_, buf_ + bytes_read_, sizeof(buf_) - bytes_read_));
  548. if (rv < 0) {
  549. if (errno != EAGAIN && errno != EWOULDBLOCK) {
  550. PLOG(ERROR) << "read() failed";
  551. CloseSocket(fd_);
  552. return;
  553. } else {
  554. // It would block, so we just return and continue to watch for the next
  555. // opportunity to read.
  556. return;
  557. }
  558. } else if (!rv) {
  559. // No more data to read. It's time to process the message.
  560. break;
  561. } else {
  562. bytes_read_ += rv;
  563. }
  564. }
  565. // Validate the message. The shortest message is kStartToken\0x\0x
  566. const size_t kMinMessageLength = base::size(kStartToken) + 4;
  567. if (bytes_read_ < kMinMessageLength) {
  568. buf_[bytes_read_] = 0;
  569. LOG(ERROR) << "Invalid socket message (wrong length):" << buf_;
  570. CleanupAndDeleteSelf();
  571. return;
  572. }
  573. std::string str(buf_, bytes_read_);
  574. std::vector<std::string> tokens =
  575. base::SplitString(str, std::string(1, kTokenDelimiter),
  576. base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
  577. if (tokens.size() < 3 || tokens[0] != kStartToken) {
  578. LOG(ERROR) << "Wrong message format: " << str;
  579. CleanupAndDeleteSelf();
  580. return;
  581. }
  582. // Stop the expiration timer to prevent this SocketReader object from being
  583. // terminated unexpectly.
  584. timer_.Stop();
  585. std::string current_dir = tokens[1];
  586. // Remove the first two tokens. The remaining tokens should be the command
  587. // line argv array.
  588. tokens.erase(tokens.begin());
  589. tokens.erase(tokens.begin());
  590. // Return to the UI thread to handle opening a new browser tab.
  591. ui_task_runner_->PostTask(
  592. FROM_HERE, base::BindOnce(&ProcessSingleton::LinuxWatcher::HandleMessage,
  593. parent_, current_dir, tokens, this));
  594. fd_watch_controller_.reset();
  595. // LinuxWatcher::HandleMessage() is in charge of destroying this SocketReader
  596. // object by invoking SocketReader::FinishWithACK().
  597. }
  598. void ProcessSingleton::LinuxWatcher::SocketReader::FinishWithACK(
  599. const char* message,
  600. size_t length) {
  601. if (message && length) {
  602. // Not necessary to care about the return value.
  603. WriteToSocket(fd_, message, length);
  604. }
  605. if (shutdown(fd_, SHUT_WR) < 0)
  606. PLOG(ERROR) << "shutdown() failed";
  607. base::PostTask(
  608. FROM_HERE, {BrowserThread::IO},
  609. base::BindOnce(&ProcessSingleton::LinuxWatcher::RemoveSocketReader,
  610. parent_, this));
  611. // We will be deleted once the posted RemoveSocketReader task runs.
  612. }
  613. ///////////////////////////////////////////////////////////////////////////////
  614. // ProcessSingleton
  615. //
  616. ProcessSingleton::ProcessSingleton(
  617. const base::FilePath& user_data_dir,
  618. const NotificationCallback& notification_callback)
  619. : notification_callback_(notification_callback),
  620. current_pid_(base::GetCurrentProcId()) {
  621. // The user_data_dir may have not been created yet.
  622. base::ThreadRestrictions::ScopedAllowIO allow_io;
  623. base::CreateDirectoryAndGetError(user_data_dir, nullptr);
  624. socket_path_ = user_data_dir.Append(kSingletonSocketFilename);
  625. lock_path_ = user_data_dir.Append(kSingletonLockFilename);
  626. cookie_path_ = user_data_dir.Append(kSingletonCookieFilename);
  627. kill_callback_ = base::BindRepeating(&ProcessSingleton::KillProcess,
  628. base::Unretained(this));
  629. }
  630. ProcessSingleton::~ProcessSingleton() {
  631. DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  632. // Manually free resources with IO explicitly allowed.
  633. base::ThreadRestrictions::ScopedAllowIO allow_io;
  634. watcher_ = nullptr;
  635. ignore_result(socket_dir_.Delete());
  636. }
  637. ProcessSingleton::NotifyResult ProcessSingleton::NotifyOtherProcess() {
  638. return NotifyOtherProcessWithTimeout(
  639. *base::CommandLine::ForCurrentProcess(), kRetryAttempts,
  640. base::TimeDelta::FromSeconds(kTimeoutInSeconds), true);
  641. }
  642. ProcessSingleton::NotifyResult ProcessSingleton::NotifyOtherProcessWithTimeout(
  643. const base::CommandLine& cmd_line,
  644. int retry_attempts,
  645. const base::TimeDelta& timeout,
  646. bool kill_unresponsive) {
  647. DCHECK_GE(retry_attempts, 0);
  648. DCHECK_GE(timeout.InMicroseconds(), 0);
  649. base::TimeDelta sleep_interval = timeout / retry_attempts;
  650. ScopedSocket socket;
  651. for (int retries = 0; retries <= retry_attempts; ++retries) {
  652. // Try to connect to the socket.
  653. if (ConnectSocket(&socket, socket_path_, cookie_path_))
  654. break;
  655. // If we're in a race with another process, they may be in Create() and have
  656. // created the lock but not attached to the socket. So we check if the
  657. // process with the pid from the lockfile is currently running and is a
  658. // chrome browser. If so, we loop and try again for |timeout|.
  659. std::string hostname;
  660. int pid;
  661. if (!ParseLockPath(lock_path_, &hostname, &pid)) {
  662. // No lockfile exists.
  663. return PROCESS_NONE;
  664. }
  665. if (hostname.empty()) {
  666. // Invalid lockfile.
  667. UnlinkPath(lock_path_);
  668. return PROCESS_NONE;
  669. }
  670. if (hostname != net::GetHostName() && !IsChromeProcess(pid)) {
  671. // Locked by process on another host. If the user selected to unlock
  672. // the profile, try to continue; otherwise quit.
  673. if (DisplayProfileInUseError(lock_path_, hostname, pid)) {
  674. UnlinkPath(lock_path_);
  675. return PROCESS_NONE;
  676. }
  677. return PROFILE_IN_USE;
  678. }
  679. if (!IsChromeProcess(pid)) {
  680. // Orphaned lockfile (no process with pid, or non-chrome process.)
  681. UnlinkPath(lock_path_);
  682. return PROCESS_NONE;
  683. }
  684. if (IsSameChromeInstance(pid)) {
  685. // Orphaned lockfile (pid is part of same chrome instance we are, even
  686. // though we haven't tried to create a lockfile yet).
  687. UnlinkPath(lock_path_);
  688. return PROCESS_NONE;
  689. }
  690. if (retries == retry_attempts) {
  691. // Retries failed. Kill the unresponsive chrome process and continue.
  692. if (!kill_unresponsive || !KillProcessByLockPath())
  693. return PROFILE_IN_USE;
  694. return PROCESS_NONE;
  695. }
  696. base::PlatformThread::Sleep(sleep_interval);
  697. }
  698. timeval socket_timeout = TimeDeltaToTimeVal(timeout);
  699. setsockopt(socket.fd(), SOL_SOCKET, SO_SNDTIMEO, &socket_timeout,
  700. sizeof(socket_timeout));
  701. // Found another process, prepare our command line
  702. // format is "START\0<current dir>\0<argv[0]>\0...\0<argv[n]>".
  703. std::string to_send(kStartToken);
  704. to_send.push_back(kTokenDelimiter);
  705. base::FilePath current_dir;
  706. if (!base::PathService::Get(base::DIR_CURRENT, &current_dir))
  707. return PROCESS_NONE;
  708. to_send.append(current_dir.value());
  709. const std::vector<std::string>& argv = electron::ElectronCommandLine::argv();
  710. for (std::vector<std::string>::const_iterator it = argv.begin();
  711. it != argv.end(); ++it) {
  712. to_send.push_back(kTokenDelimiter);
  713. to_send.append(*it);
  714. }
  715. // Send the message
  716. if (!WriteToSocket(socket.fd(), to_send.data(), to_send.length())) {
  717. // Try to kill the other process, because it might have been dead.
  718. if (!kill_unresponsive || !KillProcessByLockPath())
  719. return PROFILE_IN_USE;
  720. return PROCESS_NONE;
  721. }
  722. if (shutdown(socket.fd(), SHUT_WR) < 0)
  723. PLOG(ERROR) << "shutdown() failed";
  724. // Read ACK message from the other process. It might be blocked for a certain
  725. // timeout, to make sure the other process has enough time to return ACK.
  726. char buf[kMaxACKMessageLength + 1];
  727. ssize_t len = ReadFromSocket(socket.fd(), buf, kMaxACKMessageLength, timeout);
  728. // Failed to read ACK, the other process might have been frozen.
  729. if (len <= 0) {
  730. if (!kill_unresponsive || !KillProcessByLockPath())
  731. return PROFILE_IN_USE;
  732. return PROCESS_NONE;
  733. }
  734. buf[len] = '\0';
  735. if (strncmp(buf, kShutdownToken, base::size(kShutdownToken) - 1) == 0) {
  736. // The other process is shutting down, it's safe to start a new process.
  737. return PROCESS_NONE;
  738. } else if (strncmp(buf, kACKToken, base::size(kACKToken) - 1) == 0) {
  739. #if defined(TOOLKIT_VIEWS) && defined(OS_LINUX) && !defined(OS_CHROMEOS)
  740. // Likely NULL in unit tests.
  741. views::LinuxUI* linux_ui = views::LinuxUI::instance();
  742. if (linux_ui)
  743. linux_ui->NotifyWindowManagerStartupComplete();
  744. #endif
  745. // Assume the other process is handling the request.
  746. return PROCESS_NOTIFIED;
  747. }
  748. NOTREACHED() << "The other process returned unknown message: " << buf;
  749. return PROCESS_NOTIFIED;
  750. }
  751. ProcessSingleton::NotifyResult ProcessSingleton::NotifyOtherProcessOrCreate() {
  752. return NotifyOtherProcessWithTimeoutOrCreate(
  753. *base::CommandLine::ForCurrentProcess(), kRetryAttempts,
  754. base::TimeDelta::FromSeconds(kTimeoutInSeconds));
  755. }
  756. void ProcessSingleton::StartListeningOnSocket() {
  757. watcher_ = new LinuxWatcher(this);
  758. base::PostTask(FROM_HERE, {BrowserThread::IO},
  759. base::BindOnce(&ProcessSingleton::LinuxWatcher::StartListening,
  760. watcher_, 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::RepeatingCallback<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::IsThreadInitialized(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([email protected]): 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. }