Audio plugin host https://kx.studio/carla
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1628 lines
44KB

  1. /*
  2. * Carla Pipe Utilities
  3. * Copyright (C) 2013-2017 Filipe Coelho <falktx@falktx.com>
  4. *
  5. * This program is free software; you can redistribute it and/or
  6. * modify it under the terms of the GNU General Public License as
  7. * published by the Free Software Foundation; either version 2 of
  8. * the License, or any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * For a full copy of the GNU General Public License see the doc/GPL.txt file.
  16. */
  17. #include "CarlaPipeUtils.hpp"
  18. #include "CarlaString.hpp"
  19. #include "CarlaMIDI.h"
  20. // needed for atom-util
  21. #ifndef nullptr
  22. # undef NULL
  23. # define NULL nullptr
  24. #endif
  25. #ifdef BUILDING_CARLA
  26. # include "lv2/atom-util.h"
  27. #else
  28. # include "lv2/lv2plug.in/ns/ext/atom/util.h"
  29. #endif
  30. #include <clocale>
  31. #include <fcntl.h>
  32. #include "water/misc/Time.h"
  33. #include "water/text/String.h"
  34. #ifndef CARLA_OS_WIN
  35. # include <cerrno>
  36. # include <signal.h>
  37. # include <sys/wait.h>
  38. # ifdef CARLA_OS_LINUX
  39. # include <sys/prctl.h>
  40. # endif
  41. #endif
  42. #ifdef CARLA_OS_WIN
  43. # define INVALID_PIPE_VALUE INVALID_HANDLE_VALUE
  44. #else
  45. # define INVALID_PIPE_VALUE -1
  46. #endif
  47. #ifdef CARLA_OS_WIN
  48. // -----------------------------------------------------------------------
  49. // win32 stuff
  50. static inline
  51. ssize_t ReadFileWin32(const HANDLE pipeh, void* const buf, const std::size_t numBytes)
  52. {
  53. DWORD dsize = numBytes;
  54. DWORD available = 0;
  55. if (::PeekNamedPipe(pipeh, nullptr, 0, nullptr, &available, nullptr) == FALSE || available == 0)
  56. return -1;
  57. if (::ReadFile(pipeh, buf, dsize, &dsize, nullptr) != FALSE)
  58. return static_cast<ssize_t>(dsize);
  59. return -1;
  60. }
  61. static inline
  62. ssize_t WriteFileWin32(const HANDLE pipeh, const void* const buf, const std::size_t numBytes)
  63. {
  64. DWORD dsize = numBytes;
  65. if (::WriteFile(pipeh, buf, dsize, &dsize, nullptr) != FALSE)
  66. return static_cast<ssize_t>(dsize);
  67. return -1;
  68. }
  69. #endif // CARLA_OS_WIN
  70. // -----------------------------------------------------------------------
  71. // startProcess
  72. #ifdef CARLA_OS_WIN
  73. static inline
  74. bool startProcess(const char* const argv[], PROCESS_INFORMATION* const processInfo)
  75. {
  76. CARLA_SAFE_ASSERT_RETURN(processInfo != nullptr, false);
  77. using water::String;
  78. String command;
  79. for (int i=0; argv[i] != nullptr; ++i)
  80. {
  81. String arg(argv[i]);
  82. #if 0 // FIXME
  83. // If there are spaces, surround it with quotes. If there are quotes,
  84. // replace them with \" so that CommandLineToArgv will correctly parse them.
  85. if (arg.containsAnyOf("\" "))
  86. arg = arg.replace("\"", "\\\"").quoted();
  87. #endif
  88. command << arg << ' ';
  89. }
  90. command = command.trim();
  91. STARTUPINFO startupInfo;
  92. carla_zeroStruct(startupInfo);
  93. startupInfo.cb = sizeof(startupInfo);
  94. return CreateProcess(nullptr, const_cast<LPSTR>(command.toRawUTF8()),
  95. nullptr, nullptr, FALSE, CREATE_NO_WINDOW | CREATE_UNICODE_ENVIRONMENT,
  96. nullptr, nullptr, &startupInfo, processInfo) != FALSE;
  97. }
  98. static inline
  99. bool waitForClientConnect(const HANDLE pipe, const uint32_t timeOutMilliseconds) noexcept
  100. {
  101. CARLA_SAFE_ASSERT_RETURN(pipe != INVALID_PIPE_VALUE, false);
  102. CARLA_SAFE_ASSERT_RETURN(timeOutMilliseconds > 0, false);
  103. bool connecting = true;
  104. const uint32_t timeoutEnd(water::Time::getMillisecondCounter() + timeOutMilliseconds);
  105. for (; connecting && ::ConnectNamedPipe(pipe, nullptr) == FALSE;)
  106. {
  107. const DWORD err = ::GetLastError();
  108. switch (err)
  109. {
  110. case ERROR_PIPE_CONNECTED:
  111. connecting = false;
  112. break;
  113. case ERROR_IO_PENDING:
  114. case ERROR_PIPE_LISTENING:
  115. if (water::Time::getMillisecondCounter() < timeoutEnd)
  116. {
  117. carla_msleep(5);
  118. continue;
  119. }
  120. carla_stderr("waitForClientFirstMessage() - connect timed out");
  121. return false;
  122. default:
  123. carla_stderr("waitForClientFirstMessage() - connect returned %i", int(err));
  124. return false;
  125. }
  126. }
  127. return true;
  128. }
  129. #else
  130. static inline
  131. bool startProcess(const char* const argv[], pid_t& pidinst) noexcept
  132. {
  133. const ScopedEnvVar sev1("LD_LIBRARY_PATH", nullptr);
  134. const ScopedEnvVar sev2("LD_PRELOAD", nullptr);
  135. const pid_t ret = pidinst = vfork();
  136. switch (ret)
  137. {
  138. case 0: { // child process
  139. execvp(argv[0], const_cast<char* const*>(argv));
  140. CarlaString error(std::strerror(errno));
  141. carla_stderr2("exec failed: %s", error.buffer());
  142. _exit(1); // this is not noexcept safe but doesn't matter anyway
  143. } break;
  144. case -1: { // error
  145. CarlaString error(std::strerror(errno));
  146. carla_stderr2("fork() failed: %s", error.buffer());
  147. } break;
  148. }
  149. return (ret > 0);
  150. }
  151. #endif
  152. // -----------------------------------------------------------------------
  153. // waitForClientFirstMessage
  154. template<typename P>
  155. static inline
  156. bool waitForClientFirstMessage(const P& pipe, const uint32_t timeOutMilliseconds) noexcept
  157. {
  158. CARLA_SAFE_ASSERT_RETURN(pipe != INVALID_PIPE_VALUE, false);
  159. CARLA_SAFE_ASSERT_RETURN(timeOutMilliseconds > 0, false);
  160. char c;
  161. ssize_t ret;
  162. const uint32_t timeoutEnd(water::Time::getMillisecondCounter() + timeOutMilliseconds);
  163. #ifdef CARLA_OS_WIN
  164. if (! waitForClientConnect(pipe, timeOutMilliseconds))
  165. return false;
  166. #endif
  167. for (;;)
  168. {
  169. try {
  170. #ifdef CARLA_OS_WIN
  171. ret = ::ReadFileWin32(pipe, &c, 1);
  172. #else
  173. ret = ::read(pipe, &c, 1);
  174. #endif
  175. } CARLA_SAFE_EXCEPTION_RETURN("read pipe", false);
  176. switch (ret)
  177. {
  178. case 1:
  179. if (c == '\n')
  180. return true;
  181. carla_stderr("waitForClientFirstMessage() - read has wrong first char '%c'", c);return false;
  182. return false;
  183. case -1: // failed to read
  184. #ifdef CARLA_OS_WIN
  185. if (::GetLastError() == ERROR_NO_DATA)
  186. #else
  187. if (errno == EAGAIN)
  188. #endif
  189. {
  190. if (water::Time::getMillisecondCounter() < timeoutEnd)
  191. {
  192. carla_msleep(5);
  193. continue;
  194. }
  195. carla_stderr("waitForClientFirstMessage() - read timed out");
  196. }
  197. else
  198. {
  199. #ifdef CARLA_OS_WIN
  200. carla_stderr("waitForClientFirstMessage() - read failed");
  201. #else
  202. CarlaString error(std::strerror(errno));
  203. carla_stderr("waitForClientFirstMessage() - read failed: %s", error.buffer());
  204. #endif
  205. }
  206. return false;
  207. default: // ???
  208. carla_stderr("waitForClientFirstMessage() - read returned %i", int(ret));
  209. return false;
  210. }
  211. }
  212. }
  213. // -----------------------------------------------------------------------
  214. // waitForChildToStop / waitForProcessToStop
  215. #ifdef CARLA_OS_WIN
  216. static inline
  217. bool waitForProcessToStop(const PROCESS_INFORMATION& processInfo, const uint32_t timeOutMilliseconds) noexcept
  218. {
  219. CARLA_SAFE_ASSERT_RETURN(processInfo.hProcess != INVALID_HANDLE_VALUE, false);
  220. CARLA_SAFE_ASSERT_RETURN(timeOutMilliseconds > 0, false);
  221. const uint32_t timeoutEnd(water::Time::getMillisecondCounter() + timeOutMilliseconds);
  222. for (;;)
  223. {
  224. switch (WaitForSingleObject(processInfo.hProcess, 0))
  225. {
  226. case WAIT_OBJECT_0:
  227. case -1:
  228. return true;
  229. }
  230. if (water::Time::getMillisecondCounter() >= timeoutEnd)
  231. break;
  232. carla_msleep(5);
  233. }
  234. return false;
  235. }
  236. static inline
  237. void waitForProcessToStopOrKillIt(const PROCESS_INFORMATION& processInfo, const uint32_t timeOutMilliseconds) noexcept
  238. {
  239. CARLA_SAFE_ASSERT_RETURN(processInfo.hProcess != INVALID_HANDLE_VALUE,);
  240. CARLA_SAFE_ASSERT_RETURN(timeOutMilliseconds > 0,);
  241. if (! waitForProcessToStop(processInfo, timeOutMilliseconds))
  242. {
  243. carla_stderr("waitForProcessToStopOrKillIt() - process didn't stop, force termination");
  244. if (TerminateProcess(processInfo.hProcess, 9) != FALSE)
  245. {
  246. // wait for process to stop
  247. waitForProcessToStop(processInfo, timeOutMilliseconds);
  248. }
  249. }
  250. }
  251. #else
  252. static inline
  253. bool waitForChildToStop(const pid_t pid, const uint32_t timeOutMilliseconds, bool sendTerminate) noexcept
  254. {
  255. CARLA_SAFE_ASSERT_RETURN(pid > 0, false);
  256. CARLA_SAFE_ASSERT_RETURN(timeOutMilliseconds > 0, false);
  257. pid_t ret;
  258. const uint32_t timeoutEnd(water::Time::getMillisecondCounter() + timeOutMilliseconds);
  259. for (;;)
  260. {
  261. try {
  262. ret = ::waitpid(pid, nullptr, WNOHANG);
  263. } CARLA_SAFE_EXCEPTION_BREAK("waitpid");
  264. switch (ret)
  265. {
  266. case -1:
  267. if (errno == ECHILD)
  268. {
  269. // success, child doesn't exist
  270. return true;
  271. }
  272. else
  273. {
  274. CarlaString error(std::strerror(errno));
  275. carla_stderr("waitForChildToStop() - waitpid failed: %s", error.buffer());
  276. return false;
  277. }
  278. break;
  279. case 0:
  280. if (sendTerminate)
  281. {
  282. sendTerminate = false;
  283. ::kill(pid, SIGTERM);
  284. }
  285. if (water::Time::getMillisecondCounter() < timeoutEnd)
  286. {
  287. carla_msleep(5);
  288. continue;
  289. }
  290. carla_stderr("waitForChildToStop() - timed out");
  291. break;
  292. default:
  293. if (ret == pid)
  294. {
  295. // success
  296. return true;
  297. }
  298. else
  299. {
  300. carla_stderr("waitForChildToStop() - got wrong pid %i (requested was %i)", int(ret), int(pid));
  301. return false;
  302. }
  303. }
  304. break;
  305. }
  306. return false;
  307. }
  308. static inline
  309. void waitForChildToStopOrKillIt(pid_t& pid, const uint32_t timeOutMilliseconds) noexcept
  310. {
  311. CARLA_SAFE_ASSERT_RETURN(pid > 0,);
  312. CARLA_SAFE_ASSERT_RETURN(timeOutMilliseconds > 0,);
  313. if (! waitForChildToStop(pid, timeOutMilliseconds, true))
  314. {
  315. carla_stderr("waitForChildToStopOrKillIt() - process didn't stop, force killing");
  316. if (::kill(pid, SIGKILL) != -1)
  317. {
  318. // wait for killing to take place
  319. waitForChildToStop(pid, timeOutMilliseconds, false);
  320. }
  321. else
  322. {
  323. CarlaString error(std::strerror(errno));
  324. carla_stderr("waitForChildToStopOrKillIt() - kill failed: %s", error.buffer());
  325. }
  326. }
  327. }
  328. #endif
  329. // -----------------------------------------------------------------------
  330. struct CarlaPipeCommon::PrivateData {
  331. // pipes
  332. #ifdef CARLA_OS_WIN
  333. PROCESS_INFORMATION processInfo;
  334. HANDLE pipeRecv;
  335. HANDLE pipeSend;
  336. #else
  337. pid_t pid;
  338. int pipeRecv;
  339. int pipeSend;
  340. #endif
  341. // read functions must only be called in context of idlePipe()
  342. bool isReading;
  343. // the client side is closing down, only waiting for response from server
  344. bool clientClosingDown;
  345. // other side of pipe has closed
  346. bool pipeClosed;
  347. // print error only once
  348. bool lastMessageFailed;
  349. // for debugging
  350. bool isServer;
  351. // common write lock
  352. CarlaMutex writeLock;
  353. // temporary buffers for _readline()
  354. mutable char tmpBuf[0xff+1];
  355. mutable CarlaString tmpStr;
  356. PrivateData() noexcept
  357. #ifdef CARLA_OS_WIN
  358. : processInfo(),
  359. #else
  360. : pid(-1),
  361. #endif
  362. pipeRecv(INVALID_PIPE_VALUE),
  363. pipeSend(INVALID_PIPE_VALUE),
  364. isReading(false),
  365. clientClosingDown(false),
  366. pipeClosed(true),
  367. lastMessageFailed(false),
  368. isServer(false),
  369. writeLock(),
  370. tmpBuf(),
  371. tmpStr()
  372. {
  373. #ifdef CARLA_OS_WIN
  374. carla_zeroStruct(processInfo);
  375. processInfo.hProcess = INVALID_HANDLE_VALUE;
  376. processInfo.hThread = INVALID_HANDLE_VALUE;
  377. #endif
  378. carla_zeroChars(tmpBuf, 0xff+1);
  379. }
  380. CARLA_DECLARE_NON_COPY_STRUCT(PrivateData)
  381. };
  382. // -----------------------------------------------------------------------
  383. CarlaPipeCommon::CarlaPipeCommon() noexcept
  384. : pData(new PrivateData())
  385. {
  386. carla_debug("CarlaPipeCommon::CarlaPipeCommon()");
  387. }
  388. CarlaPipeCommon::~CarlaPipeCommon() /*noexcept*/
  389. {
  390. carla_debug("CarlaPipeCommon::~CarlaPipeCommon()");
  391. delete pData;
  392. }
  393. // -------------------------------------------------------------------
  394. bool CarlaPipeCommon::isPipeRunning() const noexcept
  395. {
  396. return (pData->pipeRecv != INVALID_PIPE_VALUE && pData->pipeSend != INVALID_PIPE_VALUE && ! pData->pipeClosed);
  397. }
  398. void CarlaPipeCommon::idlePipe(const bool onlyOnce) noexcept
  399. {
  400. const char* locale = nullptr;
  401. for (;;)
  402. {
  403. const char* const msg(_readline());
  404. if (msg == nullptr)
  405. break;
  406. if (locale == nullptr && ! onlyOnce)
  407. {
  408. locale = carla_strdup_safe(::setlocale(LC_NUMERIC, nullptr));
  409. ::setlocale(LC_NUMERIC, "C");
  410. }
  411. pData->isReading = true;
  412. if (std::strcmp(msg, "__carla-quit__") == 0)
  413. {
  414. pData->pipeClosed = true;
  415. }
  416. else if (! pData->clientClosingDown)
  417. {
  418. try {
  419. msgReceived(msg);
  420. } CARLA_SAFE_EXCEPTION("msgReceived");
  421. }
  422. pData->isReading = false;
  423. delete[] msg;
  424. if (onlyOnce || pData->pipeRecv == INVALID_PIPE_VALUE)
  425. break;
  426. }
  427. if (locale != nullptr)
  428. {
  429. ::setlocale(LC_NUMERIC, locale);
  430. delete[] locale;
  431. }
  432. }
  433. // -------------------------------------------------------------------
  434. void CarlaPipeCommon::lockPipe() const noexcept
  435. {
  436. pData->writeLock.lock();
  437. }
  438. bool CarlaPipeCommon::tryLockPipe() const noexcept
  439. {
  440. return pData->writeLock.tryLock();
  441. }
  442. void CarlaPipeCommon::unlockPipe() const noexcept
  443. {
  444. pData->writeLock.unlock();
  445. }
  446. CarlaMutex& CarlaPipeCommon::getPipeLock() const noexcept
  447. {
  448. return pData->writeLock;
  449. }
  450. // -------------------------------------------------------------------
  451. bool CarlaPipeCommon::readNextLineAsBool(bool& value) const noexcept
  452. {
  453. CARLA_SAFE_ASSERT_RETURN(pData->isReading, false);
  454. if (const char* const msg = _readlineblock())
  455. {
  456. value = (std::strcmp(msg, "true") == 0);
  457. delete[] msg;
  458. return true;
  459. }
  460. return false;
  461. }
  462. bool CarlaPipeCommon::readNextLineAsByte(uint8_t& value) const noexcept
  463. {
  464. CARLA_SAFE_ASSERT_RETURN(pData->isReading, false);
  465. if (const char* const msg = _readlineblock())
  466. {
  467. int tmp = std::atoi(msg);
  468. delete[] msg;
  469. if (tmp >= 0 && tmp <= 0xFF)
  470. {
  471. value = static_cast<uint8_t>(tmp);
  472. return true;
  473. }
  474. }
  475. return false;
  476. }
  477. bool CarlaPipeCommon::readNextLineAsInt(int32_t& value) const noexcept
  478. {
  479. CARLA_SAFE_ASSERT_RETURN(pData->isReading, false);
  480. if (const char* const msg = _readlineblock())
  481. {
  482. value = std::atoi(msg);
  483. delete[] msg;
  484. return true;
  485. }
  486. return false;
  487. }
  488. bool CarlaPipeCommon::readNextLineAsUInt(uint32_t& value) const noexcept
  489. {
  490. CARLA_SAFE_ASSERT_RETURN(pData->isReading, false);
  491. if (const char* const msg = _readlineblock())
  492. {
  493. int32_t tmp = std::atoi(msg);
  494. delete[] msg;
  495. if (tmp >= 0)
  496. {
  497. value = static_cast<uint32_t>(tmp);
  498. return true;
  499. }
  500. }
  501. return false;
  502. }
  503. bool CarlaPipeCommon::readNextLineAsLong(int64_t& value) const noexcept
  504. {
  505. CARLA_SAFE_ASSERT_RETURN(pData->isReading, false);
  506. if (const char* const msg = _readlineblock())
  507. {
  508. value = std::atol(msg);
  509. delete[] msg;
  510. return true;
  511. }
  512. return false;
  513. }
  514. bool CarlaPipeCommon::readNextLineAsULong(uint64_t& value) const noexcept
  515. {
  516. CARLA_SAFE_ASSERT_RETURN(pData->isReading, false);
  517. if (const char* const msg = _readlineblock())
  518. {
  519. int64_t tmp = std::atol(msg);
  520. delete[] msg;
  521. if (tmp >= 0)
  522. {
  523. value = static_cast<uint64_t>(tmp);
  524. return true;
  525. }
  526. }
  527. return false;
  528. }
  529. bool CarlaPipeCommon::readNextLineAsFloat(float& value) const noexcept
  530. {
  531. CARLA_SAFE_ASSERT_RETURN(pData->isReading, false);
  532. if (const char* const msg = _readlineblock())
  533. {
  534. value = static_cast<float>(std::atof(msg));
  535. delete[] msg;
  536. return true;
  537. }
  538. return false;
  539. }
  540. bool CarlaPipeCommon::readNextLineAsDouble(double& value) const noexcept
  541. {
  542. CARLA_SAFE_ASSERT_RETURN(pData->isReading, false);
  543. if (const char* const msg = _readlineblock())
  544. {
  545. value = std::atof(msg);
  546. delete[] msg;
  547. return true;
  548. }
  549. return false;
  550. }
  551. bool CarlaPipeCommon::readNextLineAsString(const char*& value) const noexcept
  552. {
  553. CARLA_SAFE_ASSERT_RETURN(pData->isReading, false);
  554. if (const char* const msg = _readlineblock())
  555. {
  556. value = msg;
  557. return true;
  558. }
  559. return false;
  560. }
  561. // -------------------------------------------------------------------
  562. // must be locked before calling
  563. bool CarlaPipeCommon::writeMessage(const char* const msg) const noexcept
  564. {
  565. CARLA_SAFE_ASSERT_RETURN(msg != nullptr && msg[0] != '\0', false);
  566. const std::size_t size(std::strlen(msg));
  567. CARLA_SAFE_ASSERT_RETURN(size > 0, false);
  568. CARLA_SAFE_ASSERT_RETURN(msg[size-1] == '\n', false);
  569. return _writeMsgBuffer(msg, size);
  570. }
  571. bool CarlaPipeCommon::writeMessage(const char* const msg, std::size_t size) const noexcept
  572. {
  573. CARLA_SAFE_ASSERT_RETURN(msg != nullptr && msg[0] != '\0', false);
  574. CARLA_SAFE_ASSERT_RETURN(size > 0, false);
  575. CARLA_SAFE_ASSERT_RETURN(msg[size-1] == '\n', false);
  576. return _writeMsgBuffer(msg, size);
  577. }
  578. bool CarlaPipeCommon::writeAndFixMessage(const char* const msg) const noexcept
  579. {
  580. CARLA_SAFE_ASSERT_RETURN(msg != nullptr, false);
  581. const std::size_t size(std::strlen(msg));
  582. char fixedMsg[size+2];
  583. if (size > 0)
  584. {
  585. std::strcpy(fixedMsg, msg);
  586. for (std::size_t i=0; i<size; ++i)
  587. {
  588. if (fixedMsg[i] == '\n')
  589. fixedMsg[i] = '\r';
  590. }
  591. if (fixedMsg[size-1] == '\r')
  592. {
  593. fixedMsg[size-1] = '\n';
  594. fixedMsg[size ] = '\0';
  595. fixedMsg[size+1] = '\0';
  596. }
  597. else
  598. {
  599. fixedMsg[size ] = '\n';
  600. fixedMsg[size+1] = '\0';
  601. }
  602. }
  603. else
  604. {
  605. fixedMsg[0] = '\n';
  606. fixedMsg[1] = '\0';
  607. }
  608. return _writeMsgBuffer(fixedMsg, size+1);
  609. }
  610. bool CarlaPipeCommon::flushMessages() const noexcept
  611. {
  612. #ifdef CARLA_OS_WIN
  613. // TESTING remove later
  614. const CarlaMutexTryLocker cmtl(pData->writeLock);
  615. CARLA_SAFE_ASSERT_RETURN(cmtl.wasNotLocked(), false);
  616. CARLA_SAFE_ASSERT_RETURN(pData->pipeSend != INVALID_PIPE_VALUE, false);
  617. try {
  618. return (::FlushFileBuffers(pData->pipeSend) != FALSE);
  619. } CARLA_SAFE_EXCEPTION_RETURN("CarlaPipeCommon::writeMsgBuffer", false);
  620. #else
  621. // nothing to do
  622. return true;
  623. #endif
  624. }
  625. // -------------------------------------------------------------------
  626. void CarlaPipeCommon::writeErrorMessage(const char* const error) const noexcept
  627. {
  628. CARLA_SAFE_ASSERT_RETURN(error != nullptr && error[0] != '\0',);
  629. const CarlaMutexLocker cml(pData->writeLock);
  630. _writeMsgBuffer("error\n", 6);
  631. writeAndFixMessage(error);
  632. flushMessages();
  633. }
  634. void CarlaPipeCommon::writeControlMessage(const uint32_t index, const float value) const noexcept
  635. {
  636. char tmpBuf[0xff+1];
  637. tmpBuf[0xff] = '\0';
  638. const CarlaMutexLocker cml(pData->writeLock);
  639. const ScopedLocale csl;
  640. _writeMsgBuffer("control\n", 8);
  641. {
  642. std::snprintf(tmpBuf, 0xff, "%i\n", index);
  643. _writeMsgBuffer(tmpBuf, std::strlen(tmpBuf));
  644. std::snprintf(tmpBuf, 0xff, "%f\n", value);
  645. _writeMsgBuffer(tmpBuf, std::strlen(tmpBuf));
  646. }
  647. flushMessages();
  648. }
  649. void CarlaPipeCommon::writeConfigureMessage(const char* const key, const char* const value) const noexcept
  650. {
  651. CARLA_SAFE_ASSERT_RETURN(key != nullptr && key[0] != '\0',);
  652. CARLA_SAFE_ASSERT_RETURN(value != nullptr,);
  653. const CarlaMutexLocker cml(pData->writeLock);
  654. _writeMsgBuffer("configure\n", 10);
  655. {
  656. writeAndFixMessage(key);
  657. writeAndFixMessage(value);
  658. }
  659. flushMessages();
  660. }
  661. void CarlaPipeCommon::writeProgramMessage(const uint32_t index) const noexcept
  662. {
  663. char tmpBuf[0xff+1];
  664. tmpBuf[0xff] = '\0';
  665. const CarlaMutexLocker cml(pData->writeLock);
  666. _writeMsgBuffer("program\n", 8);
  667. {
  668. std::snprintf(tmpBuf, 0xff, "%i\n", index);
  669. _writeMsgBuffer(tmpBuf, std::strlen(tmpBuf));
  670. }
  671. flushMessages();
  672. }
  673. void CarlaPipeCommon::writeMidiProgramMessage(const uint32_t bank, const uint32_t program) const noexcept
  674. {
  675. char tmpBuf[0xff+1];
  676. tmpBuf[0xff] = '\0';
  677. const CarlaMutexLocker cml(pData->writeLock);
  678. _writeMsgBuffer("midiprogram\n", 12);
  679. {
  680. std::snprintf(tmpBuf, 0xff, "%i\n", bank);
  681. _writeMsgBuffer(tmpBuf, std::strlen(tmpBuf));
  682. std::snprintf(tmpBuf, 0xff, "%i\n", program);
  683. _writeMsgBuffer(tmpBuf, std::strlen(tmpBuf));
  684. }
  685. flushMessages();
  686. }
  687. void CarlaPipeCommon::writeMidiNoteMessage(const bool onOff, const uint8_t channel, const uint8_t note, const uint8_t velocity) const noexcept
  688. {
  689. CARLA_SAFE_ASSERT_RETURN(channel < MAX_MIDI_CHANNELS,);
  690. CARLA_SAFE_ASSERT_RETURN(note < MAX_MIDI_NOTE,);
  691. CARLA_SAFE_ASSERT_RETURN(velocity < MAX_MIDI_VALUE,);
  692. char tmpBuf[0xff+1];
  693. tmpBuf[0xff] = '\0';
  694. const CarlaMutexLocker cml(pData->writeLock);
  695. _writeMsgBuffer("note\n", 5);
  696. {
  697. std::snprintf(tmpBuf, 0xff, "%s\n", bool2str(onOff));
  698. _writeMsgBuffer(tmpBuf, std::strlen(tmpBuf));
  699. std::snprintf(tmpBuf, 0xff, "%i\n", channel);
  700. _writeMsgBuffer(tmpBuf, std::strlen(tmpBuf));
  701. std::snprintf(tmpBuf, 0xff, "%i\n", note);
  702. _writeMsgBuffer(tmpBuf, std::strlen(tmpBuf));
  703. std::snprintf(tmpBuf, 0xff, "%i\n", velocity);
  704. _writeMsgBuffer(tmpBuf, std::strlen(tmpBuf));
  705. }
  706. flushMessages();
  707. }
  708. void CarlaPipeCommon::writeLv2AtomMessage(const uint32_t index, const LV2_Atom* const atom) const noexcept
  709. {
  710. CARLA_SAFE_ASSERT_RETURN(atom != nullptr,);
  711. char tmpBuf[0xff+1];
  712. tmpBuf[0xff] = '\0';
  713. const uint32_t atomTotalSize(lv2_atom_total_size(atom));
  714. CarlaString base64atom(CarlaString::asBase64(atom, atomTotalSize));
  715. const CarlaMutexLocker cml(pData->writeLock);
  716. _writeMsgBuffer("atom\n", 5);
  717. {
  718. std::snprintf(tmpBuf, 0xff, "%i\n", index);
  719. _writeMsgBuffer(tmpBuf, std::strlen(tmpBuf));
  720. std::snprintf(tmpBuf, 0xff, "%i\n", atomTotalSize);
  721. _writeMsgBuffer(tmpBuf, std::strlen(tmpBuf));
  722. writeAndFixMessage(base64atom.buffer());
  723. }
  724. flushMessages();
  725. }
  726. void CarlaPipeCommon::writeLv2UridMessage(const uint32_t urid, const char* const uri) const noexcept
  727. {
  728. CARLA_SAFE_ASSERT_RETURN(urid != 0,);
  729. CARLA_SAFE_ASSERT_RETURN(uri != nullptr && uri[0] != '\0',);
  730. char tmpBuf[0xff+1];
  731. tmpBuf[0xff] = '\0';
  732. const CarlaMutexLocker cml(pData->writeLock);
  733. _writeMsgBuffer("urid\n", 5);
  734. {
  735. std::snprintf(tmpBuf, 0xff, "%i\n", urid);
  736. _writeMsgBuffer(tmpBuf, std::strlen(tmpBuf));
  737. writeAndFixMessage(uri);
  738. }
  739. flushMessages();
  740. }
  741. // -------------------------------------------------------------------
  742. // internal
  743. const char* CarlaPipeCommon::_readline() const noexcept
  744. {
  745. CARLA_SAFE_ASSERT_RETURN(pData->pipeRecv != INVALID_PIPE_VALUE, nullptr);
  746. char c;
  747. char* ptr = pData->tmpBuf;
  748. ssize_t ret = -1;
  749. pData->tmpStr.clear();
  750. for (int i=0; i<0xff; ++i)
  751. {
  752. try {
  753. #ifdef CARLA_OS_WIN
  754. ret = ::ReadFileWin32(pData->pipeRecv, &c, 1);
  755. #else
  756. ret = ::read(pData->pipeRecv, &c, 1);
  757. #endif
  758. } CARLA_SAFE_EXCEPTION_BREAK("CarlaPipeCommon::readline() - read");
  759. if (ret != 1 || c == '\n')
  760. break;
  761. if (c == '\r')
  762. c = '\n';
  763. *ptr++ = c;
  764. if (i+1 == 0xff)
  765. {
  766. i = 0;
  767. *ptr = '\0';
  768. pData->tmpStr += pData->tmpBuf;
  769. ptr = pData->tmpBuf;
  770. }
  771. }
  772. if (ptr != pData->tmpBuf)
  773. {
  774. *ptr = '\0';
  775. pData->tmpStr += pData->tmpBuf;
  776. }
  777. else if (pData->tmpStr.isEmpty() && ret != 1)
  778. {
  779. // some error
  780. return nullptr;
  781. }
  782. try {
  783. return pData->tmpStr.dup();
  784. } CARLA_SAFE_EXCEPTION_RETURN("CarlaPipeCommon::readline() - dup", nullptr);
  785. }
  786. const char* CarlaPipeCommon::_readlineblock(const uint32_t timeOutMilliseconds) const noexcept
  787. {
  788. const uint32_t timeoutEnd(water::Time::getMillisecondCounter() + timeOutMilliseconds);
  789. for (;;)
  790. {
  791. if (const char* const msg = _readline())
  792. return msg;
  793. if (water::Time::getMillisecondCounter() >= timeoutEnd)
  794. break;
  795. carla_msleep(5);
  796. }
  797. carla_stderr("readlineblock timed out");
  798. return nullptr;
  799. }
  800. bool CarlaPipeCommon::_writeMsgBuffer(const char* const msg, const std::size_t size) const noexcept
  801. {
  802. // TESTING remove later
  803. const CarlaMutexTryLocker cmtl(pData->writeLock);
  804. CARLA_SAFE_ASSERT_RETURN(cmtl.wasNotLocked(), false);
  805. CARLA_SAFE_ASSERT_RETURN(pData->pipeSend != INVALID_PIPE_VALUE, false);
  806. ssize_t ret;
  807. try {
  808. #ifdef CARLA_OS_WIN
  809. ret = ::WriteFileWin32(pData->pipeSend, msg, size);
  810. #else
  811. ret = ::write(pData->pipeSend, msg, size);
  812. #endif
  813. } CARLA_SAFE_EXCEPTION_RETURN("CarlaPipeCommon::writeMsgBuffer", false);
  814. if (ret == static_cast<ssize_t>(size))
  815. {
  816. if (pData->lastMessageFailed)
  817. pData->lastMessageFailed = false;
  818. return true;
  819. }
  820. #if 0
  821. // ignore errors if the other side of the pipe has closed
  822. if (pData->pipeClosed)
  823. return false;
  824. #endif
  825. if (! pData->lastMessageFailed)
  826. {
  827. pData->lastMessageFailed = true;
  828. fprintf(stderr,
  829. "CarlaPipeCommon::_writeMsgBuffer(..., " P_SIZE ") - failed with " P_SSIZE " (%s), message was:\n%s",
  830. size, ret, bool2str(pData->isServer), msg);
  831. }
  832. return false;
  833. }
  834. // -----------------------------------------------------------------------
  835. CarlaPipeServer::CarlaPipeServer() noexcept
  836. : CarlaPipeCommon()
  837. {
  838. carla_debug("CarlaPipeServer::CarlaPipeServer()");
  839. pData->isServer = true;
  840. }
  841. CarlaPipeServer::~CarlaPipeServer() /*noexcept*/
  842. {
  843. carla_debug("CarlaPipeServer::~CarlaPipeServer()");
  844. stopPipeServer(5*1000);
  845. }
  846. uintptr_t CarlaPipeServer::getPID() const noexcept
  847. {
  848. #ifndef CARLA_OS_WIN
  849. return static_cast<uintptr_t>(pData->pid);
  850. #else
  851. return 0;
  852. #endif
  853. }
  854. // -----------------------------------------------------------------------
  855. bool CarlaPipeServer::startPipeServer(const char* const filename,
  856. const char* const arg1,
  857. const char* const arg2,
  858. const int size) noexcept
  859. {
  860. CARLA_SAFE_ASSERT_RETURN(pData->pipeRecv == INVALID_PIPE_VALUE, false);
  861. CARLA_SAFE_ASSERT_RETURN(pData->pipeSend == INVALID_PIPE_VALUE, false);
  862. #ifdef CARLA_OS_WIN
  863. CARLA_SAFE_ASSERT_RETURN(pData->processInfo.hThread == INVALID_HANDLE_VALUE, false);
  864. CARLA_SAFE_ASSERT_RETURN(pData->processInfo.hProcess == INVALID_HANDLE_VALUE, false);
  865. #else
  866. CARLA_SAFE_ASSERT_RETURN(pData->pid == -1, false);
  867. #endif
  868. CARLA_SAFE_ASSERT_RETURN(filename != nullptr && filename[0] != '\0', false);
  869. CARLA_SAFE_ASSERT_RETURN(arg1 != nullptr, false);
  870. CARLA_SAFE_ASSERT_RETURN(arg2 != nullptr, false);
  871. carla_debug("CarlaPipeServer::startPipeServer(\"%s\", \"%s\", \"%s\")", filename, arg1, arg2);
  872. char pipeRecvServerStr[100+1];
  873. char pipeSendServerStr[100+1];
  874. char pipeRecvClientStr[100+1];
  875. char pipeSendClientStr[100+1];
  876. pipeRecvServerStr[100] = '\0';
  877. pipeSendServerStr[100] = '\0';
  878. pipeRecvClientStr[100] = '\0';
  879. pipeSendClientStr[100] = '\0';
  880. const CarlaMutexLocker cml(pData->writeLock);
  881. //----------------------------------------------------------------
  882. // create pipes
  883. #ifdef CARLA_OS_WIN
  884. HANDLE pipe1, pipe2;
  885. std::srand(static_cast<uint>(std::time(nullptr)));
  886. static ulong sCounter = 0;
  887. ++sCounter;
  888. const int randint = std::rand();
  889. std::snprintf(pipeRecvServerStr, 100, "\\\\.\\pipe\\carla-pipe1-%i-%li", randint, sCounter);
  890. std::snprintf(pipeSendServerStr, 100, "\\\\.\\pipe\\carla-pipe2-%i-%li", randint, sCounter);
  891. std::snprintf(pipeRecvClientStr, 100, "ignored");
  892. std::snprintf(pipeSendClientStr, 100, "ignored");
  893. pipe1 = ::CreateNamedPipeA(pipeRecvServerStr, PIPE_ACCESS_DUPLEX, PIPE_TYPE_BYTE|PIPE_READMODE_BYTE|PIPE_NOWAIT, 2, size, size, 0, nullptr);
  894. if (pipe1 == INVALID_HANDLE_VALUE)
  895. {
  896. fail("pipe creation failed");
  897. return false;
  898. }
  899. pipe2 = ::CreateNamedPipeA(pipeSendServerStr, PIPE_ACCESS_DUPLEX, PIPE_TYPE_BYTE|PIPE_READMODE_BYTE|PIPE_NOWAIT, 2, size, size, 0, nullptr);
  900. if (pipe2 == INVALID_HANDLE_VALUE)
  901. {
  902. try { ::CloseHandle(pipe1); } CARLA_SAFE_EXCEPTION("CloseHandle(pipe1)");
  903. fail("pipe creation failed");
  904. return false;
  905. }
  906. const HANDLE pipeRecvClient = pipe2;
  907. const HANDLE pipeSendClient = pipe1;
  908. #else
  909. int pipe1[2]; // read by server, written by client
  910. int pipe2[2]; // read by client, written by server
  911. if (::pipe(pipe1) != 0)
  912. {
  913. fail("pipe1 creation failed");
  914. return false;
  915. }
  916. if (::pipe(pipe2) != 0)
  917. {
  918. try { ::close(pipe1[0]); } CARLA_SAFE_EXCEPTION("close(pipe1[0])");
  919. try { ::close(pipe1[1]); } CARLA_SAFE_EXCEPTION("close(pipe1[1])");
  920. fail("pipe2 creation failed");
  921. return false;
  922. }
  923. /* */ int pipeRecvServer = pipe1[0];
  924. /* */ int pipeSendServer = pipe2[1];
  925. const int pipeRecvClient = pipe2[0];
  926. const int pipeSendClient = pipe1[1];
  927. std::snprintf(pipeRecvServerStr, 100, "%i", pipeRecvServer);
  928. std::snprintf(pipeSendServerStr, 100, "%i", pipeSendServer);
  929. std::snprintf(pipeRecvClientStr, 100, "%i", pipeRecvClient);
  930. std::snprintf(pipeSendClientStr, 100, "%i", pipeSendClient);
  931. //----------------------------------------------------------------
  932. // set size, non-fatal
  933. #ifdef CARLA_OS_LINUX
  934. try {
  935. ::fcntl(pipeRecvClient, F_SETPIPE_SZ, size);
  936. } CARLA_SAFE_EXCEPTION("Set pipe size");
  937. try {
  938. ::fcntl(pipeRecvServer, F_SETPIPE_SZ, size);
  939. } CARLA_SAFE_EXCEPTION("Set pipe size");
  940. #endif
  941. //----------------------------------------------------------------
  942. // set non-block
  943. int ret;
  944. try {
  945. ret = ::fcntl(pipeRecvClient, F_SETFL, ::fcntl(pipeRecvClient, F_GETFL) | O_NONBLOCK);
  946. } catch (...) {
  947. ret = -1;
  948. fail("failed to set pipe as non-block");
  949. }
  950. if (ret == 0)
  951. {
  952. try {
  953. ret = ::fcntl(pipeRecvServer, F_SETFL, ::fcntl(pipeRecvServer, F_GETFL) | O_NONBLOCK);
  954. } catch (...) {
  955. ret = -1;
  956. fail("failed to set pipe as non-block");
  957. }
  958. }
  959. if (ret < 0)
  960. {
  961. try { ::close(pipe1[0]); } CARLA_SAFE_EXCEPTION("close(pipe1[0])");
  962. try { ::close(pipe1[1]); } CARLA_SAFE_EXCEPTION("close(pipe1[1])");
  963. try { ::close(pipe2[0]); } CARLA_SAFE_EXCEPTION("close(pipe2[0])");
  964. try { ::close(pipe2[1]); } CARLA_SAFE_EXCEPTION("close(pipe2[1])");
  965. return false;
  966. }
  967. #endif
  968. //----------------------------------------------------------------
  969. // set arguments
  970. const char* argv[8];
  971. //----------------------------------------------------------------
  972. // argv[0] => filename
  973. argv[0] = filename;
  974. //----------------------------------------------------------------
  975. // argv[1-2] => args
  976. argv[1] = arg1;
  977. argv[2] = arg2;
  978. //----------------------------------------------------------------
  979. // argv[3-6] => pipes
  980. argv[3] = pipeRecvServerStr;
  981. argv[4] = pipeSendServerStr;
  982. argv[5] = pipeRecvClientStr;
  983. argv[6] = pipeSendClientStr;
  984. //----------------------------------------------------------------
  985. // argv[7] => null
  986. argv[7] = nullptr;
  987. //----------------------------------------------------------------
  988. // start process
  989. #ifdef CARLA_OS_WIN
  990. if (! startProcess(argv, &pData->processInfo))
  991. {
  992. carla_zeroStruct(pData->processInfo);
  993. pData->processInfo.hProcess = INVALID_HANDLE_VALUE;
  994. pData->processInfo.hThread = INVALID_HANDLE_VALUE;
  995. try { ::CloseHandle(pipe1); } CARLA_SAFE_EXCEPTION("CloseHandle(pipe1)");
  996. try { ::CloseHandle(pipe2); } CARLA_SAFE_EXCEPTION("CloseHandle(pipe2)");
  997. fail("startProcess() failed");
  998. return false;
  999. }
  1000. // just to make sure
  1001. CARLA_SAFE_ASSERT(pData->processInfo.hThread != INVALID_HANDLE_VALUE);
  1002. CARLA_SAFE_ASSERT(pData->processInfo.hProcess != INVALID_HANDLE_VALUE);
  1003. #else
  1004. if (! startProcess(argv, pData->pid))
  1005. {
  1006. pData->pid = -1;
  1007. try { ::close(pipe1[0]); } CARLA_SAFE_EXCEPTION("close(pipe1[0])");
  1008. try { ::close(pipe1[1]); } CARLA_SAFE_EXCEPTION("close(pipe1[1])");
  1009. try { ::close(pipe2[0]); } CARLA_SAFE_EXCEPTION("close(pipe2[0])");
  1010. try { ::close(pipe2[1]); } CARLA_SAFE_EXCEPTION("close(pipe2[1])");
  1011. fail("startProcess() failed");
  1012. return false;
  1013. }
  1014. //----------------------------------------------------------------
  1015. // close duplicated handles used by the client
  1016. try { ::close(pipeRecvServer); } CARLA_SAFE_EXCEPTION("close(pipeRecvServer)");
  1017. try { ::close(pipeSendServer); } CARLA_SAFE_EXCEPTION("close(pipeSendServer)");
  1018. pipeRecvServer = pipeSendServer = INVALID_PIPE_VALUE;
  1019. #endif
  1020. //----------------------------------------------------------------
  1021. // wait for client to say something
  1022. if (waitForClientFirstMessage(pipeRecvClient, 10*1000 /* 10 secs */))
  1023. {
  1024. #ifdef CARLA_OS_WIN
  1025. CARLA_SAFE_ASSERT(waitForClientConnect(pipeSendClient, 1000 /* 1 sec */));
  1026. #endif
  1027. pData->pipeRecv = pipeRecvClient;
  1028. pData->pipeSend = pipeSendClient;
  1029. pData->pipeClosed = false;
  1030. carla_stdout("ALL OK!");
  1031. return true;
  1032. }
  1033. //----------------------------------------------------------------
  1034. // failed to set non-block or get first child message, cannot continue
  1035. #ifdef CARLA_OS_WIN
  1036. if (TerminateProcess(pData->processInfo.hProcess, 9) != FALSE)
  1037. {
  1038. // wait for process to stop
  1039. waitForProcessToStop(pData->processInfo, 2*1000);
  1040. }
  1041. // clear pData->processInfo
  1042. try { CloseHandle(pData->processInfo.hThread); } CARLA_SAFE_EXCEPTION("CloseHandle(pData->processInfo.hThread)");
  1043. try { CloseHandle(pData->processInfo.hProcess); } CARLA_SAFE_EXCEPTION("CloseHandle(pData->processInfo.hProcess)");
  1044. carla_zeroStruct(pData->processInfo);
  1045. pData->processInfo.hProcess = INVALID_HANDLE_VALUE;
  1046. pData->processInfo.hThread = INVALID_HANDLE_VALUE;
  1047. #else
  1048. if (::kill(pData->pid, SIGKILL) != -1)
  1049. {
  1050. // wait for killing to take place
  1051. waitForChildToStop(pData->pid, 2*1000, false);
  1052. }
  1053. pData->pid = -1;
  1054. #endif
  1055. //----------------------------------------------------------------
  1056. // close pipes
  1057. #ifdef CARLA_OS_WIN
  1058. try { ::CloseHandle(pipeRecvClient); } CARLA_SAFE_EXCEPTION("CloseHandle(pipeRecvClient)");
  1059. try { ::CloseHandle(pipeSendClient); } CARLA_SAFE_EXCEPTION("CloseHandle(pipeSendClient)");
  1060. #else
  1061. try { ::close (pipeRecvClient); } CARLA_SAFE_EXCEPTION("close(pipeRecvClient)");
  1062. try { ::close (pipeSendClient); } CARLA_SAFE_EXCEPTION("close(pipeSendClient)");
  1063. #endif
  1064. return false;
  1065. }
  1066. void CarlaPipeServer::stopPipeServer(const uint32_t timeOutMilliseconds) noexcept
  1067. {
  1068. carla_debug("CarlaPipeServer::stopPipeServer(%i)", timeOutMilliseconds);
  1069. #ifdef CARLA_OS_WIN
  1070. if (pData->processInfo.hThread != INVALID_HANDLE_VALUE || pData->processInfo.hProcess != INVALID_HANDLE_VALUE)
  1071. {
  1072. const CarlaMutexLocker cml(pData->writeLock);
  1073. if (pData->pipeSend != INVALID_PIPE_VALUE)
  1074. {
  1075. _writeMsgBuffer("__carla-quit__\n", 15);
  1076. flushMessages();
  1077. }
  1078. waitForProcessToStopOrKillIt(pData->processInfo, timeOutMilliseconds);
  1079. try { CloseHandle(pData->processInfo.hThread); } CARLA_SAFE_EXCEPTION("CloseHandle(pData->processInfo.hThread)");
  1080. try { CloseHandle(pData->processInfo.hProcess); } CARLA_SAFE_EXCEPTION("CloseHandle(pData->processInfo.hProcess)");
  1081. carla_zeroStruct(pData->processInfo);
  1082. pData->processInfo.hProcess = INVALID_HANDLE_VALUE;
  1083. pData->processInfo.hThread = INVALID_HANDLE_VALUE;
  1084. }
  1085. #else
  1086. if (pData->pid != -1)
  1087. {
  1088. const CarlaMutexLocker cml(pData->writeLock);
  1089. if (pData->pipeSend != INVALID_PIPE_VALUE)
  1090. {
  1091. _writeMsgBuffer("__carla-quit__\n", 15);
  1092. flushMessages();
  1093. }
  1094. waitForChildToStopOrKillIt(pData->pid, timeOutMilliseconds);
  1095. pData->pid = -1;
  1096. }
  1097. #endif
  1098. closePipeServer();
  1099. }
  1100. void CarlaPipeServer::closePipeServer() noexcept
  1101. {
  1102. carla_debug("CarlaPipeServer::closePipeServer()");
  1103. pData->pipeClosed = true;
  1104. const CarlaMutexLocker cml(pData->writeLock);
  1105. if (pData->pipeRecv != INVALID_PIPE_VALUE)
  1106. {
  1107. #ifdef CARLA_OS_WIN
  1108. DisconnectNamedPipe(pData->pipeRecv);
  1109. try { ::CloseHandle(pData->pipeRecv); } CARLA_SAFE_EXCEPTION("CloseHandle(pData->pipeRecv)");
  1110. #else
  1111. try { ::close (pData->pipeRecv); } CARLA_SAFE_EXCEPTION("close(pData->pipeRecv)");
  1112. #endif
  1113. pData->pipeRecv = INVALID_PIPE_VALUE;
  1114. }
  1115. if (pData->pipeSend != INVALID_PIPE_VALUE)
  1116. {
  1117. #ifdef CARLA_OS_WIN
  1118. DisconnectNamedPipe(pData->pipeSend);
  1119. try { ::CloseHandle(pData->pipeSend); } CARLA_SAFE_EXCEPTION("CloseHandle(pData->pipeSend)");
  1120. #else
  1121. try { ::close (pData->pipeSend); } CARLA_SAFE_EXCEPTION("close(pData->pipeSend)");
  1122. #endif
  1123. pData->pipeSend = INVALID_PIPE_VALUE;
  1124. }
  1125. }
  1126. void CarlaPipeServer::writeShowMessage() const noexcept
  1127. {
  1128. const CarlaMutexLocker cml(pData->writeLock);
  1129. _writeMsgBuffer("show\n", 5);
  1130. flushMessages();
  1131. }
  1132. void CarlaPipeServer::writeFocusMessage() const noexcept
  1133. {
  1134. const CarlaMutexLocker cml(pData->writeLock);
  1135. _writeMsgBuffer("focus\n", 6);
  1136. flushMessages();
  1137. }
  1138. void CarlaPipeServer::writeHideMessage() const noexcept
  1139. {
  1140. const CarlaMutexLocker cml(pData->writeLock);
  1141. _writeMsgBuffer("show\n", 5);
  1142. flushMessages();
  1143. }
  1144. // -----------------------------------------------------------------------
  1145. CarlaPipeClient::CarlaPipeClient() noexcept
  1146. : CarlaPipeCommon()
  1147. {
  1148. carla_debug("CarlaPipeClient::CarlaPipeClient()");
  1149. }
  1150. CarlaPipeClient::~CarlaPipeClient() /*noexcept*/
  1151. {
  1152. carla_debug("CarlaPipeClient::~CarlaPipeClient()");
  1153. closePipeClient();
  1154. }
  1155. bool CarlaPipeClient::initPipeClient(const char* argv[]) noexcept
  1156. {
  1157. CARLA_SAFE_ASSERT_RETURN(pData->pipeRecv == INVALID_PIPE_VALUE, false);
  1158. CARLA_SAFE_ASSERT_RETURN(pData->pipeSend == INVALID_PIPE_VALUE, false);
  1159. carla_debug("CarlaPipeClient::initPipeClient(%p)", argv);
  1160. const CarlaMutexLocker cml(pData->writeLock);
  1161. //----------------------------------------------------------------
  1162. // read arguments
  1163. #ifdef CARLA_OS_WIN
  1164. const char* const pipeRecvServerStr = argv[3];
  1165. const char* const pipeSendServerStr = argv[4];
  1166. HANDLE pipeRecvServer = ::CreateFileA(pipeRecvServerStr, GENERIC_READ, 0x0, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr);
  1167. HANDLE pipeSendServer = ::CreateFileA(pipeSendServerStr, GENERIC_WRITE, 0x0, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr);
  1168. CARLA_SAFE_ASSERT_RETURN(pipeRecvServer != INVALID_HANDLE_VALUE, false);
  1169. CARLA_SAFE_ASSERT_RETURN(pipeSendServer != INVALID_HANDLE_VALUE, false);
  1170. #else
  1171. const int pipeRecvServer = std::atoi(argv[3]);
  1172. const int pipeSendServer = std::atoi(argv[4]);
  1173. /* */ int pipeRecvClient = std::atoi(argv[5]);
  1174. /* */ int pipeSendClient = std::atoi(argv[6]);
  1175. CARLA_SAFE_ASSERT_RETURN(pipeRecvServer > 0, false);
  1176. CARLA_SAFE_ASSERT_RETURN(pipeSendServer > 0, false);
  1177. CARLA_SAFE_ASSERT_RETURN(pipeRecvClient > 0, false);
  1178. CARLA_SAFE_ASSERT_RETURN(pipeSendClient > 0, false);
  1179. //----------------------------------------------------------------
  1180. // close duplicated handles used by the client
  1181. try { ::close(pipeRecvClient); } CARLA_SAFE_EXCEPTION("close(pipeRecvClient)");
  1182. try { ::close(pipeSendClient); } CARLA_SAFE_EXCEPTION("close(pipeSendClient)");
  1183. pipeRecvClient = pipeSendClient = INVALID_PIPE_VALUE;
  1184. //----------------------------------------------------------------
  1185. // kill ourselves if parent dies
  1186. # ifdef CARLA_OS_LINUX
  1187. ::prctl(PR_SET_PDEATHSIG, SIGKILL);
  1188. // TODO, osx version too, see https://stackoverflow.com/questions/284325/how-to-make-child-process-die-after-parent-exits
  1189. # endif
  1190. #endif
  1191. //----------------------------------------------------------------
  1192. // done
  1193. pData->pipeRecv = pipeRecvServer;
  1194. pData->pipeSend = pipeSendServer;
  1195. pData->pipeClosed = false;
  1196. pData->clientClosingDown = false;
  1197. writeMessage("\n", 1);
  1198. flushMessages();
  1199. return true;
  1200. }
  1201. void CarlaPipeClient::closePipeClient() noexcept
  1202. {
  1203. carla_debug("CarlaPipeClient::closePipeClient()");
  1204. pData->pipeClosed = true;
  1205. const CarlaMutexLocker cml(pData->writeLock);
  1206. if (pData->pipeRecv != INVALID_PIPE_VALUE)
  1207. {
  1208. #ifdef CARLA_OS_WIN
  1209. try { ::CloseHandle(pData->pipeRecv); } CARLA_SAFE_EXCEPTION("CloseHandle(pData->pipeRecv)");
  1210. #else
  1211. try { ::close (pData->pipeRecv); } CARLA_SAFE_EXCEPTION("close(pData->pipeRecv)");
  1212. #endif
  1213. pData->pipeRecv = INVALID_PIPE_VALUE;
  1214. }
  1215. if (pData->pipeSend != INVALID_PIPE_VALUE)
  1216. {
  1217. #ifdef CARLA_OS_WIN
  1218. try { ::CloseHandle(pData->pipeSend); } CARLA_SAFE_EXCEPTION("CloseHandle(pData->pipeSend)");
  1219. #else
  1220. try { ::close (pData->pipeSend); } CARLA_SAFE_EXCEPTION("close(pData->pipeSend)");
  1221. #endif
  1222. pData->pipeSend = INVALID_PIPE_VALUE;
  1223. }
  1224. }
  1225. void CarlaPipeClient::writeExitingMessageAndWait() noexcept
  1226. {
  1227. {
  1228. const CarlaMutexLocker cml(pData->writeLock);
  1229. _writeMsgBuffer("exiting\n", 8);
  1230. flushMessages();
  1231. }
  1232. // NOTE: no more messages are handled after this point
  1233. pData->clientClosingDown = true;
  1234. // FIXME: don't sleep forever
  1235. for (; ! pData->pipeClosed;)
  1236. {
  1237. carla_msleep(50);
  1238. idlePipe(true);
  1239. }
  1240. }
  1241. // -----------------------------------------------------------------------
  1242. ScopedEnvVar::ScopedEnvVar(const char* const key, const char* const value) noexcept
  1243. : fKey(nullptr),
  1244. fOrigValue(nullptr)
  1245. {
  1246. CARLA_SAFE_ASSERT_RETURN(key != nullptr && key[0] != '\0',);
  1247. fKey = carla_strdup_safe(key);
  1248. CARLA_SAFE_ASSERT_RETURN(fKey != nullptr,);
  1249. if (const char* const origValue = std::getenv(key))
  1250. {
  1251. fOrigValue = carla_strdup_safe(origValue);
  1252. CARLA_SAFE_ASSERT_RETURN(fOrigValue != nullptr,);
  1253. }
  1254. if (value != nullptr)
  1255. carla_setenv(key, value);
  1256. else if (fOrigValue != nullptr)
  1257. carla_unsetenv(key);
  1258. }
  1259. ScopedEnvVar::~ScopedEnvVar() noexcept
  1260. {
  1261. bool hasOrigValue = false;
  1262. if (fOrigValue != nullptr)
  1263. {
  1264. hasOrigValue = true;
  1265. carla_setenv(fKey, fOrigValue);
  1266. delete[] fOrigValue;
  1267. fOrigValue = nullptr;
  1268. }
  1269. if (fKey != nullptr)
  1270. {
  1271. if (! hasOrigValue)
  1272. carla_unsetenv(fKey);
  1273. delete[] fKey;
  1274. fKey = nullptr;
  1275. }
  1276. }
  1277. // -----------------------------------------------------------------------
  1278. ScopedLocale::ScopedLocale() noexcept
  1279. : fLocale(carla_strdup_safe(::setlocale(LC_NUMERIC, nullptr)))
  1280. {
  1281. ::setlocale(LC_NUMERIC, "C");
  1282. }
  1283. ScopedLocale::~ScopedLocale() noexcept
  1284. {
  1285. if (fLocale != nullptr)
  1286. {
  1287. ::setlocale(LC_NUMERIC, fLocale);
  1288. delete[] fLocale;
  1289. }
  1290. }
  1291. // -----------------------------------------------------------------------
  1292. #undef INVALID_PIPE_VALUE