]> sigrok.org Git - libsigrok.git/blob - src/resource.c
Introduce sr_resourcepaths_get()
[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         filename = g_build_filename(datadir, subdir, name, NULL);
132         file = g_fopen(filename, "rb");
133
134         if (file)
135                 sr_info("Opened '%s'.", filename);
136         else
137                 sr_spew("Attempt to open '%s' failed: %s",
138                         filename, g_strerror(errno));
139         g_free(filename);
140
141         return file;
142 }
143
144 static int resource_open_default(struct sr_resource *res,
145                 const char *name, void *cb_data)
146 {
147         GSList *paths, *p = NULL;
148         int64_t filesize;
149         FILE *file = NULL;
150
151         (void)cb_data;
152
153         paths = sr_resourcepaths_get(res->type);
154
155         /* Currently, the enum only defines SR_RESOURCE_FIRMWARE. */
156         if (res->type != SR_RESOURCE_FIRMWARE) {
157                 sr_err("%s: unknown type %d.", __func__, res->type);
158                 return SR_ERR_ARG;
159         }
160
161         p = paths;
162         while (p && !file) {
163                 file = try_open_file((const char *)(p->data), NULL, name);
164                 p = p->next;
165         }
166         g_slist_free_full(paths, g_free);
167
168         if (!file) {
169                 sr_dbg("Failed to locate '%s'.", name);
170                 return SR_ERR;
171         }
172
173         filesize = sr_file_get_size(file);
174         if (filesize < 0) {
175                 sr_err("Failed to obtain size of '%s': %s",
176                         name, g_strerror(errno));
177                 fclose(file);
178                 return SR_ERR;
179         }
180         res->size = filesize;
181         res->handle = file;
182
183         return SR_OK;
184 }
185
186 static int resource_close_default(struct sr_resource *res, void *cb_data)
187 {
188         FILE *file;
189
190         (void)cb_data;
191
192         file = res->handle;
193         if (!file) {
194                 sr_err("%s: invalid handle.", __func__);
195                 return SR_ERR_ARG;
196         }
197
198         if (fclose(file) < 0) {
199                 sr_err("Failed to close file: %s", g_strerror(errno));
200                 return SR_ERR;
201         }
202         res->handle = NULL;
203
204         return SR_OK;
205 }
206
207 static gssize resource_read_default(const struct sr_resource *res,
208                 void *buf, size_t count, void *cb_data)
209 {
210         FILE *file;
211         size_t n_read;
212
213         (void)cb_data;
214
215         file = res->handle;
216         if (!file) {
217                 sr_err("%s: invalid handle.", __func__);
218                 return SR_ERR_ARG;
219         }
220         if (count > G_MAXSSIZE) {
221                 sr_err("%s: count %zu too large.", __func__, count);
222                 return SR_ERR_ARG;
223         }
224
225         n_read = fread(buf, 1, count, file);
226
227         if (n_read != count && ferror(file)) {
228                 sr_err("Failed to read resource file: %s", g_strerror(errno));
229                 return SR_ERR;
230         }
231         return n_read;
232 }
233
234 /**
235  * Install resource access hooks.
236  *
237  * @param ctx libsigrok context. Must not be NULL.
238  * @param open_cb Resource open callback, or NULL to unset.
239  * @param close_cb Resource close callback, or NULL to unset.
240  * @param read_cb Resource read callback, or NULL to unset.
241  * @param cb_data User data pointer passed to callbacks.
242  *
243  * @retval SR_OK Success.
244  * @retval SR_ERR_ARG Invalid argument.
245  *
246  * @since 0.4.0
247  */
248 SR_API int sr_resource_set_hooks(struct sr_context *ctx,
249                 sr_resource_open_callback open_cb,
250                 sr_resource_close_callback close_cb,
251                 sr_resource_read_callback read_cb, void *cb_data)
252 {
253         if (!ctx) {
254                 sr_err("%s: ctx was NULL.", __func__);
255                 return SR_ERR_ARG;
256         }
257         if (open_cb && close_cb && read_cb) {
258                 ctx->resource_open_cb = open_cb;
259                 ctx->resource_close_cb = close_cb;
260                 ctx->resource_read_cb = read_cb;
261                 ctx->resource_cb_data = cb_data;
262         } else if (!open_cb && !close_cb && !read_cb) {
263                 ctx->resource_open_cb = &resource_open_default;
264                 ctx->resource_close_cb = &resource_close_default;
265                 ctx->resource_read_cb = &resource_read_default;
266                 ctx->resource_cb_data = ctx;
267         } else {
268                 sr_err("%s: inconsistent callback pointers.", __func__);
269                 return SR_ERR_ARG;
270         }
271         return SR_OK;
272 }
273
274 /**
275  * Open resource.
276  *
277  * @param ctx libsigrok context. Must not be NULL.
278  * @param[out] res Resource descriptor to fill in. Must not be NULL.
279  * @param type Resource type ID.
280  * @param name Name of the resource. Must not be NULL.
281  *
282  * @retval SR_OK Success.
283  * @retval SR_ERR_ARG Invalid argument.
284  * @retval SR_ERR Other error.
285  *
286  * @private
287  */
288 SR_PRIV int sr_resource_open(struct sr_context *ctx,
289                 struct sr_resource *res, int type, const char *name)
290 {
291         int ret;
292
293         res->size = 0;
294         res->handle = NULL;
295         res->type = type;
296
297         ret = (*ctx->resource_open_cb)(res, name, ctx->resource_cb_data);
298
299         if (ret != SR_OK)
300                 sr_err("Failed to open resource '%s' (use loglevel 5/spew for"
301                        " details).", name);
302
303         return ret;
304 }
305
306 /**
307  * Close resource.
308  *
309  * @param ctx libsigrok context. Must not be NULL.
310  * @param[inout] res Resource descriptor. Must not be NULL.
311  *
312  * @retval SR_OK Success.
313  * @retval SR_ERR_ARG Invalid argument.
314  * @retval SR_ERR Other error.
315  *
316  * @private
317  */
318 SR_PRIV int sr_resource_close(struct sr_context *ctx, struct sr_resource *res)
319 {
320         int ret;
321
322         ret = (*ctx->resource_close_cb)(res, ctx->resource_cb_data);
323
324         if (ret != SR_OK)
325                 sr_err("Failed to close resource.");
326
327         return ret;
328 }
329
330 /**
331  * Read resource data.
332  *
333  * @param ctx libsigrok context. Must not be NULL.
334  * @param[in] res Resource descriptor. Must not be NULL.
335  * @param[out] buf Buffer to store @a count bytes into. Must not be NULL.
336  * @param count Number of bytes to read.
337  *
338  * @return The number of bytes actually read, or a negative value on error.
339  * @retval SR_ERR_ARG Invalid argument.
340  * @retval SR_ERR Other error.
341  *
342  * @private
343  */
344 SR_PRIV gssize sr_resource_read(struct sr_context *ctx,
345                 const struct sr_resource *res, void *buf, size_t count)
346 {
347         gssize n_read;
348
349         n_read = (*ctx->resource_read_cb)(res, buf, count,
350                         ctx->resource_cb_data);
351         if (n_read < 0)
352                 sr_err("Failed to read resource.");
353
354         return n_read;
355 }
356
357 /**
358  * Load a resource into memory.
359  *
360  * @param ctx libsigrok context. Must not be NULL.
361  * @param type Resource type ID.
362  * @param name Name of the resource. Must not be NULL.
363  * @param[out] size Size in bytes of the returned buffer. Must not be NULL.
364  * @param max_size Size limit. Error out if the resource is larger than this.
365  *
366  * @return A buffer containing the resource data, or NULL on failure. Must
367  *         be freed by the caller using g_free().
368  *
369  * @private
370  */
371 SR_PRIV void *sr_resource_load(struct sr_context *ctx,
372                 int type, const char *name, size_t *size, size_t max_size)
373 {
374         struct sr_resource res;
375         void *buf;
376         size_t res_size;
377         gssize n_read;
378
379         if (sr_resource_open(ctx, &res, type, name) != SR_OK)
380                 return NULL;
381
382         if (res.size > max_size) {
383                 sr_err("Size %" PRIu64 " of '%s' exceeds limit %zu.",
384                         res.size, name, max_size);
385                 sr_resource_close(ctx, &res);
386                 return NULL;
387         }
388         res_size = res.size;
389
390         buf = g_try_malloc(res_size);
391         if (!buf) {
392                 sr_err("Failed to allocate buffer for '%s'.", name);
393                 sr_resource_close(ctx, &res);
394                 return NULL;
395         }
396
397         n_read = sr_resource_read(ctx, &res, buf, res_size);
398         sr_resource_close(ctx, &res);
399
400         if (n_read < 0 || (size_t)n_read != res_size) {
401                 if (n_read >= 0)
402                         sr_err("Failed to read '%s': premature end of file.",
403                                 name);
404                 g_free(buf);
405                 return NULL;
406         }
407
408         *size = res_size;
409         return buf;
410 }
411
412 /** @} */