session_file.c 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505
  1. /*
  2. * This file is part of the libsigrok project.
  3. *
  4. * Copyright (C) 2013 Bert Vermeulen <bert@biot.com>
  5. *
  6. * This program is free software: you can redistribute it and/or modify
  7. * it under the terms of the GNU General Public License as published by
  8. * the Free Software Foundation, either version 3 of the License, or
  9. * (at your option) any later version.
  10. *
  11. * This program is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. * GNU General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU General Public License
  17. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  18. */
  19. #include <string.h>
  20. #include <stdlib.h>
  21. #include <unistd.h>
  22. #include <zip.h>
  23. #include <sys/types.h>
  24. #include <sys/stat.h>
  25. #include <errno.h>
  26. #include <glib.h>
  27. #include <glib/gstdio.h>
  28. #include "config.h" /* Needed for PACKAGE_VERSION and others. */
  29. #include "libsigrok.h"
  30. #include "libsigrok-internal.h"
  31. /** @cond PRIVATE */
  32. #define LOG_PREFIX "session-file"
  33. /** @endcond */
  34. /**
  35. * @file
  36. *
  37. * Loading and saving libsigrok session files.
  38. */
  39. /**
  40. * @addtogroup grp_session
  41. *
  42. * @{
  43. */
  44. extern struct sr_session *session;
  45. extern SR_PRIV struct sr_dev_driver session_driver;
  46. /** @private */
  47. SR_PRIV int sr_sessionfile_check(const char *filename)
  48. {
  49. struct stat st;
  50. struct zip *archive;
  51. struct zip_file *zf;
  52. struct zip_stat zs;
  53. int version, ret;
  54. char s[11];
  55. if (!filename)
  56. return SR_ERR_ARG;
  57. if (stat(filename, &st) == -1) {
  58. sr_err("Couldn't stat %s: %s", filename, strerror(errno));
  59. return SR_ERR;
  60. }
  61. if (!(archive = zip_open(filename, 0, &ret)))
  62. /* No logging: this can be used just to check if it's
  63. * a sigrok session file or not. */
  64. return SR_ERR;
  65. /* check "version" */
  66. version = 0;
  67. if (!(zf = zip_fopen(archive, "version", 0))) {
  68. sr_dbg("Not a sigrok session file: no version found.");
  69. return SR_ERR;
  70. }
  71. if ((ret = zip_fread(zf, s, 10)) == -1)
  72. return SR_ERR;
  73. zip_fclose(zf);
  74. s[ret] = 0;
  75. version = strtoull(s, NULL, 10);
  76. if (version > 2) {
  77. sr_dbg("Cannot handle sigrok session file version %d.", version);
  78. return SR_ERR;
  79. }
  80. sr_spew("Detected sigrok session file version %d.", version);
  81. /* read "metadata" */
  82. if (zip_stat(archive, "metadata", 0, &zs) == -1) {
  83. sr_dbg("Not a valid sigrok session file.");
  84. return SR_ERR;
  85. }
  86. return SR_OK;
  87. }
  88. /**
  89. * Load the session from the specified filename.
  90. *
  91. * @param filename The name of the session file to load. Must not be NULL.
  92. *
  93. * @return SR_OK upon success, SR_ERR_ARG upon invalid arguments,
  94. * SR_ERR_MALLOC upon memory allocation errors, or SR_ERR upon
  95. * other errors.
  96. */
  97. SR_API int sr_session_load(const char *filename)
  98. {
  99. GKeyFile *kf;
  100. GPtrArray *capturefiles;
  101. struct zip *archive;
  102. struct zip_file *zf;
  103. struct zip_stat zs;
  104. struct sr_dev_inst *sdi;
  105. struct sr_channel *ch;
  106. int ret, channelnum, devcnt, i, j;
  107. uint64_t tmp_u64, total_channels, enabled_channels, p;
  108. char **sections, **keys, *metafile, *val;
  109. char channelname[SR_MAX_CHANNELNAME_LEN + 1];
  110. if ((ret = sr_sessionfile_check(filename)) != SR_OK)
  111. return ret;
  112. if (!(archive = zip_open(filename, 0, &ret)))
  113. return SR_ERR;
  114. if (zip_stat(archive, "metadata", 0, &zs) == -1)
  115. return SR_ERR;
  116. if (!(metafile = g_try_malloc(zs.size))) {
  117. sr_err("%s: metafile malloc failed", __func__);
  118. return SR_ERR_MALLOC;
  119. }
  120. zf = zip_fopen_index(archive, zs.index, 0);
  121. zip_fread(zf, metafile, zs.size);
  122. zip_fclose(zf);
  123. kf = g_key_file_new();
  124. if (!g_key_file_load_from_data(kf, metafile, zs.size, 0, NULL)) {
  125. sr_dbg("Failed to parse metadata.");
  126. return SR_ERR;
  127. }
  128. sr_session_new();
  129. devcnt = 0;
  130. capturefiles = g_ptr_array_new_with_free_func(g_free);
  131. sections = g_key_file_get_groups(kf, NULL);
  132. for (i = 0; sections[i]; i++) {
  133. if (!strcmp(sections[i], "global"))
  134. /* nothing really interesting in here yet */
  135. continue;
  136. if (!strncmp(sections[i], "device ", 7)) {
  137. /* device section */
  138. sdi = NULL;
  139. enabled_channels = total_channels = 0;
  140. keys = g_key_file_get_keys(kf, sections[i], NULL, NULL);
  141. for (j = 0; keys[j]; j++) {
  142. val = g_key_file_get_string(kf, sections[i], keys[j], NULL);
  143. if (!strcmp(keys[j], "capturefile")) {
  144. sdi = sr_dev_inst_new(devcnt, SR_ST_ACTIVE, NULL, NULL, NULL);
  145. sdi->driver = &session_driver;
  146. if (devcnt == 0)
  147. /* first device, init the driver */
  148. sdi->driver->init(NULL);
  149. sr_dev_open(sdi);
  150. sr_session_dev_add(sdi);
  151. sdi->driver->config_set(SR_CONF_SESSIONFILE,
  152. g_variant_new_string(filename), sdi, NULL);
  153. sdi->driver->config_set(SR_CONF_CAPTUREFILE,
  154. g_variant_new_string(val), sdi, NULL);
  155. g_ptr_array_add(capturefiles, val);
  156. } else if (!strcmp(keys[j], "samplerate")) {
  157. sr_parse_sizestring(val, &tmp_u64);
  158. sdi->driver->config_set(SR_CONF_SAMPLERATE,
  159. g_variant_new_uint64(tmp_u64), sdi, NULL);
  160. } else if (!strcmp(keys[j], "unitsize")) {
  161. tmp_u64 = strtoull(val, NULL, 10);
  162. sdi->driver->config_set(SR_CONF_CAPTURE_UNITSIZE,
  163. g_variant_new_uint64(tmp_u64), sdi, NULL);
  164. } else if (!strcmp(keys[j], "total probes")) {
  165. total_channels = strtoull(val, NULL, 10);
  166. sdi->driver->config_set(SR_CONF_NUM_LOGIC_CHANNELS,
  167. g_variant_new_uint64(total_channels), sdi, NULL);
  168. for (p = 0; p < total_channels; p++) {
  169. snprintf(channelname, SR_MAX_CHANNELNAME_LEN, "%" PRIu64, p);
  170. if (!(ch = sr_channel_new(p, SR_CHANNEL_LOGIC, TRUE,
  171. channelname)))
  172. return SR_ERR;
  173. sdi->channels = g_slist_append(sdi->channels, ch);
  174. }
  175. } else if (!strncmp(keys[j], "probe", 5)) {
  176. if (!sdi)
  177. continue;
  178. enabled_channels++;
  179. tmp_u64 = strtoul(keys[j]+5, NULL, 10);
  180. /* sr_session_save() */
  181. sr_dev_channel_name_set(sdi, tmp_u64 - 1, val);
  182. } else if (!strncmp(keys[j], "trigger", 7)) {
  183. channelnum = strtoul(keys[j]+7, NULL, 10);
  184. sr_dev_trigger_set(sdi, channelnum, val);
  185. }
  186. }
  187. g_strfreev(keys);
  188. /* Disable channels not specifically listed. */
  189. if (total_channels)
  190. for (p = enabled_channels; p < total_channels; p++)
  191. sr_dev_channel_enable(sdi, p, FALSE);
  192. }
  193. devcnt++;
  194. }
  195. g_strfreev(sections);
  196. g_key_file_free(kf);
  197. return SR_OK;
  198. }
  199. /**
  200. * Save the current session to the specified file.
  201. *
  202. * @param filename The name of the filename to save the current session as.
  203. * Must not be NULL.
  204. * @param sdi The device instance from which the data was captured.
  205. * @param buf The data to be saved.
  206. * @param unitsize The number of bytes per sample.
  207. * @param units The number of samples.
  208. *
  209. * @retval SR_OK Success
  210. * @retval SR_ERR_ARG Invalid arguments
  211. * @retval SR_ERR Other errors
  212. *
  213. * @since 0.2.0
  214. */
  215. SR_API int sr_session_save(const char *filename, const struct sr_dev_inst *sdi,
  216. unsigned char *buf, int unitsize, int units)
  217. {
  218. struct sr_channel *ch;
  219. GSList *l;
  220. GVariant *gvar;
  221. uint64_t samplerate;
  222. int cnt, ret;
  223. char **channel_names;
  224. samplerate = 0;
  225. if (sr_dev_has_option(sdi, SR_CONF_SAMPLERATE)) {
  226. if (sr_config_get(sdi->driver, sdi, NULL,
  227. SR_CONF_SAMPLERATE, &gvar) == SR_OK) {
  228. samplerate = g_variant_get_uint64(gvar);
  229. g_variant_unref(gvar);
  230. }
  231. }
  232. channel_names = g_malloc0(sizeof(char *) * (g_slist_length(sdi->channels) + 1));
  233. cnt = 0;
  234. for (l = sdi->channels; l; l = l->next) {
  235. ch = l->data;
  236. if (ch->type != SR_CHANNEL_LOGIC)
  237. continue;
  238. if (ch->enabled != TRUE)
  239. continue;
  240. if (!ch->name)
  241. continue;
  242. /* Just borrowing the ptr. */
  243. channel_names[cnt++] = ch->name;
  244. }
  245. if ((ret = sr_session_save_init(filename, samplerate, channel_names)) != SR_OK)
  246. return ret;
  247. ret = sr_session_append(filename, buf, unitsize, units);
  248. return ret;
  249. }
  250. /**
  251. * Initialize a saved session file.
  252. *
  253. * @param filename The name of the filename to save the current session as.
  254. * Must not be NULL.
  255. * @param samplerate The samplerate to store for this session.
  256. * @param channels A NULL-terminated array of strings containing the names
  257. * of all the channels active in this session.
  258. *
  259. * @retval SR_OK Success
  260. * @retval SR_ERR_ARG Invalid arguments
  261. * @retval SR_ERR Other errors
  262. *
  263. * @since 0.3.0
  264. */
  265. SR_API int sr_session_save_init(const char *filename, uint64_t samplerate,
  266. char **channels)
  267. {
  268. FILE *meta;
  269. struct zip *zipfile;
  270. struct zip_source *versrc, *metasrc;
  271. int tmpfile, cnt, ret, i;
  272. char version[1], metafile[32], *s;
  273. if (!filename) {
  274. sr_err("%s: filename was NULL", __func__);
  275. return SR_ERR_ARG;
  276. }
  277. /* Quietly delete it first, libzip wants replace ops otherwise. */
  278. unlink(filename);
  279. if (!(zipfile = zip_open(filename, ZIP_CREATE, &ret)))
  280. return SR_ERR;
  281. /* "version" */
  282. version[0] = '2';
  283. if (!(versrc = zip_source_buffer(zipfile, version, 1, 0)))
  284. return SR_ERR;
  285. if (zip_add(zipfile, "version", versrc) == -1) {
  286. sr_info("error saving version into zipfile: %s",
  287. zip_strerror(zipfile));
  288. return SR_ERR;
  289. }
  290. /* init "metadata" */
  291. strcpy(metafile, "sigrok-meta-XXXXXX");
  292. if ((tmpfile = g_mkstemp(metafile)) == -1)
  293. return SR_ERR;
  294. close(tmpfile);
  295. meta = g_fopen(metafile, "wb");
  296. fprintf(meta, "[global]\n");
  297. fprintf(meta, "sigrok version = %s\n", PACKAGE_VERSION);
  298. /* metadata */
  299. fprintf(meta, "[device 1]\n");
  300. /* metadata */
  301. fprintf(meta, "capturefile = logic-1\n");
  302. cnt = 0;
  303. for (i = 0; channels[i]; i++)
  304. cnt++;
  305. fprintf(meta, "total probes = %d\n", cnt);
  306. s = sr_samplerate_string(samplerate);
  307. fprintf(meta, "samplerate = %s\n", s);
  308. g_free(s);
  309. for (i = 0; channels[i]; i++)
  310. fprintf(meta, "probe%d = %s\n", i + 1, channels[i]);
  311. fclose(meta);
  312. if (!(metasrc = zip_source_file(zipfile, metafile, 0, -1))) {
  313. unlink(metafile);
  314. return SR_ERR;
  315. }
  316. if (zip_add(zipfile, "metadata", metasrc) == -1) {
  317. unlink(metafile);
  318. return SR_ERR;
  319. }
  320. if ((ret = zip_close(zipfile)) == -1) {
  321. sr_info("error saving zipfile: %s", zip_strerror(zipfile));
  322. unlink(metafile);
  323. return SR_ERR;
  324. }
  325. unlink(metafile);
  326. return SR_OK;
  327. }
  328. /**
  329. * Append data to an existing session file.
  330. *
  331. * The session file must have been created with sr_session_save_init()
  332. * or sr_session_save() beforehand.
  333. *
  334. * @param filename The name of the filename to append to. Must not be NULL.
  335. * @param buf The data to be appended.
  336. * @param unitsize The number of bytes per sample.
  337. * @param units The number of samples.
  338. *
  339. * @retval SR_OK Success
  340. * @retval SR_ERR_ARG Invalid arguments
  341. * @retval SR_ERR Other errors
  342. *
  343. * @since 0.3.0
  344. */
  345. SR_API int sr_session_append(const char *filename, unsigned char *buf,
  346. int unitsize, int units)
  347. {
  348. struct zip *archive;
  349. struct zip_source *logicsrc;
  350. zip_int64_t num_files;
  351. struct zip_file *zf;
  352. struct zip_stat zs;
  353. struct zip_source *metasrc;
  354. GKeyFile *kf;
  355. GError *error;
  356. gsize len;
  357. int chunk_num, next_chunk_num, tmpfile, ret, i;
  358. const char *entry_name;
  359. char *metafile, tmpname[32], chunkname[16];
  360. if ((ret = sr_sessionfile_check(filename)) != SR_OK)
  361. return ret;
  362. if (!(archive = zip_open(filename, 0, &ret)))
  363. return SR_ERR;
  364. if (zip_stat(archive, "metadata", 0, &zs) == -1)
  365. return SR_ERR;
  366. metafile = g_malloc(zs.size);
  367. zf = zip_fopen_index(archive, zs.index, 0);
  368. zip_fread(zf, metafile, zs.size);
  369. zip_fclose(zf);
  370. /*
  371. * If the file was only initialized but doesn't yet have any
  372. * data it in, it won't have a unitsize field in metadata yet.
  373. */
  374. error = NULL;
  375. kf = g_key_file_new();
  376. if (!g_key_file_load_from_data(kf, metafile, zs.size, 0, &error)) {
  377. sr_err("Failed to parse metadata: %s.", error->message);
  378. return SR_ERR;
  379. }
  380. g_free(metafile);
  381. tmpname[0] = '\0';
  382. if (!g_key_file_has_key(kf, "device 1", "unitsize", &error)) {
  383. if (error && error->code != G_KEY_FILE_ERROR_KEY_NOT_FOUND) {
  384. sr_err("Failed to check unitsize key: %s", error ? error->message : "?");
  385. return SR_ERR;
  386. }
  387. /* Add unitsize field. */
  388. g_key_file_set_integer(kf, "device 1", "unitsize", unitsize);
  389. metafile = g_key_file_to_data(kf, &len, &error);
  390. strcpy(tmpname, "sigrok-meta-XXXXXX");
  391. if ((tmpfile = g_mkstemp(tmpname)) == -1)
  392. return SR_ERR;
  393. if (write(tmpfile, metafile, len) < 0) {
  394. sr_dbg("Failed to create new metadata: %s", strerror(errno));
  395. g_free(metafile);
  396. unlink(tmpname);
  397. return SR_ERR;
  398. }
  399. close(tmpfile);
  400. if (!(metasrc = zip_source_file(archive, tmpname, 0, -1))) {
  401. sr_err("Failed to create zip source for metadata.");
  402. g_free(metafile);
  403. unlink(tmpname);
  404. return SR_ERR;
  405. }
  406. if (zip_replace(archive, zs.index, metasrc) == -1) {
  407. sr_err("Failed to replace metadata file.");
  408. g_free(metafile);
  409. unlink(tmpname);
  410. return SR_ERR;
  411. }
  412. g_free(metafile);
  413. }
  414. g_key_file_free(kf);
  415. next_chunk_num = 1;
  416. num_files = zip_get_num_entries(archive, 0);
  417. for (i = 0; i < num_files; i++) {
  418. entry_name = zip_get_name(archive, i, 0);
  419. if (strncmp(entry_name, "logic-1", 7))
  420. continue;
  421. if (strlen(entry_name) == 7) {
  422. /* This file has no extra chunks, just a single "logic-1".
  423. * Rename it to "logic-1-1" * and continue with chunk 2. */
  424. if (zip_rename(archive, i, "logic-1-1") == -1) {
  425. sr_err("Failed to rename 'logic-1' to 'logic-1-1'.");
  426. unlink(tmpname);
  427. return SR_ERR;
  428. }
  429. next_chunk_num = 2;
  430. break;
  431. } else if (strlen(entry_name) > 8 && entry_name[7] == '-') {
  432. chunk_num = strtoull(entry_name + 8, NULL, 10);
  433. if (chunk_num >= next_chunk_num)
  434. next_chunk_num = chunk_num + 1;
  435. }
  436. }
  437. snprintf(chunkname, 15, "logic-1-%d", next_chunk_num);
  438. if (!(logicsrc = zip_source_buffer(archive, buf, units * unitsize, FALSE))) {
  439. unlink(tmpname);
  440. return SR_ERR;
  441. }
  442. if (zip_add(archive, chunkname, logicsrc) == -1) {
  443. unlink(tmpname);
  444. return SR_ERR;
  445. }
  446. if ((ret = zip_close(archive)) == -1) {
  447. sr_info("error saving session file: %s", zip_strerror(archive));
  448. unlink(tmpname);
  449. return SR_ERR;
  450. }
  451. unlink(tmpname);
  452. return SR_OK;
  453. }
  454. /** @} */