]> git.sven.stormbind.net Git - sven/exfatprogs.git/blob - lib/libexfat.c
Add CVE ID to debian changelog
[sven/exfatprogs.git] / lib / libexfat.c
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  *   Copyright (C) 2019 Namjae Jeon <linkinjeon@kernel.org>
4  */
5
6 #include <sys/types.h>
7 #include <sys/stat.h>
8 #include <sys/ioctl.h>
9 #include <sys/sysmacros.h>
10 #include <unistd.h>
11 #include <fcntl.h>
12 #include <stdlib.h>
13 #include <stdio.h>
14 #include <string.h>
15 #include <errno.h>
16 #include <wchar.h>
17 #include <limits.h>
18 #include <assert.h>
19
20 #include "exfat_ondisk.h"
21 #include "libexfat.h"
22 #include "version.h"
23 #include "exfat_fs.h"
24 #include "exfat_dir.h"
25
26 unsigned int print_level  = EXFAT_INFO;
27
28 void exfat_bitmap_set_range(struct exfat *exfat, char *bitmap,
29                             clus_t start_clus, clus_t count)
30 {
31         clus_t clus;
32
33         if (!exfat_heap_clus(exfat, start_clus) ||
34             !exfat_heap_clus(exfat, start_clus + count - 1))
35                 return;
36
37         clus = start_clus;
38         while (clus < start_clus + count) {
39                 exfat_bitmap_set(bitmap, clus);
40                 clus++;
41         }
42 }
43
44 static int exfat_bitmap_find_bit(struct exfat *exfat, char *bmap,
45                                  clus_t start_clu, clus_t *next,
46                                  int bit)
47 {
48         clus_t last_clu;
49
50         last_clu = le32_to_cpu(exfat->bs->bsx.clu_count) +
51                 EXFAT_FIRST_CLUSTER;
52         while (start_clu < last_clu) {
53                 if (!!exfat_bitmap_get(bmap, start_clu) == bit) {
54                         *next = start_clu;
55                         return 0;
56                 }
57                 start_clu++;
58         }
59         return 1;
60 }
61
62 int exfat_bitmap_find_zero(struct exfat *exfat, char *bmap,
63                            clus_t start_clu, clus_t *next)
64 {
65         return exfat_bitmap_find_bit(exfat, bmap,
66                                      start_clu, next, 0);
67 }
68
69 int exfat_bitmap_find_one(struct exfat *exfat, char *bmap,
70                           clus_t start_clu, clus_t *next)
71 {
72         return exfat_bitmap_find_bit(exfat, bmap,
73                                      start_clu, next, 1);
74 }
75
76 wchar_t exfat_bad_char(wchar_t w)
77 {
78         return (w < 0x0020)
79                 || (w == '*') || (w == '?') || (w == '<') || (w == '>')
80                 || (w == '|') || (w == '"') || (w == ':') || (w == '/')
81                 || (w == '\\');
82 }
83
84 void boot_calc_checksum(unsigned char *sector, unsigned short size,
85                 bool is_boot_sec, __le32 *checksum)
86 {
87         unsigned int index;
88
89         if (is_boot_sec) {
90                 for (index = 0; index < size; index++) {
91                         if ((index == 106) || (index == 107) || (index == 112))
92                                 continue;
93                         *checksum = ((*checksum & 1) ? 0x80000000 : 0) +
94                                 (*checksum >> 1) + sector[index];
95                 }
96         } else {
97                 for (index = 0; index < size; index++) {
98                         *checksum = ((*checksum & 1) ? 0x80000000 : 0) +
99                                 (*checksum >> 1) + sector[index];
100                 }
101         }
102 }
103
104 void show_version(void)
105 {
106         printf("exfatprogs version : %s\n", EXFAT_PROGS_VERSION);
107 }
108
109 static inline unsigned int sector_size_bits(unsigned int size)
110 {
111         unsigned int bits = 8;
112
113         do {
114                 bits++;
115                 size >>= 1;
116         } while (size > 256);
117
118         return bits;
119 }
120
121 static void exfat_set_default_cluster_size(struct exfat_blk_dev *bd,
122                 struct exfat_user_input *ui)
123 {
124         if (256 * MB >= bd->size)
125                 ui->cluster_size = 4 * KB;
126         else if (32 * GB >= bd->size)
127                 ui->cluster_size = 32 * KB;
128         else
129                 ui->cluster_size = 128 * KB;
130 }
131
132 void init_user_input(struct exfat_user_input *ui)
133 {
134         memset(ui, 0, sizeof(struct exfat_user_input));
135         ui->writeable = true;
136         ui->quick = true;
137 }
138
139 int exfat_get_blk_dev_info(struct exfat_user_input *ui,
140                 struct exfat_blk_dev *bd)
141 {
142         int fd, ret = -1;
143         off_t blk_dev_size;
144         struct stat st;
145         unsigned long long blk_dev_offset = 0;
146
147         fd = open(ui->dev_name, ui->writeable ? O_RDWR|O_EXCL : O_RDONLY);
148         if (fd < 0) {
149                 exfat_err("open failed : %s, %s\n", ui->dev_name,
150                         strerror(errno));
151                 return -1;
152         }
153         blk_dev_size = lseek(fd, 0, SEEK_END);
154         if (blk_dev_size <= 0) {
155                 exfat_err("invalid block device size(%s)\n",
156                         ui->dev_name);
157                 ret = blk_dev_size;
158                 close(fd);
159                 goto out;
160         }
161
162         if (fstat(fd, &st) == 0 && S_ISBLK(st.st_mode)) {
163                 char pathname[sizeof("/sys/dev/block/4294967295:4294967295/start")];
164                 FILE *fp;
165
166                 snprintf(pathname, sizeof(pathname), "/sys/dev/block/%u:%u/start",
167                         major(st.st_rdev), minor(st.st_rdev));
168                 fp = fopen(pathname, "r");
169                 if (fp != NULL) {
170                         if (fscanf(fp, "%llu", &blk_dev_offset) == 1) {
171                                 /*
172                                  * Linux kernel always reports partition offset
173                                  * in 512-byte units, regardless of sector size
174                                  */
175                                 blk_dev_offset <<= 9;
176                         }
177                         fclose(fp);
178                 }
179         }
180
181         bd->dev_fd = fd;
182         bd->offset = blk_dev_offset;
183         bd->size = blk_dev_size;
184         if (!ui->cluster_size)
185                 exfat_set_default_cluster_size(bd, ui);
186
187         if (!ui->boundary_align)
188                 ui->boundary_align = DEFAULT_BOUNDARY_ALIGNMENT;
189
190         if (ioctl(fd, BLKSSZGET, &bd->sector_size) < 0)
191                 bd->sector_size = DEFAULT_SECTOR_SIZE;
192         bd->sector_size_bits = sector_size_bits(bd->sector_size);
193         bd->num_sectors = blk_dev_size / bd->sector_size;
194         bd->num_clusters = blk_dev_size / ui->cluster_size;
195
196         exfat_debug("Block device name : %s\n", ui->dev_name);
197         exfat_debug("Block device offset : %llu\n", bd->offset);
198         exfat_debug("Block device size : %llu\n", bd->size);
199         exfat_debug("Block sector size : %u\n", bd->sector_size);
200         exfat_debug("Number of the sectors : %llu\n",
201                 bd->num_sectors);
202         exfat_debug("Number of the clusters : %u\n",
203                 bd->num_clusters);
204
205         ret = 0;
206         bd->dev_fd = fd;
207 out:
208         return ret;
209 }
210
211 ssize_t exfat_read(int fd, void *buf, size_t size, off_t offset)
212 {
213         return pread(fd, buf, size, offset);
214 }
215
216 ssize_t exfat_write(int fd, void *buf, size_t size, off_t offset)
217 {
218         return pwrite(fd, buf, size, offset);
219 }
220
221 size_t exfat_utf16_len(const __le16 *str, size_t max_size)
222 {
223         size_t i = 0;
224
225         while (le16_to_cpu(str[i]) && i < max_size)
226                 i++;
227         return i;
228 }
229
230 ssize_t exfat_utf16_enc(const char *in_str, __u16 *out_str, size_t out_size)
231 {
232         size_t mbs_len, out_len, i;
233         wchar_t *wcs;
234
235         mbs_len = mbstowcs(NULL, in_str, 0);
236         if (mbs_len == (size_t)-1) {
237                 if (errno == EINVAL || errno == EILSEQ)
238                         exfat_err("invalid character sequence in current locale\n");
239                 return -errno;
240         }
241
242         wcs = calloc(mbs_len+1, sizeof(wchar_t));
243         if (!wcs)
244                 return -ENOMEM;
245
246         /* First convert multibyte char* string to wchar_t* string */
247         if (mbstowcs(wcs, in_str, mbs_len+1) == (size_t)-1) {
248                 if (errno == EINVAL || errno == EILSEQ)
249                         exfat_err("invalid character sequence in current locale\n");
250                 free(wcs);
251                 return -errno;
252         }
253
254         /* Convert wchar_t* string (sequence of code points) to UTF-16 string */
255         for (i = 0, out_len = 0; i < mbs_len; i++) {
256                 if (2*(out_len+1) > out_size ||
257                     (wcs[i] >= 0x10000 && 2*(out_len+2) > out_size)) {
258                         exfat_err("input string is too long\n");
259                         free(wcs);
260                         return -E2BIG;
261                 }
262
263                 /* Encode code point above Plane0 as UTF-16 surrogate pair */
264                 if (wcs[i] >= 0x10000) {
265                         out_str[out_len++] =
266                           cpu_to_le16(((wcs[i] - 0x10000) >> 10) + 0xD800);
267                         wcs[i] = ((wcs[i] - 0x10000) & 0x3FF) + 0xDC00;
268                 }
269
270                 out_str[out_len++] = cpu_to_le16(wcs[i]);
271         }
272
273         free(wcs);
274         return 2*out_len;
275 }
276
277 ssize_t exfat_utf16_dec(const __u16 *in_str, size_t in_len,
278                         char *out_str, size_t out_size)
279 {
280         size_t wcs_len, out_len, c_len, i;
281         char c_str[MB_LEN_MAX];
282         wchar_t *wcs;
283         mbstate_t ps;
284         wchar_t w;
285
286         wcs = calloc(in_len/2+1, sizeof(wchar_t));
287         if (!wcs)
288                 return -ENOMEM;
289
290         /* First convert UTF-16 string to wchar_t* string */
291         for (i = 0, wcs_len = 0; i < in_len/2; i++, wcs_len++) {
292                 wcs[wcs_len] = le16_to_cpu(in_str[i]);
293                 /*
294                  * If wchar_t can store code point above Plane0
295                  * then unpack UTF-16 surrogate pair to code point
296                  */
297 #if WCHAR_MAX >= 0x10FFFF
298                 if (wcs[wcs_len] >= 0xD800 && wcs[wcs_len] <= 0xDBFF &&
299                     i+1 < in_len/2) {
300                         w = le16_to_cpu(in_str[i+1]);
301                         if (w >= 0xDC00 && w <= 0xDFFF) {
302                                 wcs[wcs_len] = 0x10000 +
303                                                ((wcs[wcs_len] - 0xD800) << 10) +
304                                                (w - 0xDC00);
305                                 i++;
306                         }
307                 }
308 #endif
309         }
310
311         memset(&ps, 0, sizeof(ps));
312
313         /* And then convert wchar_t* string to multibyte char* string */
314         for (i = 0, out_len = 0, c_len = 0; i <= wcs_len; i++) {
315                 c_len = wcrtomb(c_str, wcs[i], &ps);
316                 /*
317                  * If character is non-representable in current locale then
318                  * try to store it as Unicode replacement code point U+FFFD
319                  */
320                 if (c_len == (size_t)-1 && errno == EILSEQ)
321                         c_len = wcrtomb(c_str, 0xFFFD, &ps);
322                 /* If U+FFFD is also non-representable, try question mark */
323                 if (c_len == (size_t)-1 && errno == EILSEQ)
324                         c_len = wcrtomb(c_str, L'?', &ps);
325                 /* If also (7bit) question mark fails then we cannot do more */
326                 if (c_len == (size_t)-1) {
327                         exfat_err("invalid UTF-16 sequence\n");
328                         free(wcs);
329                         return -errno;
330                 }
331                 if (out_len+c_len > out_size) {
332                         exfat_err("input string is too long\n");
333                         free(wcs);
334                         return -E2BIG;
335                 }
336                 memcpy(out_str+out_len, c_str, c_len);
337                 out_len += c_len;
338         }
339
340         free(wcs);
341
342         /* Last iteration of above loop should have produced null byte */
343         if (c_len == 0 || out_str[out_len-1] != 0) {
344                 exfat_err("invalid UTF-16 sequence\n");
345                 return -errno;
346         }
347
348         return out_len-1;
349 }
350
351 off_t exfat_get_root_entry_offset(struct exfat_blk_dev *bd)
352 {
353         struct pbr *bs;
354         int nbytes;
355         unsigned int cluster_size, sector_size;
356         off_t root_clu_off;
357
358         bs = (struct pbr *)malloc(EXFAT_MAX_SECTOR_SIZE);
359         if (!bs) {
360                 exfat_err("failed to allocate memory\n");
361                 return -ENOMEM;
362         }
363
364         nbytes = exfat_read(bd->dev_fd, bs, EXFAT_MAX_SECTOR_SIZE, 0);
365         if (nbytes != EXFAT_MAX_SECTOR_SIZE) {
366                 exfat_err("boot sector read failed: %d\n", errno);
367                 free(bs);
368                 return -1;
369         }
370
371         if (memcmp(bs->bpb.oem_name, "EXFAT   ", 8) != 0) {
372                 exfat_err("Bad fs_name in boot sector, which does not describe a valid exfat filesystem\n");
373                 free(bs);
374                 return -1;
375         }
376
377         sector_size = 1 << bs->bsx.sect_size_bits;
378         cluster_size = (1 << bs->bsx.sect_per_clus_bits) * sector_size;
379         root_clu_off = le32_to_cpu(bs->bsx.clu_offset) * sector_size +
380                 (le32_to_cpu(bs->bsx.root_cluster) - EXFAT_RESERVED_CLUSTERS) *
381                 cluster_size;
382         free(bs);
383
384         return root_clu_off;
385 }
386
387 char *exfat_conv_volume_label(struct exfat_dentry *vol_entry)
388 {
389         char *volume_label;
390         __le16 disk_label[VOLUME_LABEL_MAX_LEN];
391
392         volume_label = malloc(VOLUME_LABEL_BUFFER_SIZE);
393         if (!volume_label)
394                 return NULL;
395
396         memcpy(disk_label, vol_entry->vol_label, sizeof(disk_label));
397         memset(volume_label, 0, VOLUME_LABEL_BUFFER_SIZE);
398         if (exfat_utf16_dec(disk_label, vol_entry->vol_char_cnt*2,
399                 volume_label, VOLUME_LABEL_BUFFER_SIZE) < 0) {
400                 exfat_err("failed to decode volume label\n");
401                 free(volume_label);
402                 return NULL;
403         }
404
405         return volume_label;
406 }
407
408 int exfat_read_volume_label(struct exfat *exfat)
409 {
410         struct exfat_dentry *dentry;
411         int err;
412         __le16 disk_label[VOLUME_LABEL_MAX_LEN];
413         struct exfat_lookup_filter filter = {
414                 .in.type = EXFAT_VOLUME,
415                 .in.dentry_count = 0,
416                 .in.filter = NULL,
417         };
418
419         err = exfat_lookup_dentry_set(exfat, exfat->root, &filter);
420         if (err)
421                 return err;
422
423         dentry = filter.out.dentry_set;
424
425         if (dentry->vol_char_cnt == 0)
426                 goto out;
427
428         if (dentry->vol_char_cnt > VOLUME_LABEL_MAX_LEN) {
429                 exfat_err("too long label. %d\n", dentry->vol_char_cnt);
430                 err = -EINVAL;
431                 goto out;
432         }
433
434         memcpy(disk_label, dentry->vol_label, sizeof(disk_label));
435         if (exfat_utf16_dec(disk_label, dentry->vol_char_cnt*2,
436                 exfat->volume_label, sizeof(exfat->volume_label)) < 0) {
437                 exfat_err("failed to decode volume label\n");
438                 err = -EINVAL;
439                 goto out;
440         }
441
442         exfat_info("label: %s\n", exfat->volume_label);
443 out:
444         free(filter.out.dentry_set);
445         return err;
446 }
447
448 int exfat_set_volume_label(struct exfat *exfat, char *label_input)
449 {
450         struct exfat_dentry *pvol;
451         struct exfat_dentry_loc loc;
452         __u16 volume_label[VOLUME_LABEL_MAX_LEN];
453         int volume_label_len, dcount, err;
454
455         struct exfat_lookup_filter filter = {
456                 .in.type = EXFAT_VOLUME,
457                 .in.dentry_count = 1,
458                 .in.filter = NULL,
459         };
460
461         err = exfat_lookup_dentry_set(exfat, exfat->root, &filter);
462         if (!err) {
463                 pvol = filter.out.dentry_set;
464                 dcount = filter.out.dentry_count;
465                 memset(pvol->vol_label, 0, sizeof(pvol->vol_label));
466         } else {
467                 pvol = calloc(sizeof(struct exfat_dentry), 1);
468                 if (!pvol)
469                         return -ENOMEM;
470
471                 dcount = 1;
472                 pvol->type = EXFAT_VOLUME;
473         }
474
475         volume_label_len = exfat_utf16_enc(label_input,
476                         volume_label, sizeof(volume_label));
477         if (volume_label_len < 0) {
478                 exfat_err("failed to encode volume label\n");
479                 free(pvol);
480                 return -1;
481         }
482
483         memcpy(pvol->vol_label, volume_label, volume_label_len);
484         pvol->vol_char_cnt = volume_label_len/2;
485
486         loc.parent = exfat->root;
487         loc.file_offset = filter.out.file_offset;
488         loc.dev_offset = filter.out.dev_offset;
489         err = exfat_add_dentry_set(exfat, &loc, pvol, dcount, false);
490         exfat_info("new label: %s\n", label_input);
491
492         free(pvol);
493
494         return err;
495 }
496
497 static inline void print_guid(const char *msg, const __u8 *guid)
498 {
499         exfat_info("%s: %02x%02x%02x%02x-%02x%02x-%02x%02x-%02x%02x-%02x%02x%02x%02x%02x%02x\n",
500                         msg,
501                         guid[0], guid[1], guid[2], guid[3],
502                         guid[4], guid[5], guid[5], guid[7],
503                         guid[8], guid[9], guid[10], guid[11],
504                         guid[12], guid[13], guid[14], guid[15]);
505 }
506
507 static int set_guid(__u8 *guid, const char *input)
508 {
509         int i, j, zero_len = 0;
510         int len = strlen(input);
511
512         if (len != VOLUME_GUID_LEN * 2 && len != VOLUME_GUID_LEN * 2 + 4) {
513                 exfat_err("invalid format for volume guid\n");
514                 return -EINVAL;
515         }
516
517         for (i = 0, j = 0; i < len; i++) {
518                 unsigned char ch = input[i];
519
520                 if (ch >= '0' && ch <= '9')
521                         ch -= '0';
522                 else if (ch >= 'a' && ch <= 'f')
523                         ch -= 'a' - 0xA;
524                 else if (ch >= 'A' && ch <= 'F')
525                         ch -= 'A' - 0xA;
526                 else if (ch == '-' && len == VOLUME_GUID_LEN * 2 + 4 &&
527                          (i == 8 || i == 13 || i == 18 || i == 23))
528                         continue;
529                 else {
530                         exfat_err("invalid character '%c' for volume GUID\n", ch);
531                         return -EINVAL;
532                 }
533
534                 if (j & 1)
535                         guid[j >> 1] |= ch;
536                 else
537                         guid[j >> 1] = ch << 4;
538
539                 j++;
540
541                 if (ch == 0)
542                         zero_len++;
543         }
544
545         if (zero_len == VOLUME_GUID_LEN * 2) {
546                 exfat_err("%s is invalid for volume GUID\n", input);
547                 return -EINVAL;
548         }
549
550         return 0;
551 }
552
553 int exfat_read_volume_guid(struct exfat *exfat)
554 {
555         int err;
556         uint16_t checksum = 0;
557         struct exfat_dentry *dentry;
558         struct exfat_lookup_filter filter = {
559                 .in.type = EXFAT_GUID,
560                 .in.dentry_count = 1,
561                 .in.filter = NULL,
562         };
563
564         err = exfat_lookup_dentry_set(exfat, exfat->root, &filter);
565         if (err)
566                 return err;
567
568         dentry = filter.out.dentry_set;
569         exfat_calc_dentry_checksum(dentry, &checksum, true);
570
571         if (cpu_to_le16(checksum) == dentry->dentry.guid.checksum)
572                 print_guid("GUID", dentry->dentry.guid.guid);
573         else
574                 exfat_info("GUID is corrupted, please delete it or set a new one\n");
575
576         free(dentry);
577
578         return err;
579 }
580
581 int __exfat_set_volume_guid(struct exfat_dentry *dentry, const char *guid)
582 {
583         int err;
584         uint16_t checksum = 0;
585
586         memset(dentry, 0, sizeof(*dentry));
587         dentry->type = EXFAT_GUID;
588
589         err = set_guid(dentry->dentry.guid.guid, guid);
590         if (err)
591                 return err;
592
593         exfat_calc_dentry_checksum(dentry, &checksum, true);
594         dentry->dentry.guid.checksum = cpu_to_le16(checksum);
595
596         return 0;
597 }
598
599 /*
600  * Create/Update/Delete GUID dentry in root directory
601  *
602  * create/update GUID if @guid is not NULL.
603  * delete GUID if @guid is NULL.
604  */
605 int exfat_set_volume_guid(struct exfat *exfat, const char *guid)
606 {
607         struct exfat_dentry *dentry;
608         struct exfat_dentry_loc loc;
609         int err;
610
611         struct exfat_lookup_filter filter = {
612                 .in.type = EXFAT_GUID,
613                 .in.dentry_count = 1,
614                 .in.filter = NULL,
615         };
616
617         err = exfat_lookup_dentry_set(exfat, exfat->root, &filter);
618         if (!err) {
619                 /* GUID entry is found */
620                 dentry = filter.out.dentry_set;
621         } else {
622                 /* no GUID to delete */
623                 if (guid == NULL)
624                         return 0;
625
626                 dentry = calloc(1, sizeof(*dentry));
627                 if (!dentry)
628                         return -ENOMEM;
629         }
630
631         if (guid) {
632                 /* Set GUID */
633                 err = __exfat_set_volume_guid(dentry, guid);
634                 if (err)
635                         goto out;
636         } else {
637                 /* Delete GUID */
638                 dentry->type &= ~EXFAT_INVAL;
639         }
640
641         loc.parent = exfat->root;
642         loc.file_offset = filter.out.file_offset;
643         loc.dev_offset = filter.out.dev_offset;
644         err = exfat_add_dentry_set(exfat, &loc, dentry, 1, false);
645         if (!err) {
646                 if (guid)
647                         print_guid("new GUID", dentry->dentry.guid.guid);
648                 else
649                         exfat_info("GUID is deleted\n");
650         }
651
652 out:
653         free(dentry);
654
655         return err;
656 }
657
658 int exfat_read_sector(struct exfat_blk_dev *bd, void *buf, unsigned int sec_off)
659 {
660         int ret;
661         unsigned long long offset =
662                 (unsigned long long)sec_off * bd->sector_size;
663
664         ret = pread(bd->dev_fd, buf, bd->sector_size, offset);
665         if (ret < 0) {
666                 exfat_err("read failed, sec_off : %u\n", sec_off);
667                 return -1;
668         }
669         return 0;
670 }
671
672 int exfat_write_sector(struct exfat_blk_dev *bd, void *buf,
673                 unsigned int sec_off)
674 {
675         int bytes;
676         unsigned long long offset =
677                 (unsigned long long)sec_off * bd->sector_size;
678
679         bytes = pwrite(bd->dev_fd, buf, bd->sector_size, offset);
680         if (bytes != (int)bd->sector_size) {
681                 exfat_err("write failed, sec_off : %u, bytes : %d\n", sec_off,
682                         bytes);
683                 return -1;
684         }
685         return 0;
686 }
687
688 int exfat_write_checksum_sector(struct exfat_blk_dev *bd,
689                 unsigned int checksum, bool is_backup)
690 {
691         __le32 *checksum_buf;
692         int ret = 0;
693         unsigned int i;
694         unsigned int sec_idx = CHECKSUM_SEC_IDX;
695
696         checksum_buf = malloc(bd->sector_size);
697         if (!checksum_buf)
698                 return -1;
699
700         if (is_backup)
701                 sec_idx += BACKUP_BOOT_SEC_IDX;
702
703         for (i = 0; i < bd->sector_size / sizeof(int); i++)
704                 checksum_buf[i] = cpu_to_le32(checksum);
705
706         ret = exfat_write_sector(bd, checksum_buf, sec_idx);
707         if (ret) {
708                 exfat_err("checksum sector write failed\n");
709                 goto free;
710         }
711
712 free:
713         free(checksum_buf);
714         return ret;
715 }
716
717 int exfat_show_volume_serial(int fd)
718 {
719         struct pbr *ppbr;
720         int ret;
721
722         ppbr = malloc(EXFAT_MAX_SECTOR_SIZE);
723         if (!ppbr) {
724                 exfat_err("Cannot allocate pbr: out of memory\n");
725                 return -1;
726         }
727
728         /* read main boot sector */
729         ret = exfat_read(fd, (char *)ppbr, EXFAT_MAX_SECTOR_SIZE, 0);
730         if (ret < 0) {
731                 exfat_err("main boot sector read failed\n");
732                 ret = -1;
733                 goto free_ppbr;
734         }
735
736         if (memcmp(ppbr->bpb.oem_name, "EXFAT   ", 8) != 0) {
737                 exfat_err("Bad fs_name in boot sector, which does not describe a valid exfat filesystem\n");
738                 ret = -1;
739                 goto free_ppbr;
740         }
741
742         exfat_info("volume serial : 0x%x\n", ppbr->bsx.vol_serial);
743
744 free_ppbr:
745         free(ppbr);
746         return ret;
747 }
748
749 static int exfat_update_boot_checksum(struct exfat_blk_dev *bd, bool is_backup)
750 {
751         unsigned int checksum = 0;
752         int ret, sec_idx, backup_sec_idx = 0;
753         unsigned char *buf;
754
755         buf = malloc(bd->sector_size);
756         if (!buf) {
757                 exfat_err("Cannot allocate pbr: out of memory\n");
758                 return -1;
759         }
760
761         if (is_backup)
762                 backup_sec_idx = BACKUP_BOOT_SEC_IDX;
763
764         for (sec_idx = BOOT_SEC_IDX; sec_idx < CHECKSUM_SEC_IDX; sec_idx++) {
765                 bool is_boot_sec = false;
766
767                 ret = exfat_read_sector(bd, buf, sec_idx + backup_sec_idx);
768                 if (ret < 0) {
769                         exfat_err("sector(%d) read failed\n", sec_idx);
770                         ret = -1;
771                         goto free_buf;
772                 }
773
774                 if (sec_idx == BOOT_SEC_IDX)
775                         is_boot_sec = true;
776
777                 boot_calc_checksum(buf, bd->sector_size, is_boot_sec,
778                         &checksum);
779         }
780
781         ret = exfat_write_checksum_sector(bd, checksum, is_backup);
782
783 free_buf:
784         free(buf);
785
786         return ret;
787 }
788
789 int exfat_set_volume_serial(struct exfat_blk_dev *bd,
790                 struct exfat_user_input *ui)
791 {
792         int ret;
793         struct pbr *ppbr;
794
795         ppbr = malloc(EXFAT_MAX_SECTOR_SIZE);
796         if (!ppbr) {
797                 exfat_err("Cannot allocate pbr: out of memory\n");
798                 return -1;
799         }
800
801         /* read main boot sector */
802         ret = exfat_read(bd->dev_fd, (char *)ppbr, EXFAT_MAX_SECTOR_SIZE,
803                         BOOT_SEC_IDX);
804         if (ret < 0) {
805                 exfat_err("main boot sector read failed\n");
806                 ret = -1;
807                 goto free_ppbr;
808         }
809
810         if (memcmp(ppbr->bpb.oem_name, "EXFAT   ", 8) != 0) {
811                 exfat_err("Bad fs_name in boot sector, which does not describe a valid exfat filesystem\n");
812                 ret = -1;
813                 goto free_ppbr;
814         }
815
816         bd->sector_size = 1 << ppbr->bsx.sect_size_bits;
817         ppbr->bsx.vol_serial = ui->volume_serial;
818
819         /* update main boot sector */
820         ret = exfat_write_sector(bd, (char *)ppbr, BOOT_SEC_IDX);
821         if (ret < 0) {
822                 exfat_err("main boot sector write failed\n");
823                 ret = -1;
824                 goto free_ppbr;
825         }
826
827         /* update backup boot sector */
828         ret = exfat_write_sector(bd, (char *)ppbr, BACKUP_BOOT_SEC_IDX);
829         if (ret < 0) {
830                 exfat_err("backup boot sector write failed\n");
831                 ret = -1;
832                 goto free_ppbr;
833         }
834
835         ret = exfat_update_boot_checksum(bd, 0);
836         if (ret < 0) {
837                 exfat_err("main checksum update failed\n");
838                 goto free_ppbr;
839         }
840
841         ret = exfat_update_boot_checksum(bd, 1);
842         if (ret < 0)
843                 exfat_err("backup checksum update failed\n");
844 free_ppbr:
845         free(ppbr);
846
847         exfat_info("New volume serial : 0x%x\n", ui->volume_serial);
848
849         return ret;
850 }
851
852 unsigned int exfat_clus_to_blk_dev_off(struct exfat_blk_dev *bd,
853                 unsigned int clu_off_sectnr, unsigned int clu)
854 {
855         return clu_off_sectnr * bd->sector_size +
856                 (clu - EXFAT_RESERVED_CLUSTERS) * bd->cluster_size;
857 }
858
859 int exfat_get_next_clus(struct exfat *exfat, clus_t clus, clus_t *next)
860 {
861         off_t offset;
862
863         *next = EXFAT_EOF_CLUSTER;
864
865         if (!exfat_heap_clus(exfat, clus))
866                 return -EINVAL;
867
868         offset = (off_t)le32_to_cpu(exfat->bs->bsx.fat_offset) <<
869                                 exfat->bs->bsx.sect_size_bits;
870         offset += sizeof(clus_t) * clus;
871
872         if (exfat_read(exfat->blk_dev->dev_fd, next, sizeof(*next), offset)
873                         != sizeof(*next))
874                 return -EIO;
875         *next = le32_to_cpu(*next);
876         return 0;
877 }
878
879 int exfat_get_inode_next_clus(struct exfat *exfat, struct exfat_inode *node,
880                               clus_t clus, clus_t *next)
881 {
882         *next = EXFAT_EOF_CLUSTER;
883
884         if (node->is_contiguous) {
885                 if (!exfat_heap_clus(exfat, clus))
886                         return -EINVAL;
887                 *next = clus + 1;
888                 return 0;
889         }
890
891         return exfat_get_next_clus(exfat, clus, next);
892 }
893
894 int exfat_set_fat(struct exfat *exfat, clus_t clus, clus_t next_clus)
895 {
896         off_t offset;
897
898         offset = le32_to_cpu(exfat->bs->bsx.fat_offset) <<
899                 exfat->bs->bsx.sect_size_bits;
900         offset += sizeof(clus_t) * clus;
901
902         if (exfat_write(exfat->blk_dev->dev_fd, &next_clus, sizeof(next_clus),
903                         offset) != sizeof(next_clus))
904                 return -EIO;
905         return 0;
906 }
907
908 off_t exfat_s2o(struct exfat *exfat, off_t sect)
909 {
910         return sect << exfat->bs->bsx.sect_size_bits;
911 }
912
913 off_t exfat_c2o(struct exfat *exfat, unsigned int clus)
914 {
915         assert(clus >= EXFAT_FIRST_CLUSTER);
916
917         return exfat_s2o(exfat, le32_to_cpu(exfat->bs->bsx.clu_offset) +
918                                 ((off_t)(clus - EXFAT_FIRST_CLUSTER) <<
919                                  exfat->bs->bsx.sect_per_clus_bits));
920 }
921
922 int exfat_o2c(struct exfat *exfat, off_t device_offset,
923               unsigned int *clu, unsigned int *offset)
924 {
925         off_t heap_offset;
926
927         heap_offset = exfat_s2o(exfat, le32_to_cpu(exfat->bs->bsx.clu_offset));
928         if (device_offset < heap_offset)
929                 return -ERANGE;
930
931         *clu = (unsigned int)((device_offset - heap_offset) /
932                               exfat->clus_size) + EXFAT_FIRST_CLUSTER;
933         if (!exfat_heap_clus(exfat, *clu))
934                 return -ERANGE;
935         *offset = (device_offset - heap_offset) % exfat->clus_size;
936         return 0;
937 }
938
939 bool exfat_heap_clus(struct exfat *exfat, clus_t clus)
940 {
941         return clus >= EXFAT_FIRST_CLUSTER &&
942                 (clus - EXFAT_FIRST_CLUSTER) < exfat->clus_count;
943 }
944
945 int exfat_root_clus_count(struct exfat *exfat)
946 {
947         struct exfat_inode *node = exfat->root;
948         clus_t clus, next;
949         int clus_count = 0;
950
951         if (!exfat_heap_clus(exfat, node->first_clus))
952                 return -EIO;
953
954         clus = node->first_clus;
955         do {
956                 if (exfat_bitmap_get(exfat->alloc_bitmap, clus))
957                         return -EINVAL;
958
959                 exfat_bitmap_set(exfat->alloc_bitmap, clus);
960
961                 if (exfat_get_inode_next_clus(exfat, node, clus, &next)) {
962                         exfat_err("ERROR: failed to read the fat entry of root");
963                         return -EIO;
964                 }
965
966                 if (next != EXFAT_EOF_CLUSTER && !exfat_heap_clus(exfat, next))
967                         return -EINVAL;
968
969                 clus = next;
970                 clus_count++;
971         } while (clus != EXFAT_EOF_CLUSTER);
972
973         node->size = clus_count * exfat->clus_size;
974         return 0;
975 }
976
977 int read_boot_sect(struct exfat_blk_dev *bdev, struct pbr **bs)
978 {
979         struct pbr *pbr;
980         int err = 0;
981         unsigned int sect_size, clu_size;
982
983         pbr = malloc(sizeof(struct pbr));
984
985         if (exfat_read(bdev->dev_fd, pbr, sizeof(*pbr), 0) !=
986             (ssize_t)sizeof(*pbr)) {
987                 exfat_err("failed to read a boot sector\n");
988                 err = -EIO;
989                 goto err;
990         }
991
992         err = -EINVAL;
993         if (memcmp(pbr->bpb.oem_name, "EXFAT   ", 8) != 0) {
994                 exfat_err("failed to find exfat file system\n");
995                 goto err;
996         }
997
998         sect_size = 1 << pbr->bsx.sect_size_bits;
999         clu_size = 1 << (pbr->bsx.sect_size_bits +
1000                          pbr->bsx.sect_per_clus_bits);
1001
1002         if (sect_size < 512 || sect_size > 4 * KB) {
1003                 exfat_err("too small or big sector size: %d\n",
1004                           sect_size);
1005                 goto err;
1006         }
1007
1008         if (clu_size < sect_size || clu_size > 32 * MB) {
1009                 exfat_err("too small or big cluster size: %d\n",
1010                           clu_size);
1011                 goto err;
1012         }
1013
1014         *bs = pbr;
1015         return 0;
1016 err:
1017         free(pbr);
1018         return err;
1019 }