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.

638 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", 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. ssize_t ignore = ::write(fPipeSend, "quit\n", 5);
  198. (void)ignore;
  199. } catch (...) {}
  200. waitChildClose();
  201. try {
  202. ::close(fPipeRecv);
  203. } catch (...) {}
  204. try {
  205. ::close(fPipeSend);
  206. } catch (...) {}
  207. fPipeRecv = -1;
  208. fPipeSend = -1;
  209. fPid = -1;
  210. }
  211. void idle()
  212. {
  213. const char* locale = nullptr;
  214. for (;;)
  215. {
  216. const char* const msg(readline());
  217. if (msg == nullptr)
  218. break;
  219. if (locale == nullptr)
  220. {
  221. locale = carla_strdup(setlocale(LC_NUMERIC, nullptr));
  222. setlocale(LC_NUMERIC, "POSIX");
  223. }
  224. fIsReading = true;
  225. msgReceived(msg);
  226. fIsReading = false;
  227. delete[] msg;
  228. }
  229. if (locale != nullptr)
  230. {
  231. setlocale(LC_NUMERIC, locale);
  232. delete[] locale;
  233. }
  234. }
  235. // -------------------------------------------------------------------
  236. bool readNextLineAsBool(bool& value) noexcept
  237. {
  238. CARLA_SAFE_ASSERT_RETURN(fIsReading, false);
  239. if (const char* const msg = readline())
  240. {
  241. value = (std::strcmp(msg, "true") == 0);
  242. delete[] msg;
  243. return true;
  244. }
  245. return false;
  246. }
  247. bool readNextLineAsInt(int32_t& value) noexcept
  248. {
  249. CARLA_SAFE_ASSERT_RETURN(fIsReading, false);
  250. if (const char* const msg = readline())
  251. {
  252. value = std::atoi(msg);
  253. delete[] msg;
  254. return true;
  255. }
  256. return false;
  257. }
  258. bool readNextLineAsUInt(uint32_t& value) noexcept
  259. {
  260. CARLA_SAFE_ASSERT_RETURN(fIsReading, false);
  261. if (const char* const msg = readline())
  262. {
  263. int32_t tmp = std::atoi(msg);
  264. delete[] msg;
  265. if (tmp >= 0)
  266. {
  267. value = static_cast<uint32_t>(tmp);
  268. return true;
  269. }
  270. }
  271. return false;
  272. }
  273. bool readNextLineAsLong(int64_t& value) noexcept
  274. {
  275. CARLA_SAFE_ASSERT_RETURN(fIsReading, false);
  276. if (const char* const msg = readline())
  277. {
  278. value = std::atol(msg);
  279. delete[] msg;
  280. return true;
  281. }
  282. return false;
  283. }
  284. bool readNextLineAsULong(uint64_t& value) noexcept
  285. {
  286. CARLA_SAFE_ASSERT_RETURN(fIsReading, false);
  287. if (const char* const msg = readline())
  288. {
  289. int64_t tmp = std::atol(msg);
  290. delete[] msg;
  291. if (tmp >= 0)
  292. {
  293. value = static_cast<uint64_t>(tmp);
  294. return true;
  295. }
  296. }
  297. return false;
  298. }
  299. bool readNextLineAsFloat(float& value) noexcept
  300. {
  301. CARLA_SAFE_ASSERT_RETURN(fIsReading, false);
  302. if (const char* const msg = readline())
  303. {
  304. const bool ret(std::sscanf(msg, "%f", &value) == 1);
  305. delete[] msg;
  306. return ret;
  307. }
  308. return false;
  309. }
  310. bool readNextLineAsString(const char*& value) noexcept
  311. {
  312. CARLA_SAFE_ASSERT_RETURN(fIsReading, false);
  313. if (const char* const msg = readline())
  314. {
  315. value = msg;
  316. return true;
  317. }
  318. return false;
  319. }
  320. // -------------------------------------------------------------------
  321. void writeMsg(const char* const msg) const noexcept
  322. {
  323. CARLA_SAFE_ASSERT_RETURN(fPipeSend != -1,);
  324. try {
  325. ssize_t ignore = ::write(fPipeSend, msg, std::strlen(msg));
  326. (void)ignore;
  327. } catch (...) {}
  328. }
  329. void writeMsg(const char* const msg, size_t size) const noexcept
  330. {
  331. CARLA_SAFE_ASSERT_RETURN(fPipeSend != -1,);
  332. try {
  333. ssize_t ignore = ::write(fPipeSend, msg, size);
  334. (void)ignore;
  335. } catch (...) {}
  336. }
  337. void writeAndFixMsg(const char* const msg) noexcept
  338. {
  339. CARLA_SAFE_ASSERT_RETURN(fPipeSend != -1,);
  340. const size_t size(msg != nullptr ? std::strlen(msg) : 0);
  341. char fixedMsg[size+2];
  342. if (size > 0)
  343. {
  344. std::strcpy(fixedMsg, msg);
  345. for (size_t i=0; i < size; ++i)
  346. {
  347. if (fixedMsg[i] == '\n')
  348. fixedMsg[i] = '\r';
  349. }
  350. if (fixedMsg[size-1] == '\r')
  351. {
  352. fixedMsg[size-1] = '\n';
  353. fixedMsg[size] = '\0';
  354. fixedMsg[size+1] = '\0';
  355. }
  356. else
  357. {
  358. fixedMsg[size] = '\n';
  359. fixedMsg[size+1] = '\0';
  360. }
  361. }
  362. else
  363. {
  364. fixedMsg[0] = '\n';
  365. fixedMsg[1] = '\0';
  366. }
  367. try {
  368. ssize_t ignore = ::write(fPipeSend, fixedMsg, size+1);
  369. (void)ignore;
  370. } catch (...) {}
  371. }
  372. void waitChildClose() noexcept
  373. {
  374. if (! wait_child(fPid))
  375. {
  376. carla_stderr2("force killing misbehaved child %i (exit)", int(fPid));
  377. if (kill(fPid, SIGKILL) == -1)
  378. carla_stderr2("kill() failed: %s (exit)", strerror(errno));
  379. else
  380. wait_child(fPid);
  381. }
  382. }
  383. // -------------------------------------------------------------------
  384. protected:
  385. // to possibly send errors somewhere
  386. virtual void fail(const char* const error)
  387. {
  388. carla_stderr2(error);
  389. }
  390. // returns true if msg handled
  391. virtual bool msgReceived(const char* const msg) noexcept = 0;
  392. // -------------------------------------------------------------------
  393. private:
  394. int fPipeRecv; // the pipe end that is used for receiving messages from UI
  395. int fPipeSend; // the pipe end that is used for sending messages to UI
  396. bool fIsReading;
  397. pid_t fPid;
  398. char fTmpBuf[0xff+1];
  399. CarlaString fTmpStr;
  400. // -------------------------------------------------------------------
  401. const char* readline() noexcept
  402. {
  403. char ch;
  404. char* ptr = fTmpBuf;
  405. ssize_t ret;
  406. fTmpStr.clear();
  407. for (int i=0; i < 0xff; ++i)
  408. {
  409. try {
  410. ret = ::read(fPipeRecv, &ch, 1);
  411. }
  412. catch (...) {
  413. break;
  414. }
  415. if (ret == 1 && ch != '\n')
  416. {
  417. if (ch == '\r')
  418. ch = '\n';
  419. *ptr++ = ch;
  420. if (i+1 == 0xff)
  421. {
  422. i = 0;
  423. ptr = fTmpBuf;
  424. fTmpStr += fTmpBuf;
  425. }
  426. continue;
  427. }
  428. if (fTmpStr.isNotEmpty() || ptr != fTmpBuf)
  429. {
  430. if (ptr != fTmpBuf)
  431. {
  432. *ptr = '\0';
  433. fTmpStr += fTmpBuf;
  434. }
  435. try {
  436. return fTmpStr.dup();
  437. }
  438. catch(...) {
  439. return nullptr;
  440. }
  441. }
  442. break;
  443. }
  444. return nullptr;
  445. }
  446. // -------------------------------------------------------------------
  447. static bool fork_exec(const char* const argv[5], int* const retp) noexcept
  448. {
  449. const pid_t ret = *retp = vfork();
  450. switch (ret)
  451. {
  452. case 0: // child process
  453. execlp(argv[0], argv[0], argv[1], argv[2], argv[3], argv[4],
  454. #ifdef CARLA_OS_MAC // fix warning
  455. NULL);
  456. #else
  457. nullptr);
  458. #endif
  459. carla_stderr2("exec failed: %s", std::strerror(errno));
  460. _exit(0); // this is not noexcept safe but doesn't matter anyway
  461. return false;
  462. case -1: // error
  463. carla_stderr2("fork() failed: %s", std::strerror(errno));
  464. _exit(0); // this is not noexcept safe but doesn't matter anyway
  465. return false;
  466. }
  467. return true;
  468. }
  469. static bool wait_child(const pid_t pid) noexcept
  470. {
  471. if (pid == -1)
  472. {
  473. carla_stderr2("Can't wait for pid -1");
  474. return false;
  475. }
  476. pid_t ret;
  477. for (int i=0, maxTime=WAIT_ZOMBIE_TIMEOUT/WAIT_STEP; i < maxTime; ++i)
  478. {
  479. try {
  480. ret = ::waitpid(pid, nullptr, WNOHANG);
  481. }
  482. catch(...) {
  483. break;
  484. }
  485. if (ret != 0)
  486. {
  487. if (ret == pid)
  488. return true;
  489. if (ret == -1)
  490. {
  491. carla_stderr2("waitpid(%i) failed: %s", int(pid), std::strerror(errno));
  492. return false;
  493. }
  494. carla_stderr2("we waited for child pid %i to exit but we got pid %i instead", int(pid), int(ret));
  495. return false;
  496. }
  497. carla_msleep(WAIT_STEP); /* wait 100 ms */
  498. }
  499. 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);
  500. return false;
  501. }
  502. };
  503. // -----------------------------------------------------------------------
  504. #endif // CARLA_PIPE_UTILS_HPP_INCLUDED