sys_start_process.c 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146
  1. /**
  2. * @file sys_start_process.c
  3. * @author Ambroz Bizjak <ambrop7@gmail.com>
  4. *
  5. * @section LICENSE
  6. *
  7. * Redistribution and use in source and binary forms, with or without
  8. * modification, are permitted provided that the following conditions are met:
  9. * 1. Redistributions of source code must retain the above copyright
  10. * notice, this list of conditions and the following disclaimer.
  11. * 2. Redistributions in binary form must reproduce the above copyright
  12. * notice, this list of conditions and the following disclaimer in the
  13. * documentation and/or other materials provided with the distribution.
  14. * 3. Neither the name of the author nor the
  15. * names of its contributors may be used to endorse or promote products
  16. * derived from this software without specific prior written permission.
  17. *
  18. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
  19. * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  20. * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  21. * DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
  22. * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  23. * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  24. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  25. * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  26. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  27. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  28. *
  29. * @section DESCRIPTION
  30. *
  31. * Synopsis:
  32. * sys.start_process(list command, string mode)
  33. *
  34. * Variables:
  35. * is_error - "true" if there was an error starting the process, "false" if the process
  36. * has been started successfully
  37. *
  38. * Synopsis:
  39. * sys.start_process::wait()
  40. *
  41. * Variables:
  42. * exit_status - the exit code if the process terminated normally, -1 if it terminated
  43. * with a signal
  44. *
  45. * Synopsis:
  46. * sys.start_process::terminate()
  47. * sys.start_process::kill()
  48. *
  49. * Synopsis:
  50. * sys.start_process::read_pipe()
  51. *
  52. * Description:
  53. * Creates a read interface to the process's standard output. Data is read using the
  54. * read() method on this object. Read errors are reported implicitly by this statement
  55. * going down and the 'is_error' variable changing to "true".
  56. * When read_pipe() is initialized for a process, it takes ownership of the read pipe
  57. * to the process. When read_pipe() is requested to terminate, it will close the pipe.
  58. * Attempting to initialize read_pipe() on a process which was not started with 'r'
  59. * in the mode argument, or where another read_pipe() object has already taken ownership
  60. * of the read pipe, will result in throwing an error to the interpreter.
  61. *
  62. * Variables:
  63. * string is_error - "true" if there was a read error, "false" if not
  64. *
  65. * Synopsis:
  66. * sys.start_process::read_pipe::read()
  67. *
  68. * Description:
  69. * Reads some data. If a read error occurs, it is reported implicitly via the
  70. * read_pipe() object going down. If end of file is reached, this and any future read()
  71. * operations will indicate that via the 'not_eof' variable. It is guaranteed that after
  72. * EOF is reached, the read_pipe() object will not go down to report any errors.
  73. * WARNING: if a read() is requested to terminate before it has completed, the
  74. * read_pipe() will become unusable and any read() invocation after that will
  75. * throw an error to the interpreter.
  76. *
  77. * Variables:
  78. * string (empty) - data that was read, or an empty string on EOF
  79. * string not_eof - "true" is EOF was not reached, "false" if it was
  80. *
  81. * Synopsis:
  82. * sys.start_process::write_pipe()
  83. *
  84. * Description:
  85. * Creates a write interface to the process's standard input. Data is written using the
  86. * write() method on this object. Write errors are reported implicitly by this statement
  87. * going down and the ''is_error variable changing to "true".
  88. * When write_pipe() is initialized for a process, it takes ownership of the write pipe
  89. * to the process. When write_pipe() is requested to terminate, it will close the pipe
  90. * (unless the close() has been used).
  91. * Attempting to initialize write_pipe() on a process which was not started with 'w'
  92. * in the mode argument, or where another write_pipe() object has already taken ownership
  93. * of the write pope, will result in throwing an error to the interpreter.
  94. *
  95. * Variables:
  96. * string is_error - "true" if there was a write error, "false" if not
  97. *
  98. * Synopsis:
  99. * sys.start_process::write_pipe::write(string data)
  100. *
  101. * Description:
  102. * Writes the given data. If a write error occurs, it is reported implicitly via the
  103. * write_pipe() object going down.
  104. * WARNING: if a write() is requested to terminate before it has completed, the
  105. * write_pipe() will become unusable and any write() or close() invocation after
  106. * that will throw an error to the interpreter.
  107. *
  108. * Synopsis:
  109. * sys.start_process::write_pipe::close(string data)
  110. *
  111. * Description:
  112. * Closes the write pipe. This will make whatever is reading the other end of the pipe
  113. * encounter EOF after it has read any pending data. It is guaranteed that after the
  114. * pipe is closed, the write_pipe() object will not go down to report any errors.
  115. * After close() is performed, any further write() or close() calls are disallowed and
  116. * will throw errors to the interpreter.
  117. */
  118. #include <stdlib.h>
  119. #include <string.h>
  120. #include <stdio.h>
  121. #include <inttypes.h>
  122. #include <limits.h>
  123. #include <unistd.h>
  124. #include <misc/offset.h>
  125. #include <structure/LinkedList0.h>
  126. #include <system/BProcess.h>
  127. #include <system/BConnection.h>
  128. #include <ncd/NCDModule.h>
  129. #include <ncd/extra/NCDBuf.h>
  130. #include <ncd/extra/value_utils.h>
  131. #include <ncd/extra/build_cmdline.h>
  132. #include <generated/blog_channel_ncd_sys_start_process.h>
  133. #define ModuleLog(i, ...) NCDModuleInst_Backend_Log((i), BLOG_CURRENT_CHANNEL, __VA_ARGS__)
  134. #define READ_BUF_SIZE 8192
  135. #define STATE_ERROR 1
  136. #define STATE_RUNNING 2
  137. #define STATE_TERMINATED 3
  138. #define STATE_DYING 4
  139. #define READER_STATE_RUNNING 1
  140. #define READER_STATE_EOF 2
  141. #define READER_STATE_ERROR 3
  142. #define READER_STATE_ABORTED 4
  143. #define WRITER_STATE_RUNNING 1
  144. #define WRITER_STATE_CLOSED 2
  145. #define WRITER_STATE_ERROR 3
  146. #define WRITER_STATE_ABORTED 4
  147. struct process_instance {
  148. NCDModuleInst *i;
  149. BProcess process;
  150. LinkedList0 waits_list;
  151. int read_fd;
  152. int write_fd;
  153. int exit_status;
  154. int state;
  155. };
  156. struct wait_instance {
  157. NCDModuleInst *i;
  158. struct process_instance *pinst;
  159. LinkedList0Node waits_list_node;
  160. int exit_status;
  161. };
  162. struct read_pipe_instance {
  163. NCDModuleInst *i;
  164. int state;
  165. int read_fd;
  166. BConnection connection;
  167. NCDBufStore store;
  168. struct read_instance *read_inst;
  169. };
  170. struct read_instance {
  171. NCDModuleInst *i;
  172. struct read_pipe_instance *read_pipe_inst;
  173. NCDBuf *buf;
  174. size_t read_size;
  175. };
  176. struct write_pipe_instance {
  177. NCDModuleInst *i;
  178. int state;
  179. int write_fd;
  180. BConnection connection;
  181. struct write_instance *write_inst;
  182. };
  183. struct write_instance {
  184. NCDModuleInst *i;
  185. struct write_pipe_instance *write_pipe_inst;
  186. const char *data;
  187. size_t length;
  188. };
  189. enum {STRING_IS_ERROR, STRING_EXIT_STATUS, STRING_NOT_EOF};
  190. static struct NCD_string_request strings[] = {
  191. {"is_error"}, {"exit_status"}, {"not_eof"}, {NULL}
  192. };
  193. static int parse_mode (NCDModuleInst *i, NCDValRef mode_arg, int *out_read, int *out_write)
  194. {
  195. if (!NCDVal_IsString(mode_arg)) {
  196. ModuleLog(i, BLOG_ERROR, "mode argument must be a string");
  197. return 0;
  198. }
  199. const char *data = NCDVal_StringData(mode_arg);
  200. size_t length = NCDVal_StringLength(mode_arg);
  201. *out_read = 0;
  202. *out_write = 0;
  203. while (length > 0) {
  204. if (*data == 'r') {
  205. *out_read = 1;
  206. }
  207. else if (*data == 'w') {
  208. *out_write = 1;
  209. }
  210. else {
  211. ModuleLog(i, BLOG_ERROR, "invalid character in mode argument");
  212. return 0;
  213. }
  214. data++;
  215. length--;
  216. }
  217. return 1;
  218. }
  219. static void instance_free (struct process_instance *o)
  220. {
  221. // close write fd
  222. if (o->write_fd != -1) {
  223. close(o->write_fd);
  224. }
  225. // close read fd
  226. if (o->read_fd != -1) {
  227. close(o->read_fd);
  228. }
  229. NCDModuleInst_Backend_Dead(o->i);
  230. }
  231. static void process_handler (void *vo, int normally, uint8_t normally_exit_status)
  232. {
  233. struct process_instance *o = vo;
  234. ASSERT(o->state == STATE_RUNNING || o->state == STATE_DYING)
  235. ModuleLog(o->i, BLOG_INFO, "process terminated");
  236. // free process
  237. BProcess_Free(&o->process);
  238. // remember exit code
  239. o->exit_status = (!normally ? -1 : normally_exit_status);
  240. // finish waits
  241. LinkedList0Node *ln;
  242. while ((ln = LinkedList0_GetFirst(&o->waits_list))) {
  243. struct wait_instance *winst = UPPER_OBJECT(ln, struct wait_instance, waits_list_node);
  244. ASSERT(winst->pinst == o)
  245. LinkedList0_Remove(&o->waits_list, &winst->waits_list_node);
  246. winst->pinst = NULL;
  247. winst->exit_status = o->exit_status;
  248. NCDModuleInst_Backend_Up(winst->i);
  249. }
  250. // if we have been requested to die, then die now
  251. if (o->state == STATE_DYING) {
  252. instance_free(o);
  253. return;
  254. }
  255. // set state
  256. o->state = STATE_TERMINATED;
  257. }
  258. static void process_func_new (void *vo, NCDModuleInst *i, const struct NCDModuleInst_new_params *params)
  259. {
  260. struct process_instance *o = vo;
  261. o->i = i;
  262. NCDModuleInst_Backend_PassMemToMethods(i);
  263. // check arguments
  264. NCDValRef command_arg;
  265. NCDValRef mode_arg;
  266. if (!NCDVal_ListRead(params->args, 2, &command_arg, &mode_arg)) {
  267. ModuleLog(i, BLOG_ERROR, "wrong arity");
  268. goto fail0;
  269. }
  270. // parse mode
  271. int is_read;
  272. int is_write;
  273. if (!parse_mode(i, mode_arg, &is_read, &is_write)) {
  274. goto fail0;
  275. }
  276. // prepare for creating pipes
  277. int fds[3];
  278. int fds_map[2];
  279. int num_fds = 0;
  280. int read_fd = -1;
  281. int write_fd = -1;
  282. // create read pipe
  283. if (is_read) {
  284. int pipefd[2];
  285. if (pipe(pipefd) < 0) {
  286. ModuleLog(i, BLOG_ERROR, "pipe failed");
  287. goto error1;
  288. }
  289. read_fd = pipefd[0];
  290. fds[num_fds] = pipefd[1];
  291. fds_map[num_fds++] = STDOUT_FILENO;
  292. }
  293. // create write pipe
  294. if (is_write) {
  295. int pipefd[2];
  296. if (pipe(pipefd) < 0) {
  297. ModuleLog(i, BLOG_ERROR, "pipe failed");
  298. goto error1;
  299. }
  300. write_fd = pipefd[1];
  301. fds[num_fds] = pipefd[0];
  302. fds_map[num_fds++] = STDIN_FILENO;
  303. }
  304. // terminate fds array
  305. fds[num_fds] = -1;
  306. // build process parameters struct
  307. struct BProcess_params p_params = {};
  308. p_params.fds = fds;
  309. p_params.fds_map = fds_map;
  310. // build command line
  311. char *exec;
  312. CmdLine cl;
  313. if (!ncd_build_cmdline(i, BLOG_CURRENT_CHANNEL, command_arg, &exec, &cl)) {
  314. goto error1;
  315. }
  316. // start process
  317. int res = BProcess_Init2(&o->process, i->params->iparams->manager, process_handler, o, exec, CmdLine_Get(&cl), p_params);
  318. CmdLine_Free(&cl);
  319. free(exec);
  320. if (!res) {
  321. ModuleLog(i, BLOG_ERROR, "BProcess_Init failed");
  322. goto error1;
  323. }
  324. // close child fds
  325. while (num_fds-- > 0) {
  326. close(fds[num_fds]);
  327. }
  328. // init waits list
  329. LinkedList0_Init(&o->waits_list);
  330. // remember our fds
  331. o->read_fd = read_fd;
  332. o->write_fd = write_fd;
  333. // set state
  334. o->state = STATE_RUNNING;
  335. // go up
  336. NCDModuleInst_Backend_Up(i);
  337. return;
  338. fail0:
  339. NCDModuleInst_Backend_DeadError(i);
  340. return;
  341. error1:
  342. if (write_fd != -1) {
  343. close(write_fd);
  344. }
  345. if (read_fd != -1) {
  346. close(read_fd);
  347. }
  348. while (num_fds-- > 0) {
  349. close(fds[num_fds]);
  350. }
  351. o->read_fd = -1;
  352. o->write_fd = -1;
  353. o->state = STATE_ERROR;
  354. NCDModuleInst_Backend_Up(i);
  355. }
  356. static void process_func_die (void *vo)
  357. {
  358. struct process_instance *o = vo;
  359. ASSERT(o->state != STATE_DYING)
  360. // if process is not running, die immediately
  361. if (o->state != STATE_RUNNING) {
  362. instance_free(o);
  363. return;
  364. }
  365. ModuleLog(o->i, BLOG_INFO, "terminating process");
  366. // send termination signal
  367. BProcess_Terminate(&o->process);
  368. // set state
  369. o->state = STATE_DYING;
  370. }
  371. static int process_func_getvar (void *vo, NCD_string_id_t name, NCDValMem *mem, NCDValRef *out)
  372. {
  373. struct process_instance *o = vo;
  374. if (name == strings[STRING_IS_ERROR].id) {
  375. int is_error = (o->state == STATE_ERROR);
  376. *out = ncd_make_boolean(mem, is_error, o->i->params->iparams->string_index);
  377. return 1;
  378. }
  379. return 0;
  380. }
  381. static void wait_func_new (void *vo, NCDModuleInst *i, const struct NCDModuleInst_new_params *params)
  382. {
  383. struct wait_instance *o = vo;
  384. o->i = i;
  385. if (!NCDVal_ListRead(params->args, 0)) {
  386. ModuleLog(i, BLOG_ERROR, "wrong arity");
  387. goto fail0;
  388. }
  389. struct process_instance *pinst = params->method_user;
  390. if (pinst->state == STATE_ERROR) {
  391. ModuleLog(i, BLOG_ERROR, "process did not start successfully");
  392. goto fail0;
  393. }
  394. if (pinst->state == STATE_TERMINATED) {
  395. // not waiting, set no pinst
  396. o->pinst = NULL;
  397. // remember exit code
  398. o->exit_status = pinst->exit_status;
  399. // go up
  400. NCDModuleInst_Backend_Up(i);
  401. } else {
  402. // waitint, set pinst
  403. o->pinst = pinst;
  404. // insert to waits list
  405. LinkedList0_Prepend(&pinst->waits_list, &o->waits_list_node);
  406. }
  407. return;
  408. fail0:
  409. NCDModuleInst_Backend_DeadError(i);
  410. }
  411. static void wait_func_die (void *vo)
  412. {
  413. struct wait_instance *o = vo;
  414. // remove from waits list
  415. if (o->pinst) {
  416. LinkedList0_Remove(&o->pinst->waits_list, &o->waits_list_node);
  417. }
  418. NCDModuleInst_Backend_Dead(o->i);
  419. }
  420. static int wait_func_getvar (void *vo, NCD_string_id_t name, NCDValMem *mem, NCDValRef *out)
  421. {
  422. struct wait_instance *o = vo;
  423. ASSERT(!o->pinst)
  424. if (name == strings[STRING_EXIT_STATUS].id) {
  425. if (o->exit_status == -1) {
  426. *out = NCDVal_NewString(mem, "-1");
  427. } else {
  428. *out = ncd_make_uintmax(mem, o->exit_status);
  429. }
  430. return 1;
  431. }
  432. return 0;
  433. }
  434. static void terminate_kill_new_common (void *vo, NCDModuleInst *i, const struct NCDModuleInst_new_params *params, int is_kill)
  435. {
  436. if (!NCDVal_ListRead(params->args, 0)) {
  437. ModuleLog(i, BLOG_ERROR, "wrong arity");
  438. goto fail0;
  439. }
  440. struct process_instance *pinst = params->method_user;
  441. if (pinst->state == STATE_ERROR) {
  442. ModuleLog(i, BLOG_ERROR, "process did not start successfully");
  443. goto fail0;
  444. }
  445. if (pinst->state != STATE_TERMINATED) {
  446. if (is_kill) {
  447. BProcess_Kill(&pinst->process);
  448. } else {
  449. BProcess_Terminate(&pinst->process);
  450. }
  451. }
  452. NCDModuleInst_Backend_Up(i);
  453. return;
  454. fail0:
  455. NCDModuleInst_Backend_DeadError(i);
  456. }
  457. static void terminate_func_new (void *vo, NCDModuleInst *i, const struct NCDModuleInst_new_params *params)
  458. {
  459. terminate_kill_new_common(vo, i, params, 0);
  460. }
  461. static void kill_func_new (void *vo, NCDModuleInst *i, const struct NCDModuleInst_new_params *params)
  462. {
  463. terminate_kill_new_common(vo, i, params, 1);
  464. }
  465. static void read_pipe_free_connection (struct read_pipe_instance *o)
  466. {
  467. // disconnect read instance
  468. if (o->read_inst) {
  469. ASSERT(o->read_inst->read_pipe_inst == o)
  470. o->read_inst->read_pipe_inst = NULL;
  471. }
  472. // free store
  473. NCDBufStore_Free(&o->store);
  474. // free connection read interface
  475. BConnection_RecvAsync_Free(&o->connection);
  476. // free connection
  477. BConnection_Free(&o->connection);
  478. // close fd
  479. if (close(o->read_fd) < 0) {
  480. ModuleLog(o->i, BLOG_ERROR, "close failed");
  481. }
  482. }
  483. static void read_pipe_abort (struct read_pipe_instance *o)
  484. {
  485. ASSERT(o->state == READER_STATE_RUNNING)
  486. // release connection resources
  487. read_pipe_free_connection(o);
  488. // set state
  489. o->state = READER_STATE_ABORTED;
  490. }
  491. static void read_pipe_connection_handler (void *vo, int event)
  492. {
  493. struct read_pipe_instance *o = vo;
  494. ASSERT(o->state == READER_STATE_RUNNING)
  495. if (event == BCONNECTION_EVENT_RECVCLOSED) {
  496. // if we have read operation, make it finish with eof
  497. if (o->read_inst) {
  498. ASSERT(o->read_inst->read_pipe_inst == o)
  499. ASSERT(o->read_inst->buf)
  500. o->read_inst->read_pipe_inst = NULL;
  501. o->read_inst->read_size = 0;
  502. NCDModuleInst_Backend_Up(o->read_inst->i);
  503. o->read_inst = NULL;
  504. }
  505. // free connection resources
  506. read_pipe_free_connection(o);
  507. // set state closed
  508. o->state = READER_STATE_EOF;
  509. return;
  510. }
  511. ModuleLog(o->i, BLOG_ERROR, "read pipe error");
  512. // free connection resources
  513. read_pipe_free_connection(o);
  514. // set state error
  515. o->state = READER_STATE_ERROR;
  516. // backtrack
  517. NCDModuleInst_Backend_DownUp(o->i);
  518. }
  519. static void read_pipe_recv_handler_done (void *vo, int data_len)
  520. {
  521. struct read_pipe_instance *o = vo;
  522. ASSERT(o->state == READER_STATE_RUNNING)
  523. ASSERT(o->read_inst)
  524. ASSERT(o->read_inst->read_pipe_inst == o)
  525. ASSERT(o->read_inst->buf)
  526. ASSERT(data_len > 0)
  527. ASSERT(data_len <= NCDBufStore_BufSize(&o->store))
  528. // finish read operation
  529. o->read_inst->read_pipe_inst = NULL;
  530. o->read_inst->read_size = data_len;
  531. NCDModuleInst_Backend_Up(o->read_inst->i);
  532. o->read_inst = NULL;
  533. }
  534. static void read_pipe_func_new (void *vo, NCDModuleInst *i, const struct NCDModuleInst_new_params *params)
  535. {
  536. struct read_pipe_instance *o = vo;
  537. o->i = i;
  538. NCDModuleInst_Backend_PassMemToMethods(i);
  539. if (!NCDVal_ListRead(params->args, 0)) {
  540. ModuleLog(i, BLOG_ERROR, "wrong arity");
  541. goto fail0;
  542. }
  543. struct process_instance *pinst = params->method_user;
  544. if (pinst->read_fd == -1) {
  545. ModuleLog(i, BLOG_ERROR, "process did not start successfully, was not opened for reading or a read_pipe was already created");
  546. goto fail0;
  547. }
  548. // init connection
  549. if (!BConnection_Init(&o->connection, BConnection_source_pipe(pinst->read_fd), i->params->iparams->reactor, o, read_pipe_connection_handler)) {
  550. ModuleLog(i, BLOG_ERROR, "BConnection_Init failed");
  551. goto fail0;
  552. }
  553. // init connection read interface
  554. BConnection_RecvAsync_Init(&o->connection);
  555. // set recv done callback
  556. StreamRecvInterface_Receiver_Init(BConnection_RecvAsync_GetIf(&o->connection), read_pipe_recv_handler_done, o);
  557. // init store
  558. NCDBufStore_Init(&o->store, READ_BUF_SIZE);
  559. // set variables
  560. o->state = READER_STATE_RUNNING;
  561. o->read_fd = pinst->read_fd;
  562. o->read_inst = NULL;
  563. // steal read fd from process instance
  564. pinst->read_fd = -1;
  565. // go up
  566. NCDModuleInst_Backend_Up(i);
  567. return;
  568. fail0:
  569. NCDModuleInst_Backend_DeadError(i);
  570. }
  571. static void read_pipe_func_die (void *vo)
  572. {
  573. struct read_pipe_instance *o = vo;
  574. // free connection resources
  575. if (o->state == READER_STATE_RUNNING) {
  576. read_pipe_free_connection(o);
  577. }
  578. NCDModuleInst_Backend_Dead(o->i);
  579. }
  580. static int read_pipe_func_getvar (void *vo, NCD_string_id_t name, NCDValMem *mem, NCDValRef *out)
  581. {
  582. struct read_pipe_instance *o = vo;
  583. if (name == strings[STRING_IS_ERROR].id) {
  584. int is_error = (o->state == READER_STATE_ERROR);
  585. *out = ncd_make_boolean(mem, is_error, o->i->params->iparams->string_index);
  586. return 1;
  587. }
  588. return 0;
  589. }
  590. static void read_func_new (void *vo, NCDModuleInst *i, const struct NCDModuleInst_new_params *params)
  591. {
  592. struct read_instance *o = vo;
  593. o->i = i;
  594. if (!NCDVal_ListRead(params->args, 0)) {
  595. ModuleLog(i, BLOG_ERROR, "wrong arity");
  596. goto fail0;
  597. }
  598. struct read_pipe_instance *read_pipe_inst = params->method_user;
  599. // check if a read error has already occured
  600. if (read_pipe_inst->state == READER_STATE_ERROR) {
  601. ModuleLog(i, BLOG_ERROR, "read() is disallowed after a read error has occured");
  602. goto fail0;
  603. }
  604. // check if the read_pipe has been aborted
  605. if (read_pipe_inst->state == READER_STATE_ABORTED) {
  606. ModuleLog(i, BLOG_ERROR, "read() is disallowed after a read() has been aborted");
  607. goto fail0;
  608. }
  609. // if EOF has already been encountered, complete the read immediately
  610. if (read_pipe_inst->state == READER_STATE_EOF) {
  611. o->buf = NULL;
  612. o->read_pipe_inst = NULL;
  613. o->read_size = 0;
  614. NCDModuleInst_Backend_Up(i);
  615. return;
  616. }
  617. ASSERT(read_pipe_inst->state == READER_STATE_RUNNING)
  618. // check if there's already a read in progress
  619. if (read_pipe_inst->read_inst) {
  620. ModuleLog(i, BLOG_ERROR, "read() is disallowed while another read() is in progress");
  621. goto fail0;
  622. }
  623. // get buffer
  624. o->buf = NCDBufStore_GetBuf(&read_pipe_inst->store);
  625. if (!o->buf) {
  626. ModuleLog(i, BLOG_ERROR, "NCDBufStore_GetBuf failed");
  627. goto fail0;
  628. }
  629. // set read_pipe
  630. o->read_pipe_inst = read_pipe_inst;
  631. // register read in read_pipe
  632. read_pipe_inst->read_inst = o;
  633. // receive
  634. size_t buf_size = NCDBufStore_BufSize(&read_pipe_inst->store);
  635. int to_read = (buf_size > INT_MAX ? INT_MAX : buf_size);
  636. StreamRecvInterface_Receiver_Recv(BConnection_RecvAsync_GetIf(&read_pipe_inst->connection), (uint8_t *)NCDBuf_Data(o->buf), to_read);
  637. return;
  638. fail0:
  639. NCDModuleInst_Backend_DeadError(i);
  640. }
  641. static void read_func_die (void *vo)
  642. {
  643. struct read_instance *o = vo;
  644. // if we're receiving, abort read_pipe
  645. if (o->read_pipe_inst) {
  646. ASSERT(o->read_pipe_inst->state == READER_STATE_RUNNING)
  647. ASSERT(o->read_pipe_inst->read_inst == o)
  648. ASSERT(o->buf)
  649. read_pipe_abort(o->read_pipe_inst);
  650. }
  651. // release buffer
  652. if (o->buf) {
  653. NCDRefTarget_Deref(NCDBuf_RefTarget(o->buf));
  654. }
  655. NCDModuleInst_Backend_Dead(o->i);
  656. }
  657. static int read_func_getvar (void *vo, NCD_string_id_t name, NCDValMem *mem, NCDValRef *out)
  658. {
  659. struct read_instance *o = vo;
  660. ASSERT(!o->read_pipe_inst)
  661. ASSERT(!(o->read_size > 0) || o->buf)
  662. if (name == NCD_STRING_EMPTY) {
  663. if (o->read_size > 0) {
  664. *out = NCDVal_NewExternalString(mem, NCDBuf_Data(o->buf), o->read_size, NCDBuf_RefTarget(o->buf));
  665. } else {
  666. *out = NCDVal_NewIdString(mem, NCD_STRING_EMPTY, o->i->params->iparams->string_index);
  667. }
  668. return 1;
  669. }
  670. if (name == strings[STRING_NOT_EOF].id) {
  671. int not_eof = (o->read_size > 0);
  672. *out = ncd_make_boolean(mem, not_eof, o->i->params->iparams->string_index);
  673. return 1;
  674. }
  675. return 0;
  676. }
  677. static void write_pipe_free_connection (struct write_pipe_instance *o)
  678. {
  679. // disconnect write instance
  680. if (o->write_inst) {
  681. ASSERT(o->write_inst->write_pipe_inst == o)
  682. o->write_inst->write_pipe_inst = NULL;
  683. }
  684. // free connection send interface
  685. BConnection_SendAsync_Free(&o->connection);
  686. // free connection
  687. BConnection_Free(&o->connection);
  688. // close fd
  689. if (close(o->write_fd) < 0) {
  690. ModuleLog(o->i, BLOG_ERROR, "close failed");
  691. }
  692. }
  693. static void write_pipe_abort (struct write_pipe_instance *o)
  694. {
  695. ASSERT(o->state == WRITER_STATE_RUNNING)
  696. // release connection resources
  697. write_pipe_free_connection(o);
  698. // set state
  699. o->state = WRITER_STATE_ABORTED;
  700. }
  701. static void write_pipe_close (struct write_pipe_instance *o)
  702. {
  703. ASSERT(o->state == WRITER_STATE_RUNNING)
  704. // release connection resources
  705. write_pipe_free_connection(o);
  706. // set state
  707. o->state = WRITER_STATE_CLOSED;
  708. }
  709. static void write_pipe_connection_handler (void *vo, int event)
  710. {
  711. struct write_pipe_instance *o = vo;
  712. ASSERT(o->state == WRITER_STATE_RUNNING)
  713. ModuleLog(o->i, BLOG_ERROR, "write pipe error");
  714. // free connection resources
  715. write_pipe_free_connection(o);
  716. // set state error
  717. o->state = WRITER_STATE_ERROR;
  718. // backtrack
  719. NCDModuleInst_Backend_DownUp(o->i);
  720. }
  721. static void write_pipe_send_handler_done (void *vo, int data_len)
  722. {
  723. struct write_pipe_instance *o = vo;
  724. ASSERT(o->state == WRITER_STATE_RUNNING)
  725. ASSERT(o->write_inst)
  726. ASSERT(o->write_inst->write_pipe_inst == o)
  727. ASSERT(data_len > 0)
  728. ASSERT(data_len <= o->write_inst->length)
  729. // update write progress
  730. o->write_inst->data += data_len;
  731. o->write_inst->length -= data_len;
  732. // if there is more data, start another write operation
  733. if (o->write_inst->length > 0) {
  734. size_t to_send = (o->write_inst->length > INT_MAX ? INT_MAX : o->write_inst->length);
  735. StreamPassInterface_Sender_Send(BConnection_SendAsync_GetIf(&o->connection), (uint8_t *)o->write_inst->data, to_send);
  736. return;
  737. }
  738. // finish write operation
  739. o->write_inst->write_pipe_inst = NULL;
  740. NCDModuleInst_Backend_Up(o->write_inst->i);
  741. o->write_inst = NULL;
  742. }
  743. static void write_pipe_func_new (void *vo, NCDModuleInst *i, const struct NCDModuleInst_new_params *params)
  744. {
  745. struct write_pipe_instance *o = vo;
  746. o->i = i;
  747. NCDModuleInst_Backend_PassMemToMethods(i);
  748. if (!NCDVal_ListRead(params->args, 0)) {
  749. ModuleLog(i, BLOG_ERROR, "wrong arity");
  750. goto fail0;
  751. }
  752. struct process_instance *pinst = params->method_user;
  753. if (pinst->write_fd == -1) {
  754. ModuleLog(i, BLOG_ERROR, "process did not start successfully, was not opened for writing or a write_pipe was already created");
  755. goto fail0;
  756. }
  757. // init connection
  758. if (!BConnection_Init(&o->connection, BConnection_source_pipe(pinst->write_fd), i->params->iparams->reactor, o, write_pipe_connection_handler)) {
  759. ModuleLog(i, BLOG_ERROR, "BConnection_Init failed");
  760. goto fail0;
  761. }
  762. // init connection send interface
  763. BConnection_SendAsync_Init(&o->connection);
  764. // set send done callback
  765. StreamPassInterface_Sender_Init(BConnection_SendAsync_GetIf(&o->connection), write_pipe_send_handler_done, o);
  766. // set variables
  767. o->state = WRITER_STATE_RUNNING;
  768. o->write_fd = pinst->write_fd;
  769. o->write_inst = NULL;
  770. // steal write fd from process instance
  771. pinst->write_fd = -1;
  772. // go up
  773. NCDModuleInst_Backend_Up(i);
  774. return;
  775. fail0:
  776. NCDModuleInst_Backend_DeadError(i);
  777. }
  778. static void write_pipe_func_die (void *vo)
  779. {
  780. struct write_pipe_instance *o = vo;
  781. // free connection resources
  782. if (o->state == WRITER_STATE_RUNNING) {
  783. write_pipe_free_connection(o);
  784. }
  785. NCDModuleInst_Backend_Dead(o->i);
  786. }
  787. static int write_pipe_func_getvar (void *vo, NCD_string_id_t name, NCDValMem *mem, NCDValRef *out)
  788. {
  789. struct write_pipe_instance *o = vo;
  790. if (name == strings[STRING_IS_ERROR].id) {
  791. int is_error = (o->state == WRITER_STATE_ERROR);
  792. *out = ncd_make_boolean(mem, is_error, o->i->params->iparams->string_index);
  793. return 1;
  794. }
  795. return 0;
  796. }
  797. static void write_func_new (void *vo, NCDModuleInst *i, const struct NCDModuleInst_new_params *params)
  798. {
  799. struct write_instance *o = vo;
  800. o->i = i;
  801. NCDValRef data_arg;
  802. if (!NCDVal_ListRead(params->args, 1, &data_arg)) {
  803. ModuleLog(i, BLOG_ERROR, "wrong arity");
  804. goto fail0;
  805. }
  806. if (!NCDVal_IsString(data_arg)) {
  807. ModuleLog(i, BLOG_ERROR, "wrong type");
  808. goto fail0;
  809. }
  810. struct write_pipe_instance *write_pipe_inst = params->method_user;
  811. // check if a write error has already occured
  812. if (write_pipe_inst->state == WRITER_STATE_ERROR) {
  813. ModuleLog(i, BLOG_ERROR, "write() is disallowed after a write error has occured");
  814. goto fail0;
  815. }
  816. // check if the write_pipe has been aborted
  817. if (write_pipe_inst->state == WRITER_STATE_ABORTED) {
  818. ModuleLog(i, BLOG_ERROR, "write() is disallowed after a write() has been aborted");
  819. goto fail0;
  820. }
  821. // check if the write_pipe has been aborted
  822. if (write_pipe_inst->state == WRITER_STATE_CLOSED) {
  823. ModuleLog(i, BLOG_ERROR, "write() is disallowed after close() has been called");
  824. goto fail0;
  825. }
  826. ASSERT(write_pipe_inst->state == WRITER_STATE_RUNNING)
  827. // check if there's already a write in progress
  828. if (write_pipe_inst->write_inst) {
  829. ModuleLog(i, BLOG_ERROR, "write() is disallowed while another write() is in progress");
  830. goto fail0;
  831. }
  832. // initialize write progress state
  833. o->data = NCDVal_StringData(data_arg);
  834. o->length = NCDVal_StringLength(data_arg);
  835. // if there's nothing to send, go up immediately
  836. if (o->length == 0) {
  837. o->write_pipe_inst = NULL;
  838. NCDModuleInst_Backend_Up(i);
  839. return;
  840. }
  841. // set write_pipe
  842. o->write_pipe_inst = write_pipe_inst;
  843. // register write in write_pipe
  844. write_pipe_inst->write_inst = o;
  845. // start send operation
  846. size_t to_send = (o->length > INT_MAX ? INT_MAX : o->length);
  847. StreamPassInterface_Sender_Send(BConnection_SendAsync_GetIf(&write_pipe_inst->connection), (uint8_t *)o->data, to_send);
  848. return;
  849. fail0:
  850. NCDModuleInst_Backend_DeadError(i);
  851. }
  852. static void write_func_die (void *vo)
  853. {
  854. struct write_instance *o = vo;
  855. // if we're sending, abort write_pipe
  856. if (o->write_pipe_inst) {
  857. ASSERT(o->write_pipe_inst->state == WRITER_STATE_RUNNING)
  858. ASSERT(o->write_pipe_inst->write_inst == o)
  859. write_pipe_abort(o->write_pipe_inst);
  860. }
  861. NCDModuleInst_Backend_Dead(o->i);
  862. }
  863. static void close_func_new (void *vo, NCDModuleInst *i, const struct NCDModuleInst_new_params *params)
  864. {
  865. if (!NCDVal_ListRead(params->args, 0)) {
  866. ModuleLog(i, BLOG_ERROR, "wrong arity");
  867. goto fail0;
  868. }
  869. struct write_pipe_instance *write_pipe_inst = params->method_user;
  870. // check if a write error has already occured
  871. if (write_pipe_inst->state == WRITER_STATE_ERROR) {
  872. ModuleLog(i, BLOG_ERROR, "close() is disallowed after a write error has occured");
  873. goto fail0;
  874. }
  875. // check if the write_pipe has been aborted
  876. if (write_pipe_inst->state == WRITER_STATE_ABORTED) {
  877. ModuleLog(i, BLOG_ERROR, "close() is disallowed after a write() has been aborted");
  878. goto fail0;
  879. }
  880. // check if the write_pipe has been closed
  881. if (write_pipe_inst->state == WRITER_STATE_CLOSED) {
  882. ModuleLog(i, BLOG_ERROR, "close() is disallowed after close() has been called");
  883. goto fail0;
  884. }
  885. // close
  886. write_pipe_close(write_pipe_inst);
  887. // go up
  888. NCDModuleInst_Backend_Up(i);
  889. return;
  890. fail0:
  891. NCDModuleInst_Backend_DeadError(i);
  892. }
  893. static struct NCDModule modules[] = {
  894. {
  895. .type = "sys.start_process",
  896. .func_new2 = process_func_new,
  897. .func_die = process_func_die,
  898. .func_getvar2 = process_func_getvar,
  899. .alloc_size = sizeof(struct process_instance)
  900. }, {
  901. .type = "sys.start_process::wait",
  902. .func_new2 = wait_func_new,
  903. .func_die = wait_func_die,
  904. .func_getvar2 = wait_func_getvar,
  905. .alloc_size = sizeof(struct wait_instance)
  906. }, {
  907. .type = "sys.start_process::terminate",
  908. .func_new2 = terminate_func_new,
  909. }, {
  910. .type = "sys.start_process::kill",
  911. .func_new2 = kill_func_new,
  912. }, {
  913. .type = "sys.start_process::read_pipe",
  914. .func_new2 = read_pipe_func_new,
  915. .func_die = read_pipe_func_die,
  916. .func_getvar2 = read_pipe_func_getvar,
  917. .alloc_size = sizeof(struct read_pipe_instance)
  918. }, {
  919. .type = "sys.start_process::read_pipe::read",
  920. .func_new2 = read_func_new,
  921. .func_die = read_func_die,
  922. .func_getvar2 = read_func_getvar,
  923. .alloc_size = sizeof(struct read_instance)
  924. }, {
  925. .type = "sys.start_process::write_pipe",
  926. .func_new2 = write_pipe_func_new,
  927. .func_die = write_pipe_func_die,
  928. .func_getvar2 = write_pipe_func_getvar,
  929. .alloc_size = sizeof(struct write_pipe_instance)
  930. }, {
  931. .type = "sys.start_process::write_pipe::write",
  932. .func_new2 = write_func_new,
  933. .func_die = write_func_die,
  934. .alloc_size = sizeof(struct write_instance)
  935. }, {
  936. .type = "sys.start_process::write_pipe::close",
  937. .func_new2 = close_func_new
  938. }, {
  939. .type = NULL
  940. }
  941. };
  942. const struct NCDModuleGroup ncdmodule_sys_start_process = {
  943. .modules = modules,
  944. .strings = strings
  945. };