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.

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