]> sigrok.org Git - libsigrok.git/blob - src/resource.c
output/csv: use intermediate time_t var, silence compiler warning
[libsigrok.git] / src / resource.c
1 /*
2  * This file is part of the libsigrok project.
3  *
4  * Copyright (C) 2015 Daniel Elstner <daniel.kitta@gmail.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 <config.h>
21 #include <errno.h>
22 #include <stdio.h>
23 #include <glib.h>
24 #include <glib/gstdio.h>
25 #include <libsigrok/libsigrok.h>
26 #include "libsigrok-internal.h"
27
28 /** @cond PRIVATE */
29 #define LOG_PREFIX "resource"
30 /** @endcond */
31
32 /**
33  * @file
34  *
35  * Access to resource files.
36  */
37
38 /**
39  * Get a list of paths where we look for resource (e.g. firmware) files.
40  *
41  * @param res_type The type of resource to get the search paths for.
42  *
43  * @return List of strings that must be freed after use, including the strings.
44  *
45  * @since 0.6.0
46  */
47 SR_API GSList *sr_resourcepaths_get(int res_type)
48 {
49         const char *subdir = NULL;
50         GSList *l = NULL;
51         const char *env;
52         const char *const *datadirs;
53
54         if (res_type == SR_RESOURCE_FIRMWARE) {
55                 subdir = "sigrok-firmware";
56
57                 env = g_getenv("SIGROK_FIRMWARE_DIR");
58                 if (env)
59                         l = g_slist_append(l, g_strdup(env));
60
61                 env = g_getenv("SIGROK_FIRMWARE_PATH");
62                 if (env) {
63                         char **dir_list, **dir_iter, *dir_item;
64                         dir_list = g_strsplit(env, G_SEARCHPATH_SEPARATOR_S, 0);
65                         for (dir_iter = dir_list; *dir_iter; dir_iter++) {
66                                 dir_item = *dir_iter;
67                                 if (!dir_item || !*dir_item)
68                                         continue;
69                                 l = g_slist_append(l, g_strdup(dir_item));
70                         }
71                         g_strfreev(dir_list);
72                 }
73         }
74
75         l = g_slist_append(l, g_build_filename(g_get_user_data_dir(), subdir, NULL));
76
77 #ifdef FIRMWARE_DIR
78         if (res_type == SR_RESOURCE_FIRMWARE) {
79                 /*
80                  * Scan the hard-coded directory before the system directories to
81                  * avoid picking up possibly outdated files from a system install.
82                  */
83                 l = g_slist_append(l, g_strdup(FIRMWARE_DIR));
84         }
85 #endif
86
87         datadirs = g_get_system_data_dirs();
88         while (*datadirs)
89                 l = g_slist_append(l, g_build_filename(*datadirs++, subdir, NULL));
90
91         return l;
92 }
93
94 /**
95  * Retrieve the size of the open stream @a file.
96  *
97  * This function only works on seekable streams. However, the set of seekable
98  * streams is generally congruent with the set of streams that have a size.
99  * Code that needs to work with any type of stream (including pipes) should
100  * require neither seekability nor advance knowledge of the size.
101  * On failure, the return value is negative and errno is set.
102  *
103  * @param file An I/O stream opened in binary mode.
104  * @return The size of @a file in bytes, or a negative value on failure.
105  *
106  * @private
107  */
108 SR_PRIV int64_t sr_file_get_size(FILE *file)
109 {
110         off_t filepos, filesize;
111
112         /* ftello() and fseeko() are not standard C, but part of POSIX.1-2001.
113          * Thus, if these functions are available at all, they can reasonably
114          * be expected to also conform to POSIX semantics. In particular, this
115          * means that ftello() after fseeko(..., SEEK_END) has a defined result
116          * and can be used to get the size of a seekable stream.
117          * On Windows, the result is fully defined only for binary streams.
118          */
119         filepos = ftello(file);
120         if (filepos < 0)
121                 return -1;
122
123         if (fseeko(file, 0, SEEK_END) < 0)
124                 return -1;
125
126         filesize = ftello(file);
127         if (filesize < 0)
128                 return -1;
129
130         if (fseeko(file, filepos, SEEK_SET) < 0)
131                 return -1;
132
133         return filesize;
134 }
135
136 static FILE *try_open_file(const char *datadir, const char *subdir,
137                 const char *name)
138 {
139         char *filename;
140         FILE *file;
141
142         if (subdir)
143                 filename = g_build_filename(datadir, subdir, name, NULL);
144         else
145                 filename = g_build_filename(datadir, name, NULL);
146
147         file = g_fopen(filename, "rb");
148
149         if (file)
150                 sr_info("Opened '%s'.", filename);
151         else
152                 sr_spew("Attempt to open '%s' failed: %s",
153                         filename, g_strerror(errno));
154         g_free(filename);
155
156         return file;
157 }
158
159 static int resource_open_default(struct sr_resource *res,
160                 const char *name, void *cb_data)
161 {
162         GSList *paths, *p = NULL;
163         int64_t filesize;
164         FILE *file = NULL;
165
166         (void)cb_data;
167
168         paths = sr_resourcepaths_get(res->type);
169
170         /* Currently, the enum only defines SR_RESOURCE_FIRMWARE. */
171         if (res->type != SR_RESOURCE_FIRMWARE) {
172                 sr_err("%s: unknown type %d.", __func__, res->type);
173                 return SR_ERR_ARG;
174         }
175
176         p = paths;
177         while (p && !file) {
178                 file = try_open_file((const char *)(p->data), NULL, name);
179                 p = p->next;
180         }
181         g_slist_free_full(paths, g_free);
182
183         if (!file) {
184                 sr_dbg("Failed to locate '%s'.", name);
185                 return SR_ERR;
186         }
187
188         filesize = sr_file_get_size(file);
189         if (filesize < 0) {
190                 sr_err("Failed to obtain size of '%s': %s",
191                         name, g_strerror(errno));
192                 fclose(file);
193                 return SR_ERR;
194         }
195         res->size = filesize;
196         res->handle = file;
197
198         return SR_OK;
199 }
200
201 static int resource_close_default(struct sr_resource *res, void *cb_data)
202 {
203         FILE *file;
204
205         (void)cb_data;
206
207         file = res->handle;
208         if (!file) {
209                 sr_err("%s: invalid handle.", __func__);
210                 return SR_ERR_ARG;
211         }
212
213         if (fclose(file) < 0) {
214                 sr_err("Failed to close file: %s", g_strerror(errno));
215                 return SR_ERR;
216         }
217         res->handle = NULL;
218
219         return SR_OK;
220 }
221
222 static gssize resource_read_default(const struct sr_resource *res,
223                 void *buf, size_t count, void *cb_data)
224 {
225         FILE *file;
226         size_t n_read;
227
228         (void)cb_data;
229
230         file = res->handle;
231         if (!file) {
232                 sr_err("%s: invalid handle.", __func__);
233                 return SR_ERR_ARG;
234         }
235         if (count > G_MAXSSIZE) {
236                 sr_err("%s: count %zu too large.", __func__, count);
237                 return SR_ERR_ARG;
238         }
239
240         n_read = fread(buf, 1, count, file);
241
242         if (n_read != count && ferror(file)) {
243                 sr_err("Failed to read resource file: %s", g_strerror(errno));
244                 return SR_ERR;
245         }
246         return n_read;
247 }
248
249 /**
250  * Install resource access hooks.
251  *
252  * @param ctx libsigrok context. Must not be NULL.
253  * @param open_cb Resource open callback, or NULL to unset.
254  * @param close_cb Resource close callback, or NULL to unset.
255  * @param read_cb Resource read callback, or NULL to unset.
256  * @param cb_data User data pointer passed to callbacks.
257  *
258  * @retval SR_OK Success.
259  * @retval SR_ERR_ARG Invalid argument.
260  *
261  * @since 0.4.0
262  */
263 SR_API int sr_resource_set_hooks(struct sr_context *ctx,
264                 sr_resource_open_callback open_cb,
265                 sr_resource_close_callback close_cb,
266                 sr_resource_read_callback read_cb, void *cb_data)
267 {
268         if (!ctx) {
269                 sr_err("%s: ctx was NULL.", __func__);
270                 return SR_ERR_ARG;
271         }
272         if (open_cb && close_cb && read_cb) {
273                 ctx->resource_open_cb = open_cb;
274                 ctx->resource_close_cb = close_cb;
275                 ctx->resource_read_cb = read_cb;
276                 ctx->resource_cb_data = cb_data;
277         } else if (!open_cb && !close_cb && !read_cb) {
278                 ctx->resource_open_cb = &resource_open_default;
279                 ctx->resource_close_cb = &resource_close_default;
280                 ctx->resource_read_cb = &resource_read_default;
281                 ctx->resource_cb_data = ctx;
282         } else {
283                 sr_err("%s: inconsistent callback pointers.", __func__);
284                 return SR_ERR_ARG;
285         }
286         return SR_OK;
287 }
288
289 /**
290  * Open resource.
291  *
292  * @param ctx libsigrok context. Must not be NULL.
293  * @param[out] res Resource descriptor to fill in. Must not be NULL.
294  * @param type Resource type ID.
295  * @param name Name of the resource. Must not be NULL.
296  *
297  * @retval SR_OK Success.
298  * @retval SR_ERR_ARG Invalid argument.
299  * @retval SR_ERR Other error.
300  *
301  * @private
302  */
303 SR_PRIV int sr_resource_open(struct sr_context *ctx,
304                 struct sr_resource *res, int type, const char *name)
305 {
306         int ret;
307
308         res->size = 0;
309         res->handle = NULL;
310         res->type = type;
311
312         ret = (*ctx->resource_open_cb)(res, name, ctx->resource_cb_data);
313
314         if (ret != SR_OK)
315                 sr_err("Failed to open resource '%s' (use loglevel 5/spew for"
316                        " details).", name);
317
318         return ret;
319 }
320
321 /**
322  * Close resource.
323  *
324  * @param ctx libsigrok context. Must not be NULL.
325  * @param[inout] res Resource descriptor. Must not be NULL.
326  *
327  * @retval SR_OK Success.
328  * @retval SR_ERR_ARG Invalid argument.
329  * @retval SR_ERR Other error.
330  *
331  * @private
332  */
333 SR_PRIV int sr_resource_close(struct sr_context *ctx, struct sr_resource *res)
334 {
335         int ret;
336
337         ret = (*ctx->resource_close_cb)(res, ctx->resource_cb_data);
338
339         if (ret != SR_OK)
340                 sr_err("Failed to close resource.");
341
342         return ret;
343 }
344
345 /**
346  * Read resource data.
347  *
348  * @param ctx libsigrok context. Must not be NULL.
349  * @param[in] res Resource descriptor. Must not be NULL.
350  * @param[out] buf Buffer to store @a count bytes into. Must not be NULL.
351  * @param count Number of bytes to read.
352  *
353  * @return The number of bytes actually read, or a negative value on error.
354  * @retval SR_ERR_ARG Invalid argument.
355  * @retval SR_ERR Other error.
356  *
357  * @private
358  */
359 SR_PRIV gssize sr_resource_read(struct sr_context *ctx,
360                 const struct sr_resource *res, void *buf, size_t count)
361 {
362         gssize n_read;
363
364         n_read = (*ctx->resource_read_cb)(res, buf, count,
365                         ctx->resource_cb_data);
366         if (n_read < 0)
367                 sr_err("Failed to read resource.");
368
369         return n_read;
370 }
371
372 /**
373  * Load a resource into memory.
374  *
375  * @param ctx libsigrok context. Must not be NULL.
376  * @param type Resource type ID.
377  * @param name Name of the resource. Must not be NULL.
378  * @param[out] size Size in bytes of the returned buffer. Must not be NULL.
379  * @param max_size Size limit. Error out if the resource is larger than this.
380  *
381  * @return A buffer containing the resource data, or NULL on failure. Must
382  *         be freed by the caller using g_free().
383  *
384  * @private
385  */
386 SR_PRIV void *sr_resource_load(struct sr_context *ctx,
387                 int type, const char *name, size_t *size, size_t max_size)
388 {
389         struct sr_resource res;
390         void *buf;
391         size_t res_size;
392         gssize n_read;
393
394         if (sr_resource_open(ctx, &res, type, name) != SR_OK)
395                 return NULL;
396
397         if (res.size > max_size) {
398                 sr_err("Size %" PRIu64 " of '%s' exceeds limit %zu.",
399                         res.size, name, max_size);
400                 sr_resource_close(ctx, &res);
401                 return NULL;
402         }
403         res_size = res.size;
404
405         buf = g_try_malloc(res_size);
406         if (!buf) {
407                 sr_err("Failed to allocate buffer for '%s'.", name);
408                 sr_resource_close(ctx, &res);
409                 return NULL;
410         }
411
412         n_read = sr_resource_read(ctx, &res, buf, res_size);
413         sr_resource_close(ctx, &res);
414
415         if (n_read < 0 || (size_t)n_read != res_size) {
416                 if (n_read >= 0)
417                         sr_err("Failed to read '%s': premature end of file.",
418                                 name);
419                 g_free(buf);
420                 return NULL;
421         }
422
423         *size = res_size;
424         return buf;
425 }