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.

649 lines
17KB

  1. /*
  2. * Carla Pipe utils based on lv2fil UI code
  3. * Copyright (C) 2009 Nedko Arnaudov <nedko@arnaudov.name>
  4. * Copyright (C) 2013-2014 Filipe Coelho <falktx@falktx.com>
  5. *
  6. * This program is free software; you can redistribute it and/or
  7. * modify it under the terms of the GNU General Public License as
  8. * published by the Free Software Foundation; either version 2 of
  9. * the License, or any later version.
  10. *
  11. * This program is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. * GNU General Public License for more details.
  15. *
  16. * For a full copy of the GNU General Public License see the doc/GPL.txt file.
  17. */
  18. #ifndef CARLA_PIPE_UTILS_HPP_INCLUDED
  19. #define CARLA_PIPE_UTILS_HPP_INCLUDED
  20. #include "CarlaMutex.hpp"
  21. #include "CarlaString.hpp"
  22. #include <cerrno>
  23. #include <clocale>
  24. #include <fcntl.h>
  25. #include <signal.h>
  26. #include <sys/wait.h>
  27. #define WAIT_START_TIMEOUT 3000 /* ms */
  28. #define WAIT_ZOMBIE_TIMEOUT 3000 /* ms */
  29. #define WAIT_STEP 100 /* ms */
  30. // -----------------------------------------------------------------------
  31. class CarlaPipeServer
  32. {
  33. protected:
  34. CarlaPipeServer()
  35. : fWriteLock(),
  36. fPipeRecv(-1),
  37. fPipeSend(-1),
  38. fIsReading(false),
  39. fPid(-1),
  40. fTmpStr()
  41. {
  42. carla_debug("CarlaPipeServer::CarlaPipeServer()");
  43. carla_zeroChar(fTmpBuf, 0xff+1);
  44. }
  45. // -------------------------------------------------------------------
  46. public:
  47. virtual ~CarlaPipeServer()
  48. {
  49. carla_debug("CarlaPipeServer::~CarlaPipeServer()");
  50. stop();
  51. }
  52. bool isOk() const noexcept
  53. {
  54. return (fPipeRecv != -1 && fPipeSend != -1 && fPid != -1);
  55. }
  56. bool start(const char* const filename, const char* const arg1, const char* const arg2) noexcept
  57. {
  58. CARLA_SAFE_ASSERT_RETURN(filename != nullptr && filename[0] != '\0', false);
  59. CARLA_SAFE_ASSERT_RETURN(arg1 != nullptr, false);
  60. CARLA_SAFE_ASSERT_RETURN(arg2 != nullptr, false);
  61. carla_debug("CarlaPipeServer::start(\"%s\", \"%s\", \"%s\")", filename, arg1, arg2);
  62. const CarlaMutexLocker cml(fWriteLock);
  63. //----------------------------------------------------------------
  64. const char* argv[6];
  65. //----------------------------------------------------------------
  66. // argv[0] => filename
  67. argv[0] = filename;
  68. //----------------------------------------------------------------
  69. // argv[1-2] => args
  70. argv[1] = arg1;
  71. argv[2] = arg2;
  72. //----------------------------------------------------------------
  73. // argv[3-4] => pipes
  74. int pipe1[2]; // written by host process, read by plugin UI process
  75. int pipe2[2]; // written by plugin UI process, read by host process
  76. if (::pipe(pipe1) != 0)
  77. {
  78. fail("pipe1 creation failed");
  79. return false;
  80. }
  81. if (::pipe(pipe2) != 0)
  82. {
  83. try { ::close(pipe1[0]); } catch (...) {}
  84. try { ::close(pipe1[1]); } catch (...) {}
  85. fail("pipe2 creation failed");
  86. return false;
  87. }
  88. char pipeRecv[100+1];
  89. char pipeSend[100+1];
  90. std::snprintf(pipeRecv, 100, "%d", pipe1[0]); // [0] means reading end
  91. std::snprintf(pipeSend, 100, "%d", pipe2[1]); // [1] means writting end
  92. pipeRecv[100] = '\0';
  93. pipeSend[100] = '\0';
  94. argv[3] = pipeRecv; // reading end
  95. argv[4] = pipeSend; // writting end
  96. //----------------------------------------------------------------
  97. // argv[5] => null
  98. argv[5] = nullptr;
  99. //----------------------------------------------------------------
  100. // fork
  101. int ret = -1;
  102. if ((! fork_exec(argv, &ret)) || ret == -1)
  103. {
  104. try { ::close(pipe1[0]); } catch (...) {}
  105. try { ::close(pipe1[1]); } catch (...) {}
  106. try { ::close(pipe2[0]); } catch (...) {}
  107. try { ::close(pipe2[1]); } catch (...) {}
  108. fail("fork_exec() failed");
  109. return false;
  110. }
  111. fPid = ret;
  112. // fork duplicated the handles, close pipe ends that are used by the child process
  113. try { ::close(pipe1[0]); } catch(...) {}
  114. try { ::close(pipe2[1]); } catch(...) {}
  115. fPipeSend = pipe1[1]; // [1] means writting end
  116. fPipeRecv = pipe2[0]; // [0] means reading end
  117. // set non-block
  118. try {
  119. ret = ::fcntl(fPipeRecv, F_SETFL, ::fcntl(fPipeRecv, F_GETFL) | O_NONBLOCK);
  120. } catch (...) {
  121. ret = -1;
  122. fail("failed to set pipe as non-block");
  123. }
  124. //----------------------------------------------------------------
  125. // wait a while for child process to confirm it is alive
  126. if (ret != -1)
  127. {
  128. char ch;
  129. ssize_t ret2;
  130. for (int i=0; ;)
  131. {
  132. try {
  133. ret2 = ::read(fPipeRecv, &ch, 1);
  134. }
  135. catch (...) {
  136. fail("failed to read from pipe");
  137. break;
  138. }
  139. switch (ret2)
  140. {
  141. case -1:
  142. if (errno == EAGAIN)
  143. {
  144. if (i < WAIT_START_TIMEOUT / WAIT_STEP)
  145. {
  146. carla_msleep(WAIT_STEP);
  147. ++i;
  148. continue;
  149. }
  150. carla_stderr("we have waited for child with pid %d to appear for %.1f seconds and we are giving up", int(fPid), float(WAIT_START_TIMEOUT)/1000.0f);
  151. }
  152. else
  153. {
  154. CarlaString error(std::strerror(errno));
  155. carla_stderr("read() failed: %s", error.buffer());
  156. }
  157. break;
  158. case 1:
  159. if (ch == '\n') {
  160. // success
  161. return true;
  162. }
  163. carla_stderr("read() has wrong first char '%c'", ch);
  164. break;
  165. default:
  166. carla_stderr("read() returned %i", int(ret2));
  167. break;
  168. }
  169. break;
  170. }
  171. }
  172. carla_stderr("force killing misbehaved child %i (start)", int(fPid));
  173. if (kill(fPid, SIGKILL) == -1)
  174. {
  175. CarlaString error(std::strerror(errno));
  176. carla_stderr("kill() failed: %s (start)\n", error.buffer());
  177. }
  178. // wait a while child to exit, we dont like zombie processes
  179. wait_child(fPid);
  180. // close pipes
  181. try { ::close(fPipeRecv); } catch (...) {}
  182. try { ::close(fPipeSend); } catch (...) {}
  183. fPipeRecv = -1;
  184. fPipeSend = -1;
  185. fPid = -1;
  186. return false;
  187. }
  188. void stop() noexcept
  189. {
  190. carla_debug("CarlaPipeServer::stop()");
  191. if (fPipeSend == -1 || fPipeRecv == -1 || fPid == -1)
  192. return;
  193. const CarlaMutexLocker cml(fWriteLock);
  194. try {
  195. ssize_t ignore = ::write(fPipeSend, "quit\n", 5);
  196. (void)ignore;
  197. } CARLA_SAFE_EXCEPTION("CarlaPipeServer::stop");
  198. waitChildClose();
  199. try { ::close(fPipeRecv); } catch (...) {}
  200. try { ::close(fPipeSend); } catch (...) {}
  201. fPipeRecv = -1;
  202. fPipeSend = -1;
  203. fPid = -1;
  204. }
  205. void idle()
  206. {
  207. const char* locale = nullptr;
  208. for (;;)
  209. {
  210. const char* const msg(readline());
  211. if (msg == nullptr)
  212. break;
  213. if (locale == nullptr)
  214. {
  215. locale = carla_strdup(setlocale(LC_NUMERIC, nullptr));
  216. ::setlocale(LC_NUMERIC, "POSIX");
  217. }
  218. fIsReading = true;
  219. msgReceived(msg);
  220. fIsReading = false;
  221. delete[] msg;
  222. }
  223. if (locale != nullptr)
  224. {
  225. ::setlocale(LC_NUMERIC, locale);
  226. delete[] locale;
  227. }
  228. }
  229. // -------------------------------------------------------------------
  230. bool readNextLineAsBool(bool& value) noexcept
  231. {
  232. CARLA_SAFE_ASSERT_RETURN(fIsReading, false);
  233. if (const char* const msg = readline())
  234. {
  235. value = (std::strcmp(msg, "true") == 0);
  236. delete[] msg;
  237. return true;
  238. }
  239. return false;
  240. }
  241. bool readNextLineAsInt(int32_t& value) noexcept
  242. {
  243. CARLA_SAFE_ASSERT_RETURN(fIsReading, false);
  244. if (const char* const msg = readline())
  245. {
  246. value = std::atoi(msg);
  247. delete[] msg;
  248. return true;
  249. }
  250. return false;
  251. }
  252. bool readNextLineAsUInt(uint32_t& value) noexcept
  253. {
  254. CARLA_SAFE_ASSERT_RETURN(fIsReading, false);
  255. if (const char* const msg = readline())
  256. {
  257. int32_t tmp = std::atoi(msg);
  258. delete[] msg;
  259. if (tmp >= 0)
  260. {
  261. value = static_cast<uint32_t>(tmp);
  262. return true;
  263. }
  264. }
  265. return false;
  266. }
  267. bool readNextLineAsLong(int64_t& value) noexcept
  268. {
  269. CARLA_SAFE_ASSERT_RETURN(fIsReading, false);
  270. if (const char* const msg = readline())
  271. {
  272. value = std::atol(msg);
  273. delete[] msg;
  274. return true;
  275. }
  276. return false;
  277. }
  278. bool readNextLineAsULong(uint64_t& value) noexcept
  279. {
  280. CARLA_SAFE_ASSERT_RETURN(fIsReading, false);
  281. if (const char* const msg = readline())
  282. {
  283. int64_t tmp = std::atol(msg);
  284. delete[] msg;
  285. if (tmp >= 0)
  286. {
  287. value = static_cast<uint64_t>(tmp);
  288. return true;
  289. }
  290. }
  291. return false;
  292. }
  293. bool readNextLineAsFloat(float& value) noexcept
  294. {
  295. CARLA_SAFE_ASSERT_RETURN(fIsReading, false);
  296. if (const char* const msg = readline())
  297. {
  298. const bool ret(std::sscanf(msg, "%f", &value) == 1);
  299. delete[] msg;
  300. return ret;
  301. }
  302. return false;
  303. }
  304. bool readNextLineAsString(const char*& value) noexcept
  305. {
  306. CARLA_SAFE_ASSERT_RETURN(fIsReading, false);
  307. if (const char* const msg = readline())
  308. {
  309. value = msg;
  310. return true;
  311. }
  312. return false;
  313. }
  314. // -------------------------------------------------------------------
  315. // must be locked before calling
  316. void writeMsg(const char* const msg) const noexcept
  317. {
  318. CARLA_SAFE_ASSERT_RETURN(fPipeSend != -1,);
  319. // TESTING remove later
  320. const bool wasLocked(! fWriteLock.tryLock());
  321. CARLA_SAFE_ASSERT_RETURN(wasLocked, fWriteLock.unlock());
  322. try {
  323. ssize_t ignore = ::write(fPipeSend, msg, std::strlen(msg));
  324. (void)ignore;
  325. } CARLA_SAFE_EXCEPTION("CarlaPipeServer::writeMsg");
  326. }
  327. void writeMsg(const char* const msg, size_t size) const noexcept
  328. {
  329. CARLA_SAFE_ASSERT_RETURN(fPipeSend != -1,);
  330. // TESTING remove later
  331. const bool wasLocked(! fWriteLock.tryLock());
  332. CARLA_SAFE_ASSERT_RETURN(wasLocked, fWriteLock.unlock());
  333. try {
  334. ssize_t ignore = ::write(fPipeSend, msg, size);
  335. (void)ignore;
  336. } CARLA_SAFE_EXCEPTION("CarlaPipeServer::writeMsg");
  337. }
  338. void writeAndFixMsg(const char* const msg) noexcept
  339. {
  340. CARLA_SAFE_ASSERT_RETURN(fPipeSend != -1,);
  341. // TESTING remove later
  342. const bool wasLocked(! fWriteLock.tryLock());
  343. CARLA_SAFE_ASSERT_RETURN(wasLocked, fWriteLock.unlock());
  344. const size_t size(msg != nullptr ? std::strlen(msg) : 0);
  345. char fixedMsg[size+2];
  346. if (size > 0)
  347. {
  348. std::strcpy(fixedMsg, msg);
  349. for (size_t i=0; i < size; ++i)
  350. {
  351. if (fixedMsg[i] == '\n')
  352. fixedMsg[i] = '\r';
  353. }
  354. if (fixedMsg[size-1] == '\r')
  355. {
  356. fixedMsg[size-1] = '\n';
  357. fixedMsg[size] = '\0';
  358. fixedMsg[size+1] = '\0';
  359. }
  360. else
  361. {
  362. fixedMsg[size] = '\n';
  363. fixedMsg[size+1] = '\0';
  364. }
  365. }
  366. else
  367. {
  368. fixedMsg[0] = '\n';
  369. fixedMsg[1] = '\0';
  370. }
  371. try {
  372. ssize_t ignore = ::write(fPipeSend, fixedMsg, size+1);
  373. (void)ignore;
  374. } CARLA_SAFE_EXCEPTION("CarlaPipeServer::writeAndFixMsg");
  375. }
  376. // -------------------------------------------------------------------
  377. void waitChildClose() noexcept
  378. {
  379. if (! wait_child(fPid))
  380. {
  381. carla_stderr2("force killing misbehaved child %i (exit)", int(fPid));
  382. if (kill(fPid, SIGKILL) == -1)
  383. carla_stderr2("kill() failed: %s (exit)", std::strerror(errno));
  384. else
  385. wait_child(fPid);
  386. }
  387. }
  388. // -------------------------------------------------------------------
  389. protected:
  390. // common write lock
  391. CarlaMutex fWriteLock;
  392. // to possibly send errors somewhere
  393. virtual void fail(const char* const error)
  394. {
  395. carla_stderr2(error);
  396. }
  397. // returns true if msg handled
  398. virtual bool msgReceived(const char* const msg) noexcept = 0;
  399. // -------------------------------------------------------------------
  400. private:
  401. int fPipeRecv; // the pipe end that is used for receiving messages from UI
  402. int fPipeSend; // the pipe end that is used for sending messages to UI
  403. bool fIsReading;
  404. pid_t fPid;
  405. char fTmpBuf[0xff+1];
  406. CarlaString fTmpStr;
  407. // -------------------------------------------------------------------
  408. const char* readline() noexcept
  409. {
  410. char ch;
  411. char* ptr = fTmpBuf;
  412. ssize_t ret;
  413. fTmpStr.clear();
  414. for (int i=0; i < 0xff; ++i)
  415. {
  416. try {
  417. ret = ::read(fPipeRecv, &ch, 1);
  418. }
  419. catch (...) {
  420. break;
  421. }
  422. if (ret == 1 && ch != '\n')
  423. {
  424. if (ch == '\r')
  425. ch = '\n';
  426. *ptr++ = ch;
  427. if (i+1 == 0xff)
  428. {
  429. i = 0;
  430. ptr = fTmpBuf;
  431. fTmpStr += fTmpBuf;
  432. }
  433. continue;
  434. }
  435. if (fTmpStr.isNotEmpty() || ptr != fTmpBuf)
  436. {
  437. if (ptr != fTmpBuf)
  438. {
  439. *ptr = '\0';
  440. fTmpStr += fTmpBuf;
  441. }
  442. try {
  443. return fTmpStr.dup();
  444. }
  445. catch(...) {
  446. return nullptr;
  447. }
  448. }
  449. break;
  450. }
  451. return nullptr;
  452. }
  453. // -------------------------------------------------------------------
  454. static bool fork_exec(const char* const argv[6], int* const retp) noexcept
  455. {
  456. const pid_t ret = *retp = vfork();
  457. switch (ret)
  458. {
  459. case 0: // child process
  460. execvp(argv[0], const_cast<char* const*>(argv));
  461. carla_stderr2("exec failed: %s", std::strerror(errno));
  462. _exit(0); // this is not noexcept safe but doesn't matter anyway
  463. return false;
  464. case -1: // error
  465. carla_stderr2("fork() failed: %s", std::strerror(errno));
  466. _exit(0); // this is not noexcept safe but doesn't matter anyway
  467. return false;
  468. }
  469. return true;
  470. }
  471. static bool wait_child(const pid_t pid) noexcept
  472. {
  473. if (pid <= 0)
  474. {
  475. carla_stderr2("Can't wait for pid %i", int(pid));
  476. return false;
  477. }
  478. pid_t ret;
  479. for (int i=0, maxTime=WAIT_ZOMBIE_TIMEOUT/WAIT_STEP; i < maxTime; ++i)
  480. {
  481. try {
  482. ret = ::waitpid(pid, nullptr, WNOHANG);
  483. } CARLA_SAFE_EXCEPTION_BREAK("wait_child");
  484. if (ret != 0)
  485. {
  486. if (ret == pid)
  487. return true;
  488. if (ret == -1)
  489. {
  490. if (errno == ECHILD)
  491. return true;
  492. CarlaString error(std::strerror(errno));
  493. carla_stderr2("waitpid(%i) failed: %s", int(pid), error.buffer());
  494. return false;
  495. }
  496. carla_stderr2("we waited for child pid %i to exit but we got pid %i instead", int(pid), int(ret));
  497. return false;
  498. }
  499. carla_msleep(WAIT_STEP); /* wait 100 ms */
  500. }
  501. carla_stderr2("we waited for child with pid %i to exit for %.1f seconds and we are giving up", int(pid), float(WAIT_START_TIMEOUT)/1000.0f);
  502. return false;
  503. }
  504. };
  505. // -----------------------------------------------------------------------
  506. #endif // CARLA_PIPE_UTILS_HPP_INCLUDED