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