sys_start_process.c 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257
  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 [, map options])
  33. *
  34. * Options:
  35. * "keep_stdout":"true" - Start the program with the same stdout as the NCD process.
  36. * Must not be present if the process is being opened for reading.
  37. * "keep_stderr":true" - Start the program with the same stderr as the NCD process.
  38. * "do_setsid":"true" - Call setsid() in the child before exec. This is needed to
  39. * start the 'agetty' program.
  40. * "username":username_string - Start the process under the permissions of the
  41. * specified user.
  42. * "term_on_deinit":"false" - do not send SIGTERM to the process when this statement
  43. * is requested to terminate
  44. * "deinit_kill_time":milliseconds - how long to wait for the process to terminate
  45. * after this statement is requested to terminate until we send SIGKILL. If this option
  46. * is not present or is "never", SIGKILL will not be sent. If this option is empty, the
  47. * process will be sent SIGKILL immediately when the statement is requested to terminate.
  48. *
  49. * Variables:
  50. * is_error - "true" if there was an error starting the process, "false" if the process
  51. * has been started successfully
  52. *
  53. * Synopsis:
  54. * sys.start_process::wait()
  55. *
  56. * Variables:
  57. * exit_status - the exit code if the process terminated normally, -1 if it terminated
  58. * with a signal
  59. *
  60. * Synopsis:
  61. * sys.start_process::terminate()
  62. * sys.start_process::kill()
  63. *
  64. * Synopsis:
  65. * sys.start_process::read_pipe()
  66. *
  67. * Description:
  68. * Creates a read interface to the process's standard output. Data is read using the
  69. * read() method on this object. Read errors are reported implicitly by this statement
  70. * going down and the 'is_error' variable changing to "true".
  71. * When read_pipe() is initialized for a process, it takes ownership of the read pipe
  72. * to the process. When read_pipe() is requested to terminate, it will close the pipe.
  73. * Attempting to initialize read_pipe() on a process which was not started with 'r'
  74. * in the mode argument, or where another read_pipe() object has already taken ownership
  75. * of the read pipe, will result in throwing an error to the interpreter.
  76. *
  77. * Variables:
  78. * string is_error - "true" if there was a read error, "false" if not
  79. *
  80. * Synopsis:
  81. * sys.start_process::read_pipe::read()
  82. *
  83. * Description:
  84. * Reads some data. If a read error occurs, it is reported implicitly via the
  85. * read_pipe() object going down. If end of file is reached, this and any future read()
  86. * operations will indicate that via the 'not_eof' variable. It is guaranteed that after
  87. * EOF is reached, the read_pipe() object will not go down to report any errors.
  88. * WARNING: if a read() is requested to terminate before it has completed, the
  89. * read_pipe() will become unusable and any read() invocation after that will
  90. * throw an error to the interpreter.
  91. *
  92. * Variables:
  93. * string (empty) - data that was read, or an empty string on EOF
  94. * string not_eof - "true" is EOF was not reached, "false" if it was
  95. *
  96. * Synopsis:
  97. * sys.start_process::write_pipe()
  98. *
  99. * Description:
  100. * Creates a write interface to the process's standard input. Data is written using the
  101. * write() method on this object. Write errors are reported implicitly by this statement
  102. * going down and the ''is_error variable changing to "true".
  103. * When write_pipe() is initialized for a process, it takes ownership of the write pipe
  104. * to the process. When write_pipe() is requested to terminate, it will close the pipe
  105. * (unless the close() has been used).
  106. * Attempting to initialize write_pipe() on a process which was not started with 'w'
  107. * in the mode argument, or where another write_pipe() object has already taken ownership
  108. * of the write pope, will result in throwing an error to the interpreter.
  109. *
  110. * Variables:
  111. * string is_error - "true" if there was a write error, "false" if not
  112. *
  113. * Synopsis:
  114. * sys.start_process::write_pipe::write(string data)
  115. *
  116. * Description:
  117. * Writes the given data. If a write error occurs, it is reported implicitly via the
  118. * write_pipe() object going down.
  119. * WARNING: if a write() is requested to terminate before it has completed, the
  120. * write_pipe() will become unusable and any write() or close() invocation after
  121. * that will throw an error to the interpreter.
  122. *
  123. * Synopsis:
  124. * sys.start_process::write_pipe::close(string data)
  125. *
  126. * Description:
  127. * Closes the write pipe. This will make whatever is reading the other end of the pipe
  128. * encounter EOF after it has read any pending data. It is guaranteed that after the
  129. * pipe is closed, the write_pipe() object will not go down to report any errors.
  130. * After close() is performed, any further write() or close() calls are disallowed and
  131. * will throw errors to the interpreter.
  132. */
  133. #include <stdlib.h>
  134. #include <string.h>
  135. #include <stdio.h>
  136. #include <inttypes.h>
  137. #include <limits.h>
  138. #include <unistd.h>
  139. #include <misc/offset.h>
  140. #include <structure/LinkedList0.h>
  141. #include <system/BProcess.h>
  142. #include <system/BConnection.h>
  143. #include <ncd/extra/NCDBuf.h>
  144. #include <ncd/extra/build_cmdline.h>
  145. #include <ncd/extra/NCDBProcessOpts.h>
  146. #include <ncd/module_common.h>
  147. #include <generated/blog_channel_ncd_sys_start_process.h>
  148. #define READ_BUF_SIZE 8192
  149. #define PROCESS_STATE_ERROR 1
  150. #define PROCESS_STATE_RUNNING 2
  151. #define PROCESS_STATE_TERMINATED 3
  152. #define PROCESS_STATE_DYING 4
  153. #define READER_STATE_RUNNING 1
  154. #define READER_STATE_EOF 2
  155. #define READER_STATE_ERROR 3
  156. #define READER_STATE_ABORTED 4
  157. #define WRITER_STATE_RUNNING 1
  158. #define WRITER_STATE_CLOSED 2
  159. #define WRITER_STATE_ERROR 3
  160. #define WRITER_STATE_ABORTED 4
  161. struct process_instance {
  162. NCDModuleInst *i;
  163. BProcess process;
  164. BSmallTimer kill_timer;
  165. LinkedList0 waits_list;
  166. btime_t deinit_kill_time;
  167. int term_on_deinit;
  168. int read_fd;
  169. int write_fd;
  170. int exit_status;
  171. int state;
  172. };
  173. struct wait_instance {
  174. NCDModuleInst *i;
  175. struct process_instance *pinst;
  176. LinkedList0Node waits_list_node;
  177. int exit_status;
  178. };
  179. struct read_pipe_instance {
  180. NCDModuleInst *i;
  181. int state;
  182. int read_fd;
  183. BConnection connection;
  184. NCDBufStore store;
  185. struct read_instance *read_inst;
  186. };
  187. struct read_instance {
  188. NCDModuleInst *i;
  189. struct read_pipe_instance *read_pipe_inst;
  190. NCDBuf *buf;
  191. size_t read_size;
  192. };
  193. struct write_pipe_instance {
  194. NCDModuleInst *i;
  195. int state;
  196. int write_fd;
  197. BConnection connection;
  198. struct write_instance *write_inst;
  199. };
  200. struct write_instance {
  201. NCDModuleInst *i;
  202. struct write_pipe_instance *write_pipe_inst;
  203. b_cstring cstr;
  204. size_t pos;
  205. };
  206. static int parse_mode (NCDModuleInst *i, NCDValRef mode_arg, int *out_read, int *out_write)
  207. {
  208. if (!NCDVal_IsString(mode_arg)) {
  209. ModuleLog(i, BLOG_ERROR, "mode argument must be a string");
  210. return 0;
  211. }
  212. *out_read = 0;
  213. *out_write = 0;
  214. b_cstring cstr = NCDVal_StringCstring(mode_arg);
  215. B_CSTRING_LOOP_CHARS(cstr, char_pos, ch, {
  216. if (ch == 'r') {
  217. *out_read = 1;
  218. }
  219. else if (ch == 'w') {
  220. *out_write = 1;
  221. }
  222. else {
  223. ModuleLog(i, BLOG_ERROR, "invalid character in mode argument");
  224. return 0;
  225. }
  226. })
  227. return 1;
  228. }
  229. static void process_free (struct process_instance *o)
  230. {
  231. // close write fd
  232. if (o->write_fd != -1) {
  233. if (close(o->write_fd) < 0) {
  234. ModuleLog(o->i, BLOG_ERROR, "close failed");
  235. }
  236. }
  237. // close read fd
  238. if (o->read_fd != -1) {
  239. if (close(o->read_fd) < 0) {
  240. ModuleLog(o->i, BLOG_ERROR, "close failed");
  241. }
  242. }
  243. NCDModuleInst_Backend_Dead(o->i);
  244. }
  245. static void process_handler (void *vo, int normally, uint8_t normally_exit_status)
  246. {
  247. struct process_instance *o = vo;
  248. ASSERT(o->state == PROCESS_STATE_RUNNING || o->state == PROCESS_STATE_DYING)
  249. ModuleLog(o->i, BLOG_INFO, "process terminated");
  250. // free kill timer
  251. BReactor_RemoveSmallTimer(o->i->params->iparams->reactor, &o->kill_timer);
  252. // free process
  253. BProcess_Free(&o->process);
  254. // remember exit code
  255. o->exit_status = (!normally ? -1 : normally_exit_status);
  256. // finish waits
  257. LinkedList0Node *ln;
  258. while ((ln = LinkedList0_GetFirst(&o->waits_list))) {
  259. struct wait_instance *winst = UPPER_OBJECT(ln, struct wait_instance, waits_list_node);
  260. ASSERT(winst->pinst == o)
  261. LinkedList0_Remove(&o->waits_list, &winst->waits_list_node);
  262. winst->pinst = NULL;
  263. winst->exit_status = o->exit_status;
  264. NCDModuleInst_Backend_Up(winst->i);
  265. }
  266. // if we have been requested to die, then die now
  267. if (o->state == PROCESS_STATE_DYING) {
  268. process_free(o);
  269. return;
  270. }
  271. // set state
  272. o->state = PROCESS_STATE_TERMINATED;
  273. }
  274. static void process_kill_timer_handler (BSmallTimer *kill_timer)
  275. {
  276. struct process_instance *o = UPPER_OBJECT(kill_timer, struct process_instance, kill_timer);
  277. ASSERT(o->state == PROCESS_STATE_DYING)
  278. ModuleLog(o->i, BLOG_INFO, "killing process after timeout");
  279. BProcess_Kill(&o->process);
  280. }
  281. static int opts_func_unknown (void *user, NCDValRef key, NCDValRef val)
  282. {
  283. struct process_instance *o = user;
  284. if (NCDVal_IsString(key) && NCDVal_StringEquals(key, "term_on_deinit")) {
  285. if (!ncd_read_boolean(val, &o->term_on_deinit)) {
  286. ModuleLog(o->i, BLOG_ERROR, "term_on_deinit: bad value");
  287. return 0;
  288. }
  289. return 1;
  290. }
  291. if (NCDVal_IsString(key) && NCDVal_StringEquals(key, "deinit_kill_time")) {
  292. if (NCDVal_IsString(val) && NCDVal_StringEquals(val, "never")) {
  293. o->deinit_kill_time = -2;
  294. }
  295. else if (NCDVal_IsString(val) && NCDVal_StringEqualsId(val, NCD_STRING_EMPTY, o->i->params->iparams->string_index)) {
  296. o->deinit_kill_time = -1;
  297. }
  298. else if (!ncd_read_time(val, &o->deinit_kill_time)) {
  299. ModuleLog(o->i, BLOG_ERROR, "wrong value for deinit_kill_time option");
  300. return 0;
  301. }
  302. return 1;
  303. }
  304. return 0;
  305. }
  306. static void process_func_new (void *vo, NCDModuleInst *i, const struct NCDModuleInst_new_params *params)
  307. {
  308. struct process_instance *o = vo;
  309. o->i = i;
  310. NCDModuleInst_Backend_PassMemToMethods(i);
  311. // check arguments
  312. NCDValRef command_arg;
  313. NCDValRef mode_arg;
  314. NCDValRef options_arg = NCDVal_NewInvalid();
  315. if (!NCDVal_ListRead(params->args, 2, &command_arg, &mode_arg) &&
  316. !NCDVal_ListRead(params->args, 3, &command_arg, &mode_arg, &options_arg)
  317. ) {
  318. ModuleLog(i, BLOG_ERROR, "wrong arity");
  319. goto fail0;
  320. }
  321. // parse mode
  322. int is_read;
  323. int is_write;
  324. if (!parse_mode(i, mode_arg, &is_read, &is_write)) {
  325. goto fail0;
  326. }
  327. // parse options
  328. NCDBProcessOpts opts;
  329. int keep_stdout;
  330. int keep_stderr;
  331. o->deinit_kill_time = -2;
  332. o->term_on_deinit = 1;
  333. if (!NCDBProcessOpts_Init2(&opts, options_arg, opts_func_unknown, o, i, BLOG_CURRENT_CHANNEL, &keep_stdout, &keep_stderr)) {
  334. goto fail0;
  335. }
  336. // keep-stdout option and read mode are not compatible
  337. if (keep_stdout && is_read) {
  338. ModuleLog(i, BLOG_ERROR, "keep-stdout and read mode are not compatible");
  339. goto fail1;
  340. }
  341. // prepare for creating pipes
  342. int fds[4];
  343. int fds_map[3];
  344. int start_num_fds = opts.nfds;
  345. int num_fds = start_num_fds;
  346. memcpy(fds, opts.fds, num_fds * sizeof(int));
  347. memcpy(fds_map, opts.fds_map, num_fds * sizeof(int));
  348. int read_fd = -1;
  349. int write_fd = -1;
  350. // create read pipe
  351. if (is_read) {
  352. int pipefd[2];
  353. if (pipe(pipefd) < 0) {
  354. ModuleLog(i, BLOG_ERROR, "pipe failed");
  355. goto error1;
  356. }
  357. read_fd = pipefd[0];
  358. fds[num_fds] = pipefd[1];
  359. fds_map[num_fds++] = STDOUT_FILENO;
  360. }
  361. // create write pipe
  362. if (is_write) {
  363. int pipefd[2];
  364. if (pipe(pipefd) < 0) {
  365. ModuleLog(i, BLOG_ERROR, "pipe failed");
  366. goto error1;
  367. }
  368. write_fd = pipefd[1];
  369. fds[num_fds] = pipefd[0];
  370. fds_map[num_fds++] = STDIN_FILENO;
  371. }
  372. // terminate fds array
  373. fds[num_fds] = -1;
  374. // build process parameters struct
  375. struct BProcess_params p_params = {};
  376. p_params.fds = fds;
  377. p_params.fds_map = fds_map;
  378. p_params.do_setsid = opts.do_setsid;
  379. p_params.username = opts.username;
  380. // build command line
  381. char *exec;
  382. CmdLine cl;
  383. if (!ncd_build_cmdline(i, BLOG_CURRENT_CHANNEL, command_arg, &exec, &cl)) {
  384. goto error1;
  385. }
  386. // start process
  387. int res = BProcess_Init2(&o->process, i->params->iparams->manager, process_handler, o, exec, CmdLine_Get(&cl), p_params);
  388. CmdLine_Free(&cl);
  389. free(exec);
  390. if (!res) {
  391. ModuleLog(i, BLOG_ERROR, "BProcess_Init failed");
  392. goto error1;
  393. }
  394. // init kill timer
  395. BSmallTimer_Init(&o->kill_timer, process_kill_timer_handler);
  396. // close child fds
  397. while (num_fds-- > start_num_fds) {
  398. if (close(fds[num_fds]) < 0) {
  399. ModuleLog(i, BLOG_ERROR, "close failed");
  400. }
  401. }
  402. // free opts
  403. NCDBProcessOpts_Free(&opts);
  404. // init waits list
  405. LinkedList0_Init(&o->waits_list);
  406. // remember our fds
  407. o->read_fd = read_fd;
  408. o->write_fd = write_fd;
  409. // set state
  410. o->state = PROCESS_STATE_RUNNING;
  411. // go up
  412. NCDModuleInst_Backend_Up(i);
  413. return;
  414. fail1:
  415. NCDBProcessOpts_Free(&opts);
  416. fail0:
  417. NCDModuleInst_Backend_DeadError(i);
  418. return;
  419. error1:
  420. if (write_fd != -1) {
  421. if (close(write_fd) < 0) {
  422. ModuleLog(i, BLOG_ERROR, "close failed");
  423. }
  424. }
  425. if (read_fd != -1) {
  426. if (close(read_fd) < 0) {
  427. ModuleLog(i, BLOG_ERROR, "close failed");
  428. }
  429. }
  430. while (num_fds-- > start_num_fds) {
  431. if (close(fds[num_fds]) < 0) {
  432. ModuleLog(i, BLOG_ERROR, "close failed");
  433. }
  434. }
  435. NCDBProcessOpts_Free(&opts);
  436. o->read_fd = -1;
  437. o->write_fd = -1;
  438. o->state = PROCESS_STATE_ERROR;
  439. NCDModuleInst_Backend_Up(i);
  440. }
  441. static void process_func_die (void *vo)
  442. {
  443. struct process_instance *o = vo;
  444. ASSERT(o->state != PROCESS_STATE_DYING)
  445. // if process is not running, die immediately
  446. if (o->state != PROCESS_STATE_RUNNING) {
  447. process_free(o);
  448. return;
  449. }
  450. if (o->term_on_deinit) {
  451. ModuleLog(o->i, BLOG_INFO, "terminating process");
  452. // send termination signal
  453. BProcess_Terminate(&o->process);
  454. } else {
  455. ModuleLog(o->i, BLOG_INFO, "not terminating process as requested");
  456. }
  457. if (o->deinit_kill_time == -1) {
  458. // user wants SIGKILL immediately
  459. ModuleLog(o->i, BLOG_INFO, "killing process immediately");
  460. BProcess_Kill(&o->process);
  461. } else if (o->deinit_kill_time >= 0) {
  462. // user wants SIGKILL after some time
  463. BReactor_SetSmallTimer(o->i->params->iparams->reactor, &o->kill_timer, BTIMER_SET_RELATIVE, o->deinit_kill_time);
  464. }
  465. // set state
  466. o->state = PROCESS_STATE_DYING;
  467. }
  468. static int process_func_getvar (void *vo, NCD_string_id_t name, NCDValMem *mem, NCDValRef *out)
  469. {
  470. struct process_instance *o = vo;
  471. if (name == NCD_STRING_IS_ERROR) {
  472. int is_error = (o->state == PROCESS_STATE_ERROR);
  473. *out = ncd_make_boolean(mem, is_error, o->i->params->iparams->string_index);
  474. return 1;
  475. }
  476. return 0;
  477. }
  478. static void wait_func_new (void *vo, NCDModuleInst *i, const struct NCDModuleInst_new_params *params)
  479. {
  480. struct wait_instance *o = vo;
  481. o->i = i;
  482. if (!NCDVal_ListRead(params->args, 0)) {
  483. ModuleLog(i, BLOG_ERROR, "wrong arity");
  484. goto fail0;
  485. }
  486. struct process_instance *pinst = params->method_user;
  487. if (pinst->state == PROCESS_STATE_ERROR) {
  488. ModuleLog(i, BLOG_ERROR, "wait() is disallowed after the process has failed to start");
  489. goto fail0;
  490. }
  491. if (pinst->state == PROCESS_STATE_TERMINATED) {
  492. // not waiting, set no pinst
  493. o->pinst = NULL;
  494. // remember exit code
  495. o->exit_status = pinst->exit_status;
  496. // go up
  497. NCDModuleInst_Backend_Up(i);
  498. } else {
  499. // waitint, set pinst
  500. o->pinst = pinst;
  501. // insert to waits list
  502. LinkedList0_Prepend(&pinst->waits_list, &o->waits_list_node);
  503. }
  504. return;
  505. fail0:
  506. NCDModuleInst_Backend_DeadError(i);
  507. }
  508. static void wait_func_die (void *vo)
  509. {
  510. struct wait_instance *o = vo;
  511. // remove from waits list
  512. if (o->pinst) {
  513. LinkedList0_Remove(&o->pinst->waits_list, &o->waits_list_node);
  514. }
  515. NCDModuleInst_Backend_Dead(o->i);
  516. }
  517. static int wait_func_getvar (void *vo, NCD_string_id_t name, NCDValMem *mem, NCDValRef *out)
  518. {
  519. struct wait_instance *o = vo;
  520. ASSERT(!o->pinst)
  521. if (name == NCD_STRING_EXIT_STATUS) {
  522. if (o->exit_status == -1) {
  523. *out = NCDVal_NewString(mem, "-1");
  524. } else {
  525. *out = ncd_make_uintmax(mem, o->exit_status);
  526. }
  527. return 1;
  528. }
  529. return 0;
  530. }
  531. static void terminate_kill_new_common (void *vo, NCDModuleInst *i, const struct NCDModuleInst_new_params *params, int is_kill)
  532. {
  533. if (!NCDVal_ListRead(params->args, 0)) {
  534. ModuleLog(i, BLOG_ERROR, "wrong arity");
  535. goto fail0;
  536. }
  537. struct process_instance *pinst = params->method_user;
  538. if (pinst->state == PROCESS_STATE_ERROR) {
  539. ModuleLog(i, BLOG_ERROR, "terminate()/kill() is disallowed after the process has failed to start");
  540. goto fail0;
  541. }
  542. if (pinst->state != PROCESS_STATE_TERMINATED) {
  543. if (is_kill) {
  544. BProcess_Kill(&pinst->process);
  545. } else {
  546. BProcess_Terminate(&pinst->process);
  547. }
  548. }
  549. NCDModuleInst_Backend_Up(i);
  550. return;
  551. fail0:
  552. NCDModuleInst_Backend_DeadError(i);
  553. }
  554. static void terminate_func_new (void *vo, NCDModuleInst *i, const struct NCDModuleInst_new_params *params)
  555. {
  556. terminate_kill_new_common(vo, i, params, 0);
  557. }
  558. static void kill_func_new (void *vo, NCDModuleInst *i, const struct NCDModuleInst_new_params *params)
  559. {
  560. terminate_kill_new_common(vo, i, params, 1);
  561. }
  562. static void read_pipe_free_connection (struct read_pipe_instance *o)
  563. {
  564. // disconnect read instance
  565. if (o->read_inst) {
  566. ASSERT(o->read_inst->read_pipe_inst == o)
  567. o->read_inst->read_pipe_inst = NULL;
  568. }
  569. // free store
  570. NCDBufStore_Free(&o->store);
  571. // free connection read interface
  572. BConnection_RecvAsync_Free(&o->connection);
  573. // free connection
  574. BConnection_Free(&o->connection);
  575. // close fd
  576. if (close(o->read_fd) < 0) {
  577. ModuleLog(o->i, BLOG_ERROR, "close failed");
  578. }
  579. }
  580. static void read_pipe_abort (struct read_pipe_instance *o)
  581. {
  582. ASSERT(o->state == READER_STATE_RUNNING)
  583. // release connection resources
  584. read_pipe_free_connection(o);
  585. // set state
  586. o->state = READER_STATE_ABORTED;
  587. }
  588. static void read_pipe_connection_handler (void *vo, int event)
  589. {
  590. struct read_pipe_instance *o = vo;
  591. ASSERT(o->state == READER_STATE_RUNNING)
  592. if (event == BCONNECTION_EVENT_RECVCLOSED) {
  593. // if we have read operation, make it finish with eof
  594. if (o->read_inst) {
  595. ASSERT(o->read_inst->read_pipe_inst == o)
  596. ASSERT(o->read_inst->buf)
  597. o->read_inst->read_pipe_inst = NULL;
  598. o->read_inst->read_size = 0;
  599. NCDModuleInst_Backend_Up(o->read_inst->i);
  600. o->read_inst = NULL;
  601. }
  602. // free connection resources
  603. read_pipe_free_connection(o);
  604. // set state closed
  605. o->state = READER_STATE_EOF;
  606. return;
  607. }
  608. ModuleLog(o->i, BLOG_ERROR, "read pipe error");
  609. // free connection resources
  610. read_pipe_free_connection(o);
  611. // set state error
  612. o->state = READER_STATE_ERROR;
  613. // backtrack
  614. NCDModuleInst_Backend_DownUp(o->i);
  615. }
  616. static void read_pipe_recv_handler_done (void *vo, int data_len)
  617. {
  618. struct read_pipe_instance *o = vo;
  619. ASSERT(o->state == READER_STATE_RUNNING)
  620. ASSERT(o->read_inst)
  621. ASSERT(o->read_inst->read_pipe_inst == o)
  622. ASSERT(o->read_inst->buf)
  623. ASSERT(data_len > 0)
  624. ASSERT(data_len <= NCDBufStore_BufSize(&o->store))
  625. // finish read operation
  626. o->read_inst->read_pipe_inst = NULL;
  627. o->read_inst->read_size = data_len;
  628. NCDModuleInst_Backend_Up(o->read_inst->i);
  629. o->read_inst = NULL;
  630. }
  631. static void read_pipe_func_new (void *vo, NCDModuleInst *i, const struct NCDModuleInst_new_params *params)
  632. {
  633. struct read_pipe_instance *o = vo;
  634. o->i = i;
  635. NCDModuleInst_Backend_PassMemToMethods(i);
  636. if (!NCDVal_ListRead(params->args, 0)) {
  637. ModuleLog(i, BLOG_ERROR, "wrong arity");
  638. goto fail0;
  639. }
  640. struct process_instance *pinst = params->method_user;
  641. if (pinst->read_fd == -1) {
  642. ModuleLog(i, BLOG_ERROR, "process did not start successfully, was not opened for reading or a read_pipe was already created");
  643. goto fail0;
  644. }
  645. // init connection
  646. if (!BConnection_Init(&o->connection, BConnection_source_pipe(pinst->read_fd), i->params->iparams->reactor, o, read_pipe_connection_handler)) {
  647. ModuleLog(i, BLOG_ERROR, "BConnection_Init failed");
  648. goto fail0;
  649. }
  650. // init connection read interface
  651. BConnection_RecvAsync_Init(&o->connection);
  652. // set recv done callback
  653. StreamRecvInterface_Receiver_Init(BConnection_RecvAsync_GetIf(&o->connection), read_pipe_recv_handler_done, o);
  654. // init store
  655. NCDBufStore_Init(&o->store, READ_BUF_SIZE);
  656. // set variables
  657. o->state = READER_STATE_RUNNING;
  658. o->read_fd = pinst->read_fd;
  659. o->read_inst = NULL;
  660. // steal read fd from process instance
  661. pinst->read_fd = -1;
  662. // go up
  663. NCDModuleInst_Backend_Up(i);
  664. return;
  665. fail0:
  666. NCDModuleInst_Backend_DeadError(i);
  667. }
  668. static void read_pipe_func_die (void *vo)
  669. {
  670. struct read_pipe_instance *o = vo;
  671. // free connection resources
  672. if (o->state == READER_STATE_RUNNING) {
  673. read_pipe_free_connection(o);
  674. }
  675. NCDModuleInst_Backend_Dead(o->i);
  676. }
  677. static int read_pipe_func_getvar (void *vo, NCD_string_id_t name, NCDValMem *mem, NCDValRef *out)
  678. {
  679. struct read_pipe_instance *o = vo;
  680. if (name == NCD_STRING_IS_ERROR) {
  681. int is_error = (o->state == READER_STATE_ERROR);
  682. *out = ncd_make_boolean(mem, is_error, o->i->params->iparams->string_index);
  683. return 1;
  684. }
  685. return 0;
  686. }
  687. static void read_func_new (void *vo, NCDModuleInst *i, const struct NCDModuleInst_new_params *params)
  688. {
  689. struct read_instance *o = vo;
  690. o->i = i;
  691. if (!NCDVal_ListRead(params->args, 0)) {
  692. ModuleLog(i, BLOG_ERROR, "wrong arity");
  693. goto fail0;
  694. }
  695. struct read_pipe_instance *read_pipe_inst = params->method_user;
  696. // check if a read error has already occured
  697. if (read_pipe_inst->state == READER_STATE_ERROR) {
  698. ModuleLog(i, BLOG_ERROR, "read() is disallowed after a read error has occured");
  699. goto fail0;
  700. }
  701. // check if the read_pipe has been aborted
  702. if (read_pipe_inst->state == READER_STATE_ABORTED) {
  703. ModuleLog(i, BLOG_ERROR, "read() is disallowed after a read() has been aborted");
  704. goto fail0;
  705. }
  706. // if EOF has already been encountered, complete the read immediately
  707. if (read_pipe_inst->state == READER_STATE_EOF) {
  708. o->buf = NULL;
  709. o->read_pipe_inst = NULL;
  710. o->read_size = 0;
  711. NCDModuleInst_Backend_Up(i);
  712. return;
  713. }
  714. ASSERT(read_pipe_inst->state == READER_STATE_RUNNING)
  715. // check if there's already a read in progress
  716. if (read_pipe_inst->read_inst) {
  717. ModuleLog(i, BLOG_ERROR, "read() is disallowed while another read() is in progress");
  718. goto fail0;
  719. }
  720. // get buffer
  721. o->buf = NCDBufStore_GetBuf(&read_pipe_inst->store);
  722. if (!o->buf) {
  723. ModuleLog(i, BLOG_ERROR, "NCDBufStore_GetBuf failed");
  724. goto fail0;
  725. }
  726. // set read_pipe
  727. o->read_pipe_inst = read_pipe_inst;
  728. // register read in read_pipe
  729. read_pipe_inst->read_inst = o;
  730. // receive
  731. size_t buf_size = NCDBufStore_BufSize(&read_pipe_inst->store);
  732. int to_read = (buf_size > INT_MAX ? INT_MAX : buf_size);
  733. StreamRecvInterface_Receiver_Recv(BConnection_RecvAsync_GetIf(&read_pipe_inst->connection), (uint8_t *)NCDBuf_Data(o->buf), to_read);
  734. return;
  735. fail0:
  736. NCDModuleInst_Backend_DeadError(i);
  737. }
  738. static void read_func_die (void *vo)
  739. {
  740. struct read_instance *o = vo;
  741. // if we're receiving, abort read_pipe
  742. if (o->read_pipe_inst) {
  743. ASSERT(o->read_pipe_inst->state == READER_STATE_RUNNING)
  744. ASSERT(o->read_pipe_inst->read_inst == o)
  745. ASSERT(o->buf)
  746. read_pipe_abort(o->read_pipe_inst);
  747. }
  748. // release buffer
  749. if (o->buf) {
  750. BRefTarget_Deref(NCDBuf_RefTarget(o->buf));
  751. }
  752. NCDModuleInst_Backend_Dead(o->i);
  753. }
  754. static int read_func_getvar (void *vo, NCD_string_id_t name, NCDValMem *mem, NCDValRef *out)
  755. {
  756. struct read_instance *o = vo;
  757. ASSERT(!o->read_pipe_inst)
  758. ASSERT(!(o->read_size > 0) || o->buf)
  759. if (name == NCD_STRING_EMPTY) {
  760. if (o->read_size > 0) {
  761. *out = NCDVal_NewExternalString(mem, NCDBuf_Data(o->buf), o->read_size, NCDBuf_RefTarget(o->buf));
  762. } else {
  763. *out = NCDVal_NewIdString(mem, NCD_STRING_EMPTY, o->i->params->iparams->string_index);
  764. }
  765. return 1;
  766. }
  767. if (name == NCD_STRING_NOT_EOF) {
  768. int not_eof = (o->read_size > 0);
  769. *out = ncd_make_boolean(mem, not_eof, o->i->params->iparams->string_index);
  770. return 1;
  771. }
  772. return 0;
  773. }
  774. static void write_pipe_free_connection (struct write_pipe_instance *o)
  775. {
  776. // disconnect write instance
  777. if (o->write_inst) {
  778. ASSERT(o->write_inst->write_pipe_inst == o)
  779. o->write_inst->write_pipe_inst = NULL;
  780. }
  781. // free connection send interface
  782. BConnection_SendAsync_Free(&o->connection);
  783. // free connection
  784. BConnection_Free(&o->connection);
  785. // close fd
  786. if (close(o->write_fd) < 0) {
  787. ModuleLog(o->i, BLOG_ERROR, "close failed");
  788. }
  789. }
  790. static void write_pipe_abort (struct write_pipe_instance *o)
  791. {
  792. ASSERT(o->state == WRITER_STATE_RUNNING)
  793. // release connection resources
  794. write_pipe_free_connection(o);
  795. // set state
  796. o->state = WRITER_STATE_ABORTED;
  797. }
  798. static void write_pipe_close (struct write_pipe_instance *o)
  799. {
  800. ASSERT(o->state == WRITER_STATE_RUNNING)
  801. // release connection resources
  802. write_pipe_free_connection(o);
  803. // set state
  804. o->state = WRITER_STATE_CLOSED;
  805. }
  806. static void write_pipe_connection_handler (void *vo, int event)
  807. {
  808. struct write_pipe_instance *o = vo;
  809. ASSERT(o->state == WRITER_STATE_RUNNING)
  810. ModuleLog(o->i, BLOG_ERROR, "write pipe error");
  811. // free connection resources
  812. write_pipe_free_connection(o);
  813. // set state error
  814. o->state = WRITER_STATE_ERROR;
  815. // backtrack
  816. NCDModuleInst_Backend_DownUp(o->i);
  817. }
  818. static void write_pipe_send_handler_done (void *vo, int data_len)
  819. {
  820. struct write_pipe_instance *o = vo;
  821. ASSERT(o->state == WRITER_STATE_RUNNING)
  822. ASSERT(o->write_inst)
  823. ASSERT(o->write_inst->write_pipe_inst == o)
  824. ASSERT(data_len > 0)
  825. ASSERT(data_len <= o->write_inst->cstr.length - o->write_inst->pos)
  826. struct write_instance *wr = o->write_inst;
  827. // update write progress
  828. wr->pos += data_len;
  829. // if there is more data, start another write operation
  830. if (wr->pos < wr->cstr.length) {
  831. size_t chunk_length;
  832. const char *chunk_data = b_cstring_get(wr->cstr, wr->pos, wr->cstr.length - wr->pos, &chunk_length);
  833. size_t to_send = (chunk_length > INT_MAX ? INT_MAX : chunk_length);
  834. StreamPassInterface_Sender_Send(BConnection_SendAsync_GetIf(&o->connection), (uint8_t *)chunk_data, to_send);
  835. return;
  836. }
  837. // finish write operation
  838. wr->write_pipe_inst = NULL;
  839. NCDModuleInst_Backend_Up(wr->i);
  840. o->write_inst = NULL;
  841. }
  842. static void write_pipe_func_new (void *vo, NCDModuleInst *i, const struct NCDModuleInst_new_params *params)
  843. {
  844. struct write_pipe_instance *o = vo;
  845. o->i = i;
  846. NCDModuleInst_Backend_PassMemToMethods(i);
  847. if (!NCDVal_ListRead(params->args, 0)) {
  848. ModuleLog(i, BLOG_ERROR, "wrong arity");
  849. goto fail0;
  850. }
  851. struct process_instance *pinst = params->method_user;
  852. if (pinst->write_fd == -1) {
  853. ModuleLog(i, BLOG_ERROR, "process did not start successfully, was not opened for writing or a write_pipe was already created");
  854. goto fail0;
  855. }
  856. // init connection
  857. if (!BConnection_Init(&o->connection, BConnection_source_pipe(pinst->write_fd), i->params->iparams->reactor, o, write_pipe_connection_handler)) {
  858. ModuleLog(i, BLOG_ERROR, "BConnection_Init failed");
  859. goto fail0;
  860. }
  861. // init connection send interface
  862. BConnection_SendAsync_Init(&o->connection);
  863. // set send done callback
  864. StreamPassInterface_Sender_Init(BConnection_SendAsync_GetIf(&o->connection), write_pipe_send_handler_done, o);
  865. // set variables
  866. o->state = WRITER_STATE_RUNNING;
  867. o->write_fd = pinst->write_fd;
  868. o->write_inst = NULL;
  869. // steal write fd from process instance
  870. pinst->write_fd = -1;
  871. // go up
  872. NCDModuleInst_Backend_Up(i);
  873. return;
  874. fail0:
  875. NCDModuleInst_Backend_DeadError(i);
  876. }
  877. static void write_pipe_func_die (void *vo)
  878. {
  879. struct write_pipe_instance *o = vo;
  880. // free connection resources
  881. if (o->state == WRITER_STATE_RUNNING) {
  882. write_pipe_free_connection(o);
  883. }
  884. NCDModuleInst_Backend_Dead(o->i);
  885. }
  886. static int write_pipe_func_getvar (void *vo, NCD_string_id_t name, NCDValMem *mem, NCDValRef *out)
  887. {
  888. struct write_pipe_instance *o = vo;
  889. if (name == NCD_STRING_IS_ERROR) {
  890. int is_error = (o->state == WRITER_STATE_ERROR);
  891. *out = ncd_make_boolean(mem, is_error, o->i->params->iparams->string_index);
  892. return 1;
  893. }
  894. return 0;
  895. }
  896. static void write_func_new (void *vo, NCDModuleInst *i, const struct NCDModuleInst_new_params *params)
  897. {
  898. struct write_instance *o = vo;
  899. o->i = i;
  900. NCDValRef data_arg;
  901. if (!NCDVal_ListRead(params->args, 1, &data_arg)) {
  902. ModuleLog(i, BLOG_ERROR, "wrong arity");
  903. goto fail0;
  904. }
  905. if (!NCDVal_IsString(data_arg)) {
  906. ModuleLog(i, BLOG_ERROR, "wrong type");
  907. goto fail0;
  908. }
  909. struct write_pipe_instance *write_pipe_inst = params->method_user;
  910. // check if a write error has already occured
  911. if (write_pipe_inst->state == WRITER_STATE_ERROR) {
  912. ModuleLog(i, BLOG_ERROR, "write() is disallowed after a write error has occured");
  913. goto fail0;
  914. }
  915. // check if the write_pipe has been aborted
  916. if (write_pipe_inst->state == WRITER_STATE_ABORTED) {
  917. ModuleLog(i, BLOG_ERROR, "write() is disallowed after a write() has been aborted");
  918. goto fail0;
  919. }
  920. // check if the write_pipe has been aborted
  921. if (write_pipe_inst->state == WRITER_STATE_CLOSED) {
  922. ModuleLog(i, BLOG_ERROR, "write() is disallowed after close() has been called");
  923. goto fail0;
  924. }
  925. ASSERT(write_pipe_inst->state == WRITER_STATE_RUNNING)
  926. // check if there's already a write in progress
  927. if (write_pipe_inst->write_inst) {
  928. ModuleLog(i, BLOG_ERROR, "write() is disallowed while another write() is in progress");
  929. goto fail0;
  930. }
  931. // initialize write progress state
  932. o->cstr = NCDVal_StringCstring(data_arg);
  933. o->pos = 0;
  934. // if there's nothing to send, go up immediately
  935. if (o->cstr.length == 0) {
  936. o->write_pipe_inst = NULL;
  937. NCDModuleInst_Backend_Up(i);
  938. return;
  939. }
  940. // set write_pipe
  941. o->write_pipe_inst = write_pipe_inst;
  942. // register write in write_pipe
  943. write_pipe_inst->write_inst = o;
  944. // start send operation
  945. size_t chunk_length;
  946. const char *chunk_data = b_cstring_get(o->cstr, o->pos, o->cstr.length - o->pos, &chunk_length);
  947. size_t to_send = (chunk_length > INT_MAX ? INT_MAX : chunk_length);
  948. StreamPassInterface_Sender_Send(BConnection_SendAsync_GetIf(&write_pipe_inst->connection), (uint8_t *)chunk_data, to_send);
  949. return;
  950. fail0:
  951. NCDModuleInst_Backend_DeadError(i);
  952. }
  953. static void write_func_die (void *vo)
  954. {
  955. struct write_instance *o = vo;
  956. // if we're sending, abort write_pipe
  957. if (o->write_pipe_inst) {
  958. ASSERT(o->write_pipe_inst->state == WRITER_STATE_RUNNING)
  959. ASSERT(o->write_pipe_inst->write_inst == o)
  960. write_pipe_abort(o->write_pipe_inst);
  961. }
  962. NCDModuleInst_Backend_Dead(o->i);
  963. }
  964. static void close_func_new (void *vo, NCDModuleInst *i, const struct NCDModuleInst_new_params *params)
  965. {
  966. if (!NCDVal_ListRead(params->args, 0)) {
  967. ModuleLog(i, BLOG_ERROR, "wrong arity");
  968. goto fail0;
  969. }
  970. struct write_pipe_instance *write_pipe_inst = params->method_user;
  971. // check if a write error has already occured
  972. if (write_pipe_inst->state == WRITER_STATE_ERROR) {
  973. ModuleLog(i, BLOG_ERROR, "close() is disallowed after a write error has occured");
  974. goto fail0;
  975. }
  976. // check if the write_pipe has been aborted
  977. if (write_pipe_inst->state == WRITER_STATE_ABORTED) {
  978. ModuleLog(i, BLOG_ERROR, "close() is disallowed after a write() has been aborted");
  979. goto fail0;
  980. }
  981. // check if the write_pipe has been closed
  982. if (write_pipe_inst->state == WRITER_STATE_CLOSED) {
  983. ModuleLog(i, BLOG_ERROR, "close() is disallowed after close() has been called");
  984. goto fail0;
  985. }
  986. // close
  987. write_pipe_close(write_pipe_inst);
  988. // go up
  989. NCDModuleInst_Backend_Up(i);
  990. return;
  991. fail0:
  992. NCDModuleInst_Backend_DeadError(i);
  993. }
  994. static struct NCDModule modules[] = {
  995. {
  996. .type = "sys.start_process",
  997. .func_new2 = process_func_new,
  998. .func_die = process_func_die,
  999. .func_getvar2 = process_func_getvar,
  1000. .alloc_size = sizeof(struct process_instance)
  1001. }, {
  1002. .type = "sys.start_process::wait",
  1003. .func_new2 = wait_func_new,
  1004. .func_die = wait_func_die,
  1005. .func_getvar2 = wait_func_getvar,
  1006. .alloc_size = sizeof(struct wait_instance)
  1007. }, {
  1008. .type = "sys.start_process::terminate",
  1009. .func_new2 = terminate_func_new
  1010. }, {
  1011. .type = "sys.start_process::kill",
  1012. .func_new2 = kill_func_new
  1013. }, {
  1014. .type = "sys.start_process::read_pipe",
  1015. .func_new2 = read_pipe_func_new,
  1016. .func_die = read_pipe_func_die,
  1017. .func_getvar2 = read_pipe_func_getvar,
  1018. .alloc_size = sizeof(struct read_pipe_instance)
  1019. }, {
  1020. .type = "sys.start_process::read_pipe::read",
  1021. .func_new2 = read_func_new,
  1022. .func_die = read_func_die,
  1023. .func_getvar2 = read_func_getvar,
  1024. .alloc_size = sizeof(struct read_instance)
  1025. }, {
  1026. .type = "sys.start_process::write_pipe",
  1027. .func_new2 = write_pipe_func_new,
  1028. .func_die = write_pipe_func_die,
  1029. .func_getvar2 = write_pipe_func_getvar,
  1030. .alloc_size = sizeof(struct write_pipe_instance)
  1031. }, {
  1032. .type = "sys.start_process::write_pipe::write",
  1033. .func_new2 = write_func_new,
  1034. .func_die = write_func_die,
  1035. .alloc_size = sizeof(struct write_instance)
  1036. }, {
  1037. .type = "sys.start_process::write_pipe::close",
  1038. .func_new2 = close_func_new
  1039. }, {
  1040. .type = NULL
  1041. }
  1042. };
  1043. const struct NCDModuleGroup ncdmodule_sys_start_process = {
  1044. .modules = modules
  1045. };