file_open.c 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569
  1. /**
  2. * @file file_open.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. * file_open(string filename, string mode)
  33. *
  34. * Variables:
  35. * string is_error - "true" if the file_open object is in error state, "false"
  36. * otherwise
  37. *
  38. * Description:
  39. * Opens a file for subsequent reading or writing. The 'mode' argument must
  40. * be one of: "r", "w", "a", "r+", "w+", "a+"; it corresponds to the mode string
  41. * that will be passed to the fopen() function.
  42. * When the file_open() statement goes up, the error state is set depending on
  43. * whether opening succeeded or failed. The 'is_error' variable should be used
  44. * to check the error state.
  45. * If an error occurs afterward within read(), write() or seek(), the error state
  46. * is set, and the file_open() statement is toggled down and back up. This way,
  47. * the same piece of user code can handle all file errors.
  48. *
  49. * Synopsis:
  50. * file_open::read()
  51. *
  52. * Variables:
  53. * string (empty) - the data which was read, or an empty string if EOF was reached
  54. * string not_eof - "false" if EOF was reached, "true" if not
  55. *
  56. * Description:
  57. * Reads data from an opened file. The file must not be in error state.
  58. * If reading fails, this statement will never go up, the error state of the
  59. * file_open() statement will be set, and the file_open() statement will trigger
  60. * backtracking (go down and up).
  61. *
  62. * Synopsis:
  63. * file_open::write(string data)
  64. *
  65. * Description:
  66. * Writes data to an opened file. The file must not be in error state.
  67. * If writing fails, this statement will never go up, the error state of the
  68. * file_open() statement will be set, and the file_open() statement will trigger
  69. * backtracking (go down and up).
  70. *
  71. * Synopsis:
  72. * file_open::seek(string position, string whence)
  73. *
  74. * Description:
  75. * Sets the file position indicator. The 'position' argument must be a possibly
  76. * negative decimal number, and is interpreted relative to 'whence'. Here, 'whence'
  77. * may be one of:
  78. * - "set", meaning beginning of file,
  79. * - "cur", meaning the current position, and
  80. * - "end", meaning the end of file.
  81. * Errors are handled as in read() and write(). Note that if the position argument
  82. * is too small or too large to convert to off_t, this is not a seek error, and only
  83. * the seek command will fail.
  84. *
  85. * Synopsis:
  86. * file_open::close()
  87. *
  88. * Description:
  89. * Closes the file. The file must not be in error state.
  90. * Errors are handled as handled as in read() and write(), i.e. the process is
  91. * backtracked to file_open() with the error state set.
  92. * On success, the error state of the file is set (but without backtracking), and
  93. * the close() statement goes up .
  94. */
  95. #include <stddef.h>
  96. #include <stdio.h>
  97. #include <stdint.h>
  98. #include <limits.h>
  99. #include <misc/debug.h>
  100. #include <misc/balloc.h>
  101. #include <misc/parse_number.h>
  102. #include <ncd/NCDModule.h>
  103. #include <ncd/static_strings.h>
  104. #include <ncd/value_utils.h>
  105. #include <generated/blog_channel_ncd_file_open.h>
  106. #define ModuleLog(i, ...) NCDModuleInst_Backend_Log((i), BLOG_CURRENT_CHANNEL, __VA_ARGS__)
  107. #define START_READ_SIZE 512
  108. #define MAX_READ_SIZE 8192
  109. struct open_instance {
  110. NCDModuleInst *i;
  111. FILE *fh;
  112. };
  113. struct read_instance {
  114. NCDModuleInst *i;
  115. char *data;
  116. size_t length;
  117. };
  118. enum {STRING_IS_ERROR, STRING_NOT_EOF};
  119. static struct NCD_string_request strings[] = {
  120. {"is_error"}, {"not_eof"}, {NULL}
  121. };
  122. static int parse_mode (const char *data, char *out)
  123. {
  124. switch (*data) {
  125. case 'r':
  126. case 'w':
  127. case 'a':
  128. *out++ = *data++;
  129. break;
  130. default:
  131. return 0;
  132. }
  133. switch (*data) {
  134. case '\0':
  135. goto finish;
  136. case '+':
  137. *out++ = *data++;
  138. break;
  139. default:
  140. return 0;
  141. }
  142. switch (*data) {
  143. case '\0':
  144. goto finish;
  145. default:
  146. return 0;
  147. }
  148. finish:
  149. *out = '\0';
  150. return 1;
  151. }
  152. static void trigger_error (struct open_instance *o)
  153. {
  154. if (o->fh) {
  155. // close file
  156. if (fclose(o->fh) != 0) {
  157. ModuleLog(o->i, BLOG_ERROR, "fclose failed");
  158. }
  159. // set no file, indicating error
  160. o->fh = NULL;
  161. }
  162. // go down and up
  163. NCDModuleInst_Backend_Down(o->i);
  164. NCDModuleInst_Backend_Up(o->i);
  165. }
  166. static void open_func_new (void *vo, NCDModuleInst *i, const struct NCDModuleInst_new_params *params)
  167. {
  168. struct open_instance *o = vo;
  169. o->i = i;
  170. // check arguments
  171. NCDValRef filename_arg;
  172. NCDValRef mode_arg;
  173. if (!NCDVal_ListRead(params->args, 2, &filename_arg, &mode_arg)) {
  174. ModuleLog(o->i, BLOG_ERROR, "wrong arity");
  175. goto fail0;
  176. }
  177. if (!NCDVal_IsStringNoNulls(filename_arg) || !NCDVal_IsStringNoNulls(mode_arg)) {
  178. ModuleLog(o->i, BLOG_ERROR, "wrong type");
  179. goto fail0;
  180. }
  181. // check mode
  182. char mode[5];
  183. if (!parse_mode(NCDVal_StringValue(mode_arg), mode)) {
  184. ModuleLog(o->i, BLOG_ERROR, "wrong mode");
  185. goto fail0;
  186. }
  187. // open file
  188. o->fh = fopen(NCDVal_StringValue(filename_arg), mode);
  189. if (!o->fh) {
  190. ModuleLog(o->i, BLOG_ERROR, "fopen failed");
  191. }
  192. // go up
  193. NCDModuleInst_Backend_Up(i);
  194. return;
  195. fail0:
  196. NCDModuleInst_Backend_SetError(i);
  197. NCDModuleInst_Backend_Dead(i);
  198. }
  199. static void open_func_die (void *vo)
  200. {
  201. struct open_instance *o = vo;
  202. // close file
  203. if (o->fh) {
  204. if (fclose(o->fh) != 0) {
  205. ModuleLog(o->i, BLOG_ERROR, "fclose failed");
  206. }
  207. }
  208. NCDModuleInst_Backend_Dead(o->i);
  209. }
  210. static int open_func_getvar (void *vo, NCD_string_id_t name, NCDValMem *mem, NCDValRef *out)
  211. {
  212. struct open_instance *o = vo;
  213. if (name == strings[STRING_IS_ERROR].id) {
  214. *out = ncd_make_boolean(mem, !o->fh, o->i->params->iparams->string_index);
  215. if (NCDVal_IsInvalid(*out)) {
  216. ModuleLog(o->i, BLOG_ERROR, "ncd_make_boolean failed");
  217. }
  218. return 1;
  219. }
  220. return 0;
  221. }
  222. static void read_func_new (void *vo, NCDModuleInst *i, const struct NCDModuleInst_new_params *params)
  223. {
  224. struct read_instance *o = vo;
  225. o->i = i;
  226. // check arguments
  227. if (!NCDVal_ListRead(params->args, 0)) {
  228. ModuleLog(o->i, BLOG_ERROR, "wrong arity");
  229. goto fail0;
  230. }
  231. // get open instance
  232. struct open_instance *open_inst = NCDModuleInst_Backend_GetUser((NCDModuleInst *)params->method_user);
  233. // make sure it's not in error
  234. if (!open_inst->fh) {
  235. ModuleLog(o->i, BLOG_ERROR, "open instance is in error");
  236. goto fail0;
  237. }
  238. // allocate buffer
  239. size_t capacity = START_READ_SIZE;
  240. o->data = BAlloc(capacity);
  241. if (!o->data) {
  242. ModuleLog(o->i, BLOG_ERROR, "BAlloc failed");
  243. goto fail0;
  244. }
  245. // starting with empty buffer
  246. o->length = 0;
  247. while (1) {
  248. // read
  249. size_t readed = fread(o->data + o->length, 1, capacity - o->length, open_inst->fh);
  250. if (readed == 0) {
  251. break;
  252. }
  253. ASSERT(readed <= capacity - o->length)
  254. // increment length
  255. o->length += readed;
  256. if (o->length == capacity) {
  257. // do not reallocate beyond limit
  258. if (capacity > MAX_READ_SIZE / 2) {
  259. break;
  260. }
  261. // reallocate buffer
  262. capacity *= 2;
  263. char *new_data = BRealloc(o->data, capacity);
  264. if (!new_data) {
  265. ModuleLog(o->i, BLOG_ERROR, "BRealloc failed");
  266. goto fail1;
  267. }
  268. o->data = new_data;
  269. }
  270. }
  271. if (o->length == 0) {
  272. // free buffer
  273. BFree(o->data);
  274. o->data = NULL;
  275. // if we couldn't read anything due to an error, trigger
  276. // error in the open instance, and don't go up
  277. if (!feof(open_inst->fh)) {
  278. ModuleLog(o->i, BLOG_ERROR, "fread failed");
  279. trigger_error(open_inst);
  280. return;
  281. }
  282. }
  283. // go up
  284. NCDModuleInst_Backend_Up(i);
  285. return;
  286. fail1:
  287. BFree(o->data);
  288. fail0:
  289. NCDModuleInst_Backend_SetError(i);
  290. NCDModuleInst_Backend_Dead(i);
  291. }
  292. static void read_func_die (void *vo)
  293. {
  294. struct read_instance *o = vo;
  295. // free buffer
  296. if (o->data) {
  297. BFree(o->data);
  298. }
  299. NCDModuleInst_Backend_Dead(o->i);
  300. }
  301. static int read_func_getvar (void *vo, NCD_string_id_t name, NCDValMem *mem, NCDValRef *out)
  302. {
  303. struct read_instance *o = vo;
  304. if (name == NCD_STRING_EMPTY) {
  305. const char *data = (!o->data ? "" : o->data);
  306. *out = NCDVal_NewStringBin(mem, (const uint8_t *)data, o->length);
  307. if (NCDVal_IsInvalid(*out)) {
  308. ModuleLog(o->i, BLOG_ERROR, "NCDVal_NewStringBin failed");
  309. }
  310. return 1;
  311. }
  312. if (name == strings[STRING_NOT_EOF].id) {
  313. *out = ncd_make_boolean(mem, (o->length != 0), o->i->params->iparams->string_index);
  314. if (NCDVal_IsInvalid(*out)) {
  315. ModuleLog(o->i, BLOG_ERROR, "ncd_make_boolean failed");
  316. }
  317. return 1;
  318. }
  319. return 0;
  320. }
  321. static void write_func_new (void *unused, NCDModuleInst *i, const struct NCDModuleInst_new_params *params)
  322. {
  323. // check arguments
  324. NCDValRef data_arg;
  325. if (!NCDVal_ListRead(params->args, 1, &data_arg)) {
  326. ModuleLog(i, BLOG_ERROR, "wrong arity");
  327. goto fail0;
  328. }
  329. if (!NCDVal_IsString(data_arg)) {
  330. ModuleLog(i, BLOG_ERROR, "wrong type");
  331. goto fail0;
  332. }
  333. // get open instance
  334. struct open_instance *open_inst = NCDModuleInst_Backend_GetUser((NCDModuleInst *)params->method_user);
  335. // make sure it's not in error
  336. if (!open_inst->fh) {
  337. ModuleLog(i, BLOG_ERROR, "open instance is in error");
  338. goto fail0;
  339. }
  340. // get data pointer and length
  341. const char *data = NCDVal_StringValue(data_arg);
  342. size_t length = NCDVal_StringLength(data_arg);
  343. while (length > 0) {
  344. // write
  345. size_t written = fwrite(data, 1, length, open_inst->fh);
  346. if (written == 0) {
  347. ModuleLog(i, BLOG_ERROR, "fwrite failed");
  348. trigger_error(open_inst);
  349. return;
  350. }
  351. ASSERT(written <= length)
  352. // update writing state
  353. data += written;
  354. length -= written;
  355. }
  356. // go up
  357. NCDModuleInst_Backend_Up(i);
  358. return;
  359. fail0:
  360. NCDModuleInst_Backend_SetError(i);
  361. NCDModuleInst_Backend_Dead(i);
  362. }
  363. static void seek_func_new (void *unused, NCDModuleInst *i, const struct NCDModuleInst_new_params *params)
  364. {
  365. // check arguments
  366. NCDValRef position_arg;
  367. NCDValRef whence_arg;
  368. if (!NCDVal_ListRead(params->args, 2, &position_arg, &whence_arg)) {
  369. ModuleLog(i, BLOG_ERROR, "wrong arity");
  370. goto fail0;
  371. }
  372. if (!NCDVal_IsString(position_arg) || !NCDVal_IsString(whence_arg)) {
  373. ModuleLog(i, BLOG_ERROR, "wrong type");
  374. goto fail0;
  375. }
  376. // parse position
  377. int position_sign;
  378. uintmax_t position_mag;
  379. if (!parse_signmag_integer_bin(NCDVal_StringValue(position_arg), NCDVal_StringLength(position_arg), &position_sign, &position_mag)) {
  380. ModuleLog(i, BLOG_ERROR, "wrong position");
  381. goto fail0;
  382. }
  383. // parse whence
  384. int whence;
  385. if (NCDVal_StringEquals(whence_arg, "set")) {
  386. whence = SEEK_SET;
  387. }
  388. else if (NCDVal_StringEquals(whence_arg, "cur")) {
  389. whence = SEEK_CUR;
  390. }
  391. else if (NCDVal_StringEquals(whence_arg, "end")) {
  392. whence = SEEK_END;
  393. }
  394. else {
  395. ModuleLog(i, BLOG_ERROR, "wrong whence");
  396. goto fail0;
  397. }
  398. // determine min/max values of off_t (non-portable hack)
  399. off_t off_t_min = (sizeof(off_t) == 8 ? INT64_MIN : INT32_MIN);
  400. off_t off_t_max = (sizeof(off_t) == 8 ? INT64_MAX : INT32_MAX);
  401. // compute position as off_t
  402. off_t position;
  403. if (position_sign < 0 && position_mag > 0) {
  404. if (position_mag - 1 > -(off_t_min + 1)) {
  405. ModuleLog(i, BLOG_ERROR, "position underflow");
  406. goto fail0;
  407. }
  408. position = -(off_t)(position_mag - 1) - 1;
  409. } else {
  410. if (position_mag > off_t_max) {
  411. ModuleLog(i, BLOG_ERROR, "position overflow");
  412. goto fail0;
  413. }
  414. position = position_mag;
  415. }
  416. // get open instance
  417. struct open_instance *open_inst = NCDModuleInst_Backend_GetUser((NCDModuleInst *)params->method_user);
  418. // make sure it's not in error
  419. if (!open_inst->fh) {
  420. ModuleLog(i, BLOG_ERROR, "open instance is in error");
  421. goto fail0;
  422. }
  423. // seek
  424. if (fseeko(open_inst->fh, position, whence) < 0) {
  425. ModuleLog(i, BLOG_ERROR, "fseeko failed");
  426. trigger_error(open_inst);
  427. return;
  428. }
  429. // go up
  430. NCDModuleInst_Backend_Up(i);
  431. return;
  432. fail0:
  433. NCDModuleInst_Backend_SetError(i);
  434. NCDModuleInst_Backend_Dead(i);
  435. }
  436. static void close_func_new (void *unused, NCDModuleInst *i, const struct NCDModuleInst_new_params *params)
  437. {
  438. // check arguments
  439. if (!NCDVal_ListRead(params->args, 0)) {
  440. ModuleLog(i, BLOG_ERROR, "wrong arity");
  441. goto fail0;
  442. }
  443. // get open instance
  444. struct open_instance *open_inst = NCDModuleInst_Backend_GetUser((NCDModuleInst *)params->method_user);
  445. // make sure it's not in error
  446. if (!open_inst->fh) {
  447. ModuleLog(i, BLOG_ERROR, "open instance is in error");
  448. goto fail0;
  449. }
  450. // close
  451. int res = fclose(open_inst->fh);
  452. open_inst->fh = NULL;
  453. if (res != 0) {
  454. ModuleLog(i, BLOG_ERROR, "fclose failed");
  455. trigger_error(open_inst);
  456. return;
  457. }
  458. // go up
  459. NCDModuleInst_Backend_Up(i);
  460. return;
  461. fail0:
  462. NCDModuleInst_Backend_SetError(i);
  463. NCDModuleInst_Backend_Dead(i);
  464. }
  465. static struct NCDModule modules[] = {
  466. {
  467. .type = "file_open",
  468. .func_new2 = open_func_new,
  469. .func_die = open_func_die,
  470. .func_getvar2 = open_func_getvar,
  471. .alloc_size = sizeof(struct open_instance)
  472. }, {
  473. .type = "file_open::read",
  474. .func_new2 = read_func_new,
  475. .func_die = read_func_die,
  476. .func_getvar2 = read_func_getvar,
  477. .alloc_size = sizeof(struct read_instance)
  478. }, {
  479. .type = "file_open::write",
  480. .func_new2 = write_func_new,
  481. }, {
  482. .type = "file_open::seek",
  483. .func_new2 = seek_func_new,
  484. }, {
  485. .type = "file_open::close",
  486. .func_new2 = close_func_new,
  487. }, {
  488. .type = NULL
  489. }
  490. };
  491. const struct NCDModuleGroup ncdmodule_file_open = {
  492. .modules = modules,
  493. .strings = strings
  494. };