OSDN Git Service

Initial code drop.
authorrelan <relan@users.noreply.github.com>
Mon, 14 Sep 2009 18:44:13 +0000 (18:44 +0000)
committerrelan <relan@users.noreply.github.com>
Mon, 24 Aug 2015 05:26:09 +0000 (08:26 +0300)
SConstruct [new file with mode: 0644]
fsck/main.c [new file with mode: 0644]
fuse/main.c [new file with mode: 0644]
libexfat/cluster.c [new file with mode: 0644]
libexfat/exfat.h [new file with mode: 0644]
libexfat/exfatfs.h [new file with mode: 0644]
libexfat/io.c [new file with mode: 0644]
libexfat/log.c [new file with mode: 0644]
libexfat/lookup.c [new file with mode: 0644]
libexfat/utf.c [new file with mode: 0644]
libexfat/utils.c [new file with mode: 0644]

diff --git a/SConstruct b/SConstruct
new file mode 100644 (file)
index 0000000..e970b1c
--- /dev/null
@@ -0,0 +1,19 @@
+#
+#  SConstruct
+#  SConscript for all components.
+#
+#  Created by Andrew Nayenko on 10.09.09.
+#  This software is distributed under the GNU General Public License 
+#  version 3 or any later.
+#
+
+# Define __DARWIN_64_BIT_INO_T=0 is needed for Snow Leopard support because
+# in it's headers inode numbers are 64-bit by default, but libfuse operates
+# 32-bit inode numbers. It's also possible to link against libfuse_ino64
+# instead.
+cflags = '-Wall -O2 -ggdb -D_FILE_OFFSET_BITS=64 -D__DARWIN_64_BIT_INO_T=0 -Ilibexfat'
+ldflags = ''
+
+Library('libexfat/exfat', Glob('libexfat/*.c'), CFLAGS = cflags, LINKFLAGS = ldflags)
+Program('fsck/exfatck', Glob('fsck/*.c'), CFLAGS = cflags, LINKFLAGS = ldflags, LIBS = ['exfat'], LIBPATH = 'libexfat')
+Program('fuse/fuse-exfat', Glob('fuse/*.c'), CFLAGS = cflags + ' -DFUSE_USE_VERSION=26', LINKFLAGS = ldflags, LIBS = ['exfat', 'fuse'], LIBPATH = 'libexfat')
diff --git a/fsck/main.c b/fsck/main.c
new file mode 100644 (file)
index 0000000..ca7d7e0
--- /dev/null
@@ -0,0 +1,126 @@
+/*
+ *  main.c
+ *  exFAT file system checker.
+ *
+ *  Created by Andrew Nayenko on 02.09.09.
+ *  This software is distributed under the GNU General Public License 
+ *  version 3 or any later.
+ */
+
+#include <stdio.h>
+#include <string.h>
+#include <exfat.h>
+#include <exfatfs.h>
+#include <inttypes.h>
+
+#define exfat_debug(format, ...)
+
+#define MB (1024 * 1024)
+
+uint64_t files_count, directories_count;
+
+static uint64_t bytes2mb(uint64_t bytes)
+{
+       return (bytes + MB / 2) / MB;
+}
+
+static void sbck(const struct exfat* ef)
+{
+       const uint32_t block_size = (1 << ef->sb->block_bits); /* in bytes */
+       const uint32_t cluster_size = CLUSTER_SIZE(*ef->sb); /* in bytes */
+       const uint64_t total = le32_to_cpu(ef->sb->cluster_count) * cluster_size;
+
+#if 0 /* low-level info */
+       printf("First block           %8"PRIu64"\n",
+                       le64_to_cpu(ef->sb->block_start));
+       printf("Blocks count          %8"PRIu64"\n",
+                       le64_to_cpu(ef->sb->block_count));
+       printf("FAT first block       %8u\n",
+                       le32_to_cpu(ef->sb->fat_block_start));
+       printf("FAT blocks count      %8u\n",
+                       le32_to_cpu(ef->sb->fat_block_count));
+       printf("First cluster block   %8u\n",
+                       le32_to_cpu(ef->sb->cluster_block_start));
+       printf("Clusters count        %8u\n",
+                       le32_to_cpu(ef->sb->cluster_count));
+       printf("First cluster of root %8u\n",
+                       le32_to_cpu(ef->sb->rootdir_cluster));
+#endif
+       printf("Block size            %8u bytes\n", block_size);
+       printf("Cluster size          %8u bytes\n", cluster_size);
+       printf("Total space           %8"PRIu64" MB\n", bytes2mb(total));
+       printf("Used space            %8"PRIu64" MB (%hhu%%)\n",
+                       bytes2mb(total * ef->sb->allocated_percent / 100),
+                       ef->sb->allocated_percent);
+       printf("Free space            %8"PRIu64" MB (%hhu%%)\n",
+                       bytes2mb(total * (100 - ef->sb->allocated_percent) / 100),
+                       100 - ef->sb->allocated_percent);
+}
+
+static void dirck(struct exfat* ef, const char* path)
+{
+       struct exfat_node parent, node;
+       struct exfat_iterator it;
+       char subpath[EXFAT_NAME_MAX + 1];
+
+       if (exfat_lookup(ef, &parent, path) != 0)
+               exfat_bug("directory `%s' is not found", path);
+       if (!(parent.flags & EXFAT_ATTRIB_DIR))
+               exfat_bug("`%s' is not a directory (0x%x)", path, parent.flags);
+
+       exfat_opendir(&parent, &it);
+       while (exfat_readdir(ef, &node, &it) == 0)
+       {
+               exfat_debug("%s/%s: %s, %llu bytes, cluster %u", path, node.name,
+                               IS_CONTIGUOUS(node) ? "contiguous" : "fragmented",
+                               node.size, node.start_cluster);
+               if (node.flags & EXFAT_ATTRIB_DIR)
+               {
+                       directories_count++;
+                       strcpy(subpath, path);
+                       strcat(subpath, "/");
+                       exfat_get_name(&node, subpath + strlen(subpath),
+                                       EXFAT_NAME_MAX - strlen(subpath));
+                       dirck(ef, subpath);
+               }
+               else
+                       files_count++;
+       }
+       exfat_closedir(&it);
+}
+
+static void fsck(struct exfat* ef)
+{
+       sbck(ef);
+       dirck(ef, "");
+}
+
+int main(int argc, char* argv[])
+{
+       struct exfat ef;
+
+       if (argc != 2)
+       {
+               fprintf(stderr, "usage: %s <spec>\n", argv[0]);
+               return 1;
+       }
+       printf("exfatck %u.%u\n",
+                       EXFAT_VERSION_MAJOR, EXFAT_VERSION_MINOR);
+
+       if (exfat_mount(&ef, argv[1]) != 0)
+               return 1;
+
+       printf("Checking file system on %s.\n", argv[1]);
+       fsck(&ef);
+       exfat_unmount(&ef);
+       printf("Totally %"PRIu64" directories and %"PRIu64" files.\n",
+                       directories_count, files_count);
+
+       fputs("File system checking finished: ", stdout);
+       if (exfat_errors == 0)
+               puts("seems OK.");
+       else
+               printf("%d ERROR%s FOUND!!!\n", exfat_errors,
+                               exfat_errors > 1 ? "S WERE" : " WAS");
+       return 0;
+}
diff --git a/fuse/main.c b/fuse/main.c
new file mode 100644 (file)
index 0000000..939c341
--- /dev/null
@@ -0,0 +1,231 @@
+/*
+ *  main.c
+ *  FUSE-based exFAT implementation. Requires FUSE 2.6 or later.
+ *
+ *  Created by Andrew Nayenko on 01.09.09.
+ *  This software is distributed under the GNU General Public License 
+ *  version 3 or any later.
+ */
+
+#include <fuse.h>
+#include <errno.h>
+#include <fcntl.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <exfat.h>
+
+#define exfat_debug(format, ...)
+
+#if !defined(FUSE_VERSION) || (FUSE_VERSION < 26)
+       #error FUSE 2.6 or later is required
+#endif
+
+struct exfat ef;
+
+static struct exfat_node* get_node(const struct fuse_file_info *fi)
+{
+       return (struct exfat_node*) (size_t) fi->fh;
+}
+
+static void set_node(struct fuse_file_info *fi, struct exfat_node* node)
+{
+       fi->fh = (uint64_t) (size_t) node;
+}
+
+static int fuse_exfat_getattr(const char *path, struct stat *stbuf)
+{
+       struct exfat_node node;
+       int rc;
+
+       exfat_debug("[fuse_exfat_getattr] %s", path);
+
+       rc = exfat_lookup(&ef, &node, path);
+       if (rc != 0)
+               return rc;
+
+       exfat_stat(&node, stbuf);
+       return 0;
+}
+
+static int fuse_exfat_readdir(const char *path, void *buffer,
+               fuse_fill_dir_t filler, off_t offset, struct fuse_file_info *fi)
+{
+       struct exfat_node parent, node;
+       struct exfat_iterator it;
+       int rc;
+       char name[EXFAT_NAME_MAX + 1];
+
+       exfat_debug("[fuse_exfat_readdir] %s", path);
+
+       rc = exfat_lookup(&ef, &parent, path);
+       if (rc != 0)
+               return rc;
+       if (!(parent.flags & EXFAT_ATTRIB_DIR))
+               return -ENOTDIR;
+
+       filler(buffer, ".", NULL, 0);
+       filler(buffer, "..", NULL, 0);
+
+       exfat_opendir(&parent, &it);
+       while (exfat_readdir(&ef, &node, &it) == 0)
+       {
+               utf16_to_utf8(name, node.name, EXFAT_NAME_MAX, EXFAT_NAME_MAX);
+               exfat_debug("[fuse_exfat_readdir] %s: %s, %llu bytes, cluster %u",
+                               name, IS_CONTIGUOUS(node) ? "contiguous" : "fragmented",
+                               node.size, node.start_cluster);
+               filler(buffer, name, NULL, 0);
+       }
+       exfat_closedir(&it);
+       return 0;
+}
+
+static int fuse_exfat_open(const char *path, struct fuse_file_info *fi)
+{
+       struct exfat_node* node;
+
+       exfat_debug("[fuse_exfat_open] %s", path);
+
+       node = malloc(sizeof(struct exfat_node));
+       if (node == NULL)
+               return -ENOMEM;
+       if (exfat_lookup(&ef, node, path) != 0)
+       {
+               free(node);
+               return -ENOENT;
+       }
+       set_node(fi, node);
+       return 0;
+}
+
+static int fuse_exfat_release(const char *path, struct fuse_file_info *fi)
+{
+       free(get_node(fi));
+       return 0;
+}
+
+static int fuse_exfat_read(const char *path, char *buffer, size_t size,
+               off_t offset, struct fuse_file_info *fi)
+{
+       exfat_debug("[fuse_exfat_read] %s (%zu bytes)", path, size);
+       return exfat_read(&ef, get_node(fi), buffer, size, offset);
+}
+
+static int fuse_exfat_statfs(const char *path, struct statvfs *sfs)
+{
+       const uint64_t block_count = le64_to_cpu(ef.sb->block_count);
+
+       sfs->f_bsize = BLOCK_SIZE(*ef.sb);
+       sfs->f_frsize = CLUSTER_SIZE(*ef.sb);
+       sfs->f_blocks = block_count;
+       sfs->f_bavail = block_count - ef.sb->allocated_percent * block_count / 100;
+       sfs->f_bfree = sfs->f_bavail;
+       sfs->f_namemax = EXFAT_NAME_MAX;
+
+       /*
+          Below are fake values because in exFAT there is
+          a) no simple way to count files;
+          b) no such thing as inode;
+          So here we assume that inode = cluster.
+       */
+       sfs->f_files = (sfs->f_blocks - sfs->f_bfree) >> ef.sb->bpc_bits;
+       sfs->f_favail = sfs->f_bfree >> ef.sb->bpc_bits;
+       sfs->f_ffree = sfs->f_bavail;
+
+       return 0;
+}
+
+static void usage(const char* prog)
+{
+       fprintf(stderr, "Usage: %s <spec> <mountpoint> [-o options]\n", prog);
+       exit(1);
+}
+
+static struct fuse_operations fuse_exfat_ops =
+{
+       .getattr        = fuse_exfat_getattr,
+       .readdir        = fuse_exfat_readdir,
+       .open           = fuse_exfat_open,
+       .release        = fuse_exfat_release,
+       .read           = fuse_exfat_read,
+       .statfs         = fuse_exfat_statfs,
+};
+
+int main(int argc, char* argv[])
+{
+       struct fuse_args mount_args = FUSE_ARGS_INIT(0, NULL);
+       struct fuse_args newfs_args = FUSE_ARGS_INIT(0, NULL);
+       const char* spec = NULL;
+       const char* mount_point = NULL;
+       const char* mount_options = "";
+       struct fuse_chan* fc = NULL;
+       struct fuse* fh = NULL;
+       char** pp;
+
+       printf("FUSE exfat %u.%u\n", EXFAT_VERSION_MAJOR, EXFAT_VERSION_MINOR);
+
+       for (pp = argv + 1; *pp; pp++)
+       {
+               if (strcmp(*pp, "-o") == 0)
+               {
+                       pp++;
+                       if (*pp == NULL)
+                               usage(argv[0]);
+                       mount_options = *pp;
+               }
+               else if (spec == NULL)
+                       spec = *pp;
+               else if (mount_point == NULL)
+                       mount_point = *pp;
+               else
+                       usage(argv[0]);
+       }
+       if (spec == NULL || mount_point == NULL)
+               usage(argv[0]);
+
+       if (exfat_mount(&ef, spec) != 0)
+               goto error_exit;
+
+       /* create arguments for fuse_mount() */
+       if (fuse_opt_add_arg(&mount_args, "exfat") != 0 ||
+               fuse_opt_add_arg(&mount_args, "-o") != 0 ||
+               fuse_opt_add_arg(&mount_args, mount_options) != 0)
+               goto error_exfat_unmount;
+
+       /* create FUSE mount point */
+       fc = fuse_mount(mount_point, &mount_args);
+       fuse_opt_free_args(&mount_args);
+       if (fc == NULL)
+               goto error_exfat_unmount;
+
+       /* create arguments for fuse_new() */
+       if (fuse_opt_add_arg(&newfs_args, "") != 0)
+               goto error_fuse_unmount;
+
+       /* create new FUSE file system */
+       fh = fuse_new(fc, &newfs_args, &fuse_exfat_ops,
+                       sizeof(struct fuse_operations), NULL);
+       fuse_opt_free_args(&newfs_args);
+       if (fh == NULL)
+               goto error_fuse_unmount;
+
+       /* exit session on HUP, TERM and INT signals and ignore PIPE signal */
+       if (fuse_set_signal_handlers(fuse_get_session(fh)))
+               goto error_fuse_destroy;
+
+       /* FUSE main loop */
+       fuse_loop(fh);
+
+       fuse_destroy(fh);
+       fuse_unmount(mount_point, fc);
+       return 0;
+
+error_fuse_destroy:
+       fuse_destroy(fh);
+error_fuse_unmount:
+       fuse_unmount(mount_point, fc);
+error_exfat_unmount:
+       exfat_unmount(&ef);
+error_exit:
+       return 1;
+}
diff --git a/libexfat/cluster.c b/libexfat/cluster.c
new file mode 100644 (file)
index 0000000..2db8c81
--- /dev/null
@@ -0,0 +1,65 @@
+/*
+ *  cluster.c
+ *  exFAT file system implementation library.
+ *
+ *  Created by Andrew Nayenko on 03.09.09.
+ *  This software is distributed under the GNU General Public License 
+ *  version 3 or any later.
+ */
+
+#include "exfat.h"
+
+/*
+ * Cluster to block.
+ */
+static uint32_t c2b(const struct exfat* ef, cluster_t cluster)
+{
+       if (cluster < EXFAT_FIRST_DATA_CLUSTER)
+               exfat_bug("invalid cluster number %u", cluster);
+       return le32_to_cpu(ef->sb->cluster_block_start) +
+               ((cluster - EXFAT_FIRST_DATA_CLUSTER) << ef->sb->bpc_bits);
+}
+
+/*
+ * Cluster to absolute offset.
+ */
+off_t exfat_c2o(const struct exfat* ef, cluster_t cluster)
+{
+       return (off_t) c2b(ef, cluster) << ef->sb->block_bits;
+}
+
+/*
+ * Block to absolute offset.
+ */
+static off_t b2o(const struct exfat* ef, uint32_t block)
+{
+       return (off_t) block << ef->sb->block_bits;
+}
+
+cluster_t exfat_next_cluster(const struct exfat* ef, cluster_t cluster,
+               int contiguous)
+{
+       cluster_t next;
+       off_t fat_offset;
+
+       if (contiguous)
+               return cluster + 1;
+       fat_offset = b2o(ef, le32_to_cpu(ef->sb->fat_block_start))
+               + cluster * sizeof(cluster_t);
+       exfat_read_raw(&next, sizeof(next), fat_offset, ef->fd);
+       return next;
+}
+
+cluster_t exfat_advance_cluster(const struct exfat* ef, cluster_t cluster,
+               int contiguous, uint32_t count)
+{
+       uint32_t i;
+
+       for (i = 0; i < count; i++)
+       {
+               cluster = exfat_next_cluster(ef, cluster, contiguous);
+               if (CLUSTER_INVALID(cluster))
+                       break;
+       }
+       return cluster;
+}
diff --git a/libexfat/exfat.h b/libexfat/exfat.h
new file mode 100644 (file)
index 0000000..58b4568
--- /dev/null
@@ -0,0 +1,92 @@
+/*
+ *  exfat.h
+ *  Definitions of structures and constants used in exFAT file system
+ *  implementation.
+ *
+ *  Created by Andrew Nayenko on 29.08.09.
+ *  This software is distributed under the GNU General Public License 
+ *  version 3 or any later.
+ */
+
+#ifndef EXFAT_H_INCLUDED
+#define EXFAT_H_INCLUDED
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <time.h>
+#include <sys/stat.h>
+#include <sys/types.h>
+#include "exfatfs.h"
+
+#define EXFAT_VERSION_MAJOR 0
+#define EXFAT_VERSION_MINOR 5
+
+#define EXFAT_NAME_MAX 256
+#define EXFAT_ATTRIB_CONTIGUOUS 0x10000
+#define IS_CONTIGUOUS(node) (((node).flags & EXFAT_ATTRIB_CONTIGUOUS) != 0)
+#define BLOCK_SIZE(sb) (1 << (sb).block_bits)
+#define CLUSTER_SIZE(sb) (BLOCK_SIZE(sb) << (sb).bpc_bits)
+#define CLUSTER_INVALID(c) ((c) == EXFAT_CLUSTER_BAD || (c) == EXFAT_CLUSTER_END)
+
+struct exfat
+{
+       struct exfat_super_block* sb;
+       int fd;
+       time_t mount_time;
+       le16_t* upcase;
+       size_t upcase_chars;
+};
+
+struct exfat_node
+{
+       cluster_t start_cluster;
+       int flags;
+       uint64_t size;
+       time_t mtime, atime;
+       le16_t name[EXFAT_NAME_MAX + 1];
+};
+
+struct exfat_iterator
+{
+       cluster_t cluster;
+       off_t offset;
+       int contiguous;
+       char* chunk;
+};
+
+extern int exfat_errors;
+
+void exfat_bug(const char* format, ...);
+void exfat_error(const char* format, ...);
+void exfat_warn(const char* format, ...);
+void exfat_debug(const char* format, ...);
+
+void exfat_read_raw(void* buffer, size_t size, off_t offset, int fd);
+ssize_t exfat_read(const struct exfat* ef, const struct exfat_node* node,
+               void* buffer, size_t size, off_t offset);
+
+void exfat_opendir(struct exfat_node* node, struct exfat_iterator* it);
+void exfat_closedir(struct exfat_iterator* it);
+int exfat_readdir(struct exfat* ef, struct exfat_node* node,
+               struct exfat_iterator* it);
+int exfat_lookup(struct exfat* ef, struct exfat_node* node,
+               const char* path);
+
+off_t exfat_c2o(const struct exfat* ef, cluster_t cluster);
+cluster_t exfat_next_cluster(const struct exfat* ef, cluster_t cluster,
+               int contiguous);
+cluster_t exfat_advance_cluster(const struct exfat* ef, cluster_t cluster,
+               int contiguous, uint32_t count);
+
+int exfat_mount(struct exfat* ef, const char* spec);
+void exfat_unmount(struct exfat* ef);
+void exfat_stat(const struct exfat_node* node, struct stat *stbuf);
+time_t exfat_exfat2unix(le16_t date, le16_t time);
+void exfat_get_name(const struct exfat_node* node, char* buffer, size_t n);
+
+int utf16_to_utf8(char* output, const le16_t* input, size_t outsize,
+               size_t insize);
+int utf8_to_utf16(le16_t* output, const char* input, size_t outsize,
+               size_t insize);
+
+#endif /* ifndef EXFAT_H_INCLUDED */
diff --git a/libexfat/exfatfs.h b/libexfat/exfatfs.h
new file mode 100644 (file)
index 0000000..79a7a61
--- /dev/null
@@ -0,0 +1,146 @@
+/*
+ *  exfatfs.h
+ *  Definitions of structures and constants used in exFAT file system.
+ *
+ *  Created by Andrew Nayenko on 29.08.09.
+ *  This software is distributed under the GNU General Public License 
+ *  version 3 or any later.
+ */
+
+#ifndef EXFATFS_H_INCLUDED
+#define EXFATFS_H_INCLUDED
+
+#include <stdint.h>
+
+typedef uint32_t cluster_t;            /* cluster number */
+
+typedef struct { uint16_t __u16; } le16_t;
+typedef struct { uint32_t __u32; } le32_t;
+typedef struct { uint64_t __u64; } le64_t;
+
+static inline uint16_t le16_to_cpu(le16_t v) { return v.__u16; }
+static inline uint32_t le32_to_cpu(le32_t v) { return v.__u32; }
+static inline uint64_t le64_to_cpu(le64_t v) { return v.__u64; }
+
+static inline le16_t cpu_to_le16(uint16_t v) { le16_t t = {v}; return t; }
+static inline le32_t cpu_to_le32(uint32_t v) { le32_t t = {v}; return t; }
+static inline le64_t cpu_to_le64(uint64_t v) { le64_t t = {v}; return t; }
+
+#define EXFAT_FIRST_DATA_CLUSTER 2
+
+#define EXFAT_CLUSTER_BAD 0xfffffff7 /* cluster contains bad block */
+#define EXFAT_CLUSTER_END 0xffffffff /* final cluster of file or directory */
+
+struct exfat_super_block
+{
+       uint8_t jump[3];                                /* 0x00 jmp and nop instructions */
+       uint8_t oem_name[8];                    /* 0x03 "EXFAT   " */
+       uint8_t __unknown1[53];                 /* 0x0B ? always 0 */
+       le64_t block_start;                             /* 0x40 partition first block */
+       le64_t block_count;                             /* 0x48 partition blocks count */
+       le32_t fat_block_start;                 /* 0x50 FAT first block */
+       le32_t fat_block_count;                 /* 0x54 FAT blocks count */
+       le32_t cluster_block_start;             /* 0x58 first cluster block */
+       le32_t cluster_count;                   /* 0x5C total clusters count */
+       le32_t rootdir_cluster;                 /* 0x60 first cluster of the root dir */
+       le32_t volume_serial;                   /* 0x64 */
+       le16_t __unknown2;                              /* 0x68 version? always 0x00 0x01 */
+       le16_t volume_state;                    /* 0x6A */
+       uint8_t block_bits;                             /* 0x6C block size as (1 << n) */
+       uint8_t bpc_bits;                               /* 0x6D blocks per cluster as (1 << n) */
+       uint8_t __unknown3;                             /* 0x6E ? always 1 */
+       uint8_t __unknown4;                             /* 0x6F drive number? always 0x80 */
+       uint8_t allocated_percent;              /* 0x70 percentage of allocated space */
+       uint8_t __unknown5[397];                /* 0x71 padding? all zero */
+       le16_t boot_signature;                  /* the value of 0xAA55 */
+};
+
+#define EXFAT_ENTRY_VALID     0x80
+#define EXFAT_ENTRY_CONTINUED 0x40
+
+#define EXFAT_ENTRY_EOD       (0x00)
+#define EXFAT_ENTRY_BITMAP    (0x01 | EXFAT_ENTRY_VALID)
+#define EXFAT_ENTRY_UPCASE    (0x02 | EXFAT_ENTRY_VALID)
+#define EXFAT_ENTRY_LABEL     (0x03 | EXFAT_ENTRY_VALID)
+#define EXFAT_ENTRY_FILE      (0x05 | EXFAT_ENTRY_VALID)
+#define EXFAT_ENTRY_FILE_INFO (0x00 | EXFAT_ENTRY_VALID | EXFAT_ENTRY_CONTINUED)
+#define EXFAT_ENTRY_FILE_NAME (0x01 | EXFAT_ENTRY_VALID | EXFAT_ENTRY_CONTINUED)
+
+struct exfat_entry                                     /* common container for all entries */
+{
+       uint8_t type;                                   /* any of EXFAT_ENTRY_xxx */
+       uint8_t data[31];
+};
+
+#define EXFAT_ENAME_MAX 15
+
+struct exfat_bitmap                                    /* allocated clusters bitmap */
+{
+       uint8_t type;                                   /* EXFAT_ENTRY_BITMAP */
+       uint8_t __unknown1[19];
+       le32_t start_cluster;
+       le64_t size;                                    /* in bytes */
+};
+
+struct exfat_upcase                                    /* upper case translation table */
+{
+       uint8_t type;                                   /* EXFAT_ENTRY_UPCASE */
+       uint8_t __unknown1[3];
+       le32_t checksum;
+       uint8_t __unknown2[12];
+       le32_t start_cluster;
+       le64_t size;                                    /* in bytes */
+};
+
+struct exfat_label                                     /* volume label */
+{
+       uint8_t type;                                   /* EXFAT_ENTRY_LABEL */
+       uint8_t length;                                 /* number of characters */
+       le16_t name[EXFAT_ENAME_MAX];   /* in UTF-16LE */
+};
+
+#define EXFAT_ATTRIB_RO     0x01
+#define EXFAT_ATTRIB_HIDDEN 0x02
+#define EXFAT_ATTRIB_SYSTEM 0x04
+#define EXFAT_ATTRIB_VOLUME 0x08
+#define EXFAT_ATTRIB_DIR    0x10
+#define EXFAT_ATTRIB_ARCH   0x20
+
+struct exfat_file                                      /* file or directory */
+{
+       uint8_t type;                                   /* EXFAT_ENTRY_FILE */
+       uint8_t continuations;
+       le16_t checksum;
+       le16_t attrib;                                  /* combination of EXFAT_ATTRIB_xxx */
+       le16_t __unknown1;
+       le16_t crtime, crdate;                  /* creation date and time */
+       le16_t mtime, mdate;                    /* latest modification date and time */
+       le16_t atime, adate;                    /* latest access date and time */
+       uint8_t crtime_cs;                              /* creation time in cs (centiseconds) */
+       uint8_t mtime_cs;                               /* latest modification time in cs */
+       uint8_t __unknown2[10];
+};
+
+#define EXFAT_FLAG_FRAGMENTED 1
+#define EXFAT_FLAG_CONTIGUOUS 3
+
+struct exfat_file_info                         /* file or directory info */
+{
+       uint8_t type;                                   /* EXFAT_ENTRY_FILE_INFO */
+       uint8_t flag;                                   /* fragmented or contiguous */
+       uint8_t __unknown1;
+       uint8_t name_length;
+       le16_t hash;
+       uint8_t __unknown[14];
+       le32_t start_cluster;
+       le64_t size;                                    /* in bytes */
+};
+
+struct exfat_file_name                         /* file or directory name */
+{
+       uint8_t type;                                   /* EXFAT_ENTRY_FILE_NAME */
+       uint8_t __unknown;
+       le16_t name[EXFAT_ENAME_MAX];   /* in UTF-16LE */
+};
+
+#endif /* ifndef EXFATFS_H_INCLUDED */
diff --git a/libexfat/io.c b/libexfat/io.c
new file mode 100644 (file)
index 0000000..6e728cb
--- /dev/null
@@ -0,0 +1,65 @@
+/*
+ *  io.c
+ *  exFAT file system implementation library.
+ *
+ *  Created by Andrew Nayenko on 02.09.09.
+ *  This software is distributed under the GNU General Public License 
+ *  version 3 or any later.
+ */
+
+#include "exfat.h"
+#include <sys/types.h>
+#include <sys/uio.h>
+#define __USE_UNIX98 /* for pread() in Linux */
+#include <unistd.h>
+
+#if _FILE_OFFSET_BITS != 64
+       #error You should define _FILE_OFFSET_BITS=64
+#endif
+
+#define MIN(a, b) ((a) < (b) ? (a) : (b))
+
+void exfat_read_raw(void* buffer, size_t size, off_t offset, int fd)
+{
+       if (pread(fd, buffer, size, offset) != size)
+               exfat_bug("failed to read %zu bytes from file at %llu", size, offset);
+}
+
+ssize_t exfat_read(const struct exfat* ef, const struct exfat_node* node,
+               void* buffer, size_t size, off_t offset)
+{
+       cluster_t cluster;
+       char* bufp = buffer;
+       off_t lsize, loffset, remainder;
+
+       if (offset >= node->size)
+               return 0;
+       if (size == 0)
+               return 0;
+
+       cluster = exfat_advance_cluster(ef, node->start_cluster,
+                       IS_CONTIGUOUS(*node), offset / CLUSTER_SIZE(*ef->sb));
+       if (CLUSTER_INVALID(cluster))
+       {
+               exfat_error("got invalid cluster");
+               return -1;
+       }
+
+       loffset = offset % CLUSTER_SIZE(*ef->sb);
+       remainder = MIN(size, node->size - offset);
+       while (remainder > 0)
+       {
+               lsize = MIN(CLUSTER_SIZE(*ef->sb) - loffset, remainder);
+               exfat_read_raw(bufp, lsize, exfat_c2o(ef, cluster) + loffset, ef->fd);
+               bufp += lsize;
+               loffset = 0;
+               remainder -= lsize;
+               cluster = exfat_next_cluster(ef, cluster, IS_CONTIGUOUS(*node));
+               if (CLUSTER_INVALID(cluster))
+               {
+                       exfat_error("got invalid cluster");
+                       return -1;
+               }
+       }
+       return size - remainder;
+}
diff --git a/libexfat/log.c b/libexfat/log.c
new file mode 100644 (file)
index 0000000..60bd822
--- /dev/null
@@ -0,0 +1,76 @@
+/*
+ *  log.c
+ *  exFAT file system implementation library.
+ *
+ *  Created by Andrew Nayenko on 02.09.09.
+ *  This software is distributed under the GNU General Public License 
+ *  version 3 or any later.
+ */
+
+#include "exfat.h"
+#include <stdarg.h>
+
+int exfat_errors;
+
+/*
+ * This message means an internal bug in exFAT implementation.
+ */
+void exfat_bug(const char* format, ...)
+{
+       va_list ap;
+
+       fflush(stdout);
+       fputs("BUG: ", stderr);
+       va_start(ap, format);
+       vfprintf(stderr, format, ap);
+       va_end(ap);
+       fputs(".\n", stderr);
+       exit(1);
+}
+
+/*
+ * This message means an error in exFAT file system.
+ */
+void exfat_error(const char* format, ...)
+{
+       va_list ap;
+
+       exfat_errors++;
+       fflush(stdout);
+       fputs("ERROR: ", stderr);
+       va_start(ap, format);
+       vfprintf(stderr, format, ap);
+       va_end(ap);
+       fputs(".\n", stderr);
+}
+
+/*
+ * This message means that there is something unexpected in exFAT file system
+ * that can be a potential problem.
+ */
+void exfat_warn(const char* format, ...)
+{
+       va_list ap;
+
+       fflush(stdout);
+       fputs("WARN: ", stderr);
+       va_start(ap, format);
+       vfprintf(stderr, format, ap);
+       va_end(ap);
+       fputs(".\n", stderr);
+}
+
+/*
+ * Just debug message. Disabled by default.
+ */
+void exfat_debug(const char* format, ...)
+{
+       va_list ap;
+
+       fflush(stdout);
+       fputs("DEBUG: ", stderr);
+       va_start(ap, format);
+       vfprintf(stderr, format, ap);
+       va_end(ap);
+       fputs(".\n", stderr);
+}
diff --git a/libexfat/lookup.c b/libexfat/lookup.c
new file mode 100644 (file)
index 0000000..a125895
--- /dev/null
@@ -0,0 +1,268 @@
+/*
+ *  lookup.c
+ *  exFAT file system implementation library.
+ *
+ *  Created by Andrew Nayenko on 02.09.09.
+ *  This software is distributed under the GNU General Public License 
+ *  version 3 or any later.
+ */
+
+#include "exfat.h"
+#include <string.h>
+#include <errno.h>
+#include <inttypes.h>
+
+void exfat_opendir(struct exfat_node* node, struct exfat_iterator* it)
+{
+       if (!(node->flags & EXFAT_ATTRIB_DIR))
+               exfat_bug("`%s' is not a directory", node->name);
+       it->cluster = node->start_cluster;
+       it->offset = 0;
+       it->contiguous = IS_CONTIGUOUS(*node);
+       it->chunk = NULL;
+}
+
+void exfat_closedir(struct exfat_iterator* it)
+{
+       it->cluster = 0;
+       it->offset = 0;
+       it->contiguous = 0;
+       free(it->chunk);
+       it->chunk = NULL;
+}
+
+/*
+ * Reads one entry in directory at position pointed by iterator and fills
+ * node structure.
+ */
+int exfat_readdir(struct exfat* ef, struct exfat_node* node,
+               struct exfat_iterator* it)
+{
+       const struct exfat_entry* entry;
+       const struct exfat_file* file;
+       const struct exfat_file_info* file_info;
+       const struct exfat_file_name* file_name;
+       const struct exfat_upcase* upcase;
+       uint8_t continuations = 0;
+       le16_t* namep = NULL;
+
+       if (it->chunk == NULL)
+       {
+               it->chunk = malloc(CLUSTER_SIZE(*ef->sb));
+               if (it->chunk == NULL)
+               {
+                       exfat_error("out of memory");
+                       return -ENOMEM;
+               }
+               exfat_read_raw(it->chunk, CLUSTER_SIZE(*ef->sb),
+                               exfat_c2o(ef, it->cluster), ef->fd);
+       }
+
+       for (;;)
+       {
+               /* every directory (even empty one) occupies at least one cluster and
+                  must contain EOD entry */
+               entry = (const struct exfat_entry*)
+                               (it->chunk + it->offset % CLUSTER_SIZE(*ef->sb));
+               /* move iterator to the next entry in the directory */
+               it->offset += sizeof(struct exfat_entry);
+
+               switch (entry->type)
+               {
+               case EXFAT_ENTRY_EOD:
+                       if (continuations != 0)
+                       {
+                               exfat_error("expected %hhu continuations before EOD",
+                                               continuations);
+                               return -EIO;
+                       }
+                       return -ENOENT; /* that's OK, means end of directory */
+
+               case EXFAT_ENTRY_FILE:
+                       if (continuations != 0)
+                       {
+                               exfat_error("expected %hhu continuations before new entry",
+                                               continuations);
+                               return -EIO;
+                       }
+                       memset(node, 0, sizeof(struct exfat_node));
+                       file = (const struct exfat_file*) entry;
+                       node->flags = le16_to_cpu(file->attrib);
+                       node->mtime = exfat_exfat2unix(file->mdate, file->mtime);
+                       node->atime = exfat_exfat2unix(file->adate, file->atime);
+                       namep = node->name;
+                       continuations = file->continuations;
+                       /* each file entry must have at least 2 continuations:
+                          info and name */
+                       if (continuations < 2)
+                       {
+                               exfat_error("too few continuations (%hhu)", continuations);
+                               return -EIO;
+                       }
+                       break;
+
+               case EXFAT_ENTRY_FILE_INFO:
+                       if (continuations < 2)
+                       {
+                               exfat_error("unexpected continuation (%hhu)",
+                                               continuations);
+                               return -EIO;
+                       }
+                       file_info = (const struct exfat_file_info*) entry;
+                       node->size = le64_to_cpu(file_info->size);
+                       node->start_cluster = le32_to_cpu(file_info->start_cluster);
+                       if (file_info->flag == EXFAT_FLAG_CONTIGUOUS)
+                               node->flags |= EXFAT_ATTRIB_CONTIGUOUS;
+                       --continuations;
+                       break;
+
+               case EXFAT_ENTRY_FILE_NAME:
+                       if (continuations == 0)
+                       {
+                               exfat_error("unexpected continuation");
+                               return -EIO;
+                       }
+                       file_name = (const struct exfat_file_name*) entry;
+                       memcpy(namep, file_name->name, EXFAT_ENAME_MAX * sizeof(le16_t));
+                       namep += EXFAT_ENAME_MAX;
+                       if (--continuations == 0)
+                               return 0; /* entry completed */
+                       break;
+
+               case EXFAT_ENTRY_UPCASE:
+                       if (ef->upcase != NULL)
+                               break;
+                       upcase = (const struct exfat_upcase*) entry;
+                       if (CLUSTER_INVALID(le32_to_cpu(upcase->start_cluster)))
+                       {
+                               exfat_error("invalid cluster in upcase table");
+                               return -EIO;
+                       }
+                       if (le64_to_cpu(upcase->size) == 0 ||
+                               le64_to_cpu(upcase->size) > 0xffff * sizeof(uint16_t) ||
+                               le64_to_cpu(upcase->size) % sizeof(uint16_t) != 0)
+                       {
+                               exfat_error("bad upcase table size (%"PRIu64" bytes)",
+                                               le64_to_cpu(upcase->size));
+                               return -EIO;
+                       }
+                       ef->upcase = malloc(le64_to_cpu(upcase->size));
+                       ef->upcase_chars = le64_to_cpu(upcase->size) / sizeof(le16_t);
+
+                       /* set up a few fields in node just to satisfy exfat_read() */
+                       memset(node, 0, sizeof(struct exfat_node));
+                       node->start_cluster = le32_to_cpu(upcase->start_cluster);
+                       node->flags = EXFAT_ATTRIB_CONTIGUOUS;
+                       node->size = le64_to_cpu(upcase->size);
+                       if (exfat_read(ef, node, ef->upcase, node->size, 0) != node->size)
+                               return -EIO;
+                       break;
+               }
+
+               /* fetch the next cluster if needed */
+               if ((it->offset & (CLUSTER_SIZE(*ef->sb) - 1)) == 0)
+               {
+                       it->cluster = exfat_next_cluster(ef, it->cluster, it->contiguous);
+                       if (CLUSTER_INVALID(it->cluster))
+                       {
+                               exfat_error("invalid cluster while reading directory");
+                               return -EIO;
+                       }
+                       exfat_read_raw(it->chunk, CLUSTER_SIZE(*ef->sb),
+                                       exfat_c2o(ef, it->cluster), ef->fd);
+               }
+       }
+       /* we never reach here */
+}
+
+static int compare_char(struct exfat* ef, uint16_t a, uint16_t b)
+{
+       if (a >= ef->upcase_chars || b >= ef->upcase_chars)
+               return a - b;
+       else
+               return le16_to_cpu(ef->upcase[a]) - le16_to_cpu(ef->upcase[b]);
+}
+
+static int compare_name(struct exfat* ef, const le16_t* a, const le16_t* b)
+{
+       while (le16_to_cpu(*a) && le16_to_cpu(*b))
+       {
+               if (compare_char(ef, le16_to_cpu(*a), le16_to_cpu(*b)) != 0)
+                       break;
+               a++;
+               b++;
+       }
+       return le16_to_cpu(*a) - le16_to_cpu(*b);
+}
+
+static int lookup_name(struct exfat* ef, struct exfat_node* node,
+               const le16_t* name)
+{
+       struct exfat_iterator it;
+
+       exfat_opendir(node, &it);
+       while (exfat_readdir(ef, node, &it) == 0)
+       {
+               if (compare_name(ef, name, node->name) == 0)
+               {
+                       exfat_closedir(&it);
+                       return 0;
+               }
+       }
+       exfat_closedir(&it);
+       return -ENOENT;
+}
+
+int exfat_lookup(struct exfat* ef, struct exfat_node* node,
+               const char* path)
+{
+       le16_t buffer[EXFAT_NAME_MAX + 1];
+       int rc;
+       le16_t* p;
+       le16_t* subpath;
+
+       if (strlen(path) > EXFAT_NAME_MAX)
+       {
+               exfat_error("file name `%s' is too long", path);
+               return -ENAMETOOLONG;
+       }
+
+       rc = utf8_to_utf16(buffer, path, EXFAT_NAME_MAX, strlen(path));
+       if (rc != 0)
+               return rc;
+
+       /* start from the root directory */
+       node->flags = EXFAT_ATTRIB_DIR;
+       node->size = 0;
+       node->start_cluster = le32_to_cpu(ef->sb->rootdir_cluster);
+       node->name[0] = cpu_to_le16('\0');
+       /* exFAT does not have time attributes for the root directory */
+       node->mtime = ef->mount_time;
+       node->atime = ef->mount_time;
+
+       for (subpath = p = buffer; p; subpath = p + 1)
+       {
+               while (le16_to_cpu(*subpath) == '/')
+                       subpath++;              /* skip leading slashes */
+               for (p = subpath; ; p++)
+               {
+                       if (le16_to_cpu(*p) == '\0')
+                       {
+                               p = NULL;
+                               break;
+                       }
+                       if (le16_to_cpu(*p) == '/')
+                       {
+                               *p = cpu_to_le16('\0');
+                               break;
+                       }
+               }
+               if (le16_to_cpu(*subpath) == '\0')
+                       break;                  /* skip trailing slashes */
+               if (le16_to_cpu(subpath[0]) == '.' && le16_to_cpu(subpath[1]) == '\0')
+                       continue;               /* skip "." component */
+               if (lookup_name(ef, node, subpath) != 0)
+                       return -ENOENT;
+       }
+       return 0;
+}
diff --git a/libexfat/utf.c b/libexfat/utf.c
new file mode 100644 (file)
index 0000000..6465661
--- /dev/null
@@ -0,0 +1,213 @@
+/*
+ *  utf.c
+ *  exFAT file system implementation library.
+ *
+ *  Created by Andrew Nayenko on 13.09.09.
+ *  This software is distributed under the GNU General Public License 
+ *  version 3 or any later.
+ */
+
+#include "exfat.h"
+#include <errno.h>
+
+static char* wchar_to_utf8(char* output, wchar_t wc, size_t outsize)
+{
+       if (wc <= 0x7f)
+       {
+               if (outsize < 1)
+                       return NULL;
+               *output++ = (char) wc;
+       }
+       else if (wc <= 0x7ff)
+       {
+               if (outsize < 2)
+                       return NULL;
+               *output++ = 0xc0 | (wc >> 6);
+               *output++ = 0x80 | (wc & 0x3f);
+       }
+       else if (wc <= 0xffff)
+       {
+               if (outsize < 3)
+                       return NULL;
+               *output++ = 0xe0 | (wc >> 12);
+               *output++ = 0x80 | ((wc >> 6) & 0x3f);
+               *output++ = 0x80 | (wc & 0x3f);
+       }
+       else if (wc <= 0x1fffff)
+       {
+               if (outsize < 4)
+                       return NULL;
+               *output++ = 0xf0 | (wc >> 18);
+               *output++ = 0x80 | ((wc >> 12) & 0x3f);
+               *output++ = 0x80 | ((wc >> 6) & 0x3f);
+               *output++ = 0x80 | (wc & 0x3f);
+       }
+       else if (wc <= 0x3ffffff)
+       {
+               if (outsize < 5)
+                       return NULL;
+               *output++ = 0xf8 | (wc >> 24);
+               *output++ = 0x80 | ((wc >> 18) & 0x3f);
+               *output++ = 0x80 | ((wc >> 12) & 0x3f);
+               *output++ = 0x80 | ((wc >> 6) & 0x3f);
+               *output++ = 0x80 | (wc & 0x3f);
+       }
+       else if (wc <= 0x7fffffff)
+       {
+               if (outsize < 6)
+                       return NULL;
+               *output++ = 0xfc | (wc >> 30);
+               *output++ = 0x80 | ((wc >> 24) & 0x3f);
+               *output++ = 0x80 | ((wc >> 18) & 0x3f);
+               *output++ = 0x80 | ((wc >> 12) & 0x3f);
+               *output++ = 0x80 | ((wc >> 6) & 0x3f);
+               *output++ = 0x80 | (wc & 0x3f);
+       }
+       else
+               return NULL;
+
+       return output;
+}
+
+static const le16_t* utf16_to_wchar(const le16_t* input, wchar_t* wc,
+               size_t insize)
+{
+       if ((le16_to_cpu(input[0]) & 0xfc00) == 0xd800)
+       {
+               if (insize < 2 || (le16_to_cpu(input[1]) & 0xfc00) != 0xdc00)
+                       return NULL;
+               *wc = ((wchar_t) (le16_to_cpu(input[0]) & 0x3ff) << 10);
+               *wc |= (le16_to_cpu(input[1]) & 0x3ff);
+               return input + 2;
+       }
+       else
+       {
+               *wc = le16_to_cpu(*input);
+               return input + 1;
+       }
+}
+
+int utf16_to_utf8(char* output, const le16_t* input, size_t outsize,
+               size_t insize)
+{
+       const le16_t* inp = input;
+       char* outp = output;
+       wchar_t wc;
+
+       while (inp - input < insize && le16_to_cpu(*inp))
+       {
+               inp = utf16_to_wchar(inp, &wc, insize - (inp - input));
+               if (inp == NULL)
+               {
+                       exfat_error("illegal UTF-16 sequence");
+                       return -EILSEQ;
+               }
+               outp = wchar_to_utf8(outp, wc, outsize - (outp - output));
+               if (outp == NULL)
+               {
+                       exfat_error("name is too long");
+                       return -ENAMETOOLONG;
+               }
+       }
+       *outp = '\0';
+       return 0;
+}
+
+static const char* utf8_to_wchar(const char* input, wchar_t* wc,
+               size_t insize)
+{
+       if ((input[0] & 0x80) == 0 && insize >= 1)
+       {
+               *wc = (wchar_t) input[0];
+               return input + 1;
+       }
+       if ((input[0] & 0xe0) == 0xc0 && insize >= 2)
+       {
+               *wc = (((wchar_t) input[0] & 0x1f) << 6) |
+                      ((wchar_t) input[1] & 0x3f);
+               return input + 2;
+       }
+       if ((input[0] & 0xf0) == 0xe0 && insize >= 3)
+       {
+               *wc = (((wchar_t) input[0] & 0x0f) << 12) |
+                     (((wchar_t) input[1] & 0x3f) << 6) |
+                      ((wchar_t) input[2] & 0x3f);
+               return input + 3;
+       }
+       if ((input[0] & 0xf8) == 0xf0 && insize >= 4)
+       {
+               *wc = (((wchar_t) input[0] & 0x07) << 18) |
+                     (((wchar_t) input[1] & 0x3f) << 12) |
+                     (((wchar_t) input[2] & 0x3f) << 6) |
+                      ((wchar_t) input[3] & 0x3f);
+               return input + 4;
+       }
+       if ((input[0] & 0xfc) == 0xf8 && insize >= 5)
+       {
+               *wc = (((wchar_t) input[0] & 0x03) << 24) |
+                     (((wchar_t) input[1] & 0x3f) << 18) |
+                     (((wchar_t) input[2] & 0x3f) << 12) |
+                     (((wchar_t) input[3] & 0x3f) << 6) |
+                      ((wchar_t) input[4] & 0x3f);
+               return input + 5;
+       }
+       if ((input[0] & 0xfe) == 0xfc && insize >= 6)
+       {
+               *wc = (((wchar_t) input[0] & 0x01) << 30) |
+                     (((wchar_t) input[1] & 0x3f) << 24) |
+                     (((wchar_t) input[2] & 0x3f) << 18) |
+                     (((wchar_t) input[3] & 0x3f) << 12) |
+                     (((wchar_t) input[4] & 0x3f) << 6) |
+                      ((wchar_t) input[5] & 0x3f);
+               return input + 6;
+       }
+       return NULL;
+}
+
+static le16_t* wchar_to_utf16(le16_t* output, wchar_t wc, size_t outsize)
+{
+       if (wc <= 0xffff) /* if character is from BMP */
+       {
+               if (outsize == 0)
+               {
+                       exfat_error("name is too long");
+                       return NULL;
+               }
+               output[0] = cpu_to_le16(wc);
+               return output + 1;
+       }
+       if (outsize < 2)
+       {
+               exfat_error("name is too long");
+               return NULL;
+       }
+       output[0] = cpu_to_le16(0xd800 | ((wc >> 10) & 0x3ff));
+       output[1] = cpu_to_le16(0xdc00 | (wc & 0x3ff));
+       return output + 2;
+}
+
+int utf8_to_utf16(le16_t* output, const char* input, size_t outsize,
+               size_t insize)
+{
+       const char* inp = input;
+       le16_t* outp = output;
+       wchar_t wc;
+
+       while (inp - input < insize && *inp)
+       {
+               inp = utf8_to_wchar(inp, &wc, insize - (inp - input));
+               if (inp == NULL)
+               {
+                       exfat_error("illegal UTF-8 sequence");
+                       return -EILSEQ;
+               }
+               outp = wchar_to_utf16(outp, wc, outsize - (outp - output));
+               if (outp == NULL)
+               {
+                       exfat_error("name is too long");
+                       return -ENAMETOOLONG;
+               }
+       }
+       *outp = cpu_to_le16(0);
+       return 0;
+}
diff --git a/libexfat/utils.c b/libexfat/utils.c
new file mode 100644 (file)
index 0000000..47dd1ed
--- /dev/null
@@ -0,0 +1,179 @@
+/*
+ *  utils.c
+ *  exFAT file system implementation library.
+ *
+ *  Created by Andrew Nayenko on 04.09.09.
+ *  This software is distributed under the GNU General Public License 
+ *  version 3 or any later.
+ */
+
+#include "exfat.h"
+#include <stdlib.h>
+#include <string.h>
+#include <errno.h>
+#include <fcntl.h>
+#include <unistd.h>
+#include <time.h>
+#include <sys/time.h>
+
+int exfat_mount(struct exfat* ef, const char* spec)
+{
+       ef->sb = malloc(sizeof(struct exfat_super_block));
+       if (ef->sb == NULL)
+       {
+               exfat_error("memory allocation failed");
+               return -ENOMEM;
+       }
+
+       ef->fd = open(spec, O_RDONLY); /* currently read only */
+       if (ef->fd < 0)
+       {
+               free(ef->sb);
+               exfat_error("failed to open `%s'", spec);
+               return -EIO;
+       }
+
+       exfat_read_raw(ef->sb, sizeof(struct exfat_super_block), 0, ef->fd);
+       if (memcmp(ef->sb->oem_name, "EXFAT   ", 8) != 0)
+       {
+               close(ef->fd);
+               free(ef->sb);
+               exfat_error("exFAT file system is not found");
+               return -EIO;
+       }
+
+       ef->mount_time = time(NULL);
+       ef->upcase = NULL;
+       ef->upcase_chars = 0;
+
+       return 0;
+}
+
+void exfat_unmount(struct exfat* ef)
+{
+       close(ef->fd);
+       ef->fd = 0;
+       free(ef->sb);
+       ef->sb = NULL;
+       free(ef->upcase);
+       ef->upcase = NULL;
+       ef->upcase_chars = 0;
+}
+
+void exfat_stat(const struct exfat_node* node, struct stat *stbuf)
+{
+       memset(stbuf, 0, sizeof(struct stat));
+       if (node->flags & EXFAT_ATTRIB_DIR)
+               stbuf->st_mode = S_IFDIR | 0755;
+       else
+               stbuf->st_mode = S_IFREG | 0444;
+       stbuf->st_nlink = 1;
+       stbuf->st_size = node->size;
+       stbuf->st_mtime = node->mtime;
+       stbuf->st_atime = node->atime;
+       stbuf->st_ctime = 0; /* unapplicable */
+}
+
+#define SEC_IN_MIN 60ll
+#define SEC_IN_HOUR (60 * SEC_IN_MIN)
+#define SEC_IN_DAY (24 * SEC_IN_HOUR)
+#define SEC_IN_YEAR (365 * SEC_IN_DAY) /* not leap year */
+/* Unix epoch started at 0:00:00 UTC 1 January 1970 */
+#define UNIX_EPOCH_YEAR 1970
+/* exFAT epoch started at 0:00:00 UTC 1 January 1980 */
+#define EXFAT_EPOCH_YEAR 1980
+/* number of years from Unix epoch to exFAT epoch */
+#define EPOCH_DIFF_YEAR (EXFAT_EPOCH_YEAR - UNIX_EPOCH_YEAR)
+/* number of seconds from Unix epoch to exFAT epoch (considering leap years) */
+#define EPOCH_DIFF_SEC (EPOCH_DIFF_YEAR*365 + EPOCH_DIFF_YEAR/4) * SEC_IN_DAY
+
+static const time_t days_in_year[] =
+{
+       /* Jan  Feb  Mar  Apr  May  Jun  Jul  Aug  Sep  Oct  Nov  Dec */
+       0,   0,  31,  59,  90, 120, 151, 181, 212, 243, 273, 304, 334
+};
+
+union exfat_date
+{
+       uint16_t raw;
+       struct
+       {
+               uint16_t day   : 5; /* 1-31 */
+               uint16_t month : 4; /* 1-12 */
+               uint16_t year  : 7; /* 1-127 (+1980) */
+       };
+};
+
+union exfat_time
+{
+       uint16_t raw;
+       struct
+       {
+               uint16_t twosec : 5; /* 0-29 (2 sec granularity) */
+               uint16_t min    : 6; /* 0-59 */
+               uint16_t hour   : 5; /* 0-23 */
+       };
+};
+
+static time_t get_time_shift(void)
+{
+       struct timeval tv;
+       struct timezone tz;
+
+       if (gettimeofday(&tv, &tz) != 0)
+               return 0;
+       return -tz.tz_minuteswest * SEC_IN_MIN;
+}
+
+time_t exfat_exfat2unix(le16_t date, le16_t time)
+{
+       union exfat_date edate;
+       union exfat_time etime;
+       time_t unix_time = EPOCH_DIFF_SEC;
+
+       edate.raw = le16_to_cpu(date);
+       etime.raw = le16_to_cpu(time);
+
+       /*
+       exfat_debug("%hu-%02hu-%02hu %hu:%02hu:%02hu",
+                       edate.year + 1980, edate.month, edate.day,
+                       etime.hour, etime.min, etime.twosec * 2);
+       */
+
+       if (edate.day == 0 || edate.month == 0 || edate.month > 12)
+       {
+               exfat_error("bad date %hu-%02hu-%02hu",
+                               edate.year + EXFAT_EPOCH_YEAR, edate.month, edate.day);
+               return 0;
+       }
+       if (etime.hour > 23 || etime.min > 59 || etime.twosec > 29)
+       {
+               exfat_error("bad time %hu:%02hu:%02hu",
+                       etime.hour, etime.min, etime.twosec * 2);
+               return 0;
+       }
+
+       /* every 4th year between 1904 and 2096 is leap */
+       unix_time += edate.year * SEC_IN_YEAR + edate.year / 4 * SEC_IN_DAY;
+       unix_time += days_in_year[edate.month] * SEC_IN_DAY;
+       /* if it's leap year and February has passed we should add 1 day */
+       if (edate.year % 4 == 0 && edate.month > 2)
+               unix_time += SEC_IN_DAY;
+       unix_time += edate.day * SEC_IN_DAY;
+
+       unix_time += etime.hour * SEC_IN_HOUR;
+       unix_time += etime.min * SEC_IN_MIN;
+       /* exFAT represents time with 2 sec granularity */
+       unix_time += etime.twosec * 2;
+
+       /* exFAT stores timestamps in local time, so we correct it to UTC */
+       unix_time -= get_time_shift();
+
+       return unix_time;
+}
+
+void exfat_get_name(const struct exfat_node* node, char* buffer, size_t n)
+{
+       if (utf16_to_utf8(buffer, node->name, n, EXFAT_NAME_MAX) != 0)
+               exfat_bug("failed to convert name to UTF-8");
+}