vfs_fruit: avoid dereferencing fsp->base_fsp in fruit_fstat_meta_stream()
[amitay/samba.git] / source3 / modules / vfs_fruit.c
index aea3ad682ebd4a69a4e0b481bb4b4abb1765b824..19101efba740ce6de504cc97c2219add7101c34d 100644 (file)
@@ -33,6 +33,7 @@
 #include "lib/util/tevent_ntstatus.h"
 #include "lib/util/tevent_unix.h"
 #include "offload_token.h"
+#include "string_replace.h"
 
 /*
  * Enhanced OS X and Netatalk compatibility
@@ -140,6 +141,9 @@ struct fruit_config_data {
        bool aapl_zero_file_id;
        const char *model;
        bool time_machine;
+       off_t time_machine_max_size;
+       bool wipe_intentionally_left_blank_rfork;
+       bool delete_empty_adfiles;
 
        /*
         * Additional options, all enabled by default,
@@ -178,6 +182,19 @@ static const struct enum_list fruit_encoding[] = {
        { -1, NULL}
 };
 
+static const char *fruit_catia_maps =
+       "0x01:0xf001,0x02:0xf002,0x03:0xf003,0x04:0xf004,"
+       "0x05:0xf005,0x06:0xf006,0x07:0xf007,0x08:0xf008,"
+       "0x09:0xf009,0x0a:0xf00a,0x0b:0xf00b,0x0c:0xf00c,"
+       "0x0d:0xf00d,0x0e:0xf00e,0x0f:0xf00f,0x10:0xf010,"
+       "0x11:0xf011,0x12:0xf012,0x13:0xf013,0x14:0xf014,"
+       "0x15:0xf015,0x16:0xf016,0x17:0xf017,0x18:0xf018,"
+       "0x19:0xf019,0x1a:0xf01a,0x1b:0xf01b,0x1c:0xf01c,"
+       "0x1d:0xf01d,0x1e:0xf01e,0x1f:0xf01f,"
+       "0x22:0xf020,0x2a:0xf021,0x3a:0xf022,0x3c:0xf023,"
+       "0x3e:0xf024,0x3f:0xf025,0x5c:0xf026,0x7c:0xf027,"
+       "0x0d:0xf00d";
+
 /*****************************************************************************
  * Defines, functions and data structures that deal with AppleDouble
  *****************************************************************************/
@@ -247,6 +264,7 @@ typedef enum {ADOUBLE_META, ADOUBLE_RSRC} adouble_type_t;
 #define ADEDLEN_VERSION     4
 #define ADEDLEN_FILLER      16
 #define AD_FILLER_TAG       "Netatalk        " /* should be 16 bytes */
+#define AD_FILLER_TAG_OSX   "Mac OS X        " /* should be 16 bytes */
 #define ADEDLEN_NENTRIES    2
 #define AD_HEADER_LEN       (ADEDLEN_MAGIC + ADEDLEN_VERSION + \
                             ADEDLEN_FILLER + ADEDLEN_NENTRIES) /* 26 */
@@ -399,6 +417,7 @@ struct adouble {
        adouble_type_t            ad_type;
        uint32_t                  ad_magic;
        uint32_t                  ad_version;
+       uint8_t                   ad_filler[ADEDLEN_FILLER];
        struct ad_entry           ad_eid[ADEID_MAX];
        char                     *ad_data;
        struct ad_xattr_header    adx_header;
@@ -450,12 +469,65 @@ static const uint32_t set_eid[] = {
        AD_DEV, AD_INO, AD_SYN, AD_ID
 };
 
+static char empty_resourcefork[] = {
+       0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00,
+       0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x1E,
+       0x54, 0x68, 0x69, 0x73, 0x20, 0x72, 0x65, 0x73,
+       0x6F, 0x75, 0x72, 0x63, 0x65, 0x20, 0x66, 0x6F,
+       0x72, 0x6B, 0x20, 0x69, 0x6E, 0x74, 0x65, 0x6E,
+       0x74, 0x69, 0x6F, 0x6E, 0x61, 0x6C, 0x6C, 0x79,
+       0x20, 0x6C, 0x65, 0x66, 0x74, 0x20, 0x62, 0x6C,
+       0x61, 0x6E, 0x6B, 0x20, 0x20, 0x20, 0x00, 0x00,
+       0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+       0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+       0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+       0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+       0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+       0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+       0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+       0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+       0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+       0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+       0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+       0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+       0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+       0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+       0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+       0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+       0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+       0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+       0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+       0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+       0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+       0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+       0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+       0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+       0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00,
+       0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x1E,
+       0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+       0x00, 0x1C, 0x00, 0x1E, 0xFF, 0xFF
+};
+
 struct fio {
        /* tcon config handle */
        struct fruit_config_data *config;
 
        /* Denote stream type, meta or rsrc */
        adouble_type_t type;
+
+       /* Whether the create created the stream */
+       bool created;
+
+       /*
+        * AFP_AfpInfo stream created, but not written yet, thus still a fake
+        * pipe fd. This is set to true in fruit_open_meta if there was no
+        * exisiting stream but the caller requested O_CREAT. It is later set to
+        * false when we get a write on the stream that then does open and
+        * create the stream.
+        */
+       bool fake_fd;
+       int flags;
+       int mode;
 };
 
 /*
@@ -468,6 +540,10 @@ static int ad_fset(struct adouble *ad, files_struct *fsp);
 static int adouble_path(TALLOC_CTX *ctx,
                        const struct smb_filename *smb_fname__in,
                        struct smb_filename **ppsmb_fname_out);
+static AfpInfo *afpinfo_new(TALLOC_CTX *ctx);
+static ssize_t afpinfo_pack(const AfpInfo *ai, char *buf);
+static AfpInfo *afpinfo_unpack(TALLOC_CTX *ctx, const void *data);
+
 
 /**
  * Return a pointer to an AppleDouble entry
@@ -653,6 +729,141 @@ static bool ad_pack(struct adouble *ad)
        return true;
 }
 
+static bool ad_unpack_xattrs(struct adouble *ad)
+{
+       struct ad_xattr_header *h = &ad->adx_header;
+       const char *p = ad->ad_data;
+       uint32_t hoff;
+       uint32_t i;
+
+       if (ad_getentrylen(ad, ADEID_FINDERI) <= ADEDLEN_FINDERI) {
+               return true;
+       }
+
+       /* 2 bytes padding */
+       hoff = ad_getentryoff(ad, ADEID_FINDERI) + ADEDLEN_FINDERI + 2;
+
+       h->adx_magic       = RIVAL(p, hoff + 0);
+       h->adx_debug_tag   = RIVAL(p, hoff + 4); /* Not used -> not checked */
+       h->adx_total_size  = RIVAL(p, hoff + 8);
+       h->adx_data_start  = RIVAL(p, hoff + 12);
+       h->adx_data_length = RIVAL(p, hoff + 16);
+       h->adx_flags       = RSVAL(p, hoff + 32); /* Not used -> not checked */
+       h->adx_num_attrs   = RSVAL(p, hoff + 34);
+
+       if (h->adx_magic != AD_XATTR_HDR_MAGIC) {
+               DBG_ERR("Bad magic: 0x%" PRIx32 "\n", h->adx_magic);
+               return false;
+       }
+
+       if (h->adx_total_size > ad_getentryoff(ad, ADEID_RFORK)) {
+               DBG_ERR("Bad total size: 0x%" PRIx32 "\n", h->adx_total_size);
+               return false;
+       }
+       if (h->adx_total_size > AD_XATTR_MAX_HDR_SIZE) {
+               DBG_ERR("Bad total size: 0x%" PRIx32 "\n", h->adx_total_size);
+               return false;
+       }
+
+       if (h->adx_data_start < (hoff + AD_XATTR_HDR_SIZE)) {
+               DBG_ERR("Bad start: 0x%" PRIx32 "\n", h->adx_data_start);
+               return false;
+       }
+
+       if ((h->adx_data_start + h->adx_data_length) < h->adx_data_start) {
+               DBG_ERR("Bad length: %" PRIu32 "\n", h->adx_data_length);
+               return false;
+       }
+       if ((h->adx_data_start + h->adx_data_length) >
+           ad->adx_header.adx_total_size)
+       {
+               DBG_ERR("Bad length: %" PRIu32 "\n", h->adx_data_length);
+               return false;
+       }
+
+       if (h->adx_num_attrs > AD_XATTR_MAX_ENTRIES) {
+               DBG_ERR("Bad num xattrs: %" PRIu16 "\n", h->adx_num_attrs);
+               return false;
+       }
+
+       if (h->adx_num_attrs == 0) {
+               return true;
+       }
+
+       ad->adx_entries = talloc_zero_array(
+               ad, struct ad_xattr_entry, h->adx_num_attrs);
+       if (ad->adx_entries == NULL) {
+               return false;
+       }
+
+       hoff += AD_XATTR_HDR_SIZE;
+
+       for (i = 0; i < h->adx_num_attrs; i++) {
+               struct ad_xattr_entry *e = &ad->adx_entries[i];
+
+               hoff = (hoff + 3) & ~3;
+
+               e->adx_offset  = RIVAL(p, hoff + 0);
+               e->adx_length  = RIVAL(p, hoff + 4);
+               e->adx_flags   = RSVAL(p, hoff + 8);
+               e->adx_namelen = *(p + hoff + 10);
+
+               if (e->adx_offset >= ad->adx_header.adx_total_size) {
+                       DBG_ERR("Bad adx_offset: %" PRIx32 "\n",
+                               e->adx_offset);
+                       return false;
+               }
+
+               if ((e->adx_offset + e->adx_length) < e->adx_offset) {
+                       DBG_ERR("Bad adx_length: %" PRIx32 "\n",
+                               e->adx_length);
+                       return false;
+               }
+
+               if ((e->adx_offset + e->adx_length) >
+                   ad->adx_header.adx_total_size)
+               {
+                       DBG_ERR("Bad adx_length: %" PRIx32 "\n",
+                               e->adx_length);
+                       return false;
+               }
+
+               if (e->adx_namelen == 0) {
+                       DBG_ERR("Bad adx_namelen: %" PRIx32 "\n",
+                               e->adx_namelen);
+                       return false;
+               }
+               if ((hoff + 11 + e->adx_namelen) < hoff + 11) {
+                       DBG_ERR("Bad adx_namelen: %" PRIx32 "\n",
+                               e->adx_namelen);
+                       return false;
+               }
+               if ((hoff + 11 + e->adx_namelen) >
+                   ad->adx_header.adx_data_start)
+               {
+                       DBG_ERR("Bad adx_namelen: %" PRIx32 "\n",
+                               e->adx_namelen);
+                       return false;
+               }
+
+               e->adx_name = talloc_strndup(ad->adx_entries,
+                                            p + hoff + 11,
+                                            e->adx_namelen);
+               if (e->adx_name == NULL) {
+                       return false;
+               }
+
+               DBG_DEBUG("xattr [%s] offset [0x%x] size [0x%x]\n",
+                         e->adx_name, e->adx_offset, e->adx_length);
+               dump_data(10, (uint8_t *)(ad->ad_data + e->adx_offset),
+                         e->adx_length);
+
+               hoff += 11 + e->adx_namelen;
+       }
+
+       return true;
+}
+
 /**
  * Unpack an AppleDouble blob into a struct adoble
  **/
@@ -662,6 +873,7 @@ static bool ad_unpack(struct adouble *ad, const size_t nentries,
        size_t bufsize = talloc_get_size(ad->ad_data);
        size_t adentries, i;
        uint32_t eid, len, off;
+       bool ok;
 
        /*
         * The size of the buffer ad->ad_data is checked when read, so
@@ -682,6 +894,8 @@ static bool ad_unpack(struct adouble *ad, const size_t nentries,
                return false;
        }
 
+       memcpy(ad->ad_filler, ad->ad_data + ADEDOFF_FILLER, ADEDLEN_FILLER);
+
        adentries = RSVAL(ad->ad_data, ADEDOFF_NENTRIES);
        if (adentries != nentries) {
                DEBUG(1, ("invalid number of entries: %zu\n",
@@ -775,58 +989,500 @@ static bool ad_unpack(struct adouble *ad, const size_t nentries,
                ad->ad_eid[eid].ade_len = len;
        }
 
+       ok = ad_unpack_xattrs(ad);
+       if (!ok) {
+               return false;
+       }
+
        return true;
 }
 
-/**
- * Convert from Apple's ._ file to Netatalk
- *
- * Apple's AppleDouble may contain a FinderInfo entry longer then 32
- * bytes containing packed xattrs. Netatalk can't deal with that, so
- * we simply discard the packed xattrs.
- *
- * @return -1 in case an error occurred, 0 if no conversion was done, 1
- * otherwise
- **/
-static int ad_convert(struct adouble *ad, int fd)
+static bool ad_convert_move_reso(struct adouble *ad,
+                                const struct smb_filename *smb_fname)
 {
-       int rc = 0;
        char *map = MAP_FAILED;
-       size_t origlen;
+       size_t maplen;
+       ssize_t len;
+       int rc;
+       bool ok;
 
-       origlen = ad_getentryoff(ad, ADEID_RFORK) +
+       if (ad_getentrylen(ad, ADEID_RFORK) == 0) {
+               return true;
+       }
+
+       maplen = ad_getentryoff(ad, ADEID_RFORK) +
                ad_getentrylen(ad, ADEID_RFORK);
 
        /* FIXME: direct use of mmap(), vfs_aio_fork does it too */
-       map = mmap(NULL, origlen, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);
+       map = mmap(NULL, maplen, PROT_READ|PROT_WRITE, MAP_SHARED,
+                  ad->ad_fd, 0);
        if (map == MAP_FAILED) {
-               DEBUG(2, ("mmap AppleDouble: %s\n", strerror(errno)));
-               rc = -1;
-               goto exit;
+               DBG_ERR("mmap AppleDouble: %s\n", strerror(errno));
+               return false;
        }
 
-       if (ad_getentrylen(ad, ADEID_RFORK) > 0) {
-               memmove(map + ad_getentryoff(ad, ADEID_FINDERI) + ADEDLEN_FINDERI,
-                       map + ad_getentryoff(ad, ADEID_RFORK),
-                       ad_getentrylen(ad, ADEID_RFORK));
+
+       memmove(map + ADEDOFF_RFORK_DOT_UND,
+               map + ad_getentryoff(ad, ADEID_RFORK),
+               ad_getentrylen(ad, ADEID_RFORK));
+
+       rc = munmap(map, maplen);
+       if (rc != 0) {
+               DBG_ERR("munmap failed: %s\n", strerror(errno));
+               return false;
+       }
+
+       ad_setentryoff(ad, ADEID_RFORK, ADEDOFF_RFORK_DOT_UND);
+
+       ok = ad_pack(ad);
+       if (!ok) {
+               DBG_WARNING("ad_pack [%s] failed\n", smb_fname->base_name);
+               return false;
+       }
+
+       len = sys_pwrite(ad->ad_fd, ad->ad_data, AD_DATASZ_DOT_UND, 0);
+       if (len != AD_DATASZ_DOT_UND) {
+               DBG_ERR("%s: bad size: %zd\n", smb_fname->base_name, len);
+               return false;
+       }
+
+       return true;
+}
+
+static bool ad_convert_xattr(struct adouble *ad,
+                            const struct smb_filename *smb_fname,
+                            bool *converted_xattr)
+{
+       static struct char_mappings **string_replace_cmaps = NULL;
+       char *map = MAP_FAILED;
+       size_t maplen;
+       uint16_t i;
+       ssize_t len;
+       int saved_errno = 0;
+       NTSTATUS status;
+       int rc;
+       bool ok;
+
+       *converted_xattr = false;
+
+       if (ad_getentrylen(ad, ADEID_FINDERI) == ADEDLEN_FINDERI) {
+               return true;
+       }
+
+       if (string_replace_cmaps == NULL) {
+               const char **mappings = NULL;
+
+               mappings = str_list_make_v3_const(
+                       talloc_tos(), fruit_catia_maps, NULL);
+               if (mappings == NULL) {
+                       return false;
+               }
+               string_replace_cmaps = string_replace_init_map(mappings);
+               TALLOC_FREE(mappings);
+       }
+
+       maplen = ad_getentryoff(ad, ADEID_RFORK) +
+               ad_getentrylen(ad, ADEID_RFORK);
+
+       /* FIXME: direct use of mmap(), vfs_aio_fork does it too */
+       map = mmap(NULL, maplen, PROT_READ|PROT_WRITE, MAP_SHARED,
+                  ad->ad_fd, 0);
+       if (map == MAP_FAILED) {
+               DBG_ERR("mmap AppleDouble: %s\n", strerror(errno));
+               return false;
+       }
+
+       for (i = 0; i < ad->adx_header.adx_num_attrs; i++) {
+               struct ad_xattr_entry *e = &ad->adx_entries[i];
+               char *mapped_name = NULL;
+               char *tmp = NULL;
+               struct smb_filename *stream_name = NULL;
+               files_struct *fsp = NULL;
+               ssize_t nwritten;
+
+               status = string_replace_allocate(ad->ad_handle->conn,
+                                                e->adx_name,
+                                                string_replace_cmaps,
+                                                talloc_tos(),
+                                                &mapped_name,
+                                                vfs_translate_to_windows);
+               if (!NT_STATUS_IS_OK(status) &&
+                   !NT_STATUS_EQUAL(status, NT_STATUS_NONE_MAPPED))
+               {
+                       DBG_ERR("string_replace_allocate failed\n");
+                       ok = false;
+                       goto fail;
+               }
+
+               tmp = mapped_name;
+               mapped_name = talloc_asprintf(talloc_tos(), ":%s", tmp);
+               TALLOC_FREE(tmp);
+               if (mapped_name == NULL) {
+                       ok = false;
+                       goto fail;
+               }
+
+               stream_name = synthetic_smb_fname(talloc_tos(),
+                                                 smb_fname->base_name,
+                                                 mapped_name,
+                                                 NULL,
+                                                 smb_fname->flags);
+               TALLOC_FREE(mapped_name);
+               if (stream_name == NULL) {
+                       DBG_ERR("synthetic_smb_fname failed\n");
+                       ok = false;
+                       goto fail;
+               }
+
+               DBG_DEBUG("stream_name: %s\n", smb_fname_str_dbg(stream_name));
+
+               status = SMB_VFS_CREATE_FILE(
+                       ad->ad_handle->conn,            /* conn */
+                       NULL,                           /* req */
+                       0,                              /* root_dir_fid */
+                       stream_name,                    /* fname */
+                       FILE_GENERIC_WRITE,             /* access_mask */
+                       FILE_SHARE_READ | FILE_SHARE_WRITE, /* share_access */
+                       FILE_OPEN_IF,                   /* create_disposition */
+                       0,                              /* create_options */
+                       0,                              /* file_attributes */
+                       INTERNAL_OPEN_ONLY,             /* oplock_request */
+                       NULL,                           /* lease */
+                       0,                              /* allocation_size */
+                       0,                              /* private_flags */
+                       NULL,                           /* sd */
+                       NULL,                           /* ea_list */
+                       &fsp,                           /* result */
+                       NULL,                           /* psbuf */
+                       NULL, NULL);                    /* create context */
+               TALLOC_FREE(stream_name);
+               if (!NT_STATUS_IS_OK(status)) {
+                       DBG_ERR("SMB_VFS_CREATE_FILE failed\n");
+                       ok = false;
+                       goto fail;
+               }
+
+               nwritten = SMB_VFS_PWRITE(fsp,
+                                         map + e->adx_offset,
+                                         e->adx_length,
+                                         0);
+               if (nwritten == -1) {
+                       DBG_ERR("SMB_VFS_PWRITE failed\n");
+                       saved_errno = errno;
+                       close_file(NULL, fsp, ERROR_CLOSE);
+                       errno = saved_errno;
+                       ok = false;
+                       goto fail;
+               }
+
+               status = close_file(NULL, fsp, NORMAL_CLOSE);
+               if (!NT_STATUS_IS_OK(status)) {
+                       ok = false;
+                       goto fail;
+               }
+               fsp = NULL;
        }
 
        ad_setentrylen(ad, ADEID_FINDERI, ADEDLEN_FINDERI);
-       ad_setentryoff(ad, ADEID_RFORK,
-                      ad_getentryoff(ad, ADEID_FINDERI) + ADEDLEN_FINDERI);
+
+       ok = ad_pack(ad);
+       if (!ok) {
+               DBG_WARNING("ad_pack [%s] failed\n", smb_fname->base_name);
+               goto fail;
+       }
+
+       len = sys_pwrite(ad->ad_fd, ad->ad_data, AD_DATASZ_DOT_UND, 0);
+       if (len != AD_DATASZ_DOT_UND) {
+               DBG_ERR("%s: bad size: %zd\n", smb_fname->base_name, len);
+               ok = false;
+               goto fail;
+       }
+
+       ok = ad_convert_move_reso(ad, smb_fname);
+       if (!ok) {
+               goto fail;
+       }
+
+       *converted_xattr = true;
+       ok = true;
+
+fail:
+       rc = munmap(map, maplen);
+       if (rc != 0) {
+               DBG_ERR("munmap failed: %s\n", strerror(errno));
+               return false;
+       }
+
+       return ok;
+}
+
+static bool ad_convert_finderinfo(struct adouble *ad,
+                                 const struct smb_filename *smb_fname)
+{
+       char *p_ad = NULL;
+       AfpInfo *ai = NULL;
+       DATA_BLOB aiblob;
+       struct smb_filename *stream_name = NULL;
+       files_struct *fsp = NULL;
+       size_t size;
+       ssize_t nwritten;
+       NTSTATUS status;
+       int saved_errno = 0;
+       int cmp;
+
+       cmp = memcmp(ad->ad_filler, AD_FILLER_TAG_OSX, ADEDLEN_FILLER);
+       if (cmp != 0) {
+               return true;
+       }
+
+       p_ad = ad_get_entry(ad, ADEID_FINDERI);
+       if (p_ad == NULL) {
+               return false;
+       }
+
+       ai = afpinfo_new(talloc_tos());
+       if (ai == NULL) {
+               return false;
+       }
+
+       memcpy(ai->afpi_FinderInfo, p_ad, ADEDLEN_FINDERI);
+
+       aiblob = data_blob_talloc(talloc_tos(), NULL, AFP_INFO_SIZE);
+       if (aiblob.data == NULL) {
+               TALLOC_FREE(ai);
+               return false;
+       }
+
+       size = afpinfo_pack(ai, (char *)aiblob.data);
+       TALLOC_FREE(ai);
+       if (size != AFP_INFO_SIZE) {
+               return false;
+       }
+
+       stream_name = synthetic_smb_fname(talloc_tos(),
+                                         smb_fname->base_name,
+                                         AFPINFO_STREAM,
+                                         NULL,
+                                         smb_fname->flags);
+       if (stream_name == NULL) {
+               data_blob_free(&aiblob);
+               DBG_ERR("synthetic_smb_fname failed\n");
+               return false;
+       }
+
+       DBG_DEBUG("stream_name: %s\n", smb_fname_str_dbg(stream_name));
+
+       status = SMB_VFS_CREATE_FILE(
+               ad->ad_handle->conn,            /* conn */
+               NULL,                           /* req */
+               0,                              /* root_dir_fid */
+               stream_name,                    /* fname */
+               FILE_GENERIC_WRITE,             /* access_mask */
+               FILE_SHARE_READ | FILE_SHARE_WRITE, /* share_access */
+               FILE_OPEN_IF,                   /* create_disposition */
+               0,                              /* create_options */
+               0,                              /* file_attributes */
+               INTERNAL_OPEN_ONLY,             /* oplock_request */
+               NULL,                           /* lease */
+               0,                              /* allocation_size */
+               0,                              /* private_flags */
+               NULL,                           /* sd */
+               NULL,                           /* ea_list */
+               &fsp,                           /* result */
+               NULL,                           /* psbuf */
+               NULL, NULL);                    /* create context */
+       TALLOC_FREE(stream_name);
+       if (!NT_STATUS_IS_OK(status)) {
+               DBG_ERR("SMB_VFS_CREATE_FILE failed\n");
+               return false;
+       }
+
+       nwritten = SMB_VFS_PWRITE(fsp,
+                                 aiblob.data,
+                                 aiblob.length,
+                                 0);
+       if (nwritten == -1) {
+               DBG_ERR("SMB_VFS_PWRITE failed\n");
+               saved_errno = errno;
+               close_file(NULL, fsp, ERROR_CLOSE);
+               errno = saved_errno;
+               return false;
+       }
+
+       status = close_file(NULL, fsp, NORMAL_CLOSE);
+       if (!NT_STATUS_IS_OK(status)) {
+               return false;
+       }
+       fsp = NULL;
+
+       return true;
+}
+
+static bool ad_convert_truncate(struct adouble *ad,
+                               const struct smb_filename *smb_fname)
+{
+       int rc;
 
        /*
         * FIXME: direct ftruncate(), but we don't have a fsp for the
         * VFS call
         */
-       rc = ftruncate(fd, ad_getentryoff(ad, ADEID_RFORK)
-                      + ad_getentrylen(ad, ADEID_RFORK));
+       rc = ftruncate(ad->ad_fd, ADEDOFF_RFORK_DOT_UND +
+                      ad_getentrylen(ad, ADEID_RFORK));
+       if (rc != 0) {
+               return false;
+       }
 
-exit:
-       if (map != MAP_FAILED) {
-               munmap(map, origlen);
+       return true;
+}
+
+static bool ad_convert_blank_rfork(struct adouble *ad,
+                                  bool *blank)
+{
+       struct fruit_config_data *config = NULL;
+       uint8_t *map = MAP_FAILED;
+       size_t maplen;
+       int cmp;
+       ssize_t len;
+       int rc;
+       bool ok;
+
+       *blank = false;
+
+       SMB_VFS_HANDLE_GET_DATA(ad->ad_handle, config,
+                               struct fruit_config_data, return false);
+
+       if (!config->wipe_intentionally_left_blank_rfork) {
+               return true;
        }
-       return rc;
+
+       if (ad_getentrylen(ad, ADEID_RFORK) != sizeof(empty_resourcefork)) {
+               return true;
+       }
+
+       maplen = ad_getentryoff(ad, ADEID_RFORK) +
+               ad_getentrylen(ad, ADEID_RFORK);
+
+       /* FIXME: direct use of mmap(), vfs_aio_fork does it too */
+       map = mmap(NULL, maplen, PROT_READ|PROT_WRITE, MAP_SHARED,
+                  ad->ad_fd, 0);
+       if (map == MAP_FAILED) {
+               DBG_ERR("mmap AppleDouble: %s\n", strerror(errno));
+               return false;
+       }
+
+       cmp = memcmp(map + ADEDOFF_RFORK_DOT_UND,
+                    empty_resourcefork,
+                    sizeof(empty_resourcefork));
+       rc = munmap(map, maplen);
+       if (rc != 0) {
+               DBG_ERR("munmap failed: %s\n", strerror(errno));
+               return false;
+       }
+
+       if (cmp != 0) {
+               return true;
+       }
+
+       ad_setentrylen(ad, ADEID_RFORK, 0);
+
+       ok = ad_pack(ad);
+       if (!ok) {
+               return false;
+       }
+
+       len = sys_pwrite(ad->ad_fd, ad->ad_data, AD_DATASZ_DOT_UND, 0);
+       if (len != AD_DATASZ_DOT_UND) {
+               return false;
+       }
+
+       *blank = true;
+       return true;
+}
+
+static bool ad_convert_delete_adfile(struct adouble *ad,
+                                    const struct smb_filename *smb_fname)
+{
+       struct fruit_config_data *config = NULL;
+       struct smb_filename *ad_name = NULL;
+       int rc;
+
+       if (ad_getentrylen(ad, ADEID_RFORK) > 0) {
+               return true;
+       }
+
+       SMB_VFS_HANDLE_GET_DATA(ad->ad_handle, config,
+                               struct fruit_config_data, return false);
+
+       if (!config->delete_empty_adfiles) {
+               return true;
+       }
+
+       rc = adouble_path(talloc_tos(), smb_fname, &ad_name);
+       if (rc != 0) {
+               return false;
+       }
+
+       rc = SMB_VFS_NEXT_UNLINK(ad->ad_handle, ad_name);
+       if (rc != 0) {
+               DBG_ERR("Unlinking [%s] failed: %s\n",
+                       smb_fname_str_dbg(ad_name), strerror(errno));
+               TALLOC_FREE(ad_name);
+               return false;
+       }
+
+       DBG_WARNING("Unlinked [%s] after conversion\n", smb_fname_str_dbg(ad_name));
+       TALLOC_FREE(ad_name);
+
+       return true;
+}
+
+/**
+ * Convert from Apple's ._ file to Netatalk
+ *
+ * Apple's AppleDouble may contain a FinderInfo entry longer then 32
+ * bytes containing packed xattrs.
+ *
+ * @return -1 in case an error occurred, 0 if no conversion was done, 1
+ * otherwise
+ **/
+static int ad_convert(struct adouble *ad,
+                     const struct smb_filename *smb_fname)
+{
+       bool ok;
+       bool converted_xattr = false;
+       bool blank;
+
+       ok = ad_convert_xattr(ad, smb_fname, &converted_xattr);
+       if (!ok) {
+               return -1;
+       }
+
+       ok = ad_convert_blank_rfork(ad, &blank);
+       if (!ok) {
+               return -1;
+       }
+
+       if (converted_xattr || blank) {
+               ok = ad_convert_truncate(ad, smb_fname);
+               if (!ok) {
+                       return -1;
+               }
+       }
+
+       ok = ad_convert_finderinfo(ad, smb_fname);
+       if (!ok) {
+               DBG_ERR("Failed to convert [%s]\n",
+                       smb_fname_str_dbg(smb_fname));
+               return -1;
+       }
+
+       ok = ad_convert_delete_adfile(ad, smb_fname);
+       if (!ok) {
+               return -1;
+       }
+
+       return 0;
 }
 
 /**
@@ -1020,12 +1676,10 @@ static ssize_t ad_read_rsrc_xattr(struct adouble *ad)
 static ssize_t ad_read_rsrc_adouble(struct adouble *ad,
                                const struct smb_filename *smb_fname)
 {
-       struct adouble *meta_ad = NULL;
        SMB_STRUCT_STAT sbuf;
        char *p_ad = NULL;
-       char *p_meta_ad = NULL;
-       ssize_t len;
        size_t size;
+       ssize_t len;
        int ret;
        bool ok;
 
@@ -1081,59 +1735,17 @@ static ssize_t ad_read_rsrc_adouble(struct adouble *ad,
                return -1;
        }
 
-       if (ad_getentrylen(ad, ADEID_FINDERI) == ADEDLEN_FINDERI) {
-               return len;
-       }
-
        /*
         * Try to fixup AppleDouble files created by OS X with xattrs
-        * appended to the ADEID_FINDERI entry. We simply remove the
-        * xattrs blob, this means any fancy xattr that was stored
-        * there is lost.
+        * appended to the ADEID_FINDERI entry.
         */
 
-       ret = ad_convert(ad, ad->ad_fd);
+       ret = ad_convert(ad, smb_fname);
        if (ret != 0) {
                DBG_WARNING("Failed to convert [%s]\n", smb_fname->base_name);
                return len;
        }
 
-       ok = ad_pack(ad);
-       if (!ok) {
-               DBG_WARNING("ad_pack [%s] failed\n", smb_fname->base_name);
-               return -1;
-       }
-
-       len = sys_pwrite(ad->ad_fd, ad->ad_data, AD_DATASZ_DOT_UND, 0);
-       if (len != AD_DATASZ_DOT_UND) {
-               DBG_ERR("%s: bad size: %zd\n", smb_fname->base_name, len);
-               return -1;
-       }
-
-       meta_ad = ad_init(talloc_tos(), ad->ad_handle, ADOUBLE_META);
-       if (meta_ad == NULL) {
-               return -1;
-       }
-
-       p_ad = ad_get_entry(ad, ADEID_FINDERI);
-       if (p_ad == NULL) {
-               TALLOC_FREE(meta_ad);
-               return -1;
-       }
-       p_meta_ad = ad_get_entry(meta_ad, ADEID_FINDERI);
-       if (p_meta_ad == NULL) {
-               TALLOC_FREE(meta_ad);
-               return -1;
-       }
-
-       memcpy(p_meta_ad, p_ad, ADEDLEN_FINDERI);
-
-       ret = ad_set(meta_ad, smb_fname);
-       TALLOC_FREE(meta_ad);
-       if (ret != 0) {
-               return -1;
-       }
-
        return len;
 }
 
@@ -1543,6 +2155,7 @@ static int init_fruit_config(vfs_handle_struct *handle)
 {
        struct fruit_config_data *config;
        int enumval;
+       const char *tm_size_str = NULL;
 
        config = talloc_zero(handle->conn, struct fruit_config_data);
        if (!config) {
@@ -1641,6 +2254,21 @@ static int init_fruit_config(vfs_handle_struct *handle)
        config->model = lp_parm_const_string(
                -1, FRUIT_PARAM_TYPE_NAME, "model", "MacSamba");
 
+       tm_size_str = lp_parm_const_string(
+               SNUM(handle->conn), FRUIT_PARAM_TYPE_NAME,
+               "time machine max size", NULL);
+       if (tm_size_str != NULL) {
+               config->time_machine_max_size = conv_str_size(tm_size_str);
+       }
+
+       config->wipe_intentionally_left_blank_rfork = lp_parm_bool(
+               SNUM(handle->conn), FRUIT_PARAM_TYPE_NAME,
+               "wipe_intentionally_left_blank_rfork", false);
+
+       config->delete_empty_adfiles = lp_parm_bool(
+               SNUM(handle->conn), FRUIT_PARAM_TYPE_NAME,
+               "delete_empty_adfiles", false);
+
        SMB_VFS_HANDLE_SET_DATA(handle, config,
                                NULL, struct fruit_config_data,
                                return -1);
@@ -1760,6 +2388,10 @@ static SMB_INO_T fruit_inode(const SMB_STRUCT_STAT *sbuf, const char *sname)
        SMB_INO_T result;
        char *upper_sname;
 
+       DBG_DEBUG("fruit_inode called for %ju/%ju [%s]\n",
+                 (uintmax_t)sbuf->st_ex_dev,
+                 (uintmax_t)sbuf->st_ex_ino, sname);
+
        upper_sname = talloc_strdup_upper(talloc_tos(), sname);
        SMB_ASSERT(upper_sname != NULL);
 
@@ -1777,8 +2409,8 @@ static SMB_INO_T fruit_inode(const SMB_STRUCT_STAT *sbuf, const char *sname)
        /* Hopefully all the variation is in the lower 4 (or 8) bytes! */
        memcpy(&result, hash, sizeof(result));
 
-       DEBUG(10, ("fruit_inode \"%s\": ino=0x%llu\n",
-                  sname, (unsigned long long)result));
+       DBG_DEBUG("fruit_inode \"%s\": ino=%ju\n",
+                 sname, (uintmax_t)result);
 
        return result;
 }
@@ -1980,7 +2612,7 @@ static off_t access_to_netatalk_brl(enum apple_fork fork_type,
 static off_t denymode_to_netatalk_brl(enum apple_fork fork_type,
                                      uint32_t deny_mode)
 {
-       off_t offset;
+       off_t offset = 0;
 
        switch (deny_mode) {
        case DENY_READ:
@@ -2035,7 +2667,6 @@ static NTSTATUS fruit_check_access(vfs_handle_struct *handle,
                                   uint32_t deny_mode)
 {
        NTSTATUS status = NT_STATUS_OK;
-       struct byte_range_lock *br_lck = NULL;
        bool open_for_reading, open_for_writing, deny_read, deny_write;
        off_t off;
        bool have_read = false;
@@ -2093,6 +2724,8 @@ static NTSTATUS fruit_check_access(vfs_handle_struct *handle,
 
                /* Set locks */
                if ((access_mask & FILE_READ_DATA) && have_read) {
+                       struct byte_range_lock *br_lck = NULL;
+
                        off = access_to_netatalk_brl(fork_type, FILE_READ_DATA);
                        br_lck = do_lock(
                                handle->conn->sconn->msg_ctx, fsp,
@@ -2100,13 +2733,16 @@ static NTSTATUS fruit_check_access(vfs_handle_struct *handle,
                                READ_LOCK, POSIX_LOCK, false,
                                &status, NULL);
 
+                       TALLOC_FREE(br_lck);
+
                        if (!NT_STATUS_IS_OK(status))  {
                                return status;
                        }
-                       TALLOC_FREE(br_lck);
                }
 
                if ((deny_mode & DENY_READ) && have_read) {
+                       struct byte_range_lock *br_lck = NULL;
+
                        off = denymode_to_netatalk_brl(fork_type, DENY_READ);
                        br_lck = do_lock(
                                handle->conn->sconn->msg_ctx, fsp,
@@ -2114,10 +2750,11 @@ static NTSTATUS fruit_check_access(vfs_handle_struct *handle,
                                READ_LOCK, POSIX_LOCK, false,
                                &status, NULL);
 
+                       TALLOC_FREE(br_lck);
+
                        if (!NT_STATUS_IS_OK(status)) {
                                return status;
                        }
-                       TALLOC_FREE(br_lck);
                }
        }
 
@@ -2143,6 +2780,8 @@ static NTSTATUS fruit_check_access(vfs_handle_struct *handle,
 
                /* Set locks */
                if ((access_mask & FILE_WRITE_DATA) && have_read) {
+                       struct byte_range_lock *br_lck = NULL;
+
                        off = access_to_netatalk_brl(fork_type, FILE_WRITE_DATA);
                        br_lck = do_lock(
                                handle->conn->sconn->msg_ctx, fsp,
@@ -2150,13 +2789,15 @@ static NTSTATUS fruit_check_access(vfs_handle_struct *handle,
                                READ_LOCK, POSIX_LOCK, false,
                                &status, NULL);
 
+                       TALLOC_FREE(br_lck);
+
                        if (!NT_STATUS_IS_OK(status)) {
                                return status;
                        }
-                       TALLOC_FREE(br_lck);
-
                }
                if ((deny_mode & DENY_WRITE) && have_read) {
+                       struct byte_range_lock *br_lck = NULL;
+
                        off = denymode_to_netatalk_brl(fork_type, DENY_WRITE);
                        br_lck = do_lock(
                                handle->conn->sconn->msg_ctx, fsp,
@@ -2164,15 +2805,14 @@ static NTSTATUS fruit_check_access(vfs_handle_struct *handle,
                                READ_LOCK, POSIX_LOCK, false,
                                &status, NULL);
 
+                       TALLOC_FREE(br_lck);
+
                        if (!NT_STATUS_IS_OK(status)) {
                                return status;
                        }
-                       TALLOC_FREE(br_lck);
                }
        }
 
-       TALLOC_FREE(br_lck);
-
        return status;
 }
 
@@ -2603,10 +3243,54 @@ static NTSTATUS readdir_attr_macmeta(struct vfs_handle_struct *handle,
        return status;
 }
 
+static NTSTATUS remove_virtual_nfs_aces(struct security_descriptor *psd)
+{
+       NTSTATUS status;
+       uint32_t i;
+
+       if (psd->dacl == NULL) {
+               return NT_STATUS_OK;
+       }
+
+       for (i = 0; i < psd->dacl->num_aces; i++) {
+               /* MS NFS style mode/uid/gid */
+               int cmp = dom_sid_compare_domain(
+                               &global_sid_Unix_NFS,
+                               &psd->dacl->aces[i].trustee);
+               if (cmp != 0) {
+                       /* Normal ACE entry. */
+                       continue;
+               }
+
+               /*
+                * security_descriptor_dacl_del()
+                * *must* return NT_STATUS_OK as we know
+                * we have something to remove.
+                */
+
+               status = security_descriptor_dacl_del(psd,
+                               &psd->dacl->aces[i].trustee);
+               if (!NT_STATUS_IS_OK(status)) {
+                       DBG_WARNING("failed to remove MS NFS style ACE: %s\n",
+                               nt_errstr(status));
+                       return status;
+               }
+
+               /*
+                * security_descriptor_dacl_del() may delete more
+                * then one entry subsequent to this one if the
+                * SID matches, but we only need to ensure that
+                * we stay looking at the same element in the array.
+                */
+               i--;
+       }
+       return NT_STATUS_OK;
+}
+
 /* Search MS NFS style ACE with UNIX mode */
 static NTSTATUS check_ms_nfs(vfs_handle_struct *handle,
                             files_struct *fsp,
-                            const struct security_descriptor *psd,
+                            struct security_descriptor *psd,
                             mode_t *pmode,
                             bool *pdo_chmod)
 {
@@ -2640,7 +3324,12 @@ static NTSTATUS check_ms_nfs(vfs_handle_struct *handle,
                }
        }
 
-       return NT_STATUS_OK;
+       /*
+        * Remove any incoming virtual ACE entries generated by
+        * fruit_fget_nt_acl().
+        */
+
+       return remove_virtual_nfs_aces(psd);
 }
 
 /****************************************************************************
@@ -2693,20 +3382,9 @@ static int fruit_connect(vfs_handle_struct *handle,
        }
 
        if (config->encoding == FRUIT_ENC_NATIVE) {
-               lp_do_parameter(
-                       SNUM(handle->conn),
-                       "catia:mappings",
-                       "0x01:0xf001,0x02:0xf002,0x03:0xf003,0x04:0xf004,"
-                       "0x05:0xf005,0x06:0xf006,0x07:0xf007,0x08:0xf008,"
-                       "0x09:0xf009,0x0a:0xf00a,0x0b:0xf00b,0x0c:0xf00c,"
-                       "0x0d:0xf00d,0x0e:0xf00e,0x0f:0xf00f,0x10:0xf010,"
-                       "0x11:0xf011,0x12:0xf012,0x13:0xf013,0x14:0xf014,"
-                       "0x15:0xf015,0x16:0xf016,0x17:0xf017,0x18:0xf018,"
-                       "0x19:0xf019,0x1a:0xf01a,0x1b:0xf01b,0x1c:0xf01c,"
-                       "0x1d:0xf01d,0x1e:0xf01e,0x1f:0xf01f,"
-                       "0x22:0xf020,0x2a:0xf021,0x3a:0xf022,0x3c:0xf023,"
-                       "0x3e:0xf024,0x3f:0xf025,0x5c:0xf026,0x7c:0xf027,"
-                       "0x0d:0xf00d");
+               lp_do_parameter(SNUM(handle->conn),
+                               "catia:mappings",
+                               fruit_catia_maps);
        }
 
        if (config->time_machine) {
@@ -2725,66 +3403,68 @@ static int fruit_connect(vfs_handle_struct *handle,
        return rc;
 }
 
+static int fruit_fake_fd(void)
+{
+       int pipe_fds[2];
+       int fd;
+       int ret;
+
+       /*
+        * Return a valid fd, but ensure any attempt to use it returns
+        * an error (EPIPE). Once we get a write on the handle, we open
+        * the real fd.
+        */
+       ret = pipe(pipe_fds);
+       if (ret != 0) {
+               return -1;
+       }
+       fd = pipe_fds[0];
+       close(pipe_fds[1]);
+
+       return fd;
+}
+
 static int fruit_open_meta_stream(vfs_handle_struct *handle,
                                  struct smb_filename *smb_fname,
                                  files_struct *fsp,
                                  int flags,
                                  mode_t mode)
 {
-       AfpInfo *ai = NULL;
-       char afpinfo_buf[AFP_INFO_SIZE];
-       ssize_t len, written;
-       int hostfd = -1;
-       int rc = -1;
+       struct fruit_config_data *config = NULL;
+       struct fio *fio = NULL;
+       int open_flags = flags & ~O_CREAT;
+       int fd;
 
-       hostfd = SMB_VFS_NEXT_OPEN(handle, smb_fname, fsp, flags, mode);
-       if (hostfd == -1) {
-               return -1;
-       }
+       DBG_DEBUG("Path [%s]\n", smb_fname_str_dbg(smb_fname));
 
-       if (!(flags & (O_CREAT | O_TRUNC))) {
-               return hostfd;
-       }
+       SMB_VFS_HANDLE_GET_DATA(handle, config,
+                               struct fruit_config_data, return -1);
 
-       ai = afpinfo_new(talloc_tos());
-       if (ai == NULL) {
-               rc = -1;
-               goto fail;
-       }
+       fio = VFS_ADD_FSP_EXTENSION(handle, fsp, struct fio, NULL);
+       fio->type = ADOUBLE_META;
+       fio->config = config;
 
-       len = afpinfo_pack(ai, afpinfo_buf);
-       if (len != AFP_INFO_SIZE) {
-               rc = -1;
-               goto fail;
+       fd = SMB_VFS_NEXT_OPEN(handle, smb_fname, fsp, open_flags, mode);
+       if (fd != -1) {
+               return fd;
        }
 
-       /* Set fd, needed in SMB_VFS_NEXT_PWRITE() */
-       fsp->fh->fd = hostfd;
-
-       written = SMB_VFS_NEXT_PWRITE(handle, fsp, afpinfo_buf,
-                                     AFP_INFO_SIZE, 0);
-       fsp->fh->fd = -1;
-       if (written != AFP_INFO_SIZE) {
-               DBG_ERR("bad write [%zd/%d]\n", written, AFP_INFO_SIZE);
-               rc = -1;
-               goto fail;
+       if (!(flags & O_CREAT)) {
+               VFS_REMOVE_FSP_EXTENSION(handle, fsp);
+               return -1;
        }
 
-       rc = 0;
+       fd = fruit_fake_fd();
+       if (fd == -1) {
+               VFS_REMOVE_FSP_EXTENSION(handle, fsp);
+               return -1;
+       }
 
-fail:
-       DBG_DEBUG("rc=%d, fd=%d\n", rc, hostfd);
+       fio->fake_fd = true;
+       fio->flags = flags;
+       fio->mode = mode;
 
-       if (rc != 0) {
-               int saved_errno = errno;
-               if (hostfd >= 0) {
-                       fsp->fh->fd = hostfd;
-                       SMB_VFS_NEXT_CLOSE(handle, fsp);
-               }
-               hostfd = -1;
-               errno = saved_errno;
-       }
-       return hostfd;
+       return fd;
 }
 
 static int fruit_open_meta_netatalk(vfs_handle_struct *handle,
@@ -2793,56 +3473,42 @@ static int fruit_open_meta_netatalk(vfs_handle_struct *handle,
                                    int flags,
                                    mode_t mode)
 {
-       int rc;
-       int fakefd = -1;
+       struct fruit_config_data *config = NULL;
+       struct fio *fio = NULL;
        struct adouble *ad = NULL;
-       int fds[2];
+       bool meta_exists = false;
+       int fd;
 
        DBG_DEBUG("Path [%s]\n", smb_fname_str_dbg(smb_fname));
 
-       /*
-        * Return a valid fd, but ensure any attempt to use it returns an error
-        * (EPIPE). All operations on the smb_fname or the fsp will use path
-        * based syscalls.
-        */
-       rc = pipe(fds);
-       if (rc != 0) {
-               goto exit;
+       ad = ad_get(talloc_tos(), handle, smb_fname, ADOUBLE_META);
+       if (ad != NULL) {
+               meta_exists = true;
        }
-       fakefd = fds[0];
-       close(fds[1]);
-
-       if (flags & (O_CREAT | O_TRUNC)) {
-               /*
-                * The attribute does not exist or needs to be truncated,
-                * create an AppleDouble EA
-                */
-               ad = ad_init(fsp, handle, ADOUBLE_META);
-               if (ad == NULL) {
-                       rc = -1;
-                       goto exit;
-               }
 
-               rc = ad_set(ad, fsp->fsp_name);
-               if (rc != 0) {
-                       rc = -1;
-                       goto exit;
-               }
+       TALLOC_FREE(ad);
 
-               TALLOC_FREE(ad);
+       if (!meta_exists && !(flags & O_CREAT)) {
+               errno = ENOENT;
+               return -1;
        }
 
-exit:
-       DEBUG(10, ("fruit_open meta rc=%d, fd=%d\n", rc, fakefd));
-       if (rc != 0) {
-               int saved_errno = errno;
-               if (fakefd >= 0) {
-                       close(fakefd);
-               }
-               fakefd = -1;
-               errno = saved_errno;
+       fd = fruit_fake_fd();
+       if (fd == -1) {
+               return -1;
        }
-       return fakefd;
+
+       SMB_VFS_HANDLE_GET_DATA(handle, config,
+                               struct fruit_config_data, return -1);
+
+       fio = VFS_ADD_FSP_EXTENSION(handle, fsp, struct fio, NULL);
+       fio->type = ADOUBLE_META;
+       fio->config = config;
+       fio->fake_fd = true;
+       fio->flags = flags;
+       fio->mode = mode;
+
+       return fd;
 }
 
 static int fruit_open_meta(vfs_handle_struct *handle,
@@ -2851,7 +3517,6 @@ static int fruit_open_meta(vfs_handle_struct *handle,
 {
        int fd;
        struct fruit_config_data *config = NULL;
-       struct fio *fio = NULL;
 
        DBG_DEBUG("path [%s]\n", smb_fname_str_dbg(smb_fname));
 
@@ -2876,14 +3541,6 @@ static int fruit_open_meta(vfs_handle_struct *handle,
 
        DBG_DEBUG("path [%s] fd [%d]\n", smb_fname_str_dbg(smb_fname), fd);
 
-       if (fd == -1) {
-               return -1;
-       }
-
-       fio = (struct fio *)VFS_ADD_FSP_EXTENSION(handle, fsp, struct fio, NULL);
-       fio->type = ADOUBLE_META;
-       fio->config = config;
-
        return fd;
 }
 
@@ -2915,12 +3572,9 @@ static int fruit_open_rsrc_adouble(vfs_handle_struct *handle,
                goto exit;
        }
 
-       /* Sanitize flags */
-       if (flags & O_WRONLY) {
-               /* We always need read access for the metadata header too */
-               flags &= ~O_WRONLY;
-               flags |= O_RDWR;
-       }
+       /* We always need read/write access for the metadata header too */
+       flags &= ~(O_RDONLY | O_WRONLY);
+       flags |= O_RDWR;
 
        hostfd = SMB_VFS_NEXT_OPEN(handle, smb_fname_base, fsp,
                                   flags, mode);
@@ -3007,20 +3661,6 @@ static int fruit_open_rsrc(vfs_handle_struct *handle,
        SMB_VFS_HANDLE_GET_DATA(handle, config,
                                struct fruit_config_data, return -1);
 
-       if (((flags & O_ACCMODE) == O_RDONLY)
-           && (flags & O_CREAT)
-           && !VALID_STAT(fsp->fsp_name->st))
-       {
-               /*
-                * This means the stream doesn't exist. macOS SMB server fails
-                * this with NT_STATUS_OBJECT_NAME_NOT_FOUND, so must we. Cf bug
-                * 12565 and the test for this combination in
-                * test_rfork_create().
-                */
-               errno = ENOENT;
-               return -1;
-       }
-
        switch (config->rsrc) {
        case FRUIT_RSRC_STREAM:
                fd = SMB_VFS_NEXT_OPEN(handle, smb_fname, fsp, flags, mode);
@@ -3047,7 +3687,7 @@ static int fruit_open_rsrc(vfs_handle_struct *handle,
                return -1;
        }
 
-       fio = (struct fio *)VFS_ADD_FSP_EXTENSION(handle, fsp, struct fio, NULL);
+       fio = VFS_ADD_FSP_EXTENSION(handle, fsp, struct fio, NULL);
        fio->type = ADOUBLE_RSRC;
        fio->config = config;
 
@@ -3511,16 +4151,16 @@ static int fruit_rmdir(struct vfs_handle_struct *handle,
                TALLOC_FREE(ad);
 
                ret = SMB_VFS_NEXT_UNLINK(handle, ad_smb_fname);
-               TALLOC_FREE(ad_smb_fname);
                if (ret != 0) {
                        DBG_ERR("Deleting [%s] failed\n",
                                smb_fname_str_dbg(ad_smb_fname));
                }
+               TALLOC_FREE(ad_smb_fname);
        }
 
 exit_rmdir:
        if (dh) {
-               closedir(dh);
+               SMB_VFS_CLOSEDIR(handle->conn, dh);
        }
        return SMB_VFS_NEXT_RMDIR(handle, smb_fname);
 }
@@ -3533,8 +4173,7 @@ static ssize_t fruit_pread_meta_stream(vfs_handle_struct *handle,
        int ret;
 
        nread = SMB_VFS_NEXT_PREAD(handle, fsp, data, n, offset);
-
-       if (nread == n) {
+       if (nread == -1 || nread == n) {
                return nread;
        }
 
@@ -3613,6 +4252,11 @@ static ssize_t fruit_pread_meta(vfs_handle_struct *handle,
                return 0;
        }
 
+       if (fio == NULL) {
+               DBG_ERR("Failed to fetch fsp extension");
+               return -1;
+       }
+
        /* Yes, macOS always reads from offset 0 */
        offset = 0;
        to_return = MIN(n, AFP_INFO_SIZE);
@@ -3633,6 +4277,25 @@ static ssize_t fruit_pread_meta(vfs_handle_struct *handle,
                return -1;
        }
 
+       if (nread == -1 && fio->created) {
+               AfpInfo *ai = NULL;
+               char afpinfo_buf[AFP_INFO_SIZE];
+
+               ai = afpinfo_new(talloc_tos());
+               if (ai == NULL) {
+                       return -1;
+               }
+
+               nread = afpinfo_pack(ai, afpinfo_buf);
+               TALLOC_FREE(ai);
+               if (nread != AFP_INFO_SIZE) {
+                       return -1;
+               }
+
+               memcpy(data, afpinfo_buf, to_return);
+               return to_return;
+       }
+
        return nread;
 }
 
@@ -3676,6 +4339,11 @@ static ssize_t fruit_pread_rsrc(vfs_handle_struct *handle,
        struct fio *fio = (struct fio *)VFS_FETCH_FSP_EXTENSION(handle, fsp);
        ssize_t nread;
 
+       if (fio == NULL) {
+               errno = EINVAL;
+               return -1;
+       }
+
        switch (fio->config->rsrc) {
        case FRUIT_RSRC_STREAM:
                nread = fruit_pread_rsrc_stream(handle, fsp, data, n, offset);
@@ -3727,9 +4395,7 @@ static bool fruit_must_handle_aio_stream(struct fio *fio)
                return false;
        };
 
-       if ((fio->type == ADOUBLE_META) &&
-           (fio->config->meta == FRUIT_META_NETATALK))
-       {
+       if (fio->type == ADOUBLE_META) {
                return true;
        }
 
@@ -3824,8 +4490,43 @@ static ssize_t fruit_pwrite_meta_stream(vfs_handle_struct *handle,
                                        files_struct *fsp, const void *data,
                                        size_t n, off_t offset)
 {
+       struct fio *fio = (struct fio *)VFS_FETCH_FSP_EXTENSION(handle, fsp);
        AfpInfo *ai = NULL;
+       size_t nwritten;
        int ret;
+       bool ok;
+
+       DBG_DEBUG("Path [%s] offset=%"PRIdMAX", size=%zd\n",
+                 fsp_str_dbg(fsp), (intmax_t)offset, n);
+
+       if (fio == NULL) {
+               return -1;
+       }
+
+       if (fio->fake_fd) {
+               int fd;
+
+               ret = SMB_VFS_NEXT_CLOSE(handle, fsp);
+               if (ret != 0) {
+                       DBG_ERR("Close [%s] failed: %s\n",
+                               fsp_str_dbg(fsp), strerror(errno));
+                       fsp->fh->fd = -1;
+                       return -1;
+               }
+
+               fd = SMB_VFS_NEXT_OPEN(handle,
+                                      fsp->fsp_name,
+                                      fsp,
+                                      fio->flags,
+                                      fio->mode);
+               if (fd == -1) {
+                       DBG_ERR("On-demand create [%s] in write failed: %s\n",
+                               fsp_str_dbg(fsp), strerror(errno));
+                       return -1;
+               }
+               fsp->fh->fd = fd;
+               fio->fake_fd = false;
+       }
 
        ai = afpinfo_unpack(talloc_tos(), data);
        if (ai == NULL) {
@@ -3833,18 +4534,38 @@ static ssize_t fruit_pwrite_meta_stream(vfs_handle_struct *handle,
        }
 
        if (ai_empty_finderinfo(ai)) {
-               ret = SMB_VFS_NEXT_UNLINK(handle, fsp->fsp_name);
-               if (ret != 0 && errno != ENOENT && errno != ENOATTR) {
-                       DBG_ERR("Can't delete metadata for %s: %s\n",
-                               fsp_str_dbg(fsp), strerror(errno));
-                       TALLOC_FREE(ai);
+               /*
+                * Writing an all 0 blob to the metadata stream results in the
+                * stream being removed on a macOS server. This ensures we
+                * behave the same and it verified by the "delete AFP_AfpInfo by
+                * writing all 0" test.
+                */
+               ret = SMB_VFS_NEXT_FTRUNCATE(handle, fsp, 0);
+               if (ret != 0) {
+                       DBG_ERR("SMB_VFS_NEXT_FTRUNCATE on [%s] failed\n",
+                               fsp_str_dbg(fsp));
                        return -1;
                }
 
+               ok = set_delete_on_close(
+                       fsp,
+                       true,
+                       handle->conn->session_info->security_token,
+                       handle->conn->session_info->unix_token);
+               if (!ok) {
+                       DBG_ERR("set_delete_on_close on [%s] failed\n",
+                               fsp_str_dbg(fsp));
+                       return -1;
+               }
                return n;
        }
 
-       return SMB_VFS_NEXT_PWRITE(handle, fsp, data, n, offset);
+       nwritten = SMB_VFS_NEXT_PWRITE(handle, fsp, data, n, offset);
+       if (nwritten != n) {
+               return -1;
+       }
+
+       return n;
 }
 
 static ssize_t fruit_pwrite_meta_netatalk(vfs_handle_struct *handle,
@@ -3855,26 +4576,13 @@ static ssize_t fruit_pwrite_meta_netatalk(vfs_handle_struct *handle,
        AfpInfo *ai = NULL;
        char *p = NULL;
        int ret;
+       bool ok;
 
        ai = afpinfo_unpack(talloc_tos(), data);
        if (ai == NULL) {
                return -1;
        }
 
-       if (ai_empty_finderinfo(ai)) {
-               ret = SMB_VFS_REMOVEXATTR(handle->conn,
-                                         fsp->fsp_name,
-                                         AFPINFO_EA_NETATALK);
-
-               if (ret != 0 && errno != ENOENT && errno != ENOATTR) {
-                       DBG_ERR("Can't delete metadata for %s: %s\n",
-                               fsp_str_dbg(fsp), strerror(errno));
-                       return -1;
-               }
-
-               return n;
-       }
-
        ad = ad_fget(talloc_tos(), handle, fsp, ADOUBLE_META);
        if (ad == NULL) {
                ad = ad_init(talloc_tos(), handle, ADOUBLE_META);
@@ -3899,6 +4607,28 @@ static ssize_t fruit_pwrite_meta_netatalk(vfs_handle_struct *handle,
        }
 
        TALLOC_FREE(ad);
+
+       if (!ai_empty_finderinfo(ai)) {
+               return n;
+       }
+
+       /*
+        * Writing an all 0 blob to the metadata stream results in the stream
+        * being removed on a macOS server. This ensures we behave the same and
+        * it verified by the "delete AFP_AfpInfo by writing all 0" test.
+        */
+
+       ok = set_delete_on_close(
+               fsp,
+               true,
+               handle->conn->session_info->security_token,
+               handle->conn->session_info->unix_token);
+       if (!ok) {
+               DBG_ERR("set_delete_on_close on [%s] failed\n",
+                       fsp_str_dbg(fsp));
+               return -1;
+       }
+
        return n;
 }
 
@@ -3908,29 +4638,67 @@ static ssize_t fruit_pwrite_meta(vfs_handle_struct *handle,
 {
        struct fio *fio = (struct fio *)VFS_FETCH_FSP_EXTENSION(handle, fsp);
        ssize_t nwritten;
+       uint8_t buf[AFP_INFO_SIZE];
+       size_t to_write;
+       size_t to_copy;
+       int cmp;
 
-       /*
-        * Writing an all 0 blob to the metadata stream
-        * results in the stream being removed on a macOS
-        * server. This ensures we behave the same and it
-        * verified by the "delete AFP_AfpInfo by writing all
-        * 0" test.
-        */
-       if (n != AFP_INFO_SIZE || offset != 0) {
-               DBG_ERR("unexpected offset=%jd or size=%jd\n",
-                       (intmax_t)offset, (intmax_t)n);
+       if (fio == NULL) {
+               DBG_ERR("Failed to fetch fsp extension");
+               return -1;
+       }
+
+       if (n < 3) {
+               errno = EINVAL;
+               return -1;
+       }
+
+       if (offset != 0 && n < 60) {
+               errno = EINVAL;
+               return -1;
+       }
+
+       cmp = memcmp(data, "AFP", 3);
+       if (cmp != 0) {
+               errno = EINVAL;
                return -1;
        }
 
+       if (n <= AFP_OFF_FinderInfo) {
+               /*
+                * Nothing to do here really, just return
+                */
+               return n;
+       }
+
+       offset = 0;
+
+       to_copy = n;
+       if (to_copy > AFP_INFO_SIZE) {
+               to_copy = AFP_INFO_SIZE;
+       }
+       memcpy(buf, data, to_copy);
+
+       to_write = n;
+       if (to_write != AFP_INFO_SIZE) {
+               to_write = AFP_INFO_SIZE;
+       }
+
        switch (fio->config->meta) {
        case FRUIT_META_STREAM:
-               nwritten = fruit_pwrite_meta_stream(handle, fsp, data,
-                                                   n, offset);
+               nwritten = fruit_pwrite_meta_stream(handle,
+                                                   fsp,
+                                                   buf,
+                                                   to_write,
+                                                   offset);
                break;
 
        case FRUIT_META_NETATALK:
-               nwritten = fruit_pwrite_meta_netatalk(handle, fsp, data,
-                                                     n, offset);
+               nwritten = fruit_pwrite_meta_netatalk(handle,
+                                                     fsp,
+                                                     buf,
+                                                     to_write,
+                                                     offset);
                break;
 
        default:
@@ -3938,7 +4706,14 @@ static ssize_t fruit_pwrite_meta(vfs_handle_struct *handle,
                return -1;
        }
 
-       return nwritten;
+       if (nwritten != to_write) {
+               return -1;
+       }
+
+       /*
+        * Return the requested amount, verified against macOS SMB server
+        */
+       return n;
 }
 
 static ssize_t fruit_pwrite_rsrc_stream(vfs_handle_struct *handle,
@@ -3999,6 +4774,11 @@ static ssize_t fruit_pwrite_rsrc(vfs_handle_struct *handle,
        struct fio *fio = (struct fio *)VFS_FETCH_FSP_EXTENSION(handle, fsp);
        ssize_t nwritten;
 
+       if (fio == NULL) {
+               DBG_ERR("Failed to fetch fsp extension");
+               return -1;
+       }
+
        switch (fio->config->rsrc) {
        case FRUIT_RSRC_STREAM:
                nwritten = fruit_pwrite_rsrc_stream(handle, fsp, data, n, offset);
@@ -4140,6 +4920,11 @@ static int fruit_stat_base(vfs_handle_struct *handle,
                rc = SMB_VFS_NEXT_LSTAT(handle, smb_fname);
        }
        smb_fname->stream_name = tmp_stream_name;
+
+       DBG_DEBUG("fruit_stat_base [%s] dev [%ju] ino [%ju]\n",
+                 smb_fname->base_name,
+                 (uintmax_t)smb_fname->st.st_ex_dev,
+                 (uintmax_t)smb_fname->st.st_ex_ino);
        return rc;
 }
 
@@ -4148,6 +4933,14 @@ static int fruit_stat_meta_stream(vfs_handle_struct *handle,
                                  bool follow_links)
 {
        int ret;
+       ino_t ino;
+
+       ret = fruit_stat_base(handle, smb_fname, false);
+       if (ret != 0) {
+               return -1;
+       }
+
+       ino = fruit_inode(&smb_fname->st, smb_fname->stream_name);
 
        if (follow_links) {
                ret = SMB_VFS_NEXT_STAT(handle, smb_fname);
@@ -4155,6 +4948,8 @@ static int fruit_stat_meta_stream(vfs_handle_struct *handle,
                ret = SMB_VFS_NEXT_LSTAT(handle, smb_fname);
        }
 
+       smb_fname->st.st_ex_ino = ino;
+
        return ret;
 }
 
@@ -4408,7 +5203,46 @@ static int fruit_fstat_meta_stream(vfs_handle_struct *handle,
                                   files_struct *fsp,
                                   SMB_STRUCT_STAT *sbuf)
 {
-       return SMB_VFS_NEXT_FSTAT(handle, fsp, sbuf);
+       struct fio *fio = (struct fio *)VFS_FETCH_FSP_EXTENSION(handle, fsp);
+       struct smb_filename smb_fname;
+       ino_t ino;
+       int ret;
+
+       if (fio == NULL) {
+               return -1;
+       }
+
+       if (fio->fake_fd) {
+               ret = fruit_stat_base(handle, fsp->base_fsp->fsp_name, false);
+               if (ret != 0) {
+                       return -1;
+               }
+
+               *sbuf = fsp->base_fsp->fsp_name->st;
+               sbuf->st_ex_size = AFP_INFO_SIZE;
+               sbuf->st_ex_ino = fruit_inode(sbuf, fsp->fsp_name->stream_name);
+               return 0;
+       }
+
+       smb_fname = (struct smb_filename) {
+               .base_name = fsp->fsp_name->base_name,
+       };
+
+       ret = fruit_stat_base(handle, &smb_fname, false);
+       if (ret != 0) {
+               return -1;
+       }
+       *sbuf = smb_fname.st;
+
+       ino = fruit_inode(sbuf, fsp->fsp_name->stream_name);
+
+       ret = SMB_VFS_NEXT_FSTAT(handle, fsp, sbuf);
+       if (ret != 0) {
+               return -1;
+       }
+
+       sbuf->st_ex_ino = ino;
+       return 0;
 }
 
 static int fruit_fstat_meta_netatalk(vfs_handle_struct *handle,
@@ -4555,6 +5389,45 @@ static int fruit_fstat(vfs_handle_struct *handle, files_struct *fsp,
        return rc;
 }
 
+static NTSTATUS delete_invalid_meta_stream(
+       vfs_handle_struct *handle,
+       const struct smb_filename *smb_fname,
+       TALLOC_CTX *mem_ctx,
+       unsigned int *pnum_streams,
+       struct stream_struct **pstreams,
+       off_t size)
+{
+       struct smb_filename *sname = NULL;
+       int ret;
+       bool ok;
+
+       ok = del_fruit_stream(mem_ctx, pnum_streams, pstreams, AFPINFO_STREAM);
+       if (!ok) {
+               return NT_STATUS_INTERNAL_ERROR;
+       }
+
+       if (size == 0) {
+               return NT_STATUS_OK;
+       }
+
+       sname = synthetic_smb_fname(talloc_tos(),
+                                   smb_fname->base_name,
+                                   AFPINFO_STREAM_NAME,
+                                   NULL, 0);
+       if (sname == NULL) {
+               return NT_STATUS_NO_MEMORY;
+       }
+
+       ret = SMB_VFS_NEXT_UNLINK(handle, sname);
+       TALLOC_FREE(sname);
+       if (ret != 0) {
+               DBG_ERR("Removing [%s] failed\n", smb_fname_str_dbg(sname));
+               return map_nt_error_from_unix(errno);
+       }
+
+       return NT_STATUS_OK;
+}
+
 static NTSTATUS fruit_streaminfo_meta_stream(
        vfs_handle_struct *handle,
        struct files_struct *fsp,
@@ -4565,10 +5438,7 @@ static NTSTATUS fruit_streaminfo_meta_stream(
 {
        struct stream_struct *stream = *pstreams;
        unsigned int num_streams = *pnum_streams;
-       struct smb_filename *sname = NULL;
        int i;
-       int ret;
-       bool ok;
 
        for (i = 0; i < num_streams; i++) {
                if (strequal_m(stream[i].name, AFPINFO_STREAM)) {
@@ -4580,33 +5450,18 @@ static NTSTATUS fruit_streaminfo_meta_stream(
                return NT_STATUS_OK;
        }
 
-       if (stream[i].size == AFP_INFO_SIZE) {
-               return NT_STATUS_OK;
-       }
-
-       DBG_ERR("Removing invalid AFPINFO_STREAM size [%"PRIdMAX"] "
-               "from [%s]\n", (intmax_t)stream[i].size,
-               smb_fname_str_dbg(smb_fname));
+       if (stream[i].size != AFP_INFO_SIZE) {
+               DBG_ERR("Removing invalid AFPINFO_STREAM size [%jd] from [%s]\n",
+                       (intmax_t)stream[i].size, smb_fname_str_dbg(smb_fname));
 
-       ok = del_fruit_stream(mem_ctx, pnum_streams, pstreams, AFPINFO_STREAM);
-       if (!ok) {
-               return NT_STATUS_INTERNAL_ERROR;
-       }
-
-       sname = synthetic_smb_fname(talloc_tos(),
-                                   smb_fname->base_name,
-                                   AFPINFO_STREAM_NAME,
-                                   NULL, 0);
-       if (sname == NULL) {
-               return NT_STATUS_NO_MEMORY;
+               return delete_invalid_meta_stream(handle,
+                                                 smb_fname,
+                                                 mem_ctx,
+                                                 pnum_streams,
+                                                 pstreams,
+                                                 stream[i].size);
        }
 
-       ret = SMB_VFS_NEXT_UNLINK(handle, sname);
-       TALLOC_FREE(sname);
-       if (ret != 0) {
-               DBG_ERR("Removing [%s] failed\n", smb_fname_str_dbg(sname));
-               return map_nt_error_from_unix(errno);
-       }
 
        return NT_STATUS_OK;
 }
@@ -4842,6 +5697,36 @@ static NTSTATUS fruit_streaminfo_rsrc(vfs_handle_struct *handle,
        return status;
 }
 
+static void fruit_filter_empty_streams(unsigned int *pnum_streams,
+                                      struct stream_struct **pstreams)
+{
+       unsigned num_streams = *pnum_streams;
+       struct stream_struct *streams = *pstreams;
+       unsigned i = 0;
+
+       if (!global_fruit_config.nego_aapl) {
+               return;
+       }
+
+       while (i < num_streams) {
+               struct smb_filename smb_fname = (struct smb_filename) {
+                       .stream_name = streams[i].name,
+               };
+
+               if (is_ntfs_default_stream_smb_fname(&smb_fname)
+                   || streams[i].size > 0)
+               {
+                       i++;
+                       continue;
+               }
+
+               streams[i] = streams[num_streams - 1];
+               num_streams--;
+       }
+
+       *pnum_streams = num_streams;
+}
+
 static NTSTATUS fruit_streaminfo(vfs_handle_struct *handle,
                                 struct files_struct *fsp,
                                 const struct smb_filename *smb_fname,
@@ -4863,6 +5748,8 @@ static NTSTATUS fruit_streaminfo(vfs_handle_struct *handle,
                return status;
        }
 
+       fruit_filter_empty_streams(pnum_streams, pstreams);
+
        status = fruit_streaminfo_meta(handle, fsp, smb_fname,
                                       mem_ctx, pnum_streams, pstreams);
        if (!NT_STATUS_IS_OK(status)) {
@@ -4939,10 +5826,6 @@ static int fruit_ftruncate_rsrc_xattr(struct vfs_handle_struct *handle,
                                      struct files_struct *fsp,
                                      off_t offset)
 {
-       if (offset == 0) {
-               return SMB_VFS_FREMOVEXATTR(fsp, AFPRESOURCE_EA_NETATALK);
-       }
-
 #ifdef HAVE_ATTROPEN
        return SMB_VFS_NEXT_FTRUNCATE(handle, fsp, offset);
 #endif
@@ -4990,10 +5873,6 @@ static int fruit_ftruncate_rsrc_stream(struct vfs_handle_struct *handle,
                                       struct files_struct *fsp,
                                       off_t offset)
 {
-       if (offset == 0) {
-               return SMB_VFS_NEXT_UNLINK(handle, fsp->fsp_name);
-       }
-
        return SMB_VFS_NEXT_FTRUNCATE(handle, fsp, offset);
 }
 
@@ -5004,6 +5883,11 @@ static int fruit_ftruncate_rsrc(struct vfs_handle_struct *handle,
        struct fio *fio = (struct fio *)VFS_FETCH_FSP_EXTENSION(handle, fsp);
        int ret;
 
+       if (fio == NULL) {
+               DBG_ERR("Failed to fetch fsp extension");
+               return -1;
+       }
+
        switch (fio->config->rsrc) {
        case FRUIT_RSRC_XATTR:
                ret = fruit_ftruncate_rsrc_xattr(handle, fsp, offset);
@@ -5091,6 +5975,7 @@ static NTSTATUS fruit_create_file(vfs_handle_struct *handle,
        NTSTATUS status;
        struct fruit_config_data *config = NULL;
        files_struct *fsp = NULL;
+       struct fio *fio = NULL;
 
        status = check_aapl(handle, req, in_context_blobs, out_context_blobs);
        if (!NT_STATUS_IS_OK(status)) {
@@ -5131,13 +6016,19 @@ static NTSTATUS fruit_create_file(vfs_handle_struct *handle,
         *
         * Cf the vfs_fruit torture tests in test_rfork_create().
         */
-       if (is_afpresource_stream(fsp->fsp_name) &&
-           create_disposition == FILE_OPEN)
+       if (global_fruit_config.nego_aapl &&
+           create_disposition == FILE_OPEN &&
+           smb_fname->st.st_ex_size == 0 &&
+           is_ntfs_stream_smb_fname(smb_fname) &&
+           !(is_ntfs_default_stream_smb_fname(smb_fname)))
        {
-               if (fsp->fsp_name->st.st_ex_size == 0) {
-                       status = NT_STATUS_OBJECT_NAME_NOT_FOUND;
-                       goto fail;
-               }
+               status = NT_STATUS_OBJECT_NAME_NOT_FOUND;
+               goto fail;
+       }
+
+       fio = (struct fio *)VFS_FETCH_FSP_EXTENSION(handle, fsp);
+       if (fio != NULL && pinfo != NULL && *pinfo == FILE_WAS_CREATED) {
+               fio->created = true;
        }
 
        if (is_ntfs_stream_smb_fname(smb_fname)
@@ -5275,6 +6166,13 @@ static NTSTATUS fruit_fget_nt_acl(vfs_handle_struct *handle,
                return NT_STATUS_OK;
        }
 
+       /* First remove any existing ACE's with NFS style mode/uid/gid SIDs. */
+       status = remove_virtual_nfs_aces(*ppdesc);
+       if (!NT_STATUS_IS_OK(status)) {
+               DBG_WARNING("failed to remove MS NFS style ACEs\n");
+               return status;
+       }
+
        /* MS NFS style mode */
        sid_compose(&sid, &global_sid_Unix_NFS_Mode, fsp->fsp_name->st.st_ex_mode);
        init_sec_ace(&ace, &sid, SEC_ACE_TYPE_ACCESS_DENIED, 0, 0);
@@ -5308,24 +6206,53 @@ static NTSTATUS fruit_fget_nt_acl(vfs_handle_struct *handle,
 static NTSTATUS fruit_fset_nt_acl(vfs_handle_struct *handle,
                                  files_struct *fsp,
                                  uint32_t security_info_sent,
-                                 const struct security_descriptor *psd)
+                                 const struct security_descriptor *orig_psd)
 {
        NTSTATUS status;
        bool do_chmod;
        mode_t ms_nfs_mode = 0;
        int result;
+       struct security_descriptor *psd = NULL;
+       uint32_t orig_num_aces = 0;
+
+       if (orig_psd->dacl != NULL) {
+               orig_num_aces = orig_psd->dacl->num_aces;
+       }
+
+       psd = security_descriptor_copy(talloc_tos(), orig_psd);
+       if (psd == NULL) {
+               return NT_STATUS_NO_MEMORY;
+       }
 
        DBG_DEBUG("fruit_fset_nt_acl: %s\n", fsp_str_dbg(fsp));
 
        status = check_ms_nfs(handle, fsp, psd, &ms_nfs_mode, &do_chmod);
        if (!NT_STATUS_IS_OK(status)) {
                DEBUG(1, ("fruit_fset_nt_acl: check_ms_nfs failed%s\n", fsp_str_dbg(fsp)));
+               TALLOC_FREE(psd);
                return status;
        }
 
+       /*
+        * If only ms_nfs ACE entries were sent, ensure we set the DACL
+        * sent/present flags correctly now we've removed them.
+        */
+
+       if (orig_num_aces != 0) {
+               /*
+                * Are there any ACE's left ?
+                */
+               if (psd->dacl->num_aces == 0) {
+                       /* No - clear the DACL sent/present flags. */
+                       security_info_sent &= ~SECINFO_DACL;
+                       psd->type &= ~SEC_DESC_DACL_PRESENT;
+               }
+       }
+
        status = SMB_VFS_NEXT_FSET_NT_ACL(handle, fsp, security_info_sent, psd);
        if (!NT_STATUS_IS_OK(status)) {
                DEBUG(1, ("fruit_fset_nt_acl: SMB_VFS_NEXT_FSET_NT_ACL failed%s\n", fsp_str_dbg(fsp)));
+               TALLOC_FREE(psd);
                return status;
        }
 
@@ -5343,10 +6270,12 @@ static NTSTATUS fruit_fset_nt_acl(vfs_handle_struct *handle,
                                  result, (unsigned)ms_nfs_mode,
                                  strerror(errno)));
                        status = map_nt_error_from_unix(errno);
+                       TALLOC_FREE(psd);
                        return status;
                }
        }
 
+       TALLOC_FREE(psd);
        return NT_STATUS_OK;
 }
 
@@ -5672,8 +6601,426 @@ static NTSTATUS fruit_offload_write_recv(struct vfs_handle_struct *handle,
        return NT_STATUS_OK;
 }
 
+static char *fruit_get_bandsize_line(char **lines, int numlines)
+{
+       static regex_t re;
+       static bool re_initialized = false;
+       int i;
+       int ret;
+
+       if (!re_initialized) {
+               ret = regcomp(&re, "^[[:blank:]]*<key>band-size</key>$", 0);
+               if (ret != 0) {
+                       return NULL;
+               }
+               re_initialized = true;
+       }
+
+       for (i = 0; i < numlines; i++) {
+               regmatch_t matches[1];
+
+               ret = regexec(&re, lines[i], 1, matches, 0);
+               if (ret == 0) {
+                       /*
+                        * Check if the match was on the last line, sa we want
+                        * the subsequent line.
+                        */
+                       if (i + 1 == numlines) {
+                               return NULL;
+                       }
+                       return lines[i + 1];
+               }
+               if (ret != REG_NOMATCH) {
+                       return NULL;
+               }
+       }
+
+       return NULL;
+}
+
+static bool fruit_get_bandsize_from_line(char *line, size_t *_band_size)
+{
+       static regex_t re;
+       static bool re_initialized = false;
+       regmatch_t matches[2];
+       uint64_t band_size;
+       int ret;
+       bool ok;
+
+       if (!re_initialized) {
+               ret = regcomp(&re,
+                             "^[[:blank:]]*"
+                             "<integer>\\([[:digit:]]*\\)</integer>$",
+                             0);
+               if (ret != 0) {
+                       return false;
+               }
+               re_initialized = true;
+       }
+
+       ret = regexec(&re, line, 2, matches, 0);
+       if (ret != 0) {
+               DBG_ERR("regex failed [%s]\n", line);
+               return false;
+       }
+
+       line[matches[1].rm_eo] = '\0';
+
+       ok = conv_str_u64(&line[matches[1].rm_so], &band_size);
+       if (!ok) {
+               return false;
+       }
+       *_band_size = (size_t)band_size;
+       return true;
+}
+
+/*
+ * This reads and parses an Info.plist from a TM sparsebundle looking for the
+ * "band-size" key and value.
+ */
+static bool fruit_get_bandsize(vfs_handle_struct *handle,
+                              const char *dir,
+                              size_t *band_size)
+{
+#define INFO_PLIST_MAX_SIZE 64*1024
+       char *plist = NULL;
+       struct smb_filename *smb_fname = NULL;
+       files_struct *fsp = NULL;
+       uint8_t *file_data = NULL;
+       char **lines = NULL;
+       char *band_size_line = NULL;
+       size_t plist_file_size;
+       ssize_t nread;
+       int numlines;
+       int ret;
+       bool ok = false;
+       NTSTATUS status;
+
+       plist = talloc_asprintf(talloc_tos(),
+                               "%s/%s/Info.plist",
+                               handle->conn->connectpath,
+                               dir);
+       if (plist == NULL) {
+               ok = false;
+               goto out;
+       }
+
+       smb_fname = synthetic_smb_fname(talloc_tos(), plist, NULL, NULL, 0);
+       if (smb_fname == NULL) {
+               ok = false;
+               goto out;
+       }
+
+       ret = SMB_VFS_NEXT_LSTAT(handle, smb_fname);
+       if (ret != 0) {
+               DBG_INFO("Ignoring Sparsebundle without Info.plist [%s]\n", dir);
+               ok = true;
+               goto out;
+       }
+
+       plist_file_size = smb_fname->st.st_ex_size;
+
+       if (plist_file_size > INFO_PLIST_MAX_SIZE) {
+               DBG_INFO("%s is too large, ignoring\n", plist);
+               ok = true;
+               goto out;
+       }
+
+       status = SMB_VFS_NEXT_CREATE_FILE(
+               handle,                         /* conn */
+               NULL,                           /* req */
+               0,                              /* root_dir_fid */
+               smb_fname,                      /* fname */
+               FILE_GENERIC_READ,              /* access_mask */
+               FILE_SHARE_READ | FILE_SHARE_WRITE, /* share_access */
+               FILE_OPEN,                      /* create_disposition */
+               0,                              /* create_options */
+               0,                              /* file_attributes */
+               INTERNAL_OPEN_ONLY,             /* oplock_request */
+               NULL,                           /* lease */
+               0,                              /* allocation_size */
+               0,                              /* private_flags */
+               NULL,                           /* sd */
+               NULL,                           /* ea_list */
+               &fsp,                           /* result */
+               NULL,                           /* psbuf */
+               NULL, NULL);                    /* create context */
+       if (!NT_STATUS_IS_OK(status)) {
+               DBG_INFO("Opening [%s] failed [%s]\n",
+                        smb_fname_str_dbg(smb_fname), nt_errstr(status));
+               ok = false;
+               goto out;
+       }
+
+       file_data = talloc_array(talloc_tos(), uint8_t, plist_file_size);
+       if (file_data == NULL) {
+               ok = false;
+               goto out;
+       }
+
+       nread = SMB_VFS_NEXT_PREAD(handle, fsp, file_data, plist_file_size, 0);
+       if (nread != plist_file_size) {
+               DBG_ERR("Short read on [%s]: %zu/%zd\n",
+                       fsp_str_dbg(fsp), nread, plist_file_size);
+               ok = false;
+               goto out;
+
+       }
+
+       status = close_file(NULL, fsp, NORMAL_CLOSE);
+       fsp = NULL;
+       if (!NT_STATUS_IS_OK(status)) {
+               DBG_ERR("close_file failed: %s\n", nt_errstr(status));
+               ok = false;
+               goto out;
+       }
+
+       lines = file_lines_parse((char *)file_data,
+                                plist_file_size,
+                                &numlines,
+                                talloc_tos());
+       if (lines == NULL) {
+               ok = false;
+               goto out;
+       }
+
+       band_size_line = fruit_get_bandsize_line(lines, numlines);
+       if (band_size_line == NULL) {
+               DBG_ERR("Didn't find band-size key in [%s]\n",
+                       smb_fname_str_dbg(smb_fname));
+               ok = false;
+               goto out;
+       }
+
+       ok = fruit_get_bandsize_from_line(band_size_line, band_size);
+       if (!ok) {
+               DBG_ERR("fruit_get_bandsize_from_line failed\n");
+               goto out;
+       }
+
+       DBG_DEBUG("Parsed band-size [%zu] for [%s]\n", *band_size, plist);
+
+out:
+       if (fsp != NULL) {
+               status = close_file(NULL, fsp, NORMAL_CLOSE);
+               if (!NT_STATUS_IS_OK(status)) {
+                       DBG_ERR("close_file failed: %s\n", nt_errstr(status));
+               }
+               fsp = NULL;
+       }
+       TALLOC_FREE(plist);
+       TALLOC_FREE(smb_fname);
+       TALLOC_FREE(file_data);
+       TALLOC_FREE(lines);
+       return ok;
+}
+
+struct fruit_disk_free_state {
+       off_t total_size;
+};
+
+static bool fruit_get_num_bands(vfs_handle_struct *handle,
+                               char *bundle,
+                               size_t *_nbands)
+{
+       char *path = NULL;
+       struct smb_filename *bands_dir = NULL;
+       DIR *d = NULL;
+       struct dirent *e = NULL;
+       size_t nbands;
+       int ret;
+
+       path = talloc_asprintf(talloc_tos(),
+                              "%s/%s/bands",
+                              handle->conn->connectpath,
+                              bundle);
+       if (path == NULL) {
+               return false;
+       }
+
+       bands_dir = synthetic_smb_fname(talloc_tos(),
+                                       path,
+                                       NULL,
+                                       NULL,
+                                       0);
+       TALLOC_FREE(path);
+       if (bands_dir == NULL) {
+               return false;
+       }
+
+       d = SMB_VFS_NEXT_OPENDIR(handle, bands_dir, NULL, 0);
+       if (d == NULL) {
+               TALLOC_FREE(bands_dir);
+               return false;
+       }
+
+       nbands = 0;
+
+       for (e = SMB_VFS_NEXT_READDIR(handle, d, NULL);
+            e != NULL;
+            e = SMB_VFS_NEXT_READDIR(handle, d, NULL))
+       {
+               if (ISDOT(e->d_name) || ISDOTDOT(e->d_name)) {
+                       continue;
+               }
+               nbands++;
+       }
+
+       ret = SMB_VFS_NEXT_CLOSEDIR(handle, d);
+       if (ret != 0) {
+               TALLOC_FREE(bands_dir);
+               return false;
+       }
+
+       DBG_DEBUG("%zu bands in [%s]\n", nbands, smb_fname_str_dbg(bands_dir));
+
+       TALLOC_FREE(bands_dir);
+
+       *_nbands = nbands;
+       return true;
+}
+
+static bool fruit_tmsize_do_dirent(vfs_handle_struct *handle,
+                                  struct fruit_disk_free_state *state,
+                                  struct dirent *e)
+{
+       bool ok;
+       char *p = NULL;
+       size_t sparsebundle_strlen = strlen("sparsebundle");
+       size_t bandsize = 0;
+       size_t nbands;
+       off_t tm_size;
+
+       p = strstr(e->d_name, "sparsebundle");
+       if (p == NULL) {
+               return true;
+       }
+
+       if (p[sparsebundle_strlen] != '\0') {
+               return true;
+       }
+
+       DBG_DEBUG("Processing sparsebundle [%s]\n", e->d_name);
+
+       ok = fruit_get_bandsize(handle, e->d_name, &bandsize);
+       if (!ok) {
+               /*
+                * Beware of race conditions: this may be an uninitialized
+                * Info.plist that a client is just creating. We don't want let
+                * this to trigger complete failure.
+                */
+               DBG_ERR("Processing sparsebundle [%s] failed\n", e->d_name);
+               return true;
+       }
+
+       ok = fruit_get_num_bands(handle, e->d_name, &nbands);
+       if (!ok) {
+               /*
+                * Beware of race conditions: this may be a backup sparsebundle
+                * in an early stage lacking a bands subdirectory. We don't want
+                * let this to trigger complete failure.
+                */
+               DBG_ERR("Processing sparsebundle [%s] failed\n", e->d_name);
+               return true;
+       }
+
+       if (bandsize > SIZE_MAX/nbands) {
+               DBG_ERR("tmsize overflow: bandsize [%zu] nbands [%zu]\n",
+                       bandsize, nbands);
+               return false;
+       }
+       tm_size = bandsize * nbands;
+
+       if (state->total_size + tm_size < state->total_size) {
+               DBG_ERR("tmsize overflow: bandsize [%zu] nbands [%zu]\n",
+                       bandsize, nbands);
+               return false;
+       }
+
+       state->total_size += tm_size;
+
+       DBG_DEBUG("[%s] tm_size [%jd] total_size [%jd]\n",
+                 e->d_name, (intmax_t)tm_size, (intmax_t)state->total_size);
+
+       return true;
+}
+
+/**
+ * Calculate used size of a TimeMachine volume
+ *
+ * This assumes that the volume is used only for TimeMachine.
+ *
+ * - readdir(basedir of share), then
+ * - for every element that matches regex "^\(.*\)\.sparsebundle$" :
+ * - parse "\1.sparsebundle/Info.plist" and read the band-size XML key
+ * - count band files in "\1.sparsebundle/bands/"
+ * - calculate used size of all bands: band_count * band_size
+ **/
+static uint64_t fruit_disk_free(vfs_handle_struct *handle,
+                               const struct smb_filename *smb_fname,
+                               uint64_t *_bsize,
+                               uint64_t *_dfree,
+                               uint64_t *_dsize)
+{
+       struct fruit_config_data *config = NULL;
+       struct fruit_disk_free_state state = {0};
+       DIR *d = NULL;
+       struct dirent *e = NULL;
+       uint64_t dfree;
+       uint64_t dsize;
+       int ret;
+       bool ok;
+
+       SMB_VFS_HANDLE_GET_DATA(handle, config,
+                               struct fruit_config_data,
+                               return UINT64_MAX);
+
+       if (!config->time_machine ||
+           config->time_machine_max_size == 0)
+       {
+               return SMB_VFS_NEXT_DISK_FREE(handle,
+                                             smb_fname,
+                                             _bsize,
+                                             _dfree,
+                                             _dsize);
+       }
+
+       d = SMB_VFS_NEXT_OPENDIR(handle, smb_fname, NULL, 0);
+       if (d == NULL) {
+               return UINT64_MAX;
+       }
+
+       for (e = SMB_VFS_NEXT_READDIR(handle, d, NULL);
+            e != NULL;
+            e = SMB_VFS_NEXT_READDIR(handle, d, NULL))
+       {
+               ok = fruit_tmsize_do_dirent(handle, &state, e);
+               if (!ok) {
+                       SMB_VFS_NEXT_CLOSEDIR(handle, d);
+                       return UINT64_MAX;
+               }
+       }
+
+       ret = SMB_VFS_NEXT_CLOSEDIR(handle, d);
+       if (ret != 0) {
+               return UINT64_MAX;
+       }
+
+       dsize = config->time_machine_max_size / 512;
+       dfree = dsize - (state.total_size / 512);
+       if (dfree > dsize) {
+               dfree = 0;
+       }
+
+       *_bsize = 512;
+       *_dsize = dsize;
+       *_dfree = dfree;
+       return dfree / 2;
+}
+
 static struct vfs_fn_pointers vfs_fruit_fns = {
        .connect_fn = fruit_connect,
+       .disk_free_fn = fruit_disk_free,
 
        /* File operations */
        .chmod_fn = fruit_chmod,
@@ -5707,7 +7054,7 @@ static struct vfs_fn_pointers vfs_fruit_fns = {
        .fset_nt_acl_fn = fruit_fset_nt_acl,
 };
 
-NTSTATUS vfs_fruit_init(TALLOC_CTX *);
+static_decl_vfs;
 NTSTATUS vfs_fruit_init(TALLOC_CTX *ctx)
 {
        NTSTATUS ret = smb_register_vfs(SMB_VFS_INTERFACE_VERSION, "fruit",