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