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