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.

1663 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. if (pData->pipeClosed)
  567. return false;
  568. const std::size_t size(std::strlen(msg));
  569. CARLA_SAFE_ASSERT_RETURN(size > 0, false);
  570. CARLA_SAFE_ASSERT_RETURN(msg[size-1] == '\n', false);
  571. return _writeMsgBuffer(msg, size);
  572. }
  573. bool CarlaPipeCommon::writeMessage(const char* const msg, std::size_t size) const noexcept
  574. {
  575. CARLA_SAFE_ASSERT_RETURN(msg != nullptr && msg[0] != '\0', false);
  576. CARLA_SAFE_ASSERT_RETURN(size > 0, false);
  577. CARLA_SAFE_ASSERT_RETURN(msg[size-1] == '\n', false);
  578. if (pData->pipeClosed)
  579. return false;
  580. return _writeMsgBuffer(msg, size);
  581. }
  582. bool CarlaPipeCommon::writeAndFixMessage(const char* const msg) const noexcept
  583. {
  584. CARLA_SAFE_ASSERT_RETURN(msg != nullptr, false);
  585. if (pData->pipeClosed)
  586. return false;
  587. const std::size_t size(std::strlen(msg));
  588. char fixedMsg[size+2];
  589. if (size > 0)
  590. {
  591. std::strcpy(fixedMsg, msg);
  592. for (std::size_t i=0; i<size; ++i)
  593. {
  594. if (fixedMsg[i] == '\n')
  595. fixedMsg[i] = '\r';
  596. }
  597. if (fixedMsg[size-1] == '\r')
  598. {
  599. fixedMsg[size-1] = '\n';
  600. fixedMsg[size ] = '\0';
  601. fixedMsg[size+1] = '\0';
  602. }
  603. else
  604. {
  605. fixedMsg[size ] = '\n';
  606. fixedMsg[size+1] = '\0';
  607. }
  608. }
  609. else
  610. {
  611. fixedMsg[0] = '\n';
  612. fixedMsg[1] = '\0';
  613. }
  614. return _writeMsgBuffer(fixedMsg, size+1);
  615. }
  616. bool CarlaPipeCommon::flushMessages() const noexcept
  617. {
  618. CARLA_SAFE_ASSERT_RETURN(pData->pipeSend != INVALID_PIPE_VALUE, false);
  619. #ifdef CARLA_OS_WIN
  620. try {
  621. return (::FlushFileBuffers(pData->pipeSend) != FALSE);
  622. } CARLA_SAFE_EXCEPTION_RETURN("CarlaPipeCommon::writeMsgBuffer", false);
  623. #else
  624. // nothing to do
  625. return true;
  626. #endif
  627. }
  628. // -------------------------------------------------------------------
  629. void CarlaPipeCommon::writeErrorMessage(const char* const error) const noexcept
  630. {
  631. CARLA_SAFE_ASSERT_RETURN(error != nullptr && error[0] != '\0',);
  632. const CarlaMutexLocker cml(pData->writeLock);
  633. if (! _writeMsgBuffer("error\n", 6))
  634. return;
  635. if (! writeAndFixMessage(error))
  636. return;
  637. flushMessages();
  638. }
  639. void CarlaPipeCommon::writeControlMessage(const uint32_t index, const float value) const noexcept
  640. {
  641. char tmpBuf[0xff+1];
  642. tmpBuf[0xff] = '\0';
  643. const CarlaMutexLocker cml(pData->writeLock);
  644. if (! _writeMsgBuffer("control\n", 8))
  645. return;
  646. std::snprintf(tmpBuf, 0xff, "%i\n", index);
  647. if (! _writeMsgBuffer(tmpBuf, std::strlen(tmpBuf)))
  648. return;
  649. {
  650. const ScopedLocale csl;
  651. std::snprintf(tmpBuf, 0xff, "%f\n", value);
  652. }
  653. if (! _writeMsgBuffer(tmpBuf, std::strlen(tmpBuf)))
  654. return;
  655. flushMessages();
  656. }
  657. void CarlaPipeCommon::writeConfigureMessage(const char* const key, const char* const value) const noexcept
  658. {
  659. CARLA_SAFE_ASSERT_RETURN(key != nullptr && key[0] != '\0',);
  660. CARLA_SAFE_ASSERT_RETURN(value != nullptr,);
  661. const CarlaMutexLocker cml(pData->writeLock);
  662. if (! _writeMsgBuffer("configure\n", 10))
  663. return;
  664. if (! writeAndFixMessage(key))
  665. return;
  666. if (! writeAndFixMessage(value))
  667. return;
  668. flushMessages();
  669. }
  670. void CarlaPipeCommon::writeProgramMessage(const uint32_t index) const noexcept
  671. {
  672. char tmpBuf[0xff+1];
  673. tmpBuf[0xff] = '\0';
  674. const CarlaMutexLocker cml(pData->writeLock);
  675. if (! _writeMsgBuffer("program\n", 8))
  676. return;
  677. std::snprintf(tmpBuf, 0xff, "%i\n", index);
  678. if (! _writeMsgBuffer(tmpBuf, std::strlen(tmpBuf)))
  679. return;
  680. flushMessages();
  681. }
  682. void CarlaPipeCommon::writeMidiProgramMessage(const uint32_t bank, const uint32_t program) const noexcept
  683. {
  684. char tmpBuf[0xff+1];
  685. tmpBuf[0xff] = '\0';
  686. const CarlaMutexLocker cml(pData->writeLock);
  687. if (! _writeMsgBuffer("midiprogram\n", 12))
  688. return;
  689. std::snprintf(tmpBuf, 0xff, "%i\n", bank);
  690. if (! _writeMsgBuffer(tmpBuf, std::strlen(tmpBuf)))
  691. return;
  692. std::snprintf(tmpBuf, 0xff, "%i\n", program);
  693. if (! _writeMsgBuffer(tmpBuf, std::strlen(tmpBuf)))
  694. return;
  695. flushMessages();
  696. }
  697. void CarlaPipeCommon::writeMidiNoteMessage(const bool onOff, const uint8_t channel, const uint8_t note, const uint8_t velocity) const noexcept
  698. {
  699. CARLA_SAFE_ASSERT_RETURN(channel < MAX_MIDI_CHANNELS,);
  700. CARLA_SAFE_ASSERT_RETURN(note < MAX_MIDI_NOTE,);
  701. CARLA_SAFE_ASSERT_RETURN(velocity < MAX_MIDI_VALUE,);
  702. char tmpBuf[0xff+1];
  703. tmpBuf[0xff] = '\0';
  704. const CarlaMutexLocker cml(pData->writeLock);
  705. if (! _writeMsgBuffer("note\n", 5))
  706. return;
  707. std::snprintf(tmpBuf, 0xff, "%s\n", bool2str(onOff));
  708. if (! _writeMsgBuffer(tmpBuf, std::strlen(tmpBuf)))
  709. return;
  710. std::snprintf(tmpBuf, 0xff, "%i\n", channel);
  711. if (! _writeMsgBuffer(tmpBuf, std::strlen(tmpBuf)))
  712. return;
  713. std::snprintf(tmpBuf, 0xff, "%i\n", note);
  714. if (! _writeMsgBuffer(tmpBuf, std::strlen(tmpBuf)))
  715. return;
  716. std::snprintf(tmpBuf, 0xff, "%i\n", velocity);
  717. if (! _writeMsgBuffer(tmpBuf, std::strlen(tmpBuf)))
  718. return;
  719. flushMessages();
  720. }
  721. void CarlaPipeCommon::writeLv2AtomMessage(const uint32_t index, const LV2_Atom* const atom) const noexcept
  722. {
  723. CARLA_SAFE_ASSERT_RETURN(atom != nullptr,);
  724. char tmpBuf[0xff+1];
  725. tmpBuf[0xff] = '\0';
  726. const uint32_t atomTotalSize(lv2_atom_total_size(atom));
  727. CarlaString base64atom(CarlaString::asBase64(atom, atomTotalSize));
  728. const CarlaMutexLocker cml(pData->writeLock);
  729. if (! _writeMsgBuffer("atom\n", 5))
  730. return;
  731. std::snprintf(tmpBuf, 0xff, "%i\n", index);
  732. if (! _writeMsgBuffer(tmpBuf, std::strlen(tmpBuf)))
  733. return;
  734. std::snprintf(tmpBuf, 0xff, "%i\n", atomTotalSize);
  735. if (! _writeMsgBuffer(tmpBuf, std::strlen(tmpBuf)))
  736. return;
  737. if (! writeAndFixMessage(base64atom.buffer()))
  738. return;
  739. flushMessages();
  740. }
  741. void CarlaPipeCommon::writeLv2UridMessage(const uint32_t urid, const char* const uri) const noexcept
  742. {
  743. CARLA_SAFE_ASSERT_RETURN(urid != 0,);
  744. CARLA_SAFE_ASSERT_RETURN(uri != nullptr && uri[0] != '\0',);
  745. char tmpBuf[0xff+1];
  746. tmpBuf[0xff] = '\0';
  747. const CarlaMutexLocker cml(pData->writeLock);
  748. if (! _writeMsgBuffer("urid\n", 5))
  749. return;
  750. std::snprintf(tmpBuf, 0xff, "%i\n", urid);
  751. if (! _writeMsgBuffer(tmpBuf, std::strlen(tmpBuf)))
  752. return;
  753. if (! writeAndFixMessage(uri))
  754. return;
  755. flushMessages();
  756. }
  757. // -------------------------------------------------------------------
  758. // internal
  759. const char* CarlaPipeCommon::_readline() const noexcept
  760. {
  761. CARLA_SAFE_ASSERT_RETURN(pData->pipeRecv != INVALID_PIPE_VALUE, nullptr);
  762. char c;
  763. char* ptr = pData->tmpBuf;
  764. ssize_t ret = -1;
  765. pData->tmpStr.clear();
  766. for (int i=0; i<0xff; ++i)
  767. {
  768. try {
  769. #ifdef CARLA_OS_WIN
  770. ret = ::ReadFileWin32(pData->pipeRecv, &c, 1);
  771. #else
  772. ret = ::read(pData->pipeRecv, &c, 1);
  773. #endif
  774. } CARLA_SAFE_EXCEPTION_BREAK("CarlaPipeCommon::readline() - read");
  775. if (ret != 1 || c == '\n')
  776. break;
  777. if (c == '\r')
  778. c = '\n';
  779. *ptr++ = c;
  780. if (i+1 == 0xff)
  781. {
  782. i = 0;
  783. *ptr = '\0';
  784. pData->tmpStr += pData->tmpBuf;
  785. ptr = pData->tmpBuf;
  786. }
  787. }
  788. if (ptr != pData->tmpBuf)
  789. {
  790. *ptr = '\0';
  791. pData->tmpStr += pData->tmpBuf;
  792. }
  793. else if (pData->tmpStr.isEmpty() && ret != 1)
  794. {
  795. // some error
  796. return nullptr;
  797. }
  798. try {
  799. return pData->tmpStr.dup();
  800. } CARLA_SAFE_EXCEPTION_RETURN("CarlaPipeCommon::readline() - dup", nullptr);
  801. }
  802. const char* CarlaPipeCommon::_readlineblock(const uint32_t timeOutMilliseconds) const noexcept
  803. {
  804. const uint32_t timeoutEnd(water::Time::getMillisecondCounter() + timeOutMilliseconds);
  805. for (;;)
  806. {
  807. if (const char* const msg = _readline())
  808. return msg;
  809. if (water::Time::getMillisecondCounter() >= timeoutEnd)
  810. break;
  811. carla_msleep(5);
  812. }
  813. carla_stderr("readlineblock timed out");
  814. return nullptr;
  815. }
  816. bool CarlaPipeCommon::_writeMsgBuffer(const char* const msg, const std::size_t size) const noexcept
  817. {
  818. if (pData->pipeClosed)
  819. return false;
  820. if (pData->pipeSend == INVALID_PIPE_VALUE)
  821. {
  822. carla_stderr2("CarlaPipe write error, isServer:%s, message was:\n%s", bool2str(pData->isServer), msg);
  823. return false;
  824. }
  825. ssize_t ret;
  826. try {
  827. #ifdef CARLA_OS_WIN
  828. ret = ::WriteFileWin32(pData->pipeSend, msg, size);
  829. #else
  830. ret = ::write(pData->pipeSend, msg, size);
  831. #endif
  832. } CARLA_SAFE_EXCEPTION_RETURN("CarlaPipeCommon::writeMsgBuffer", false);
  833. if (ret == static_cast<ssize_t>(size))
  834. {
  835. if (pData->lastMessageFailed)
  836. pData->lastMessageFailed = false;
  837. return true;
  838. }
  839. #if 0
  840. // ignore errors if the other side of the pipe has closed
  841. if (pData->pipeClosed)
  842. return false;
  843. #endif
  844. if (! pData->lastMessageFailed)
  845. {
  846. pData->lastMessageFailed = true;
  847. fprintf(stderr,
  848. "CarlaPipeCommon::_writeMsgBuffer(..., " P_SIZE ") - failed with " P_SSIZE " (%s), message was:\n%s",
  849. size, ret, bool2str(pData->isServer), msg);
  850. }
  851. return false;
  852. }
  853. // -----------------------------------------------------------------------
  854. CarlaPipeServer::CarlaPipeServer() noexcept
  855. : CarlaPipeCommon()
  856. {
  857. carla_debug("CarlaPipeServer::CarlaPipeServer()");
  858. pData->isServer = true;
  859. }
  860. CarlaPipeServer::~CarlaPipeServer() /*noexcept*/
  861. {
  862. carla_debug("CarlaPipeServer::~CarlaPipeServer()");
  863. stopPipeServer(5*1000);
  864. }
  865. uintptr_t CarlaPipeServer::getPID() const noexcept
  866. {
  867. #ifndef CARLA_OS_WIN
  868. return static_cast<uintptr_t>(pData->pid);
  869. #else
  870. return 0;
  871. #endif
  872. }
  873. // -----------------------------------------------------------------------
  874. bool CarlaPipeServer::startPipeServer(const char* const filename,
  875. const char* const arg1,
  876. const char* const arg2,
  877. const int size) noexcept
  878. {
  879. CARLA_SAFE_ASSERT_RETURN(pData->pipeRecv == INVALID_PIPE_VALUE, false);
  880. CARLA_SAFE_ASSERT_RETURN(pData->pipeSend == INVALID_PIPE_VALUE, false);
  881. #ifdef CARLA_OS_WIN
  882. CARLA_SAFE_ASSERT_RETURN(pData->processInfo.hThread == INVALID_HANDLE_VALUE, false);
  883. CARLA_SAFE_ASSERT_RETURN(pData->processInfo.hProcess == INVALID_HANDLE_VALUE, false);
  884. #else
  885. CARLA_SAFE_ASSERT_RETURN(pData->pid == -1, false);
  886. #endif
  887. CARLA_SAFE_ASSERT_RETURN(filename != nullptr && filename[0] != '\0', false);
  888. CARLA_SAFE_ASSERT_RETURN(arg1 != nullptr, false);
  889. CARLA_SAFE_ASSERT_RETURN(arg2 != nullptr, false);
  890. carla_debug("CarlaPipeServer::startPipeServer(\"%s\", \"%s\", \"%s\")", filename, arg1, arg2);
  891. char pipeRecvServerStr[100+1];
  892. char pipeSendServerStr[100+1];
  893. char pipeRecvClientStr[100+1];
  894. char pipeSendClientStr[100+1];
  895. pipeRecvServerStr[100] = '\0';
  896. pipeSendServerStr[100] = '\0';
  897. pipeRecvClientStr[100] = '\0';
  898. pipeSendClientStr[100] = '\0';
  899. const CarlaMutexLocker cml(pData->writeLock);
  900. //----------------------------------------------------------------
  901. // create pipes
  902. #ifdef CARLA_OS_WIN
  903. HANDLE pipe1, pipe2;
  904. std::srand(static_cast<uint>(std::time(nullptr)));
  905. static ulong sCounter = 0;
  906. ++sCounter;
  907. const int randint = std::rand();
  908. std::snprintf(pipeRecvServerStr, 100, "\\\\.\\pipe\\carla-pipe1-%i-%li", randint, sCounter);
  909. std::snprintf(pipeSendServerStr, 100, "\\\\.\\pipe\\carla-pipe2-%i-%li", randint, sCounter);
  910. std::snprintf(pipeRecvClientStr, 100, "ignored");
  911. std::snprintf(pipeSendClientStr, 100, "ignored");
  912. pipe1 = ::CreateNamedPipeA(pipeRecvServerStr, PIPE_ACCESS_DUPLEX, PIPE_TYPE_BYTE|PIPE_READMODE_BYTE|PIPE_NOWAIT, 2, size, size, 0, nullptr);
  913. if (pipe1 == INVALID_HANDLE_VALUE)
  914. {
  915. fail("pipe creation failed");
  916. return false;
  917. }
  918. pipe2 = ::CreateNamedPipeA(pipeSendServerStr, PIPE_ACCESS_DUPLEX, PIPE_TYPE_BYTE|PIPE_READMODE_BYTE|PIPE_NOWAIT, 2, size, size, 0, nullptr);
  919. if (pipe2 == INVALID_HANDLE_VALUE)
  920. {
  921. try { ::CloseHandle(pipe1); } CARLA_SAFE_EXCEPTION("CloseHandle(pipe1)");
  922. fail("pipe creation failed");
  923. return false;
  924. }
  925. const HANDLE pipeRecvClient = pipe2;
  926. const HANDLE pipeSendClient = pipe1;
  927. #else
  928. int pipe1[2]; // read by server, written by client
  929. int pipe2[2]; // read by client, written by server
  930. if (::pipe(pipe1) != 0)
  931. {
  932. fail("pipe1 creation failed");
  933. return false;
  934. }
  935. if (::pipe(pipe2) != 0)
  936. {
  937. try { ::close(pipe1[0]); } CARLA_SAFE_EXCEPTION("close(pipe1[0])");
  938. try { ::close(pipe1[1]); } CARLA_SAFE_EXCEPTION("close(pipe1[1])");
  939. fail("pipe2 creation failed");
  940. return false;
  941. }
  942. /* */ int pipeRecvServer = pipe1[0];
  943. /* */ int pipeSendServer = pipe2[1];
  944. const int pipeRecvClient = pipe2[0];
  945. const int pipeSendClient = pipe1[1];
  946. std::snprintf(pipeRecvServerStr, 100, "%i", pipeRecvServer);
  947. std::snprintf(pipeSendServerStr, 100, "%i", pipeSendServer);
  948. std::snprintf(pipeRecvClientStr, 100, "%i", pipeRecvClient);
  949. std::snprintf(pipeSendClientStr, 100, "%i", pipeSendClient);
  950. //----------------------------------------------------------------
  951. // set size, non-fatal
  952. #ifdef CARLA_OS_LINUX
  953. try {
  954. ::fcntl(pipeRecvClient, F_SETPIPE_SZ, size);
  955. } CARLA_SAFE_EXCEPTION("Set pipe size");
  956. try {
  957. ::fcntl(pipeRecvServer, F_SETPIPE_SZ, size);
  958. } CARLA_SAFE_EXCEPTION("Set pipe size");
  959. #endif
  960. //----------------------------------------------------------------
  961. // set non-block
  962. int ret;
  963. try {
  964. ret = ::fcntl(pipeRecvClient, F_SETFL, ::fcntl(pipeRecvClient, F_GETFL) | O_NONBLOCK);
  965. } catch (...) {
  966. ret = -1;
  967. fail("failed to set pipe as non-block");
  968. }
  969. if (ret == 0)
  970. {
  971. try {
  972. ret = ::fcntl(pipeRecvServer, F_SETFL, ::fcntl(pipeRecvServer, F_GETFL) | O_NONBLOCK);
  973. } catch (...) {
  974. ret = -1;
  975. fail("failed to set pipe as non-block");
  976. }
  977. }
  978. if (ret < 0)
  979. {
  980. try { ::close(pipe1[0]); } CARLA_SAFE_EXCEPTION("close(pipe1[0])");
  981. try { ::close(pipe1[1]); } CARLA_SAFE_EXCEPTION("close(pipe1[1])");
  982. try { ::close(pipe2[0]); } CARLA_SAFE_EXCEPTION("close(pipe2[0])");
  983. try { ::close(pipe2[1]); } CARLA_SAFE_EXCEPTION("close(pipe2[1])");
  984. return false;
  985. }
  986. #endif
  987. //----------------------------------------------------------------
  988. // set arguments
  989. const char* argv[8];
  990. //----------------------------------------------------------------
  991. // argv[0] => filename
  992. argv[0] = filename;
  993. //----------------------------------------------------------------
  994. // argv[1-2] => args
  995. argv[1] = arg1;
  996. argv[2] = arg2;
  997. //----------------------------------------------------------------
  998. // argv[3-6] => pipes
  999. argv[3] = pipeRecvServerStr;
  1000. argv[4] = pipeSendServerStr;
  1001. argv[5] = pipeRecvClientStr;
  1002. argv[6] = pipeSendClientStr;
  1003. //----------------------------------------------------------------
  1004. // argv[7] => null
  1005. argv[7] = nullptr;
  1006. //----------------------------------------------------------------
  1007. // start process
  1008. #ifdef CARLA_OS_WIN
  1009. if (! startProcess(argv, &pData->processInfo))
  1010. {
  1011. carla_zeroStruct(pData->processInfo);
  1012. pData->processInfo.hProcess = INVALID_HANDLE_VALUE;
  1013. pData->processInfo.hThread = INVALID_HANDLE_VALUE;
  1014. try { ::CloseHandle(pipe1); } CARLA_SAFE_EXCEPTION("CloseHandle(pipe1)");
  1015. try { ::CloseHandle(pipe2); } CARLA_SAFE_EXCEPTION("CloseHandle(pipe2)");
  1016. fail("startProcess() failed");
  1017. return false;
  1018. }
  1019. // just to make sure
  1020. CARLA_SAFE_ASSERT(pData->processInfo.hThread != INVALID_HANDLE_VALUE);
  1021. CARLA_SAFE_ASSERT(pData->processInfo.hProcess != INVALID_HANDLE_VALUE);
  1022. #else
  1023. if (! startProcess(argv, pData->pid))
  1024. {
  1025. pData->pid = -1;
  1026. try { ::close(pipe1[0]); } CARLA_SAFE_EXCEPTION("close(pipe1[0])");
  1027. try { ::close(pipe1[1]); } CARLA_SAFE_EXCEPTION("close(pipe1[1])");
  1028. try { ::close(pipe2[0]); } CARLA_SAFE_EXCEPTION("close(pipe2[0])");
  1029. try { ::close(pipe2[1]); } CARLA_SAFE_EXCEPTION("close(pipe2[1])");
  1030. fail("startProcess() failed");
  1031. return false;
  1032. }
  1033. //----------------------------------------------------------------
  1034. // close duplicated handles used by the client
  1035. try { ::close(pipeRecvServer); } CARLA_SAFE_EXCEPTION("close(pipeRecvServer)");
  1036. try { ::close(pipeSendServer); } CARLA_SAFE_EXCEPTION("close(pipeSendServer)");
  1037. pipeRecvServer = pipeSendServer = INVALID_PIPE_VALUE;
  1038. #endif
  1039. //----------------------------------------------------------------
  1040. // wait for client to say something
  1041. if (waitForClientFirstMessage(pipeRecvClient, 10*1000 /* 10 secs */))
  1042. {
  1043. #ifdef CARLA_OS_WIN
  1044. CARLA_SAFE_ASSERT(waitForClientConnect(pipeSendClient, 1000 /* 1 sec */));
  1045. #endif
  1046. pData->pipeRecv = pipeRecvClient;
  1047. pData->pipeSend = pipeSendClient;
  1048. pData->pipeClosed = false;
  1049. carla_stdout("ALL OK!");
  1050. return true;
  1051. }
  1052. //----------------------------------------------------------------
  1053. // failed to set non-block or get first child message, cannot continue
  1054. #ifdef CARLA_OS_WIN
  1055. if (TerminateProcess(pData->processInfo.hProcess, 9) != FALSE)
  1056. {
  1057. // wait for process to stop
  1058. waitForProcessToStop(pData->processInfo, 2*1000);
  1059. }
  1060. // clear pData->processInfo
  1061. try { CloseHandle(pData->processInfo.hThread); } CARLA_SAFE_EXCEPTION("CloseHandle(pData->processInfo.hThread)");
  1062. try { CloseHandle(pData->processInfo.hProcess); } CARLA_SAFE_EXCEPTION("CloseHandle(pData->processInfo.hProcess)");
  1063. carla_zeroStruct(pData->processInfo);
  1064. pData->processInfo.hProcess = INVALID_HANDLE_VALUE;
  1065. pData->processInfo.hThread = INVALID_HANDLE_VALUE;
  1066. #else
  1067. if (::kill(pData->pid, SIGKILL) != -1)
  1068. {
  1069. // wait for killing to take place
  1070. waitForChildToStop(pData->pid, 2*1000, false);
  1071. }
  1072. pData->pid = -1;
  1073. #endif
  1074. //----------------------------------------------------------------
  1075. // close pipes
  1076. #ifdef CARLA_OS_WIN
  1077. try { ::CloseHandle(pipeRecvClient); } CARLA_SAFE_EXCEPTION("CloseHandle(pipeRecvClient)");
  1078. try { ::CloseHandle(pipeSendClient); } CARLA_SAFE_EXCEPTION("CloseHandle(pipeSendClient)");
  1079. #else
  1080. try { ::close (pipeRecvClient); } CARLA_SAFE_EXCEPTION("close(pipeRecvClient)");
  1081. try { ::close (pipeSendClient); } CARLA_SAFE_EXCEPTION("close(pipeSendClient)");
  1082. #endif
  1083. return false;
  1084. }
  1085. void CarlaPipeServer::stopPipeServer(const uint32_t timeOutMilliseconds) noexcept
  1086. {
  1087. carla_debug("CarlaPipeServer::stopPipeServer(%i)", timeOutMilliseconds);
  1088. #ifdef CARLA_OS_WIN
  1089. if (pData->processInfo.hThread != INVALID_HANDLE_VALUE || pData->processInfo.hProcess != INVALID_HANDLE_VALUE)
  1090. {
  1091. const CarlaMutexLocker cml(pData->writeLock);
  1092. if (pData->pipeSend != INVALID_PIPE_VALUE)
  1093. {
  1094. if (_writeMsgBuffer("__carla-quit__\n", 15))
  1095. flushMessages();
  1096. }
  1097. waitForProcessToStopOrKillIt(pData->processInfo, timeOutMilliseconds);
  1098. try { CloseHandle(pData->processInfo.hThread); } CARLA_SAFE_EXCEPTION("CloseHandle(pData->processInfo.hThread)");
  1099. try { CloseHandle(pData->processInfo.hProcess); } CARLA_SAFE_EXCEPTION("CloseHandle(pData->processInfo.hProcess)");
  1100. carla_zeroStruct(pData->processInfo);
  1101. pData->processInfo.hProcess = INVALID_HANDLE_VALUE;
  1102. pData->processInfo.hThread = INVALID_HANDLE_VALUE;
  1103. }
  1104. #else
  1105. if (pData->pid != -1)
  1106. {
  1107. const CarlaMutexLocker cml(pData->writeLock);
  1108. if (pData->pipeSend != INVALID_PIPE_VALUE)
  1109. {
  1110. if (_writeMsgBuffer("__carla-quit__\n", 15))
  1111. flushMessages();
  1112. }
  1113. waitForChildToStopOrKillIt(pData->pid, timeOutMilliseconds);
  1114. pData->pid = -1;
  1115. }
  1116. #endif
  1117. closePipeServer();
  1118. }
  1119. void CarlaPipeServer::closePipeServer() noexcept
  1120. {
  1121. carla_debug("CarlaPipeServer::closePipeServer()");
  1122. pData->pipeClosed = true;
  1123. const CarlaMutexLocker cml(pData->writeLock);
  1124. if (pData->pipeRecv != INVALID_PIPE_VALUE)
  1125. {
  1126. #ifdef CARLA_OS_WIN
  1127. DisconnectNamedPipe(pData->pipeRecv);
  1128. try { ::CloseHandle(pData->pipeRecv); } CARLA_SAFE_EXCEPTION("CloseHandle(pData->pipeRecv)");
  1129. #else
  1130. try { ::close (pData->pipeRecv); } CARLA_SAFE_EXCEPTION("close(pData->pipeRecv)");
  1131. #endif
  1132. pData->pipeRecv = INVALID_PIPE_VALUE;
  1133. }
  1134. if (pData->pipeSend != INVALID_PIPE_VALUE)
  1135. {
  1136. #ifdef CARLA_OS_WIN
  1137. DisconnectNamedPipe(pData->pipeSend);
  1138. try { ::CloseHandle(pData->pipeSend); } CARLA_SAFE_EXCEPTION("CloseHandle(pData->pipeSend)");
  1139. #else
  1140. try { ::close (pData->pipeSend); } CARLA_SAFE_EXCEPTION("close(pData->pipeSend)");
  1141. #endif
  1142. pData->pipeSend = INVALID_PIPE_VALUE;
  1143. }
  1144. }
  1145. void CarlaPipeServer::writeShowMessage() const noexcept
  1146. {
  1147. const CarlaMutexLocker cml(pData->writeLock);
  1148. if (! _writeMsgBuffer("show\n", 5))
  1149. return;
  1150. flushMessages();
  1151. }
  1152. void CarlaPipeServer::writeFocusMessage() const noexcept
  1153. {
  1154. const CarlaMutexLocker cml(pData->writeLock);
  1155. if (! _writeMsgBuffer("focus\n", 6))
  1156. return;
  1157. flushMessages();
  1158. }
  1159. void CarlaPipeServer::writeHideMessage() const noexcept
  1160. {
  1161. const CarlaMutexLocker cml(pData->writeLock);
  1162. if (! _writeMsgBuffer("show\n", 5))
  1163. return;
  1164. flushMessages();
  1165. }
  1166. // -----------------------------------------------------------------------
  1167. CarlaPipeClient::CarlaPipeClient() noexcept
  1168. : CarlaPipeCommon()
  1169. {
  1170. carla_debug("CarlaPipeClient::CarlaPipeClient()");
  1171. }
  1172. CarlaPipeClient::~CarlaPipeClient() /*noexcept*/
  1173. {
  1174. carla_debug("CarlaPipeClient::~CarlaPipeClient()");
  1175. closePipeClient();
  1176. }
  1177. bool CarlaPipeClient::initPipeClient(const char* argv[]) noexcept
  1178. {
  1179. CARLA_SAFE_ASSERT_RETURN(pData->pipeRecv == INVALID_PIPE_VALUE, false);
  1180. CARLA_SAFE_ASSERT_RETURN(pData->pipeSend == INVALID_PIPE_VALUE, false);
  1181. carla_debug("CarlaPipeClient::initPipeClient(%p)", argv);
  1182. const CarlaMutexLocker cml(pData->writeLock);
  1183. //----------------------------------------------------------------
  1184. // read arguments
  1185. #ifdef CARLA_OS_WIN
  1186. const char* const pipeRecvServerStr = argv[3];
  1187. const char* const pipeSendServerStr = argv[4];
  1188. HANDLE pipeRecvServer = ::CreateFileA(pipeRecvServerStr, GENERIC_READ, 0x0, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr);
  1189. HANDLE pipeSendServer = ::CreateFileA(pipeSendServerStr, GENERIC_WRITE, 0x0, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr);
  1190. CARLA_SAFE_ASSERT_RETURN(pipeRecvServer != INVALID_HANDLE_VALUE, false);
  1191. CARLA_SAFE_ASSERT_RETURN(pipeSendServer != INVALID_HANDLE_VALUE, false);
  1192. #else
  1193. const int pipeRecvServer = std::atoi(argv[3]);
  1194. const int pipeSendServer = std::atoi(argv[4]);
  1195. /* */ int pipeRecvClient = std::atoi(argv[5]);
  1196. /* */ int pipeSendClient = std::atoi(argv[6]);
  1197. CARLA_SAFE_ASSERT_RETURN(pipeRecvServer > 0, false);
  1198. CARLA_SAFE_ASSERT_RETURN(pipeSendServer > 0, false);
  1199. CARLA_SAFE_ASSERT_RETURN(pipeRecvClient > 0, false);
  1200. CARLA_SAFE_ASSERT_RETURN(pipeSendClient > 0, false);
  1201. //----------------------------------------------------------------
  1202. // close duplicated handles used by the client
  1203. try { ::close(pipeRecvClient); } CARLA_SAFE_EXCEPTION("close(pipeRecvClient)");
  1204. try { ::close(pipeSendClient); } CARLA_SAFE_EXCEPTION("close(pipeSendClient)");
  1205. pipeRecvClient = pipeSendClient = INVALID_PIPE_VALUE;
  1206. //----------------------------------------------------------------
  1207. // kill ourselves if parent dies
  1208. # ifdef CARLA_OS_LINUX
  1209. ::prctl(PR_SET_PDEATHSIG, SIGKILL);
  1210. // TODO, osx version too, see https://stackoverflow.com/questions/284325/how-to-make-child-process-die-after-parent-exits
  1211. # endif
  1212. #endif
  1213. //----------------------------------------------------------------
  1214. // done
  1215. pData->pipeRecv = pipeRecvServer;
  1216. pData->pipeSend = pipeSendServer;
  1217. pData->pipeClosed = false;
  1218. pData->clientClosingDown = false;
  1219. if (writeMessage("\n", 1))
  1220. flushMessages();
  1221. return true;
  1222. }
  1223. void CarlaPipeClient::closePipeClient() noexcept
  1224. {
  1225. carla_debug("CarlaPipeClient::closePipeClient()");
  1226. pData->pipeClosed = true;
  1227. const CarlaMutexLocker cml(pData->writeLock);
  1228. if (pData->pipeRecv != INVALID_PIPE_VALUE)
  1229. {
  1230. #ifdef CARLA_OS_WIN
  1231. try { ::CloseHandle(pData->pipeRecv); } CARLA_SAFE_EXCEPTION("CloseHandle(pData->pipeRecv)");
  1232. #else
  1233. try { ::close (pData->pipeRecv); } CARLA_SAFE_EXCEPTION("close(pData->pipeRecv)");
  1234. #endif
  1235. pData->pipeRecv = INVALID_PIPE_VALUE;
  1236. }
  1237. if (pData->pipeSend != INVALID_PIPE_VALUE)
  1238. {
  1239. #ifdef CARLA_OS_WIN
  1240. try { ::CloseHandle(pData->pipeSend); } CARLA_SAFE_EXCEPTION("CloseHandle(pData->pipeSend)");
  1241. #else
  1242. try { ::close (pData->pipeSend); } CARLA_SAFE_EXCEPTION("close(pData->pipeSend)");
  1243. #endif
  1244. pData->pipeSend = INVALID_PIPE_VALUE;
  1245. }
  1246. }
  1247. void CarlaPipeClient::writeExitingMessageAndWait() noexcept
  1248. {
  1249. {
  1250. const CarlaMutexLocker cml(pData->writeLock);
  1251. if (_writeMsgBuffer("exiting\n", 8))
  1252. flushMessages();
  1253. }
  1254. // NOTE: no more messages are handled after this point
  1255. pData->clientClosingDown = true;
  1256. // FIXME: don't sleep forever
  1257. for (; ! pData->pipeClosed;)
  1258. {
  1259. carla_msleep(50);
  1260. idlePipe(true);
  1261. }
  1262. }
  1263. // -----------------------------------------------------------------------
  1264. ScopedEnvVar::ScopedEnvVar(const char* const key, const char* const value) noexcept
  1265. : fKey(nullptr),
  1266. fOrigValue(nullptr)
  1267. {
  1268. CARLA_SAFE_ASSERT_RETURN(key != nullptr && key[0] != '\0',);
  1269. fKey = carla_strdup_safe(key);
  1270. CARLA_SAFE_ASSERT_RETURN(fKey != nullptr,);
  1271. if (const char* const origValue = std::getenv(key))
  1272. {
  1273. fOrigValue = carla_strdup_safe(origValue);
  1274. CARLA_SAFE_ASSERT_RETURN(fOrigValue != nullptr,);
  1275. }
  1276. if (value != nullptr)
  1277. carla_setenv(key, value);
  1278. else if (fOrigValue != nullptr)
  1279. carla_unsetenv(key);
  1280. }
  1281. ScopedEnvVar::~ScopedEnvVar() noexcept
  1282. {
  1283. bool hasOrigValue = false;
  1284. if (fOrigValue != nullptr)
  1285. {
  1286. hasOrigValue = true;
  1287. carla_setenv(fKey, fOrigValue);
  1288. delete[] fOrigValue;
  1289. fOrigValue = nullptr;
  1290. }
  1291. if (fKey != nullptr)
  1292. {
  1293. if (! hasOrigValue)
  1294. carla_unsetenv(fKey);
  1295. delete[] fKey;
  1296. fKey = nullptr;
  1297. }
  1298. }
  1299. // -----------------------------------------------------------------------
  1300. ScopedLocale::ScopedLocale() noexcept
  1301. : fLocale(carla_strdup_safe(::setlocale(LC_NUMERIC, nullptr)))
  1302. {
  1303. ::setlocale(LC_NUMERIC, "C");
  1304. }
  1305. ScopedLocale::~ScopedLocale() noexcept
  1306. {
  1307. if (fLocale != nullptr)
  1308. {
  1309. ::setlocale(LC_NUMERIC, fLocale);
  1310. delete[] fLocale;
  1311. }
  1312. }
  1313. // -----------------------------------------------------------------------
  1314. #undef INVALID_PIPE_VALUE