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