comparison image.c @ 0:f41e1b48510d

misc: initial import
author David Demelier <markand@malikania.fr>
date Wed, 25 Nov 2020 21:13:03 +0100
parents
children f19f5f9fee56
comparison
equal deleted inserted replaced
-1:000000000000 0:f41e1b48510d
1 /*
2 * image.c -- image definition
3 *
4 * Copyright (c) 2020 David Demelier <markand@malikania.fr>
5 *
6 * Permission to use, copy, modify, and/or distribute this software for any
7 * purpose with or without fee is hereby granted, provided that the above
8 * copyright notice and this permission notice appear in all copies.
9 *
10 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17 */
18
19 #include <assert.h>
20 #include <stdlib.h>
21 #include <string.h>
22
23 #include <magic.h>
24
25 #include "image.h"
26 #include "log.h"
27 #include "util.h"
28
29 static const char *mimes[] = {
30 "image/bmp",
31 "image/jpeg",
32 "image/gif",
33 "image/png",
34 "image/svg+xml",
35 "image/tiff",
36 "image/webp"
37 };
38
39 void
40 image_finish(struct image *image)
41 {
42 assert(image);
43
44 free(image->id);
45 free(image->title);
46 free(image->author);
47 free(image->data);
48 free(image->filename);
49 memset(image, 0, sizeof (*image));
50 }
51
52 bool
53 image_isvalid(const void *src, size_t srcsz)
54 {
55 assert(src);
56
57 magic_t cookie;
58 bool ret = false;
59 const char *mime;
60
61 /*
62 * If we're unable to load the libmagic we assume it's valid image and
63 * let the browser show an invalid thing instead.
64 */
65 if (!(cookie = magic_open(MAGIC_MIME_TYPE)))
66 return true;
67
68 magic_load(cookie, NULL);
69
70 if ((mime = magic_buffer(cookie, src, srcsz))) {
71 for (size_t i = 0; i < NELEM(mimes); ++i) {
72 if (strcmp(mime, mimes[i]) == 0) {
73 ret = true;
74 break;
75 }
76 }
77 }
78
79 magic_close(cookie);
80
81 return ret;
82 }