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.

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