]> git.sven.stormbind.net Git - sven/exfatprogs.git/blob - lib/libexfat.c
New upstream version 1.1.2
[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
19 #include "exfat_ondisk.h"
20 #include "libexfat.h"
21 #include "version.h"
22
23 #define BITS_PER_LONG           (sizeof(long) * CHAR_BIT)
24
25 #ifdef WORDS_BIGENDIAN
26 #define BITOP_LE_SWIZZLE        ((BITS_PER_LONG - 1) & ~0x7)
27 #else
28 #define BITOP_LE_SWIZZLE        0
29 #endif
30
31 #define BIT_MASK(nr)            (1UL << ((nr) % BITS_PER_LONG))
32 #define BIT_WORD(nr)            ((nr) / BITS_PER_LONG)
33
34 unsigned int print_level  = EXFAT_INFO;
35
36 static inline void set_bit(int nr, void *addr)
37 {
38         unsigned long mask = BIT_MASK(nr);
39         unsigned long *p = ((unsigned long *)addr) + BIT_WORD(nr);
40
41         *p  |= mask;
42 }
43
44 static inline void clear_bit(int nr, void *addr)
45 {
46         unsigned long mask = BIT_MASK(nr);
47         unsigned long *p = ((unsigned long *)addr) + BIT_WORD(nr);
48
49         *p &= ~mask;
50 }
51
52 static inline void set_bit_le(int nr, void *addr)
53 {
54         set_bit(nr ^ BITOP_LE_SWIZZLE, addr);
55 }
56
57 static inline void clear_bit_le(int nr, void *addr)
58 {
59         clear_bit(nr ^ BITOP_LE_SWIZZLE, addr);
60 }
61
62 void exfat_set_bit(struct exfat_blk_dev *bd, char *bitmap,
63                 unsigned int clu)
64 {
65         int b;
66
67         b = clu & ((bd->sector_size << 3) - 1);
68
69         set_bit_le(b, bitmap);
70 }
71
72 void exfat_clear_bit(struct exfat_blk_dev *bd, char *bitmap,
73                 unsigned int clu)
74 {
75         int b;
76
77         b = clu & ((bd->sector_size << 3) - 1);
78
79         clear_bit_le(b, bitmap);
80 }
81
82 wchar_t exfat_bad_char(wchar_t w)
83 {
84         return (w < 0x0020)
85                 || (w == '*') || (w == '?') || (w == '<') || (w == '>')
86                 || (w == '|') || (w == '"') || (w == ':') || (w == '/')
87                 || (w == '\\');
88 }
89
90 void boot_calc_checksum(unsigned char *sector, unsigned short size,
91                 bool is_boot_sec, __le32 *checksum)
92 {
93         unsigned int index;
94
95         if (is_boot_sec) {
96                 for (index = 0; index < size; index++) {
97                         if ((index == 106) || (index == 107) || (index == 112))
98                                 continue;
99                         *checksum = ((*checksum & 1) ? 0x80000000 : 0) +
100                                 (*checksum >> 1) + sector[index];
101                 }
102         } else {
103                 for (index = 0; index < size; index++) {
104                         *checksum = ((*checksum & 1) ? 0x80000000 : 0) +
105                                 (*checksum >> 1) + sector[index];
106                 }
107         }
108 }
109
110 void show_version(void)
111 {
112         printf("exfatprogs version : %s\n", EXFAT_PROGS_VERSION);
113 }
114
115 static inline unsigned int sector_size_bits(unsigned int size)
116 {
117         unsigned int bits = 8;
118
119         do {
120                 bits++;
121                 size >>= 1;
122         } while (size > 256);
123
124         return bits;
125 }
126
127 static void exfat_set_default_cluster_size(struct exfat_blk_dev *bd,
128                 struct exfat_user_input *ui)
129 {
130         if (256 * MB >= bd->size)
131                 ui->cluster_size = 4 * KB;
132         else if (32 * GB >= bd->size)
133                 ui->cluster_size = 32 * KB;
134         else
135                 ui->cluster_size = 128 * KB;
136 }
137
138 void init_user_input(struct exfat_user_input *ui)
139 {
140         memset(ui, 0, sizeof(struct exfat_user_input));
141         ui->writeable = true;
142         ui->quick = true;
143 }
144
145 int exfat_get_blk_dev_info(struct exfat_user_input *ui,
146                 struct exfat_blk_dev *bd)
147 {
148         int fd, ret = -1;
149         off_t blk_dev_size;
150         struct stat st;
151         unsigned long long blk_dev_offset = 0;
152
153         fd = open(ui->dev_name, ui->writeable ? O_RDWR|O_EXCL : O_RDONLY);
154         if (fd < 0) {
155                 exfat_err("open failed : %s, %s\n", ui->dev_name,
156                         strerror(errno));
157                 return -1;
158         }
159         blk_dev_size = lseek(fd, 0, SEEK_END);
160         if (blk_dev_size <= 0) {
161                 exfat_err("invalid block device size(%s)\n",
162                         ui->dev_name);
163                 ret = blk_dev_size;
164                 close(fd);
165                 goto out;
166         }
167
168         if (fstat(fd, &st) == 0 && S_ISBLK(st.st_mode)) {
169                 char pathname[sizeof("/sys/dev/block/4294967295:4294967295/start")];
170                 FILE *fp;
171
172                 snprintf(pathname, sizeof(pathname), "/sys/dev/block/%u:%u/start",
173                         major(st.st_rdev), minor(st.st_rdev));
174                 fp = fopen(pathname, "r");
175                 if (fp != NULL) {
176                         if (fscanf(fp, "%llu", &blk_dev_offset) == 1) {
177                                 /*
178                                  * Linux kernel always reports partition offset
179                                  * in 512-byte units, regardless of sector size
180                                  */
181                                 blk_dev_offset <<= 9;
182                         }
183                         fclose(fp);
184                 }
185         }
186
187         bd->dev_fd = fd;
188         bd->offset = blk_dev_offset;
189         bd->size = blk_dev_size;
190         if (!ui->cluster_size)
191                 exfat_set_default_cluster_size(bd, ui);
192
193         if (!ui->boundary_align)
194                 ui->boundary_align = DEFAULT_BOUNDARY_ALIGNMENT;
195
196         if (ioctl(fd, BLKSSZGET, &bd->sector_size) < 0)
197                 bd->sector_size = DEFAULT_SECTOR_SIZE;
198         bd->sector_size_bits = sector_size_bits(bd->sector_size);
199         bd->num_sectors = blk_dev_size / bd->sector_size;
200         bd->num_clusters = blk_dev_size / ui->cluster_size;
201
202         exfat_debug("Block device name : %s\n", ui->dev_name);
203         exfat_debug("Block device offset : %llu\n", bd->offset);
204         exfat_debug("Block device size : %llu\n", bd->size);
205         exfat_debug("Block sector size : %u\n", bd->sector_size);
206         exfat_debug("Number of the sectors : %llu\n",
207                 bd->num_sectors);
208         exfat_debug("Number of the clusters : %u\n",
209                 bd->num_clusters);
210
211         ret = 0;
212         bd->dev_fd = fd;
213 out:
214         return ret;
215 }
216
217 ssize_t exfat_read(int fd, void *buf, size_t size, off_t offset)
218 {
219         return pread(fd, buf, size, offset);
220 }
221
222 ssize_t exfat_write(int fd, void *buf, size_t size, off_t offset)
223 {
224         return pwrite(fd, buf, size, offset);
225 }
226
227 size_t exfat_utf16_len(const __le16 *str, size_t max_size)
228 {
229         size_t i = 0;
230
231         while (le16_to_cpu(str[i]) && i < max_size)
232                 i++;
233         return i;
234 }
235
236 ssize_t exfat_utf16_enc(const char *in_str, __u16 *out_str, size_t out_size)
237 {
238         size_t mbs_len, out_len, i;
239         wchar_t *wcs;
240
241         mbs_len = mbstowcs(NULL, in_str, 0);
242         if (mbs_len == (size_t)-1) {
243                 if (errno == EINVAL || errno == EILSEQ)
244                         exfat_err("invalid character sequence in current locale\n");
245                 return -errno;
246         }
247
248         wcs = calloc(mbs_len+1, sizeof(wchar_t));
249         if (!wcs)
250                 return -ENOMEM;
251
252         /* First convert multibyte char* string to wchar_t* string */
253         if (mbstowcs(wcs, in_str, mbs_len+1) == (size_t)-1) {
254                 if (errno == EINVAL || errno == EILSEQ)
255                         exfat_err("invalid character sequence in current locale\n");
256                 free(wcs);
257                 return -errno;
258         }
259
260         /* Convert wchar_t* string (sequence of code points) to UTF-16 string */
261         for (i = 0, out_len = 0; i < mbs_len; i++) {
262                 if (2*(out_len+1) > out_size ||
263                     (wcs[i] >= 0x10000 && 2*(out_len+2) > out_size)) {
264                         exfat_err("input string is too long\n");
265                         free(wcs);
266                         return -E2BIG;
267                 }
268
269                 /* Encode code point above Plane0 as UTF-16 surrogate pair */
270                 if (wcs[i] >= 0x10000) {
271                         out_str[out_len++] =
272                           cpu_to_le16(((wcs[i] - 0x10000) >> 10) + 0xD800);
273                         wcs[i] = ((wcs[i] - 0x10000) & 0x3FF) + 0xDC00;
274                 }
275
276                 out_str[out_len++] = cpu_to_le16(wcs[i]);
277         }
278
279         free(wcs);
280         return 2*out_len;
281 }
282
283 ssize_t exfat_utf16_dec(const __u16 *in_str, size_t in_len,
284                         char *out_str, size_t out_size)
285 {
286         size_t wcs_len, out_len, c_len, i;
287         char c_str[MB_LEN_MAX];
288         wchar_t *wcs;
289         mbstate_t ps;
290         wchar_t w;
291
292         wcs = calloc(in_len/2+1, sizeof(wchar_t));
293         if (!wcs)
294                 return -ENOMEM;
295
296         /* First convert UTF-16 string to wchar_t* string */
297         for (i = 0, wcs_len = 0; i < in_len/2; i++, wcs_len++) {
298                 wcs[wcs_len] = le16_to_cpu(in_str[i]);
299                 /*
300                  * If wchar_t can store code point above Plane0
301                  * then unpack UTF-16 surrogate pair to code point
302                  */
303 #if WCHAR_MAX >= 0x10FFFF
304                 if (wcs[wcs_len] >= 0xD800 && wcs[wcs_len] <= 0xDBFF &&
305                     i+1 < in_len/2) {
306                         w = le16_to_cpu(in_str[i+1]);
307                         if (w >= 0xDC00 && w <= 0xDFFF) {
308                                 wcs[wcs_len] = 0x10000 +
309                                                ((wcs[wcs_len] - 0xD800) << 10) +
310                                                (w - 0xDC00);
311                                 i++;
312                         }
313                 }
314 #endif
315         }
316
317         memset(&ps, 0, sizeof(ps));
318
319         /* And then convert wchar_t* string to multibyte char* string */
320         for (i = 0, out_len = 0, c_len = 0; i <= wcs_len; i++) {
321                 c_len = wcrtomb(c_str, wcs[i], &ps);
322                 /*
323                  * If character is non-representable in current locale then
324                  * try to store it as Unicode replacement code point U+FFFD
325                  */
326                 if (c_len == (size_t)-1 && errno == EILSEQ)
327                         c_len = wcrtomb(c_str, 0xFFFD, &ps);
328                 /* If U+FFFD is also non-representable, try question mark */
329                 if (c_len == (size_t)-1 && errno == EILSEQ)
330                         c_len = wcrtomb(c_str, L'?', &ps);
331                 /* If also (7bit) question mark fails then we cannot do more */
332                 if (c_len == (size_t)-1) {
333                         exfat_err("invalid UTF-16 sequence\n");
334                         free(wcs);
335                         return -errno;
336                 }
337                 if (out_len+c_len > out_size) {
338                         exfat_err("input string is too long\n");
339                         free(wcs);
340                         return -E2BIG;
341                 }
342                 memcpy(out_str+out_len, c_str, c_len);
343                 out_len += c_len;
344         }
345
346         free(wcs);
347
348         /* Last iteration of above loop should have produced null byte */
349         if (c_len == 0 || out_str[out_len-1] != 0) {
350                 exfat_err("invalid UTF-16 sequence\n");
351                 return -errno;
352         }
353
354         return out_len-1;
355 }
356
357 off_t exfat_get_root_entry_offset(struct exfat_blk_dev *bd)
358 {
359         struct pbr *bs;
360         int nbytes;
361         unsigned int cluster_size, sector_size;
362         off_t root_clu_off;
363
364         bs = (struct pbr *)malloc(EXFAT_MAX_SECTOR_SIZE);
365         if (!bs) {
366                 exfat_err("failed to allocate memory\n");
367                 return -ENOMEM;
368         }
369
370         nbytes = exfat_read(bd->dev_fd, bs, EXFAT_MAX_SECTOR_SIZE, 0);
371         if (nbytes != EXFAT_MAX_SECTOR_SIZE) {
372                 exfat_err("boot sector read failed: %d\n", errno);
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_show_volume_label(struct exfat_blk_dev *bd, off_t root_clu_off)
409 {
410         struct exfat_dentry *vol_entry;
411         char *volume_label;
412         int nbytes;
413
414         vol_entry = malloc(sizeof(struct exfat_dentry));
415         if (!vol_entry) {
416                 exfat_err("failed to allocate memory\n");
417                 return -ENOMEM;
418         }
419
420         nbytes = exfat_read(bd->dev_fd, vol_entry,
421                 sizeof(struct exfat_dentry), root_clu_off);
422         if (nbytes != sizeof(struct exfat_dentry)) {
423                 exfat_err("volume entry read failed: %d\n", errno);
424                 free(vol_entry);
425                 return -1;
426         }
427
428         volume_label = exfat_conv_volume_label(vol_entry);
429         if (!volume_label) {
430                 free(vol_entry);
431                 return -EINVAL;
432         }
433
434         exfat_info("label: %s\n", volume_label);
435
436         free(volume_label);
437         free(vol_entry);
438         return 0;
439 }
440
441 int exfat_set_volume_label(struct exfat_blk_dev *bd,
442                 char *label_input, off_t root_clu_off)
443 {
444         struct exfat_dentry vol;
445         int nbytes;
446         __u16 volume_label[VOLUME_LABEL_MAX_LEN];
447         int volume_label_len;
448
449         volume_label_len = exfat_utf16_enc(label_input,
450                         volume_label, sizeof(volume_label));
451         if (volume_label_len < 0) {
452                 exfat_err("failed to encode volume label\n");
453                 return -1;
454         }
455
456         vol.type = EXFAT_VOLUME;
457         memset(vol.vol_label, 0, sizeof(vol.vol_label));
458         memcpy(vol.vol_label, volume_label, volume_label_len);
459         vol.vol_char_cnt = volume_label_len/2;
460
461         nbytes = exfat_write(bd->dev_fd, &vol, sizeof(struct exfat_dentry),
462                         root_clu_off);
463         if (nbytes != sizeof(struct exfat_dentry)) {
464                 exfat_err("volume entry write failed: %d\n", errno);
465                 return -1;
466         }
467         fsync(bd->dev_fd);
468
469         exfat_info("new label: %s\n", label_input);
470         return 0;
471 }
472
473 int exfat_read_sector(struct exfat_blk_dev *bd, void *buf, unsigned int sec_off)
474 {
475         int ret;
476         unsigned long long offset = sec_off * bd->sector_size;
477
478         lseek(bd->dev_fd, offset, SEEK_SET);
479         ret = read(bd->dev_fd, buf, bd->sector_size);
480         if (ret < 0) {
481                 exfat_err("read failed, sec_off : %u\n", sec_off);
482                 return -1;
483         }
484         return 0;
485 }
486
487 int exfat_write_sector(struct exfat_blk_dev *bd, void *buf,
488                 unsigned int sec_off)
489 {
490         int bytes;
491         unsigned long long offset = sec_off * bd->sector_size;
492
493         lseek(bd->dev_fd, offset, SEEK_SET);
494         bytes = write(bd->dev_fd, buf, bd->sector_size);
495         if (bytes != (int)bd->sector_size) {
496                 exfat_err("write failed, sec_off : %u, bytes : %d\n", sec_off,
497                         bytes);
498                 return -1;
499         }
500         return 0;
501 }
502
503 int exfat_write_checksum_sector(struct exfat_blk_dev *bd,
504                 unsigned int checksum, bool is_backup)
505 {
506         __le32 *checksum_buf;
507         int ret = 0;
508         unsigned int i;
509         unsigned int sec_idx = CHECKSUM_SEC_IDX;
510
511         checksum_buf = malloc(bd->sector_size);
512         if (!checksum_buf)
513                 return -1;
514
515         if (is_backup)
516                 sec_idx += BACKUP_BOOT_SEC_IDX;
517
518         for (i = 0; i < bd->sector_size / sizeof(int); i++)
519                 checksum_buf[i] = cpu_to_le32(checksum);
520
521         ret = exfat_write_sector(bd, checksum_buf, sec_idx);
522         if (ret) {
523                 exfat_err("checksum sector write failed\n");
524                 goto free;
525         }
526
527 free:
528         free(checksum_buf);
529         return ret;
530 }
531
532 int exfat_show_volume_serial(int fd)
533 {
534         struct pbr *ppbr;
535         int ret;
536
537         ppbr = malloc(EXFAT_MAX_SECTOR_SIZE);
538         if (!ppbr) {
539                 exfat_err("Cannot allocate pbr: out of memory\n");
540                 return -1;
541         }
542
543         /* read main boot sector */
544         ret = exfat_read(fd, (char *)ppbr, EXFAT_MAX_SECTOR_SIZE, 0);
545         if (ret < 0) {
546                 exfat_err("main boot sector read failed\n");
547                 ret = -1;
548                 goto free_ppbr;
549         }
550
551         exfat_info("volume serial : 0x%x\n", ppbr->bsx.vol_serial);
552
553 free_ppbr:
554         free(ppbr);
555         return ret;
556 }
557
558 static int exfat_update_boot_checksum(struct exfat_blk_dev *bd, bool is_backup)
559 {
560         unsigned int checksum = 0;
561         int ret, sec_idx, backup_sec_idx = 0;
562         unsigned char *buf;
563
564         buf = malloc(bd->sector_size);
565         if (!buf) {
566                 exfat_err("Cannot allocate pbr: out of memory\n");
567                 return -1;
568         }
569
570         if (is_backup)
571                 backup_sec_idx = BACKUP_BOOT_SEC_IDX;
572
573         for (sec_idx = BOOT_SEC_IDX; sec_idx < CHECKSUM_SEC_IDX; sec_idx++) {
574                 bool is_boot_sec = false;
575
576                 ret = exfat_read_sector(bd, buf, sec_idx + backup_sec_idx);
577                 if (ret < 0) {
578                         exfat_err("sector(%d) read failed\n", sec_idx);
579                         ret = -1;
580                         goto free_buf;
581                 }
582
583                 if (sec_idx == BOOT_SEC_IDX)
584                         is_boot_sec = true;
585
586                 boot_calc_checksum(buf, bd->sector_size, is_boot_sec,
587                         &checksum);
588         }
589
590         ret = exfat_write_checksum_sector(bd, checksum, is_backup);
591
592 free_buf:
593         free(buf);
594
595         return ret;
596 }
597
598 int exfat_set_volume_serial(struct exfat_blk_dev *bd,
599                 struct exfat_user_input *ui)
600 {
601         int ret;
602         struct pbr *ppbr;
603
604         ppbr = malloc(EXFAT_MAX_SECTOR_SIZE);
605         if (!ppbr) {
606                 exfat_err("Cannot allocate pbr: out of memory\n");
607                 return -1;
608         }
609
610         /* read main boot sector */
611         ret = exfat_read(bd->dev_fd, (char *)ppbr, EXFAT_MAX_SECTOR_SIZE,
612                         BOOT_SEC_IDX);
613         if (ret < 0) {
614                 exfat_err("main boot sector read failed\n");
615                 ret = -1;
616                 goto free_ppbr;
617         }
618
619         bd->sector_size = 1 << ppbr->bsx.sect_size_bits;
620         ppbr->bsx.vol_serial = ui->volume_serial;
621
622         /* update main boot sector */
623         ret = exfat_write_sector(bd, (char *)ppbr, BOOT_SEC_IDX);
624         if (ret < 0) {
625                 exfat_err("main boot sector write failed\n");
626                 ret = -1;
627                 goto free_ppbr;
628         }
629
630         /* update backup boot sector */
631         ret = exfat_write_sector(bd, (char *)ppbr, BACKUP_BOOT_SEC_IDX);
632         if (ret < 0) {
633                 exfat_err("backup boot sector write failed\n");
634                 ret = -1;
635                 goto free_ppbr;
636         }
637
638         ret = exfat_update_boot_checksum(bd, 0);
639         if (ret < 0) {
640                 exfat_err("main checksum update failed\n");
641                 goto free_ppbr;
642         }
643
644         ret = exfat_update_boot_checksum(bd, 1);
645         if (ret < 0)
646                 exfat_err("backup checksum update failed\n");
647 free_ppbr:
648         free(ppbr);
649
650         exfat_info("New volume serial : 0x%x\n", ui->volume_serial);
651
652         return ret;
653 }
654
655 unsigned int exfat_clus_to_blk_dev_off(struct exfat_blk_dev *bd,
656                 unsigned int clu_off_sectnr, unsigned int clu)
657 {
658         return clu_off_sectnr * bd->sector_size +
659                 (clu - EXFAT_RESERVED_CLUSTERS) * bd->cluster_size;
660 }