file_open.c 15 KB

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