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.

646 lines
16KB

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