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.

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