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.

599 lines
15KB

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