libfstools: fit: improve fit_volume_find string handling
[project/fstools.git] / libfstools / fit.c
1 // SPDX-License-Identifier: GPL-2.0-or-later
2
3 #include "common.h"
4
5 #define BUFLEN 64
6 #define DEVPATHSTR_SIZE 15
7
8 static const char *const fit0 = "/dev/fit0";
9 static const char *const fitrw = "/dev/fitrw";
10
11 struct devpath {
12 char prefix[5];
13 char device[11];
14 };
15
16 struct fit_volume {
17 struct volume v;
18 union {
19 char devpathstr[DEVPATHSTR_SIZE+1];
20 struct devpath devpath;
21 } dev;
22 };
23
24 static struct driver fit_driver;
25
26 static int fit_volume_identify(struct volume *v)
27 {
28 struct fit_volume *p = container_of(v, struct fit_volume, v);
29 int ret = FS_NONE;
30 FILE *f;
31
32 f = fopen(p->dev.devpathstr, "r");
33 if (!f)
34 return ret;
35
36 ret = block_file_identify(f, 0);
37
38 fclose(f);
39
40 return ret;
41 }
42
43 static int fit_volume_init(struct volume *v)
44 {
45 struct fit_volume *p = container_of(v, struct fit_volume, v);
46 char voldir[BUFLEN];
47 unsigned int volsize;
48
49 snprintf(voldir, sizeof(voldir), "%s/%s", block_dir_name, p->dev.devpath.device);
50
51 if (read_uint_from_file(voldir, "size", &volsize))
52 return -1;
53
54 v->type = BLOCKDEV;
55 v->size = volsize << 9; /* size is returned in sectors of 512 bytes */
56 v->blk = p->dev.devpathstr;
57
58 return block_volume_format(v, 0, p->dev.devpathstr);
59 }
60
61 static struct volume *fit_volume_find(char *name)
62 {
63 struct fit_volume *p;
64 struct stat buf;
65 const char *fname;
66 int ret;
67
68 if (!strcmp(name, "rootfs"))
69 fname = fit0;
70 else if (!strcmp(name, "rootfs_data"))
71 fname = fitrw;
72 else
73 return NULL;
74
75 ret = stat(fname, &buf);
76 if (ret)
77 return NULL;
78
79 p = calloc(1, sizeof(struct fit_volume));
80 if (!p)
81 return NULL;
82
83 strncpy(p->dev.devpathstr, fname, DEVPATHSTR_SIZE);
84 p->v.drv = &fit_driver;
85 p->v.blk = p->dev.devpathstr;
86 p->v.name = name;
87
88 return &p->v;
89 }
90
91 static struct driver fit_driver = {
92 .name = "fit",
93 .priority = 30,
94 .find = fit_volume_find,
95 .init = fit_volume_init,
96 .identify = fit_volume_identify,
97 };
98
99 DRIVER(fit_driver);