Ignore:
Timestamp:
Nov 24, 2016, 1:14:11 PM (9 years ago)
Author:
Silvan Scherrer
Message:

Samba Server: update vendor to version 4.4.3

File:
1 edited

Legend:

Unmodified
Added
Removed
  • vendor/current/source3/smbd/open.c

    r860 r988  
    2828#include "../libcli/security/security.h"
    2929#include "../librpc/gen_ndr/ndr_security.h"
     30#include "../librpc/gen_ndr/open_files.h"
     31#include "../librpc/gen_ndr/idmap.h"
     32#include "../librpc/gen_ndr/ioctl.h"
     33#include "passdb/lookup_sid.h"
    3034#include "auth.h"
     35#include "serverid.h"
    3136#include "messages.h"
     37#include "source3/lib/dbwrap/dbwrap_watch.h"
     38#include "locking/leases_db.h"
     39#include "librpc/gen_ndr/ndr_leases_db.h"
    3240
    3341extern const struct generic_mapping file_generic_mapping;
     
    3543struct deferred_open_record {
    3644        bool delayed_for_oplocks;
     45        bool async_open;
    3746        struct file_id id;
    3847};
    3948
    4049/****************************************************************************
    41  SMB1 file varient of se_access_check. Never test FILE_READ_ATTRIBUTES.
     50 If the requester wanted DELETE_ACCESS and was rejected because
     51 the file ACL didn't include DELETE_ACCESS, see if the parent ACL
     52 overrides this.
    4253****************************************************************************/
    4354
    44 NTSTATUS smb1_file_se_access_check(struct connection_struct *conn,
    45                                 const struct security_descriptor *sd,
    46                                 const struct security_token *token,
    47                                 uint32_t access_desired,
    48                                 uint32_t *access_granted)
     55static bool parent_override_delete(connection_struct *conn,
     56                                        const struct smb_filename *smb_fname,
     57                                        uint32_t access_mask,
     58                                        uint32_t rejected_mask)
    4959{
    50         *access_granted = 0;
    51 
    52         if (get_current_uid(conn) == (uid_t)0) {
     60        if ((access_mask & DELETE_ACCESS) &&
     61                    (rejected_mask & DELETE_ACCESS) &&
     62                    can_delete_file_in_directory(conn, smb_fname)) {
     63                return true;
     64        }
     65        return false;
     66}
     67
     68/****************************************************************************
     69 Check if we have open rights.
     70****************************************************************************/
     71
     72NTSTATUS smbd_check_access_rights(struct connection_struct *conn,
     73                                const struct smb_filename *smb_fname,
     74                                bool use_privs,
     75                                uint32_t access_mask)
     76{
     77        /* Check if we have rights to open. */
     78        NTSTATUS status;
     79        struct security_descriptor *sd = NULL;
     80        uint32_t rejected_share_access;
     81        uint32_t rejected_mask = access_mask;
     82        uint32_t do_not_check_mask = 0;
     83
     84        rejected_share_access = access_mask & ~(conn->share_access);
     85
     86        if (rejected_share_access) {
     87                DEBUG(10, ("smbd_check_access_rights: rejected share access 0x%x "
     88                        "on %s (0x%x)\n",
     89                        (unsigned int)access_mask,
     90                        smb_fname_str_dbg(smb_fname),
     91                        (unsigned int)rejected_share_access ));
     92                return NT_STATUS_ACCESS_DENIED;
     93        }
     94
     95        if (!use_privs && get_current_uid(conn) == (uid_t)0) {
    5396                /* I'm sorry sir, I didn't know you were root... */
    54                 *access_granted = access_desired;
    55                 if (access_desired & SEC_FLAG_MAXIMUM_ALLOWED) {
    56                         *access_granted |= FILE_GENERIC_ALL;
    57                 }
     97                DEBUG(10,("smbd_check_access_rights: root override "
     98                        "on %s. Granting 0x%x\n",
     99                        smb_fname_str_dbg(smb_fname),
     100                        (unsigned int)access_mask ));
    58101                return NT_STATUS_OK;
    59102        }
    60103
    61         /*
     104        if ((access_mask & DELETE_ACCESS) && !lp_acl_check_permissions(SNUM(conn))) {
     105                DEBUG(10,("smbd_check_access_rights: not checking ACL "
     106                        "on DELETE_ACCESS on file %s. Granting 0x%x\n",
     107                        smb_fname_str_dbg(smb_fname),
     108                        (unsigned int)access_mask ));
     109                return NT_STATUS_OK;
     110        }
     111
     112        if (access_mask == DELETE_ACCESS &&
     113                        VALID_STAT(smb_fname->st) &&
     114                        S_ISLNK(smb_fname->st.st_ex_mode)) {
     115                /* We can always delete a symlink. */
     116                DEBUG(10,("smbd_check_access_rights: not checking ACL "
     117                        "on DELETE_ACCESS on symlink %s.\n",
     118                        smb_fname_str_dbg(smb_fname) ));
     119                return NT_STATUS_OK;
     120        }
     121
     122        status = SMB_VFS_GET_NT_ACL(conn, smb_fname->base_name,
     123                        (SECINFO_OWNER |
     124                        SECINFO_GROUP |
     125                         SECINFO_DACL), talloc_tos(), &sd);
     126
     127        if (!NT_STATUS_IS_OK(status)) {
     128                DEBUG(10, ("smbd_check_access_rights: Could not get acl "
     129                        "on %s: %s\n",
     130                        smb_fname_str_dbg(smb_fname),
     131                        nt_errstr(status)));
     132
     133                if (NT_STATUS_EQUAL(status, NT_STATUS_ACCESS_DENIED)) {
     134                        goto access_denied;
     135                }
     136
     137                return status;
     138        }
     139
     140        /*
    62141         * If we can access the path to this file, by
    63142         * default we have FILE_READ_ATTRIBUTES from the
     
    65144         * "Algorithm to Check Access to an Existing File"
    66145         * in MS-FSA.pdf.
     146         *
     147         * se_file_access_check() also takes care of
     148         * owner WRITE_DAC and READ_CONTROL.
    67149         */
    68         return se_access_check(sd,
    69                                 token,
    70                                 (access_desired & ~FILE_READ_ATTRIBUTES),
    71                                 access_granted);
    72 }
    73 
    74 /****************************************************************************
    75  Check if we have open rights.
    76 ****************************************************************************/
    77 
    78 NTSTATUS smbd_check_open_rights(struct connection_struct *conn,
    79                                 const struct smb_filename *smb_fname,
    80                                 uint32_t access_mask,
    81                                 uint32_t *access_granted)
    82 {
    83         /* Check if we have rights to open. */
    84         NTSTATUS status;
    85         struct security_descriptor *sd = NULL;
    86         uint32_t rejected_share_access;
    87 
    88         rejected_share_access = access_mask & ~(conn->share_access);
    89 
    90         if (rejected_share_access) {
    91                 *access_granted = rejected_share_access;
    92                 return NT_STATUS_ACCESS_DENIED;
    93         }
    94 
    95         if ((access_mask & DELETE_ACCESS) && !lp_acl_check_permissions(SNUM(conn))) {
    96                 *access_granted = access_mask;
    97 
    98                 DEBUG(10,("smbd_check_open_rights: not checking ACL "
    99                         "on DELETE_ACCESS on file %s. Granting 0x%x\n",
    100                         smb_fname_str_dbg(smb_fname),
    101                         (unsigned int)*access_granted ));
    102                 return NT_STATUS_OK;
    103         }
    104 
    105         if (access_mask == DELETE_ACCESS &&
    106                         VALID_STAT(smb_fname->st) &&
    107                         S_ISLNK(smb_fname->st.st_ex_mode)) {
    108                 /* We can always delete a symlink. */
    109                 DEBUG(10,("smbd_check_open_rights: not checking ACL "
    110                         "on DELETE_ACCESS on symlink %s.\n",
    111                         smb_fname_str_dbg(smb_fname) ));
    112                 return NT_STATUS_OK;
    113         }
    114 
    115         status = SMB_VFS_GET_NT_ACL(conn, smb_fname->base_name,
    116                         (SECINFO_OWNER |
    117                         SECINFO_GROUP |
    118                         SECINFO_DACL),&sd);
    119 
    120         if (!NT_STATUS_IS_OK(status)) {
    121                 DEBUG(10, ("smbd_check_open_rights: Could not get acl "
    122                         "on %s: %s\n",
    123                         smb_fname_str_dbg(smb_fname),
    124                         nt_errstr(status)));
    125                 return status;
    126         }
    127 
    128         status = smb1_file_se_access_check(conn,
    129                                 sd,
     150        do_not_check_mask = FILE_READ_ATTRIBUTES;
     151
     152        /*
     153         * Samba 3.6 and earlier granted execute access even
     154         * if the ACL did not contain execute rights.
     155         * Samba 4.0 is more correct and checks it.
     156         * The compatibilty mode allows one to skip this check
     157         * to smoothen upgrades.
     158         */
     159        if (lp_acl_allow_execute_always(SNUM(conn))) {
     160                do_not_check_mask |= FILE_EXECUTE;
     161        }
     162
     163        status = se_file_access_check(sd,
    130164                                get_current_nttok(conn),
    131                                 access_mask,
    132                                 access_granted);
    133 
    134         DEBUG(10,("smbd_check_open_rights: file %s requesting "
     165                                use_privs,
     166                                (access_mask & ~do_not_check_mask),
     167                                &rejected_mask);
     168
     169        DEBUG(10,("smbd_check_access_rights: file %s requesting "
    135170                "0x%x returning 0x%x (%s)\n",
    136171                smb_fname_str_dbg(smb_fname),
    137172                (unsigned int)access_mask,
    138                 (unsigned int)*access_granted,
     173                (unsigned int)rejected_mask,
    139174                nt_errstr(status) ));
    140175
    141176        if (!NT_STATUS_IS_OK(status)) {
    142177                if (DEBUGLEVEL >= 10) {
    143                         DEBUG(10,("smbd_check_open_rights: acl for %s is:\n",
     178                        DEBUG(10,("smbd_check_access_rights: acl for %s is:\n",
    144179                                smb_fname_str_dbg(smb_fname) ));
    145180                        NDR_PRINT_DEBUG(security_descriptor, sd);
     
    149184        TALLOC_FREE(sd);
    150185
    151         return status;
     186        if (NT_STATUS_IS_OK(status) ||
     187                        !NT_STATUS_EQUAL(status, NT_STATUS_ACCESS_DENIED)) {
     188                return status;
     189        }
     190
     191        /* Here we know status == NT_STATUS_ACCESS_DENIED. */
     192
     193  access_denied:
     194
     195        if ((access_mask & FILE_WRITE_ATTRIBUTES) &&
     196                        (rejected_mask & FILE_WRITE_ATTRIBUTES) &&
     197                        !lp_store_dos_attributes(SNUM(conn)) &&
     198                        (lp_map_readonly(SNUM(conn)) ||
     199                        lp_map_archive(SNUM(conn)) ||
     200                        lp_map_hidden(SNUM(conn)) ||
     201                        lp_map_system(SNUM(conn)))) {
     202                rejected_mask &= ~FILE_WRITE_ATTRIBUTES;
     203
     204                DEBUG(10,("smbd_check_access_rights: "
     205                        "overrode "
     206                        "FILE_WRITE_ATTRIBUTES "
     207                        "on file %s\n",
     208                        smb_fname_str_dbg(smb_fname)));
     209        }
     210
     211        if (parent_override_delete(conn,
     212                                smb_fname,
     213                                access_mask,
     214                                rejected_mask)) {
     215                /* Were we trying to do an open
     216                 * for delete and didn't get DELETE
     217                 * access (only) ? Check if the
     218                 * directory allows DELETE_CHILD.
     219                 * See here:
     220                 * http://blogs.msdn.com/oldnewthing/archive/2004/06/04/148426.aspx
     221                 * for details. */
     222
     223                rejected_mask &= ~DELETE_ACCESS;
     224
     225                DEBUG(10,("smbd_check_access_rights: "
     226                        "overrode "
     227                        "DELETE_ACCESS on "
     228                        "file %s\n",
     229                        smb_fname_str_dbg(smb_fname)));
     230        }
     231
     232        if (rejected_mask != 0) {
     233                return NT_STATUS_ACCESS_DENIED;
     234        }
     235        return NT_STATUS_OK;
     236}
     237
     238static NTSTATUS check_parent_access(struct connection_struct *conn,
     239                                struct smb_filename *smb_fname,
     240                                uint32_t access_mask)
     241{
     242        NTSTATUS status;
     243        char *parent_dir = NULL;
     244        struct security_descriptor *parent_sd = NULL;
     245        uint32_t access_granted = 0;
     246
     247        if (!parent_dirname(talloc_tos(),
     248                                smb_fname->base_name,
     249                                &parent_dir,
     250                                NULL)) {
     251                return NT_STATUS_NO_MEMORY;
     252        }
     253
     254        if (get_current_uid(conn) == (uid_t)0) {
     255                /* I'm sorry sir, I didn't know you were root... */
     256                DEBUG(10,("check_parent_access: root override "
     257                        "on %s. Granting 0x%x\n",
     258                        smb_fname_str_dbg(smb_fname),
     259                        (unsigned int)access_mask ));
     260                return NT_STATUS_OK;
     261        }
     262
     263        status = SMB_VFS_GET_NT_ACL(conn,
     264                                parent_dir,
     265                                SECINFO_DACL,
     266                                    talloc_tos(),
     267                                &parent_sd);
     268
     269        if (!NT_STATUS_IS_OK(status)) {
     270                DEBUG(5,("check_parent_access: SMB_VFS_GET_NT_ACL failed for "
     271                        "%s with error %s\n",
     272                        parent_dir,
     273                        nt_errstr(status)));
     274                return status;
     275        }
     276
     277        /*
     278         * If we can access the path to this file, by
     279         * default we have FILE_READ_ATTRIBUTES from the
     280         * containing directory. See the section:
     281         * "Algorithm to Check Access to an Existing File"
     282         * in MS-FSA.pdf.
     283         *
     284         * se_file_access_check() also takes care of
     285         * owner WRITE_DAC and READ_CONTROL.
     286         */
     287        status = se_file_access_check(parent_sd,
     288                                get_current_nttok(conn),
     289                                false,
     290                                (access_mask & ~FILE_READ_ATTRIBUTES),
     291                                &access_granted);
     292        if(!NT_STATUS_IS_OK(status)) {
     293                DEBUG(5,("check_parent_access: access check "
     294                        "on directory %s for "
     295                        "path %s for mask 0x%x returned (0x%x) %s\n",
     296                        parent_dir,
     297                        smb_fname->base_name,
     298                        access_mask,
     299                        access_granted,
     300                        nt_errstr(status) ));
     301                return status;
     302        }
     303
     304        return NT_STATUS_OK;
    152305}
    153306
     
    161314                                uint32_t access_mask)
    162315{
    163         uint32_t access_granted = 0;
    164316        NTSTATUS status;
    165317
     
    182334                }
    183335                dosattrs = dos_mode(conn, smb_fname);
    184                 if (IS_DOS_READONLY(dosattrs)) {
     336                if (IS_DOS_READONLY(dosattrs)) {
    185337                        return NT_STATUS_ACCESS_DENIED;
    186338                }
    187339        }
    188340
    189 
    190         return smbd_check_open_rights(conn,
    191                                 smb_fname,
    192                                 access_mask,
    193                                 &access_granted);
     341        return smbd_check_access_rights(conn,
     342                                        smb_fname,
     343                                        false,
     344                                        access_mask);
    194345}
    195346
     
    198349****************************************************************************/
    199350
    200 static NTSTATUS fd_open(struct connection_struct *conn,
    201                     files_struct *fsp,
    202                     int flags,
    203                     mode_t mode)
     351NTSTATUS fd_open(struct connection_struct *conn,
     352                 files_struct *fsp,
     353                 int flags,
     354                 mode_t mode)
    204355{
    205356        struct smb_filename *smb_fname = fsp->fsp_name;
     
    212363         */
    213364
    214         if (fsp->posix_open || !lp_symlinks(SNUM(conn))) {
     365        if ((fsp->posix_flags & FSP_POSIX_FLAGS_OPEN) || !lp_follow_symlinks(SNUM(conn))) {
    215366                flags |= O_NOFOLLOW;
    216367        }
     
    219370        fsp->fh->fd = SMB_VFS_OPEN(conn, smb_fname, fsp, flags, mode);
    220371        if (fsp->fh->fd == -1) {
    221                 status = map_nt_error_from_unix(errno);
     372                int posix_errno = errno;
     373#ifdef O_NOFOLLOW
     374#if defined(ENOTSUP) && defined(OSF1)
     375                /* handle special Tru64 errno */
     376                if (errno == ENOTSUP) {
     377                        posix_errno = ELOOP;
     378                }
     379#endif /* ENOTSUP */
     380#ifdef EFTYPE
     381                /* fix broken NetBSD errno */
     382                if (errno == EFTYPE) {
     383                        posix_errno = ELOOP;
     384                }
     385#endif /* EFTYPE */
     386                /* fix broken FreeBSD errno */
     387                if (errno == EMLINK) {
     388                        posix_errno = ELOOP;
     389                }
     390#endif /* O_NOFOLLOW */
     391                status = map_nt_error_from_unix(posix_errno);
    222392                if (errno == EMFILE) {
    223393                        static time_t last_warned = 0L;
     
    276446                                        files_struct *fsp)
    277447{
    278         struct smb_filename *smb_fname_parent = NULL;
    279         NTSTATUS status;
     448        struct smb_filename *smb_fname_parent;
    280449        int ret;
    281450
    282         status = create_synthetic_smb_fname(talloc_tos(), inherit_from_dir,
    283                                             NULL, NULL, &smb_fname_parent);
    284         if (!NT_STATUS_IS_OK(status)) {
     451        smb_fname_parent = synthetic_smb_fname(talloc_tos(), inherit_from_dir,
     452                                               NULL, NULL);
     453        if (smb_fname_parent == NULL) {
    285454                return;
    286455        }
     
    317486        } else {
    318487                DEBUG(10,("change_file_owner_to_parent: changed new file %s to "
    319                   "parent directory uid %u.\n", fsp_str_dbg(fsp),
    320                   (unsigned int)smb_fname_parent->st.st_ex_uid));
     488                        "parent directory uid %u.\n", fsp_str_dbg(fsp),
     489                        (unsigned int)smb_fname_parent->st.st_ex_uid));
    321490                /* Ensure the uid entry is updated. */
    322491                fsp->fsp_name->st.st_ex_uid = smb_fname_parent->st.st_ex_uid;
     
    331500                                       SMB_STRUCT_STAT *psbuf)
    332501{
    333         struct smb_filename *smb_fname_parent = NULL;
     502        struct smb_filename *smb_fname_parent;
    334503        struct smb_filename *smb_fname_cwd = NULL;
    335504        char *saved_dir = NULL;
     
    338507        int ret;
    339508
    340         status = create_synthetic_smb_fname(ctx, inherit_from_dir, NULL, NULL,
    341                                             &smb_fname_parent);
    342         if (!NT_STATUS_IS_OK(status)) {
    343                 return status;
     509        smb_fname_parent = synthetic_smb_fname(ctx, inherit_from_dir,
     510                                               NULL, NULL);
     511        if (smb_fname_parent == NULL) {
     512                return NT_STATUS_NO_MEMORY;
    344513        }
    345514
     
    379548        }
    380549
    381         status = create_synthetic_smb_fname(ctx, ".", NULL, NULL,
    382                                             &smb_fname_cwd);
    383         if (!NT_STATUS_IS_OK(status)) {
    384                 return status;
     550        smb_fname_cwd = synthetic_smb_fname(ctx, ".", NULL, NULL);
     551        if (smb_fname_cwd == NULL) {
     552                status = NT_STATUS_NO_MEMORY;
     553                goto chdir;
    385554        }
    386555
     
    425594                          (unsigned int)smb_fname_parent->st.st_ex_uid,
    426595                          strerror(errno) ));
    427                 goto chdir;
    428         }
    429 
    430         DEBUG(10,("change_dir_owner_to_parent: changed ownership of new "
    431                   "directory %s to parent directory uid %u.\n",
    432                   fname, (unsigned int)smb_fname_parent->st.st_ex_uid ));
     596        } else {
     597                DEBUG(10,("change_dir_owner_to_parent: changed ownership of new "
     598                        "directory %s to parent directory uid %u.\n",
     599                        fname, (unsigned int)smb_fname_parent->st.st_ex_uid ));
     600                /* Ensure the uid entry is updated. */
     601                psbuf->st_ex_uid = smb_fname_parent->st.st_ex_uid;
     602        }
    433603
    434604 chdir:
     
    441611
    442612/****************************************************************************
     613 Open a file - returning a guaranteed ATOMIC indication of if the
     614 file was created or not.
     615****************************************************************************/
     616
     617static NTSTATUS fd_open_atomic(struct connection_struct *conn,
     618                        files_struct *fsp,
     619                        int flags,
     620                        mode_t mode,
     621                        bool *file_created)
     622{
     623        NTSTATUS status = NT_STATUS_UNSUCCESSFUL;
     624        bool file_existed = VALID_STAT(fsp->fsp_name->st);
     625
     626        *file_created = false;
     627
     628        if (!(flags & O_CREAT)) {
     629                /*
     630                 * We're not creating the file, just pass through.
     631                 */
     632                return fd_open(conn, fsp, flags, mode);
     633        }
     634
     635        if (flags & O_EXCL) {
     636                /*
     637                 * Fail if already exists, just pass through.
     638                 */
     639                status = fd_open(conn, fsp, flags, mode);
     640
     641                /*
     642                 * Here we've opened with O_CREAT|O_EXCL. If that went
     643                 * NT_STATUS_OK, we *know* we created this file.
     644                 */
     645                *file_created = NT_STATUS_IS_OK(status);
     646
     647                return status;
     648        }
     649
     650        /*
     651         * Now it gets tricky. We have O_CREAT, but not O_EXCL.
     652         * To know absolutely if we created the file or not,
     653         * we can never call O_CREAT without O_EXCL. So if
     654         * we think the file existed, try without O_CREAT|O_EXCL.
     655         * If we think the file didn't exist, try with
     656         * O_CREAT|O_EXCL. Keep bouncing between these two
     657         * requests until either the file is created, or
     658         * opened. Either way, we keep going until we get
     659         * a returnable result (error, or open/create).
     660         */
     661
     662        while(1) {
     663                int curr_flags = flags;
     664
     665                if (file_existed) {
     666                        /* Just try open, do not create. */
     667                        curr_flags &= ~(O_CREAT);
     668                        status = fd_open(conn, fsp, curr_flags, mode);
     669                        if (NT_STATUS_EQUAL(status,
     670                                        NT_STATUS_OBJECT_NAME_NOT_FOUND)) {
     671                                /*
     672                                 * Someone deleted it in the meantime.
     673                                 * Retry with O_EXCL.
     674                                 */
     675                                file_existed = false;
     676                                DEBUG(10,("fd_open_atomic: file %s existed. "
     677                                        "Retry.\n",
     678                                        smb_fname_str_dbg(fsp->fsp_name)));
     679                                        continue;
     680                        }
     681                } else {
     682                        /* Try create exclusively, fail if it exists. */
     683                        curr_flags |= O_EXCL;
     684                        status = fd_open(conn, fsp, curr_flags, mode);
     685                        if (NT_STATUS_EQUAL(status,
     686                                        NT_STATUS_OBJECT_NAME_COLLISION)) {
     687                                /*
     688                                 * Someone created it in the meantime.
     689                                 * Retry without O_CREAT.
     690                                 */
     691                                file_existed = true;
     692                                DEBUG(10,("fd_open_atomic: file %s "
     693                                        "did not exist. Retry.\n",
     694                                        smb_fname_str_dbg(fsp->fsp_name)));
     695                                continue;
     696                        }
     697                        if (NT_STATUS_IS_OK(status)) {
     698                                /*
     699                                 * Here we've opened with O_CREAT|O_EXCL
     700                                 * and got success. We *know* we created
     701                                 * this file.
     702                                 */
     703                                *file_created = true;
     704                        }
     705                }
     706                /* Create is done, or failed. */
     707                break;
     708        }
     709        return status;
     710}
     711
     712/****************************************************************************
    443713 Open a file.
    444714****************************************************************************/
     
    450720                          int flags,
    451721                          mode_t unx_mode,
    452                           uint32 access_mask, /* client requested access mask. */
    453                           uint32 open_access_mask) /* what we're actually using in the open. */
     722                          uint32_t access_mask, /* client requested access mask. */
     723                          uint32_t open_access_mask, /* what we're actually using in the open. */
     724                          bool *p_file_created)
    454725{
    455726        struct smb_filename *smb_fname = fsp->fsp_name;
     
    458729        int local_flags = flags;
    459730        bool file_existed = VALID_STAT(fsp->fsp_name->st);
    460         bool file_created = false;
    461731
    462732        fsp->fh->fd = -1;
     
    481751                                 smb_fname_str_dbg(smb_fname)));
    482752                        return NT_STATUS_ACCESS_DENIED;
    483                 } else if(flags & O_CREAT) {
     753                }
     754                if (flags & O_CREAT) {
    484755                        /* We don't want to write - but we must make sure that
    485756                           O_CREAT doesn't create the file if we have write
     
    513784            ((local_flags & O_TRUNC) == O_TRUNC) ) {
    514785                const char *wild;
    515 
    516                 /*
    517                  * We can't actually truncate here as the file may be locked.
    518                  * open_file_ntcreate will take care of the truncate later. JRA.
    519                  */
    520 
    521                 local_flags &= ~O_TRUNC;
     786                int ret;
    522787
    523788#if defined(O_NONBLOCK) && defined(S_ISFIFO)
     
    529794
    530795                if (file_existed && S_ISFIFO(smb_fname->st.st_ex_mode)) {
     796                        local_flags &= ~O_TRUNC; /* Can't truncate a FIFO. */
    531797                        local_flags |= O_NONBLOCK;
    532798                }
     
    544810                }
    545811                if ((local_flags & O_CREAT) && !file_existed &&
     812                    !(fsp->posix_flags & FSP_POSIX_FLAGS_PATHNAMES) &&
    546813                    ms_has_wild(wild))  {
    547814                        return NT_STATUS_OBJECT_NAME_INVALID;
    548815                }
    549816
    550                 /* Actually do the open */
    551                 status = fd_open(conn, fsp, local_flags, unx_mode);
     817                /* Can we access this file ? */
     818                if (!fsp->base_fsp) {
     819                        /* Only do this check on non-stream open. */
     820                        if (file_existed) {
     821                                status = smbd_check_access_rights(conn,
     822                                                smb_fname,
     823                                                false,
     824                                                access_mask);
     825
     826                                if (!NT_STATUS_IS_OK(status)) {
     827                                        DEBUG(10, ("open_file: "
     828                                                   "smbd_check_access_rights "
     829                                                   "on file %s returned %s\n",
     830                                                   smb_fname_str_dbg(smb_fname),
     831                                                   nt_errstr(status)));
     832                                }
     833
     834                                if (!NT_STATUS_IS_OK(status) &&
     835                                    !NT_STATUS_EQUAL(status,
     836                                        NT_STATUS_OBJECT_NAME_NOT_FOUND))
     837                                {
     838                                        return status;
     839                                }
     840
     841                                if (NT_STATUS_EQUAL(status,
     842                                        NT_STATUS_OBJECT_NAME_NOT_FOUND))
     843                                {
     844                                        DEBUG(10, ("open_file: "
     845                                                "file %s vanished since we "
     846                                                "checked for existence.\n",
     847                                                smb_fname_str_dbg(smb_fname)));
     848                                        file_existed = false;
     849                                        SET_STAT_INVALID(fsp->fsp_name->st);
     850                                }
     851                        }
     852
     853                        if (!file_existed) {
     854                                if (!(local_flags & O_CREAT)) {
     855                                        /* File didn't exist and no O_CREAT. */
     856                                        return NT_STATUS_OBJECT_NAME_NOT_FOUND;
     857                                }
     858
     859                                status = check_parent_access(conn,
     860                                                             smb_fname,
     861                                                             SEC_DIR_ADD_FILE);
     862                                if (!NT_STATUS_IS_OK(status)) {
     863                                        DEBUG(10, ("open_file: "
     864                                                   "check_parent_access on "
     865                                                   "file %s returned %s\n",
     866                                                   smb_fname_str_dbg(smb_fname),
     867                                                   nt_errstr(status) ));
     868                                        return status;
     869                                }
     870                        }
     871                }
     872
     873                /*
     874                 * Actually do the open - if O_TRUNC is needed handle it
     875                 * below under the share mode lock.
     876                 */
     877                status = fd_open_atomic(conn, fsp, local_flags & ~O_TRUNC,
     878                                unx_mode, p_file_created);
    552879                if (!NT_STATUS_IS_OK(status)) {
    553880                        DEBUG(3,("Error opening file %s (%s) (local_flags=%d) "
     
    557884                }
    558885
    559                 if ((local_flags & O_CREAT) && !file_existed) {
    560                         file_created = true;
    561                 }
    562 
    563         } else {
    564                 fsp->fh->fd = -1; /* What we used to call a stat open. */
    565                 if (file_existed) {
    566                         uint32_t access_granted = 0;
    567 
    568                         status = smbd_check_open_rights(conn,
    569                                         smb_fname,
    570                                         access_mask,
    571                                         &access_granted);
    572                         if (!NT_STATUS_IS_OK(status)) {
    573                                 if (NT_STATUS_EQUAL(status, NT_STATUS_ACCESS_DENIED)) {
    574                                         /*
    575                                          * On NT_STATUS_ACCESS_DENIED, access_granted
    576                                          * contains the denied bits.
    577                                          */
    578 
    579                                         if ((access_mask & FILE_WRITE_ATTRIBUTES) &&
    580                                                         (access_granted & FILE_WRITE_ATTRIBUTES) &&
    581                                                         (lp_map_readonly(SNUM(conn)) ||
    582                                                          lp_map_archive(SNUM(conn)) ||
    583                                                          lp_map_hidden(SNUM(conn)) ||
    584                                                          lp_map_system(SNUM(conn)))) {
    585                                                 access_granted &= ~FILE_WRITE_ATTRIBUTES;
    586 
    587                                                 DEBUG(10,("open_file: "
    588                                                           "overrode "
    589                                                           "FILE_WRITE_"
    590                                                           "ATTRIBUTES "
    591                                                           "on file %s\n",
    592                                                           smb_fname_str_dbg(
    593                                                                   smb_fname)));
    594                                         }
    595 
    596                                         if ((access_mask & DELETE_ACCESS) &&
    597                                             (access_granted & DELETE_ACCESS) &&
    598                                             can_delete_file_in_directory(conn,
    599                                                 smb_fname)) {
    600                                                 /* Were we trying to do a stat open
    601                                                  * for delete and didn't get DELETE
    602                                                  * access (only) ? Check if the
    603                                                  * directory allows DELETE_CHILD.
    604                                                  * See here:
    605                                                  * http://blogs.msdn.com/oldnewthing/archive/2004/06/04/148426.aspx
    606                                                  * for details. */
    607 
    608                                                 access_granted &= ~DELETE_ACCESS;
    609 
    610                                                 DEBUG(10,("open_file: "
    611                                                           "overrode "
    612                                                           "DELETE_ACCESS on "
    613                                                           "file %s\n",
    614                                                           smb_fname_str_dbg(
    615                                                                   smb_fname)));
    616                                         }
    617 
    618                                         if (access_granted != 0) {
    619                                                 DEBUG(10,("open_file: Access "
    620                                                           "denied on file "
    621                                                           "%s\n",
    622                                                           smb_fname_str_dbg(
    623                                                                   smb_fname)));
    624                                                 return status;
    625                                         }
    626                                 } else if (NT_STATUS_EQUAL(status, NT_STATUS_OBJECT_NAME_NOT_FOUND) &&
    627                                     fsp->posix_open &&
    628                                     S_ISLNK(smb_fname->st.st_ex_mode)) {
    629                                         /* This is a POSIX stat open for delete
    630                                          * or rename on a symlink that points
    631                                          * nowhere. Allow. */
    632                                         DEBUG(10,("open_file: allowing POSIX "
    633                                                   "open on bad symlink %s\n",
    634                                                   smb_fname_str_dbg(
    635                                                           smb_fname)));
    636                                 } else {
    637                                         DEBUG(10,("open_file: "
    638                                                   "smbd_check_open_rights on file "
    639                                                   "%s returned %s\n",
    640                                                   smb_fname_str_dbg(smb_fname),
    641                                                   nt_errstr(status) ));
    642                                         return status;
    643                                 }
    644                         }
    645                 }
    646         }
    647 
    648         if (!file_existed) {
    649                 int ret;
    650 
    651                 if (fsp->fh->fd == -1) {
    652                         ret = SMB_VFS_STAT(conn, smb_fname);
    653                 } else {
    654                         ret = SMB_VFS_FSTAT(fsp, &smb_fname->st);
     886                ret = SMB_VFS_FSTAT(fsp, &smb_fname->st);
     887                if (ret == -1) {
    655888                        /* If we have an fd, this stat should succeed. */
    656                         if (ret == -1) {
    657                                 DEBUG(0,("Error doing fstat on open file %s "
    658                                          "(%s)\n",
    659                                          smb_fname_str_dbg(smb_fname),
    660                                          strerror(errno) ));
    661                         }
    662                 }
    663 
    664                 /* For a non-io open, this stat failing means file not found. JRA */
    665                 if (ret == -1) {
     889                        DEBUG(0,("Error doing fstat on open file %s "
     890                                "(%s)\n",
     891                                smb_fname_str_dbg(smb_fname),
     892                                strerror(errno) ));
    666893                        status = map_nt_error_from_unix(errno);
    667894                        fd_close(fsp);
     
    669896                }
    670897
    671                 if (file_created) {
     898                if (*p_file_created) {
     899                        /* We created this file. */
     900
    672901                        bool need_re_stat = false;
    673902                        /* Do all inheritance work after we've
    674                            done a successful stat call and filled
     903                           done a successful fstat call and filled
    675904                           in the stat struct in fsp->fsp_name. */
    676905
    677906                        /* Inherit the ACL if required */
    678                         if (lp_inherit_perms(SNUM(conn))) {
     907                        if (lp_inherit_permissions(SNUM(conn))) {
    679908                                inherit_access_posix_acl(conn, parent_dir,
    680909                                                         smb_fname->base_name,
     
    691920
    692921                        if (need_re_stat) {
    693                                 if (fsp->fh->fd == -1) {
    694                                         ret = SMB_VFS_STAT(conn, smb_fname);
    695                                 } else {
    696                                         ret = SMB_VFS_FSTAT(fsp, &smb_fname->st);
    697                                         /* If we have an fd, this stat should succeed. */
    698                                         if (ret == -1) {
    699                                                 DEBUG(0,("Error doing fstat on open file %s "
    700                                                          "(%s)\n",
    701                                                          smb_fname_str_dbg(smb_fname),
    702                                                          strerror(errno) ));
    703                                         }
     922                                ret = SMB_VFS_FSTAT(fsp, &smb_fname->st);
     923                                /* If we have an fd, this stat should succeed. */
     924                                if (ret == -1) {
     925                                        DEBUG(0,("Error doing fstat on open file %s "
     926                                                 "(%s)\n",
     927                                                 smb_fname_str_dbg(smb_fname),
     928                                                 strerror(errno) ));
    704929                                }
    705930                        }
     
    708933                                     FILE_NOTIFY_CHANGE_FILE_NAME,
    709934                                     smb_fname->base_name);
     935                }
     936        } else {
     937                fsp->fh->fd = -1; /* What we used to call a stat open. */
     938                if (!file_existed) {
     939                        /* File must exist for a stat open. */
     940                        return NT_STATUS_OBJECT_NAME_NOT_FOUND;
     941                }
     942
     943                status = smbd_check_access_rights(conn,
     944                                smb_fname,
     945                                false,
     946                                access_mask);
     947
     948                if (NT_STATUS_EQUAL(status, NT_STATUS_OBJECT_NAME_NOT_FOUND) &&
     949                                (fsp->posix_flags & FSP_POSIX_FLAGS_OPEN) &&
     950                                S_ISLNK(smb_fname->st.st_ex_mode)) {
     951                        /* This is a POSIX stat open for delete
     952                         * or rename on a symlink that points
     953                         * nowhere. Allow. */
     954                        DEBUG(10,("open_file: allowing POSIX "
     955                                  "open on bad symlink %s\n",
     956                                  smb_fname_str_dbg(smb_fname)));
     957                        status = NT_STATUS_OK;
     958                }
     959
     960                if (!NT_STATUS_IS_OK(status)) {
     961                        DEBUG(10,("open_file: "
     962                                "smbd_check_access_rights on file "
     963                                "%s returned %s\n",
     964                                smb_fname_str_dbg(smb_fname),
     965                                nt_errstr(status) ));
     966                        return status;
    710967                }
    711968        }
     
    723980        }
    724981
    725         fsp->mode = smb_fname->st.st_ex_mode;
    726982        fsp->file_id = vfs_file_id_from_sbuf(conn, &smb_fname->st);
    727983        fsp->vuid = req ? req->vuid : UID_FIELD_INVALID;
    728984        fsp->file_pid = req ? req->smbpid : 0;
    729985        fsp->can_lock = True;
    730         fsp->can_read = (access_mask & (FILE_READ_DATA)) ? True : False;
    731         if (!CAN_WRITE(conn)) {
    732                 fsp->can_write = False;
    733         } else {
    734                 fsp->can_write = (access_mask & (FILE_WRITE_DATA | FILE_APPEND_DATA)) ?
    735                         True : False;
    736         }
     986        fsp->can_read = ((access_mask & FILE_READ_DATA) != 0);
     987        fsp->can_write =
     988                CAN_WRITE(conn) &&
     989                ((access_mask & (FILE_WRITE_DATA | FILE_APPEND_DATA)) != 0);
    737990        fsp->print_file = NULL;
    738991        fsp->modified = False;
     
    7481001
    7491002        DEBUG(2,("%s opened file %s read=%s write=%s (numopen=%d)\n",
    750                  conn->session_info->unix_name,
     1003                 conn->session_info->unix_info->unix_name,
    7511004                 smb_fname_str_dbg(smb_fname),
    7521005                 BOOLSTR(fsp->can_read), BOOLSTR(fsp->can_write),
     
    7631016
    7641017static bool share_conflict(struct share_mode_entry *entry,
    765                            uint32 access_mask,
    766                            uint32 share_access)
     1018                           uint32_t access_mask,
     1019                           uint32_t share_access)
    7671020{
    7681021        DEBUG(10,("share_conflict: entry->access_mask = 0x%x, "
     
    7721025                  (unsigned int)entry->share_access,
    7731026                  (unsigned int)entry->private_options));
     1027
     1028        if (server_id_is_disconnected(&entry->pid)) {
     1029                /*
     1030                 * note: cleanup should have been done by
     1031                 * delay_for_batch_oplocks()
     1032                 */
     1033                return false;
     1034        }
    7741035
    7751036        DEBUG(10,("share_conflict: access_mask = 0x%x, share_access = 0x%x\n",
     
    8461107                                      struct share_mode_entry *share_entry)
    8471108{
     1109        struct server_id self = messaging_server_id(sconn->msg_ctx);
    8481110        files_struct *fsp;
    8491111
    850         if (!procid_is_me(&share_entry->pid)) {
     1112        if (!serverid_equal(&self, &share_entry->pid)) {
    8511113                return;
    8521114        }
    8531115
    854         if (is_deferred_open_entry(share_entry) &&
    855             !open_was_deferred(share_entry->op_mid)) {
    856                 char *str = talloc_asprintf(talloc_tos(),
    857                         "Got a deferred entry without a request: "
    858                         "PANIC: %s\n",
    859                         share_mode_str(talloc_tos(), num, share_entry));
    860                 smb_panic(str);
     1116        if (share_entry->op_mid == 0) {
     1117                /* INTERNAL_OPEN_ONLY */
     1118                return;
    8611119        }
    8621120
     
    8741132        }
    8751133
    876         if (is_deferred_open_entry(share_entry) ||
    877             is_unused_share_mode_entry(share_entry)) {
    878                 goto panic;
    879         }
    880 
    881         if ((share_entry->op_type == NO_OPLOCK) &&
    882             (fsp->oplock_type == FAKE_LEVEL_II_OPLOCK)) {
    883                 /* Someone has already written to it, but I haven't yet
    884                  * noticed */
    885                 return;
    886         }
    887 
    888         if (((uint16)fsp->oplock_type) != share_entry->op_type) {
     1134        if (((uint16_t)fsp->oplock_type) != share_entry->op_type) {
    8891135                goto panic;
    8901136        }
     
    9081154#endif
    9091155
    910 bool is_stat_open(uint32 access_mask)
     1156bool is_stat_open(uint32_t access_mask)
    9111157{
    912         return (access_mask &&
    913                 ((access_mask & ~(SYNCHRONIZE_ACCESS| FILE_READ_ATTRIBUTES|
    914                                   FILE_WRITE_ATTRIBUTES))==0) &&
    915                 ((access_mask & (SYNCHRONIZE_ACCESS|FILE_READ_ATTRIBUTES|
    916                                  FILE_WRITE_ATTRIBUTES)) != 0));
     1158        const uint32_t stat_open_bits =
     1159                (SYNCHRONIZE_ACCESS|
     1160                 FILE_READ_ATTRIBUTES|
     1161                 FILE_WRITE_ATTRIBUTES);
     1162
     1163        return (((access_mask &  stat_open_bits) != 0) &&
     1164                ((access_mask & ~stat_open_bits) == 0));
     1165}
     1166
     1167static bool has_delete_on_close(struct share_mode_lock *lck,
     1168                                uint32_t name_hash)
     1169{
     1170        struct share_mode_data *d = lck->data;
     1171        uint32_t i;
     1172
     1173        if (d->num_share_modes == 0) {
     1174                return false;
     1175        }
     1176        if (!is_delete_on_close_set(lck, name_hash)) {
     1177                return false;
     1178        }
     1179        for (i=0; i<d->num_share_modes; i++) {
     1180                if (!share_mode_stale_pid(d, i)) {
     1181                        return true;
     1182                }
     1183        }
     1184        return false;
    9171185}
    9181186
    9191187/****************************************************************************
    9201188 Deal with share modes
    921  Invarient: Share mode must be locked on entry and exit.
     1189 Invariant: Share mode must be locked on entry and exit.
    9221190 Returns -1 on error, or number of share modes on success (may be zero).
    9231191****************************************************************************/
     
    9251193static NTSTATUS open_mode_check(connection_struct *conn,
    9261194                                struct share_mode_lock *lck,
    927                                 uint32_t name_hash,
    928                                 uint32 access_mask,
    929                                 uint32 share_access,
    930                                 uint32 create_options,
    931                                 bool *file_existed)
     1195                                uint32_t access_mask,
     1196                                uint32_t share_access)
    9321197{
    9331198        int i;
    9341199
    935         if(lck->num_share_modes == 0) {
     1200        if(lck->data->num_share_modes == 0) {
    9361201                return NT_STATUS_OK;
    937         }
    938 
    939         *file_existed = True;
    940 
    941         /* A delete on close prohibits everything */
    942 
    943         if (is_delete_on_close_set(lck, name_hash)) {
    944                 return NT_STATUS_DELETE_PENDING;
    9451202        }
    9461203
     
    9561213
    9571214#if defined(DEVELOPER)
    958         for(i = 0; i < lck->num_share_modes; i++) {
     1215        for(i = 0; i < lck->data->num_share_modes; i++) {
    9591216                validate_my_share_entries(conn->sconn, i,
    960                                           &lck->share_modes[i]);
     1217                                          &lck->data->share_modes[i]);
    9611218        }
    9621219#endif
    9631220
    964         if (!lp_share_modes(SNUM(conn))) {
    965                 return NT_STATUS_OK;
    966         }
    967 
    9681221        /* Now we check the share modes, after any oplock breaks. */
    969         for(i = 0; i < lck->num_share_modes; i++) {
    970 
    971                 if (!is_valid_share_mode_entry(&lck->share_modes[i])) {
     1222        for(i = 0; i < lck->data->num_share_modes; i++) {
     1223
     1224                if (!is_valid_share_mode_entry(&lck->data->share_modes[i])) {
    9721225                        continue;
    9731226                }
     
    9751228                /* someone else has a share lock on it, check to see if we can
    9761229                 * too */
    977                 if (share_conflict(&lck->share_modes[i],
     1230                if (share_conflict(&lck->data->share_modes[i],
    9781231                                   access_mask, share_access)) {
     1232
     1233                        if (share_mode_stale_pid(lck->data, i)) {
     1234                                continue;
     1235                        }
     1236
    9791237                        return NT_STATUS_SHARING_VIOLATION;
    9801238                }
     
    9891247 */
    9901248
    991 static NTSTATUS send_break_message(files_struct *fsp,
    992                                         struct share_mode_entry *exclusive,
    993                                         uint64_t mid,
    994                                         int oplock_request)
     1249NTSTATUS send_break_message(struct messaging_context *msg_ctx,
     1250                                   const struct share_mode_entry *exclusive,
     1251                                   uint16_t break_to)
    9951252{
    9961253        NTSTATUS status;
    9971254        char msg[MSG_SMB_SHARE_MODE_ENTRY_SIZE];
     1255        struct server_id_buf tmp;
    9981256
    9991257        DEBUG(10, ("Sending break request to PID %s\n",
    1000                    procid_str_static(&exclusive->pid)));
    1001         exclusive->op_mid = mid;
     1258                   server_id_str_buf(exclusive->pid, &tmp)));
    10021259
    10031260        /* Create the message. */
    10041261        share_mode_entry_to_message(msg, exclusive);
    10051262
    1006         /* Add in the FORCE_OPLOCK_BREAK_TO_NONE bit in the message if set. We
    1007            don't want this set in the share mode struct pointed to by lck. */
    1008 
    1009         if (oplock_request & FORCE_OPLOCK_BREAK_TO_NONE) {
    1010                 SSVAL(msg,OP_BREAK_MSG_OP_TYPE_OFFSET,
    1011                         exclusive->op_type | FORCE_OPLOCK_BREAK_TO_NONE);
    1012         }
    1013 
    1014         status = messaging_send_buf(fsp->conn->sconn->msg_ctx, exclusive->pid,
     1263        /* Overload entry->op_type */
     1264        /*
     1265         * This is a cut from uint32_t to uint16_t, but so far only the lower 3
     1266         * bits (LEASE_WRITE/HANDLE/READ are used anyway.
     1267         */
     1268        SSVAL(msg,OP_BREAK_MSG_OP_TYPE_OFFSET, break_to);
     1269
     1270        status = messaging_send_buf(msg_ctx, exclusive->pid,
    10151271                                    MSG_SMB_BREAK_REQUEST,
    1016                                     (uint8 *)msg,
    1017                                     MSG_SMB_SHARE_MODE_ENTRY_SIZE);
     1272                                    (uint8_t *)msg, sizeof(msg));
    10181273        if (!NT_STATUS_IS_OK(status)) {
    10191274                DEBUG(3, ("Could not send oplock break message: %s\n",
     
    10251280
    10261281/*
    1027  * Return share_mode_entry pointers for :
    1028  * 1). Batch oplock entry.
    1029  * 2). Batch or exclusive oplock entry (may be identical to #1).
    1030  * bool have_level2_oplock
    1031  * bool have_no_oplock.
    10321282 * Do internal consistency checks on the share mode for a file.
    10331283 */
    10341284
    1035 static void find_oplock_types(files_struct *fsp,
    1036                                 int oplock_request,
    1037                                 struct share_mode_lock *lck,
    1038                                 struct share_mode_entry **pp_batch,
    1039                                 struct share_mode_entry **pp_ex_or_batch,
    1040                                 bool *got_level2,
    1041                                 bool *got_no_oplock)
     1285static bool validate_oplock_types(struct share_mode_lock *lck)
    10421286{
    1043         int i;
    1044 
    1045         *pp_batch = NULL;
    1046         *pp_ex_or_batch = NULL;
    1047         *got_level2 = false;
    1048         *got_no_oplock = false;
    1049 
    1050         /* Ignore stat or internal opens, as is done in
    1051                 delay_for_batch_oplocks() and
    1052                 delay_for_exclusive_oplocks().
    1053          */
    1054         if ((oplock_request & INTERNAL_OPEN_ONLY) || is_stat_open(fsp->access_mask)) {
    1055                 return;
    1056         }
    1057 
    1058         for (i=0; i<lck->num_share_modes; i++) {
    1059                 if (!is_valid_share_mode_entry(&lck->share_modes[i])) {
     1287        struct share_mode_data *d = lck->data;
     1288        bool batch = false;
     1289        bool ex_or_batch = false;
     1290        bool level2 = false;
     1291        bool no_oplock = false;
     1292        uint32_t num_non_stat_opens = 0;
     1293        uint32_t i;
     1294
     1295        for (i=0; i<d->num_share_modes; i++) {
     1296                struct share_mode_entry *e = &d->share_modes[i];
     1297
     1298                if (!is_valid_share_mode_entry(e)) {
    10601299                        continue;
    10611300                }
    10621301
    1063                 if (lck->share_modes[i].op_type == NO_OPLOCK &&
    1064                                 is_stat_open(lck->share_modes[i].access_mask)) {
     1302                if (e->op_mid == 0) {
     1303                        /* INTERNAL_OPEN_ONLY */
     1304                        continue;
     1305                }
     1306
     1307                if (e->op_type == NO_OPLOCK && is_stat_open(e->access_mask)) {
    10651308                        /* We ignore stat opens in the table - they
    10661309                           always have NO_OPLOCK and never get or
     
    10691312                }
    10701313
    1071                 if (BATCH_OPLOCK_TYPE(lck->share_modes[i].op_type)) {
     1314                num_non_stat_opens += 1;
     1315
     1316                if (BATCH_OPLOCK_TYPE(e->op_type)) {
    10721317                        /* batch - can only be one. */
    1073                         if (*pp_ex_or_batch || *pp_batch || *got_level2 || *got_no_oplock) {
    1074                                 smb_panic("Bad batch oplock entry.");
     1318                        if (share_mode_stale_pid(d, i)) {
     1319                                DEBUG(10, ("Found stale batch oplock\n"));
     1320                                continue;
    10751321                        }
    1076                         *pp_batch = &lck->share_modes[i];
    1077                 }
    1078 
    1079                 if (EXCLUSIVE_OPLOCK_TYPE(lck->share_modes[i].op_type)) {
     1322                        if (ex_or_batch || batch || level2 || no_oplock) {
     1323                                DEBUG(0, ("Bad batch oplock entry %u.",
     1324                                          (unsigned)i));
     1325                                return false;
     1326                        }
     1327                        batch = true;
     1328                }
     1329
     1330                if (EXCLUSIVE_OPLOCK_TYPE(e->op_type)) {
     1331                        if (share_mode_stale_pid(d, i)) {
     1332                                DEBUG(10, ("Found stale duplicate oplock\n"));
     1333                                continue;
     1334                        }
    10801335                        /* Exclusive or batch - can only be one. */
    1081                         if (*pp_ex_or_batch || *got_level2 || *got_no_oplock) {
    1082                                 smb_panic("Bad exclusive or batch oplock entry.");
     1336                        if (ex_or_batch || level2 || no_oplock) {
     1337                                DEBUG(0, ("Bad exclusive or batch oplock "
     1338                                          "entry %u.", (unsigned)i));
     1339                                return false;
    10831340                        }
    1084                         *pp_ex_or_batch = &lck->share_modes[i];
    1085                 }
    1086 
    1087                 if (LEVEL_II_OPLOCK_TYPE(lck->share_modes[i].op_type)) {
    1088                         if (*pp_batch || *pp_ex_or_batch) {
    1089                                 smb_panic("Bad levelII oplock entry.");
     1341                        ex_or_batch = true;
     1342                }
     1343
     1344                if (LEVEL_II_OPLOCK_TYPE(e->op_type)) {
     1345                        if (batch || ex_or_batch) {
     1346                                if (share_mode_stale_pid(d, i)) {
     1347                                        DEBUG(10, ("Found stale LevelII "
     1348                                                   "oplock\n"));
     1349                                        continue;
     1350                                }
     1351                                DEBUG(0, ("Bad levelII oplock entry %u.",
     1352                                          (unsigned)i));
     1353                                return false;
    10901354                        }
    1091                         *got_level2 = true;
    1092                 }
    1093 
    1094                 if (lck->share_modes[i].op_type == NO_OPLOCK) {
    1095                         if (*pp_batch || *pp_ex_or_batch) {
    1096                                 smb_panic("Bad no oplock entry.");
     1355                        level2 = true;
     1356                }
     1357
     1358                if (e->op_type == NO_OPLOCK) {
     1359                        if (batch || ex_or_batch) {
     1360                                if (share_mode_stale_pid(d, i)) {
     1361                                        DEBUG(10, ("Found stale NO_OPLOCK "
     1362                                                   "entry\n"));
     1363                                        continue;
     1364                                }
     1365                                DEBUG(0, ("Bad no oplock entry %u.",
     1366                                          (unsigned)i));
     1367                                return false;
    10971368                        }
    1098                         *got_no_oplock = true;
    1099                 }
    1100         }
     1369                        no_oplock = true;
     1370                }
     1371        }
     1372
     1373        remove_stale_share_mode_entries(d);
     1374
     1375        if ((batch || ex_or_batch) && (num_non_stat_opens != 1)) {
     1376                DEBUG(1, ("got batch (%d) or ex (%d) non-exclusively (%d)\n",
     1377                          (int)batch, (int)ex_or_batch,
     1378                          (int)d->num_share_modes));
     1379                return false;
     1380        }
     1381
     1382        return true;
    11011383}
    11021384
    1103 static bool delay_for_batch_oplocks(files_struct *fsp,
    1104                                         uint64_t mid,
    1105                                         int oplock_request,
    1106                                         struct share_mode_entry *batch_entry)
     1385static bool delay_for_oplock(files_struct *fsp,
     1386                             int oplock_request,
     1387                             const struct smb2_lease *lease,
     1388                             struct share_mode_lock *lck,
     1389                             bool have_sharing_violation,
     1390                             uint32_t create_disposition,
     1391                             bool first_open_attempt)
    11071392{
    1108         if ((oplock_request & INTERNAL_OPEN_ONLY) || is_stat_open(fsp->access_mask)) {
     1393        struct share_mode_data *d = lck->data;
     1394        uint32_t i;
     1395        bool delay = false;
     1396        bool will_overwrite;
     1397
     1398        if ((oplock_request & INTERNAL_OPEN_ONLY) ||
     1399            is_stat_open(fsp->access_mask)) {
    11091400                return false;
    11101401        }
    11111402
    1112         if (batch_entry != NULL) {
    1113                 /* Found a batch oplock */
    1114                 send_break_message(fsp, batch_entry, mid, oplock_request);
    1115                 return true;
    1116         }
    1117         return false;
     1403        switch (create_disposition) {
     1404        case FILE_SUPERSEDE:
     1405        case FILE_OVERWRITE:
     1406        case FILE_OVERWRITE_IF:
     1407                will_overwrite = true;
     1408                break;
     1409        default:
     1410                will_overwrite = false;
     1411                break;
     1412        }
     1413
     1414        for (i=0; i<d->num_share_modes; i++) {
     1415                struct share_mode_entry *e = &d->share_modes[i];
     1416                struct share_mode_lease *l = NULL;
     1417                uint32_t e_lease_type = get_lease_type(d, e);
     1418                uint32_t break_to;
     1419                uint32_t delay_mask = 0;
     1420
     1421                if (e->op_type == LEASE_OPLOCK) {
     1422                        l = &d->leases[e->lease_idx];
     1423                }
     1424
     1425                if (have_sharing_violation) {
     1426                        delay_mask = SMB2_LEASE_HANDLE;
     1427                } else {
     1428                        delay_mask = SMB2_LEASE_WRITE;
     1429                }
     1430
     1431                break_to = e_lease_type & ~delay_mask;
     1432
     1433                if (will_overwrite) {
     1434                        /*
     1435                         * we'll decide about SMB2_LEASE_READ later.
     1436                         *
     1437                         * Maybe the break will be defered
     1438                         */
     1439                        break_to &= ~SMB2_LEASE_HANDLE;
     1440                }
     1441
     1442                DEBUG(10, ("entry %u: e_lease_type %u, will_overwrite: %u\n",
     1443                           (unsigned)i, (unsigned)e_lease_type,
     1444                           (unsigned)will_overwrite));
     1445
     1446                if (lease != NULL && l != NULL) {
     1447                        bool ign;
     1448
     1449                        ign = smb2_lease_equal(fsp_client_guid(fsp),
     1450                                               &lease->lease_key,
     1451                                               &l->client_guid,
     1452                                               &l->lease_key);
     1453                        if (ign) {
     1454                                continue;
     1455                        }
     1456                }
     1457
     1458                if ((e_lease_type & ~break_to) == 0) {
     1459                        if (l != NULL && l->breaking) {
     1460                                delay = true;
     1461                        }
     1462                        continue;
     1463                }
     1464
     1465                if (share_mode_stale_pid(d, i)) {
     1466                        continue;
     1467                }
     1468
     1469                if (will_overwrite) {
     1470                        /*
     1471                         * If we break anyway break to NONE directly.
     1472                         * Otherwise vfs_set_filelen() will trigger the
     1473                         * break.
     1474                         */
     1475                        break_to &= ~(SMB2_LEASE_READ|SMB2_LEASE_WRITE);
     1476                }
     1477
     1478                if (e->op_type != LEASE_OPLOCK) {
     1479                        /*
     1480                         * Oplocks only support breaking to R or NONE.
     1481                         */
     1482                        break_to &= ~(SMB2_LEASE_HANDLE|SMB2_LEASE_WRITE);
     1483                }
     1484
     1485                DEBUG(10, ("breaking from %d to %d\n",
     1486                           (int)e_lease_type, (int)break_to));
     1487                send_break_message(fsp->conn->sconn->msg_ctx, e,
     1488                                   break_to);
     1489                if (e_lease_type & delay_mask) {
     1490                        delay = true;
     1491                }
     1492                if (l != NULL && l->breaking && !first_open_attempt) {
     1493                        delay = true;
     1494                }
     1495                continue;
     1496        }
     1497
     1498        return delay;
    11181499}
    11191500
    1120 static bool delay_for_exclusive_oplocks(files_struct *fsp,
    1121                                         uint64_t mid,
    1122                                         int oplock_request,
    1123                                         struct share_mode_entry *ex_entry)
     1501static bool file_has_brlocks(files_struct *fsp)
    11241502{
    1125         if ((oplock_request & INTERNAL_OPEN_ONLY) || is_stat_open(fsp->access_mask)) {
     1503        struct byte_range_lock *br_lck;
     1504
     1505        br_lck = brl_get_locks_readonly(fsp);
     1506        if (!br_lck)
    11261507                return false;
    1127         }
    1128 
    1129         if (ex_entry != NULL) {
    1130                 send_break_message(fsp, ex_entry, mid, oplock_request);
    1131                 return true;
    1132         }
    1133         return false;
     1508
     1509        return (brl_num_locks(br_lck) > 0);
    11341510}
    11351511
    1136 static void grant_fsp_oplock_type(files_struct *fsp,
    1137                                 const struct byte_range_lock *br_lck,
    1138                                 int oplock_request,
    1139                                 bool got_level2_oplock,
    1140                                 bool got_a_none_oplock)
     1512int find_share_mode_lease(struct share_mode_data *d,
     1513                          const struct GUID *client_guid,
     1514                          const struct smb2_lease_key *key)
    11411515{
    1142         bool allow_level2 = (global_client_caps & CAP_LEVEL_II_OPLOCKS) &&
    1143                             lp_level2_oplocks(SNUM(fsp->conn));
    1144 
    1145         /* Start by granting what the client asked for,
    1146            but ensure no SAMBA_PRIVATE bits can be set. */
    1147         fsp->oplock_type = (oplock_request & ~SAMBA_PRIVATE_OPLOCK_MASK);
     1516        uint32_t i;
     1517
     1518        for (i=0; i<d->num_leases; i++) {
     1519                struct share_mode_lease *l = &d->leases[i];
     1520
     1521                if (smb2_lease_equal(client_guid,
     1522                                     key,
     1523                                     &l->client_guid,
     1524                                     &l->lease_key)) {
     1525                        return i;
     1526                }
     1527        }
     1528
     1529        return -1;
     1530}
     1531
     1532struct fsp_lease *find_fsp_lease(struct files_struct *new_fsp,
     1533                                 const struct smb2_lease_key *key,
     1534                                 const struct share_mode_lease *l)
     1535{
     1536        struct files_struct *fsp;
     1537
     1538        /*
     1539         * TODO: Measure how expensive this loop is with thousands of open
     1540         * handles...
     1541         */
     1542
     1543        for (fsp = file_find_di_first(new_fsp->conn->sconn, new_fsp->file_id);
     1544             fsp != NULL;
     1545             fsp = file_find_di_next(fsp)) {
     1546
     1547                if (fsp == new_fsp) {
     1548                        continue;
     1549                }
     1550                if (fsp->oplock_type != LEASE_OPLOCK) {
     1551                        continue;
     1552                }
     1553                if (smb2_lease_key_equal(&fsp->lease->lease.lease_key, key)) {
     1554                        fsp->lease->ref_count += 1;
     1555                        return fsp->lease;
     1556                }
     1557        }
     1558
     1559        /* Not found - must be leased in another smbd. */
     1560        new_fsp->lease = talloc_zero(new_fsp->conn->sconn, struct fsp_lease);
     1561        if (new_fsp->lease == NULL) {
     1562                return NULL;
     1563        }
     1564        new_fsp->lease->ref_count = 1;
     1565        new_fsp->lease->sconn = new_fsp->conn->sconn;
     1566        new_fsp->lease->lease.lease_key = *key;
     1567        new_fsp->lease->lease.lease_state = l->current_state;
     1568        /*
     1569         * We internally treat all leases as V2 and update
     1570         * the epoch, but when sending breaks it matters if
     1571         * the requesting lease was v1 or v2.
     1572         */
     1573        new_fsp->lease->lease.lease_version = l->lease_version;
     1574        new_fsp->lease->lease.lease_epoch = l->epoch;
     1575        return new_fsp->lease;
     1576}
     1577
     1578static NTSTATUS grant_fsp_lease(struct files_struct *fsp,
     1579                                struct share_mode_lock *lck,
     1580                                const struct smb2_lease *lease,
     1581                                uint32_t *p_lease_idx,
     1582                                uint32_t granted)
     1583{
     1584        struct share_mode_data *d = lck->data;
     1585        const struct GUID *client_guid = fsp_client_guid(fsp);
     1586        struct share_mode_lease *tmp;
     1587        NTSTATUS status;
     1588        int idx;
     1589
     1590        idx = find_share_mode_lease(d, client_guid, &lease->lease_key);
     1591
     1592        if (idx != -1) {
     1593                struct share_mode_lease *l = &d->leases[idx];
     1594                bool do_upgrade;
     1595                uint32_t existing, requested;
     1596
     1597                fsp->lease = find_fsp_lease(fsp, &lease->lease_key, l);
     1598                if (fsp->lease == NULL) {
     1599                        DEBUG(1, ("Did not find existing lease for file %s\n",
     1600                                  fsp_str_dbg(fsp)));
     1601                        return NT_STATUS_NO_MEMORY;
     1602                }
     1603
     1604                *p_lease_idx = idx;
     1605
     1606                /*
     1607                 * Upgrade only if the requested lease is a strict upgrade.
     1608                 */
     1609                existing = l->current_state;
     1610                requested = lease->lease_state;
     1611
     1612                /*
     1613                 * Tricky: This test makes sure that "requested" is a
     1614                 * strict bitwise superset of "existing".
     1615                 */
     1616                do_upgrade = ((existing & requested) == existing);
     1617
     1618                /*
     1619                 * Upgrade only if there's a change.
     1620                 */
     1621                do_upgrade &= (granted != existing);
     1622
     1623                /*
     1624                 * Upgrade only if other leases don't prevent what was asked
     1625                 * for.
     1626                 */
     1627                do_upgrade &= (granted == requested);
     1628
     1629                /*
     1630                 * only upgrade if we are not in breaking state
     1631                 */
     1632                do_upgrade &= !l->breaking;
     1633
     1634                DEBUG(10, ("existing=%"PRIu32", requested=%"PRIu32", "
     1635                           "granted=%"PRIu32", do_upgrade=%d\n",
     1636                           existing, requested, granted, (int)do_upgrade));
     1637
     1638                if (do_upgrade) {
     1639                        l->current_state = granted;
     1640                        l->epoch += 1;
     1641                }
     1642
     1643                /* Ensure we're in sync with current lease state. */
     1644                fsp_lease_update(lck, fsp_client_guid(fsp), fsp->lease);
     1645                return NT_STATUS_OK;
     1646        }
     1647
     1648        /*
     1649         * Create new lease
     1650         */
     1651
     1652        tmp = talloc_realloc(d, d->leases, struct share_mode_lease,
     1653                             d->num_leases+1);
     1654        if (tmp == NULL) {
     1655                /*
     1656                 * See [MS-SMB2]
     1657                 */
     1658                return NT_STATUS_INSUFFICIENT_RESOURCES;
     1659        }
     1660        d->leases = tmp;
     1661
     1662        fsp->lease = talloc_zero(fsp->conn->sconn, struct fsp_lease);
     1663        if (fsp->lease == NULL) {
     1664                return NT_STATUS_INSUFFICIENT_RESOURCES;
     1665        }
     1666        fsp->lease->ref_count = 1;
     1667        fsp->lease->sconn = fsp->conn->sconn;
     1668        fsp->lease->lease.lease_version = lease->lease_version;
     1669        fsp->lease->lease.lease_key = lease->lease_key;
     1670        fsp->lease->lease.lease_state = granted;
     1671        fsp->lease->lease.lease_epoch = lease->lease_epoch + 1;
     1672
     1673        *p_lease_idx = d->num_leases;
     1674
     1675        d->leases[d->num_leases] = (struct share_mode_lease) {
     1676                .client_guid = *client_guid,
     1677                .lease_key = fsp->lease->lease.lease_key,
     1678                .current_state = fsp->lease->lease.lease_state,
     1679                .lease_version = fsp->lease->lease.lease_version,
     1680                .epoch = fsp->lease->lease.lease_epoch,
     1681        };
     1682
     1683        status = leases_db_add(client_guid,
     1684                               &lease->lease_key,
     1685                               &fsp->file_id,
     1686                               fsp->conn->connectpath,
     1687                               fsp->fsp_name->base_name,
     1688                               fsp->fsp_name->stream_name);
     1689        if (!NT_STATUS_IS_OK(status)) {
     1690                DEBUG(10, ("%s: leases_db_add failed: %s\n", __func__,
     1691                           nt_errstr(status)));
     1692                TALLOC_FREE(fsp->lease);
     1693                return NT_STATUS_INSUFFICIENT_RESOURCES;
     1694        }
     1695
     1696        d->num_leases += 1;
     1697        d->modified = true;
     1698
     1699        return NT_STATUS_OK;
     1700}
     1701
     1702static bool is_same_lease(const files_struct *fsp,
     1703                          const struct share_mode_data *d,
     1704                          const struct share_mode_entry *e,
     1705                          const struct smb2_lease *lease)
     1706{
     1707        if (e->op_type != LEASE_OPLOCK) {
     1708                return false;
     1709        }
     1710        if (lease == NULL) {
     1711                return false;
     1712        }
     1713
     1714        return smb2_lease_equal(fsp_client_guid(fsp),
     1715                                &lease->lease_key,
     1716                                &d->leases[e->lease_idx].client_guid,
     1717                                &d->leases[e->lease_idx].lease_key);
     1718}
     1719
     1720static NTSTATUS grant_fsp_oplock_type(struct smb_request *req,
     1721                                      struct files_struct *fsp,
     1722                                      struct share_mode_lock *lck,
     1723                                      int oplock_request,
     1724                                      struct smb2_lease *lease)
     1725{
     1726        struct share_mode_data *d = lck->data;
     1727        bool got_handle_lease = false;
     1728        bool got_oplock = false;
     1729        uint32_t i;
     1730        uint32_t granted;
     1731        uint32_t lease_idx = UINT32_MAX;
     1732        bool ok;
     1733        NTSTATUS status;
    11481734
    11491735        if (oplock_request & INTERNAL_OPEN_ONLY) {
    11501736                /* No oplocks on internal open. */
    1151                 fsp->oplock_type = NO_OPLOCK;
     1737                oplock_request = NO_OPLOCK;
    11521738                DEBUG(10,("grant_fsp_oplock_type: oplock type 0x%x on file %s\n",
    11531739                        fsp->oplock_type, fsp_str_dbg(fsp)));
    1154                 return;
    1155         } else if (br_lck && br_lck->num_locks > 0) {
     1740        }
     1741
     1742        if (oplock_request == LEASE_OPLOCK) {
     1743                if (lease == NULL) {
     1744                        /*
     1745                         * The SMB2 layer should have checked this
     1746                         */
     1747                        return NT_STATUS_INTERNAL_ERROR;
     1748                }
     1749
     1750                granted = lease->lease_state;
     1751
     1752                if (lp_kernel_oplocks(SNUM(fsp->conn))) {
     1753                        DEBUG(10, ("No lease granted because kernel oplocks are enabled\n"));
     1754                        granted = SMB2_LEASE_NONE;
     1755                }
     1756                if ((granted & (SMB2_LEASE_READ|SMB2_LEASE_WRITE)) == 0) {
     1757                        DEBUG(10, ("No read or write lease requested\n"));
     1758                        granted = SMB2_LEASE_NONE;
     1759                }
     1760                if (granted == SMB2_LEASE_WRITE) {
     1761                        DEBUG(10, ("pure write lease requested\n"));
     1762                        granted = SMB2_LEASE_NONE;
     1763                }
     1764                if (granted == (SMB2_LEASE_WRITE|SMB2_LEASE_HANDLE)) {
     1765                        DEBUG(10, ("write and handle lease requested\n"));
     1766                        granted = SMB2_LEASE_NONE;
     1767                }
     1768        } else {
     1769                granted = map_oplock_to_lease_type(
     1770                        oplock_request & ~SAMBA_PRIVATE_OPLOCK_MASK);
     1771        }
     1772
     1773        if (lp_locking(fsp->conn->params) && file_has_brlocks(fsp)) {
    11561774                DEBUG(10,("grant_fsp_oplock_type: file %s has byte range locks\n",
    11571775                        fsp_str_dbg(fsp)));
    1158                 fsp->oplock_type = NO_OPLOCK;
    1159         }
    1160 
    1161         if (is_stat_open(fsp->access_mask)) {
    1162                 /* Leave the value already set. */
    1163                 DEBUG(10,("grant_fsp_oplock_type: oplock type 0x%x on file %s\n",
    1164                         fsp->oplock_type, fsp_str_dbg(fsp)));
    1165                 return;
    1166         }
    1167 
    1168         /*
    1169          * Match what was requested (fsp->oplock_type) with
    1170          * what was found in the existing share modes.
    1171          */
    1172 
    1173         if (got_a_none_oplock) {
    1174                 fsp->oplock_type = NO_OPLOCK;
    1175         } else if (got_level2_oplock) {
    1176                 if (fsp->oplock_type == NO_OPLOCK ||
    1177                                 fsp->oplock_type == FAKE_LEVEL_II_OPLOCK) {
    1178                         /* Store a level2 oplock, but don't tell the client */
    1179                         fsp->oplock_type = FAKE_LEVEL_II_OPLOCK;
    1180                 } else {
     1776                granted &= ~SMB2_LEASE_READ;
     1777        }
     1778
     1779        for (i=0; i<d->num_share_modes; i++) {
     1780                struct share_mode_entry *e = &d->share_modes[i];
     1781                uint32_t e_lease_type;
     1782
     1783                e_lease_type = get_lease_type(d, e);
     1784
     1785                if ((granted & SMB2_LEASE_WRITE) &&
     1786                    !is_same_lease(fsp, d, e, lease) &&
     1787                    !share_mode_stale_pid(d, i)) {
     1788                        /*
     1789                         * Can grant only one writer
     1790                         */
     1791                        granted &= ~SMB2_LEASE_WRITE;
     1792                }
     1793
     1794                if ((e_lease_type & SMB2_LEASE_HANDLE) && !got_handle_lease &&
     1795                    !share_mode_stale_pid(d, i)) {
     1796                        got_handle_lease = true;
     1797                }
     1798
     1799                if ((e->op_type != LEASE_OPLOCK) && !got_oplock &&
     1800                    !share_mode_stale_pid(d, i)) {
     1801                        got_oplock = true;
     1802                }
     1803        }
     1804
     1805        if ((granted & SMB2_LEASE_READ) && !(granted & SMB2_LEASE_WRITE)) {
     1806                bool allow_level2 =
     1807                        (global_client_caps & CAP_LEVEL_II_OPLOCKS) &&
     1808                        lp_level2_oplocks(SNUM(fsp->conn));
     1809
     1810                if (!allow_level2) {
     1811                        granted = SMB2_LEASE_NONE;
     1812                }
     1813        }
     1814
     1815        if (oplock_request == LEASE_OPLOCK) {
     1816                if (got_oplock) {
     1817                        granted &= ~SMB2_LEASE_HANDLE;
     1818                }
     1819
     1820                fsp->oplock_type = LEASE_OPLOCK;
     1821
     1822                status = grant_fsp_lease(fsp, lck, lease, &lease_idx,
     1823                                         granted);
     1824                if (!NT_STATUS_IS_OK(status)) {
     1825                        return status;
     1826
     1827                }
     1828                *lease = fsp->lease->lease;
     1829                DEBUG(10, ("lease_state=%d\n", lease->lease_state));
     1830        } else {
     1831                if (got_handle_lease) {
     1832                        granted = SMB2_LEASE_NONE;
     1833                }
     1834
     1835                switch (granted) {
     1836                case SMB2_LEASE_READ|SMB2_LEASE_WRITE|SMB2_LEASE_HANDLE:
     1837                        fsp->oplock_type = BATCH_OPLOCK|EXCLUSIVE_OPLOCK;
     1838                        break;
     1839                case SMB2_LEASE_READ|SMB2_LEASE_WRITE:
     1840                        fsp->oplock_type = EXCLUSIVE_OPLOCK;
     1841                        break;
     1842                case SMB2_LEASE_READ|SMB2_LEASE_HANDLE:
     1843                case SMB2_LEASE_READ:
    11811844                        fsp->oplock_type = LEVEL_II_OPLOCK;
    1182                 }
    1183         } else {
    1184                 /* All share_mode_entries are placeholders or deferred.
    1185                  * Silently upgrade to fake levelII if the client didn't
    1186                  * ask for an oplock. */
    1187                 if (fsp->oplock_type == NO_OPLOCK) {
    1188                         /* Store a level2 oplock, but don't tell the client */
    1189                         fsp->oplock_type = FAKE_LEVEL_II_OPLOCK;
    1190                 }
    1191         }
    1192 
    1193         /*
    1194          * Don't grant level2 to clients that don't want them
    1195          * or if we've turned them off.
    1196          */
    1197         if (fsp->oplock_type == LEVEL_II_OPLOCK && !allow_level2) {
    1198                 fsp->oplock_type = FAKE_LEVEL_II_OPLOCK;
     1845                        break;
     1846                default:
     1847                        fsp->oplock_type = NO_OPLOCK;
     1848                        break;
     1849                }
     1850
     1851                status = set_file_oplock(fsp);
     1852                if (!NT_STATUS_IS_OK(status)) {
     1853                        /*
     1854                         * Could not get the kernel oplock
     1855                         */
     1856                        fsp->oplock_type = NO_OPLOCK;
     1857                }
     1858        }
     1859
     1860        ok = set_share_mode(lck, fsp, get_current_uid(fsp->conn),
     1861                            req ? req->mid : 0,
     1862                            fsp->oplock_type,
     1863                            lease_idx);
     1864        if (!ok) {
     1865                return NT_STATUS_NO_MEMORY;
     1866        }
     1867
     1868        ok = update_num_read_oplocks(fsp, lck);
     1869        if (!ok) {
     1870                del_share_mode(lck, fsp);
     1871                return NT_STATUS_INTERNAL_ERROR;
    11991872        }
    12001873
    12011874        DEBUG(10,("grant_fsp_oplock_type: oplock type 0x%x on file %s\n",
    12021875                  fsp->oplock_type, fsp_str_dbg(fsp)));
     1876
     1877        return NT_STATUS_OK;
    12031878}
    12041879
    1205 bool request_timed_out(struct timeval request_time,
    1206                        struct timeval timeout)
     1880static bool request_timed_out(struct timeval request_time,
     1881                              struct timeval timeout)
    12071882{
    12081883        struct timeval now, end_time;
     
    12121887}
    12131888
     1889struct defer_open_state {
     1890        struct smbXsrv_connection *xconn;
     1891        uint64_t mid;
     1892};
     1893
     1894static void defer_open_done(struct tevent_req *req);
     1895
    12141896/****************************************************************************
    12151897 Handle the 1 second delay in returning a SHARING_VIOLATION error.
     
    12221904                       struct deferred_open_record *state)
    12231905{
    1224         int i;
    1225 
    1226         /* Paranoia check */
    1227 
    1228         for (i=0; i<lck->num_share_modes; i++) {
    1229                 struct share_mode_entry *e = &lck->share_modes[i];
    1230 
    1231                 if (!is_deferred_open_entry(e)) {
    1232                         continue;
    1233                 }
    1234 
    1235                 if (procid_is_me(&e->pid) && (e->op_mid == req->mid)) {
    1236                         DEBUG(0, ("Trying to defer an already deferred "
    1237                                 "request: mid=%llu, exiting\n",
    1238                                 (unsigned long long)req->mid));
    1239                         exit_server("attempt to defer a deferred request");
    1240                 }
    1241         }
    1242 
    1243         /* End paranoia check */
     1906        struct deferred_open_record *open_rec;
    12441907
    12451908        DEBUG(10,("defer_open_sharing_error: time [%u.%06u] adding deferred "
     
    12491912                  (unsigned long long)req->mid));
    12501913
     1914        open_rec = talloc(NULL, struct deferred_open_record);
     1915        if (open_rec == NULL) {
     1916                TALLOC_FREE(lck);
     1917                exit_server("talloc failed");
     1918        }
     1919
     1920        *open_rec = *state;
     1921
     1922        if (lck) {
     1923                struct defer_open_state *watch_state;
     1924                struct tevent_req *watch_req;
     1925                bool ret;
     1926
     1927                watch_state = talloc(open_rec, struct defer_open_state);
     1928                if (watch_state == NULL) {
     1929                        exit_server("talloc failed");
     1930                }
     1931                watch_state->xconn = req->xconn;
     1932                watch_state->mid = req->mid;
     1933
     1934                DEBUG(10, ("defering mid %llu\n",
     1935                           (unsigned long long)req->mid));
     1936
     1937                watch_req = dbwrap_record_watch_send(
     1938                        watch_state, req->sconn->ev_ctx, lck->data->record,
     1939                        req->sconn->msg_ctx);
     1940                if (watch_req == NULL) {
     1941                        exit_server("Could not watch share mode record");
     1942                }
     1943                tevent_req_set_callback(watch_req, defer_open_done,
     1944                                        watch_state);
     1945
     1946                ret = tevent_req_set_endtime(
     1947                        watch_req, req->sconn->ev_ctx,
     1948                        timeval_sum(&request_time, &timeout));
     1949                SMB_ASSERT(ret);
     1950        }
     1951
    12511952        if (!push_deferred_open_message_smb(req, request_time, timeout,
    1252                                        state->id, (char *)state, sizeof(*state))) {
     1953                                            state->id, open_rec)) {
     1954                TALLOC_FREE(lck);
    12531955                exit_server("push_deferred_open_message_smb failed");
    12541956        }
    1255         add_deferred_open(lck, req->mid, request_time,
    1256                           sconn_server_id(req->sconn), state->id);
     1957}
     1958
     1959static void defer_open_done(struct tevent_req *req)
     1960{
     1961        struct defer_open_state *state = tevent_req_callback_data(
     1962                req, struct defer_open_state);
     1963        NTSTATUS status;
     1964        bool ret;
     1965
     1966        status = dbwrap_record_watch_recv(req, talloc_tos(), NULL);
     1967        TALLOC_FREE(req);
     1968        if (!NT_STATUS_IS_OK(status)) {
     1969                DEBUG(5, ("dbwrap_record_watch_recv returned %s\n",
     1970                          nt_errstr(status)));
     1971                /*
     1972                 * Even if it failed, retry anyway. TODO: We need a way to
     1973                 * tell a re-scheduled open about that error.
     1974                 */
     1975        }
     1976
     1977        DEBUG(10, ("scheduling mid %llu\n", (unsigned long long)state->mid));
     1978
     1979        ret = schedule_deferred_open_message_smb(state->xconn, state->mid);
     1980        SMB_ASSERT(ret);
     1981        TALLOC_FREE(state);
    12571982}
    12581983
     
    12621987****************************************************************************/
    12631988
    1264 bool open_match_attributes(connection_struct *conn,
    1265                            uint32 old_dos_attr,
    1266                            uint32 new_dos_attr,
    1267                            mode_t existing_unx_mode,
    1268                            mode_t new_unx_mode,
    1269                            mode_t *returned_unx_mode)
     1989static bool open_match_attributes(connection_struct *conn,
     1990                                  uint32_t old_dos_attr,
     1991                                  uint32_t new_dos_attr,
     1992                                  mode_t existing_unx_mode,
     1993                                  mode_t new_unx_mode,
     1994                                  mode_t *returned_unx_mode)
    12701995{
    1271         uint32 noarch_old_dos_attr, noarch_new_dos_attr;
     1996        uint32_t noarch_old_dos_attr, noarch_new_dos_attr;
    12721997
    12731998        noarch_old_dos_attr = (old_dos_attr & ~FILE_ATTRIBUTE_ARCHIVE);
     
    13102035****************************************************************************/
    13112036
    1312 NTSTATUS fcb_or_dos_open(struct smb_request *req,
    1313                                      connection_struct *conn,
    1314                                      files_struct *fsp_to_dup_into,
    1315                                      const struct smb_filename *smb_fname,
    1316                                      struct file_id id,
    1317                                      uint16 file_pid,
    1318                                      uint16 vuid,
    1319                                      uint32 access_mask,
    1320                                      uint32 share_access,
    1321                                      uint32 create_options)
     2037static NTSTATUS fcb_or_dos_open(struct smb_request *req,
     2038                                connection_struct *conn,
     2039                                files_struct *fsp_to_dup_into,
     2040                                const struct smb_filename *smb_fname,
     2041                                struct file_id id,
     2042                                uint16_t file_pid,
     2043                                uint64_t vuid,
     2044                                uint32_t access_mask,
     2045                                uint32_t share_access,
     2046                                uint32_t create_options)
    13222047{
    13232048        files_struct *fsp;
     
    13302055
    13312056                DEBUG(10,("fcb_or_dos_open: checking file %s, fd = %d, "
    1332                           "vuid = %u, file_pid = %u, private_options = 0x%x "
     2057                          "vuid = %llu, file_pid = %u, private_options = 0x%x "
    13332058                          "access_mask = 0x%x\n", fsp_str_dbg(fsp),
    1334                           fsp->fh->fd, (unsigned int)fsp->vuid,
     2059                          fsp->fh->fd, (unsigned long long)fsp->vuid,
    13352060                          (unsigned int)fsp->file_pid,
    13362061                          (unsigned int)fsp->fh->private_options,
    13372062                          (unsigned int)fsp->access_mask ));
    13382063
    1339                 if (fsp->fh->fd != -1 &&
     2064                if (fsp != fsp_to_dup_into &&
     2065                    fsp->fh->fd != -1 &&
    13402066                    fsp->vuid == vuid &&
    13412067                    fsp->file_pid == file_pid &&
     
    13682094
    13692095static void schedule_defer_open(struct share_mode_lock *lck,
     2096                                struct file_id id,
    13702097                                struct timeval request_time,
    13712098                                struct smb_request *req)
     
    13972124
    13982125        state.delayed_for_oplocks = True;
    1399         state.id = lck->id;
     2126        state.async_open = false;
     2127        state.id = id;
    14002128
    14012129        if (!request_timed_out(request_time, timeout)) {
    14022130                defer_open(lck, request_time, timeout, req, &state);
     2131        }
     2132}
     2133
     2134/****************************************************************************
     2135 Reschedule an open call that went asynchronous.
     2136****************************************************************************/
     2137
     2138static void schedule_async_open(struct timeval request_time,
     2139                                struct smb_request *req)
     2140{
     2141        struct deferred_open_record state;
     2142        struct timeval timeout;
     2143
     2144        timeout = timeval_set(20, 0);
     2145
     2146        ZERO_STRUCT(state);
     2147        state.delayed_for_oplocks = false;
     2148        state.async_open = true;
     2149
     2150        if (!request_timed_out(request_time, timeout)) {
     2151                defer_open(NULL, request_time, timeout, req, &state);
    14032152        }
    14042153}
     
    14082157****************************************************************************/
    14092158
     2159static NTSTATUS smbd_calculate_maximum_allowed_access(
     2160        connection_struct *conn,
     2161        const struct smb_filename *smb_fname,
     2162        bool use_privs,
     2163        uint32_t *p_access_mask)
     2164{
     2165        struct security_descriptor *sd;
     2166        uint32_t access_granted;
     2167        NTSTATUS status;
     2168
     2169        if (!use_privs && (get_current_uid(conn) == (uid_t)0)) {
     2170                *p_access_mask |= FILE_GENERIC_ALL;
     2171                return NT_STATUS_OK;
     2172        }
     2173
     2174        status = SMB_VFS_GET_NT_ACL(conn, smb_fname->base_name,
     2175                                    (SECINFO_OWNER |
     2176                                     SECINFO_GROUP |
     2177                                     SECINFO_DACL),
     2178                                    talloc_tos(), &sd);
     2179
     2180        if (NT_STATUS_EQUAL(status, NT_STATUS_OBJECT_NAME_NOT_FOUND)) {
     2181                /*
     2182                 * File did not exist
     2183                 */
     2184                *p_access_mask = FILE_GENERIC_ALL;
     2185                return NT_STATUS_OK;
     2186        }
     2187        if (!NT_STATUS_IS_OK(status)) {
     2188                DEBUG(10,("Could not get acl on file %s: %s\n",
     2189                          smb_fname_str_dbg(smb_fname),
     2190                          nt_errstr(status)));
     2191                return NT_STATUS_ACCESS_DENIED;
     2192        }
     2193
     2194        /*
     2195         * If we can access the path to this file, by
     2196         * default we have FILE_READ_ATTRIBUTES from the
     2197         * containing directory. See the section:
     2198         * "Algorithm to Check Access to an Existing File"
     2199         * in MS-FSA.pdf.
     2200         *
     2201         * se_file_access_check()
     2202         * also takes care of owner WRITE_DAC and READ_CONTROL.
     2203         */
     2204        status = se_file_access_check(sd,
     2205                                 get_current_nttok(conn),
     2206                                 use_privs,
     2207                                 (*p_access_mask & ~FILE_READ_ATTRIBUTES),
     2208                                 &access_granted);
     2209
     2210        TALLOC_FREE(sd);
     2211
     2212        if (!NT_STATUS_IS_OK(status)) {
     2213                DEBUG(10, ("Access denied on file %s: "
     2214                           "when calculating maximum access\n",
     2215                           smb_fname_str_dbg(smb_fname)));
     2216                return NT_STATUS_ACCESS_DENIED;
     2217        }
     2218        *p_access_mask = (access_granted | FILE_READ_ATTRIBUTES);
     2219
     2220        if (!(access_granted & DELETE_ACCESS)) {
     2221                if (can_delete_file_in_directory(conn, smb_fname)) {
     2222                        *p_access_mask |= DELETE_ACCESS;
     2223                }
     2224        }
     2225
     2226        return NT_STATUS_OK;
     2227}
     2228
    14102229NTSTATUS smbd_calculate_access_mask(connection_struct *conn,
    14112230                                    const struct smb_filename *smb_fname,
    1412                                     bool file_existed,
     2231                                    bool use_privs,
    14132232                                    uint32_t access_mask,
    14142233                                    uint32_t *access_mask_out)
     
    14262245        /* Calculate MAXIMUM_ALLOWED_ACCESS if requested. */
    14272246        if (access_mask & MAXIMUM_ALLOWED_ACCESS) {
    1428                 if (file_existed) {
    1429 
    1430                         struct security_descriptor *sd;
    1431                         uint32_t access_granted = 0;
    1432 
    1433                         status = SMB_VFS_GET_NT_ACL(conn, smb_fname->base_name,
    1434                                         (SECINFO_OWNER |
    1435                                         SECINFO_GROUP |
    1436                                         SECINFO_DACL),&sd);
    1437 
    1438                         if (!NT_STATUS_IS_OK(status)) {
    1439                                 DEBUG(10,("smbd_calculate_access_mask: "
    1440                                         "Could not get acl on file %s: %s\n",
    1441                                         smb_fname_str_dbg(smb_fname),
    1442                                         nt_errstr(status)));
    1443                                 return NT_STATUS_ACCESS_DENIED;
    1444                         }
    1445 
    1446                         status = smb1_file_se_access_check(conn,
    1447                                         sd,
    1448                                         get_current_nttok(conn),
    1449                                         access_mask,
    1450                                         &access_granted);
    1451 
    1452                         TALLOC_FREE(sd);
    1453 
    1454                         if (!NT_STATUS_IS_OK(status)) {
    1455                                 DEBUG(10, ("smbd_calculate_access_mask: "
    1456                                         "Access denied on file %s: "
    1457                                         "when calculating maximum access\n",
    1458                                         smb_fname_str_dbg(smb_fname)));
    1459                                 return NT_STATUS_ACCESS_DENIED;
    1460                         }
    1461 
    1462                         if (!(access_granted & DELETE_ACCESS)) {
    1463                                 if (can_delete_file_in_directory(conn, smb_fname)) {
    1464                                         access_granted |= DELETE_ACCESS;
    1465                                 }
    1466                         }
    1467 
    1468                         /*
    1469                          * If we can access the path to this file, by
    1470                          * default we have FILE_READ_ATTRIBUTES from the
    1471                          * containing directory. See the section.
    1472                          * "Algorithm to Check Access to an Existing File"
    1473                          * in MS-FSA.pdf.
    1474                          */
    1475                         access_mask = access_granted | FILE_READ_ATTRIBUTES;
    1476                 } else {
    1477                         access_mask = FILE_GENERIC_ALL;
     2247
     2248                status = smbd_calculate_maximum_allowed_access(
     2249                        conn, smb_fname, use_privs, &access_mask);
     2250
     2251                if (!NT_STATUS_IS_OK(status)) {
     2252                        return status;
    14782253                }
    14792254
     
    15022277****************************************************************************/
    15032278
    1504 void remove_deferred_open_entry(struct file_id id, uint64_t mid,
    1505                                 struct server_id pid)
     2279/****************************************************************************
     2280 Return true if this is a state pointer to an asynchronous create.
     2281****************************************************************************/
     2282
     2283bool is_deferred_open_async(const struct deferred_open_record *rec)
    15062284{
    1507         struct share_mode_lock *lck = get_share_mode_lock(talloc_tos(), id,
    1508                         NULL, NULL, NULL);
    1509         if (lck == NULL) {
    1510                 DEBUG(0, ("could not get share mode lock\n"));
    1511         } else {
    1512                 del_deferred_open_entry(lck, mid, pid);
    1513                 TALLOC_FREE(lck);
    1514         }
     2285        return rec->async_open;
    15152286}
    15162287
    1517 /****************************************************************
    1518  Ensure we get the brlock lock followed by the share mode lock
    1519  in the correct order to prevent deadlocks if other smbd's are
    1520  using the brlock database on this file simultaneously with this open
    1521  (that code also gets the locks in brlock -> share mode lock order).
    1522 ****************************************************************/
    1523 
    1524 static bool acquire_ordered_locks(TALLOC_CTX *mem_ctx,
    1525                                 files_struct *fsp,
    1526                                 const struct file_id id,
    1527                                 const char *connectpath,
    1528                                 const struct smb_filename *smb_fname,
    1529                                 const struct timespec *p_old_write_time,
    1530                                 struct share_mode_lock **p_lck,
    1531                                 struct byte_range_lock **p_br_lck)
     2288static bool clear_ads(uint32_t create_disposition)
    15322289{
    1533         /* Ordering - we must get the br_lck for this
    1534            file before the share mode. */
    1535         if (lp_locking(fsp->conn->params)) {
    1536                 *p_br_lck = brl_get_locks_readonly(fsp);
    1537                 if (*p_br_lck == NULL) {
    1538                         DEBUG(0, ("Could not get br_lock\n"));
    1539                         return false;
    1540                 }
    1541                 /* Note - we don't need to free the returned
    1542                    br_lck explicitly as it was allocated on talloc_tos()
    1543                    and so will be autofreed (and release the lock)
    1544                    once the frame context disappears.
    1545 
    1546                    If it was set to fsp->brlock_rec then it was
    1547                    talloc_move'd to hang off the fsp pointer and
    1548                    in this case is guarenteed to not be holding the
    1549                    lock on the brlock database. */
    1550         }
    1551 
    1552         *p_lck = get_share_mode_lock(mem_ctx,
    1553                                 id,
    1554                                 connectpath,
    1555                                 smb_fname,
    1556                                 p_old_write_time);
    1557 
    1558         if (*p_lck == NULL) {
    1559                 DEBUG(0, ("Could not get share mode lock\n"));
    1560                 TALLOC_FREE(*p_br_lck);
    1561                 return false;
    1562         }
    1563         return true;
     2290        bool ret = false;
     2291
     2292        switch (create_disposition) {
     2293        case FILE_SUPERSEDE:
     2294        case FILE_OVERWRITE_IF:
     2295        case FILE_OVERWRITE:
     2296                ret = true;
     2297                break;
     2298        default:
     2299                break;
     2300        }
     2301        return ret;
     2302}
     2303
     2304static int disposition_to_open_flags(uint32_t create_disposition)
     2305{
     2306        int ret = 0;
     2307
     2308        /*
     2309         * Currently we're using FILE_SUPERSEDE as the same as
     2310         * FILE_OVERWRITE_IF but they really are
     2311         * different. FILE_SUPERSEDE deletes an existing file
     2312         * (requiring delete access) then recreates it.
     2313         */
     2314
     2315        switch (create_disposition) {
     2316        case FILE_SUPERSEDE:
     2317        case FILE_OVERWRITE_IF:
     2318                /*
     2319                 * If file exists replace/overwrite. If file doesn't
     2320                 * exist create.
     2321                 */
     2322                ret = O_CREAT|O_TRUNC;
     2323                break;
     2324
     2325        case FILE_OPEN:
     2326                /*
     2327                 * If file exists open. If file doesn't exist error.
     2328                 */
     2329                ret = 0;
     2330                break;
     2331
     2332        case FILE_OVERWRITE:
     2333                /*
     2334                 * If file exists overwrite. If file doesn't exist
     2335                 * error.
     2336                 */
     2337                ret = O_TRUNC;
     2338                break;
     2339
     2340        case FILE_CREATE:
     2341                /*
     2342                 * If file exists error. If file doesn't exist create.
     2343                 */
     2344                ret = O_CREAT|O_EXCL;
     2345                break;
     2346
     2347        case FILE_OPEN_IF:
     2348                /*
     2349                 * If file exists open. If file doesn't exist create.
     2350                 */
     2351                ret = O_CREAT;
     2352                break;
     2353        }
     2354        return ret;
     2355}
     2356
     2357static int calculate_open_access_flags(uint32_t access_mask,
     2358                                       uint32_t private_flags)
     2359{
     2360        bool need_write, need_read;
     2361
     2362        /*
     2363         * Note that we ignore the append flag as append does not
     2364         * mean the same thing under DOS and Unix.
     2365         */
     2366
     2367        need_write = (access_mask & (FILE_WRITE_DATA | FILE_APPEND_DATA));
     2368        if (!need_write) {
     2369                return O_RDONLY;
     2370        }
     2371
     2372        /* DENY_DOS opens are always underlying read-write on the
     2373           file handle, no matter what the requested access mask
     2374           says. */
     2375
     2376        need_read =
     2377                ((private_flags & NTCREATEX_OPTIONS_PRIVATE_DENY_DOS) ||
     2378                 access_mask & (FILE_READ_ATTRIBUTES|FILE_READ_DATA|
     2379                                FILE_READ_EA|FILE_EXECUTE));
     2380
     2381        if (!need_read) {
     2382                return O_WRONLY;
     2383        }
     2384        return O_RDWR;
    15642385}
    15652386
     
    15702391static NTSTATUS open_file_ntcreate(connection_struct *conn,
    15712392                            struct smb_request *req,
    1572                             uint32 access_mask,         /* access bits (FILE_READ_DATA etc.) */
    1573                             uint32 share_access,        /* share constants (FILE_SHARE_READ etc) */
    1574                             uint32 create_disposition,  /* FILE_OPEN_IF etc. */
    1575                             uint32 create_options,      /* options such as delete on close. */
    1576                             uint32 new_dos_attributes,  /* attributes used for new file. */
     2393                            uint32_t access_mask,               /* access bits (FILE_READ_DATA etc.) */
     2394                            uint32_t share_access,      /* share constants (FILE_SHARE_READ etc) */
     2395                            uint32_t create_disposition,        /* FILE_OPEN_IF etc. */
     2396                            uint32_t create_options,    /* options such as delete on close. */
     2397                            uint32_t new_dos_attributes,        /* attributes used for new file. */
    15772398                            int oplock_request,         /* internal Samba oplock codes. */
     2399                            struct smb2_lease *lease,
    15782400                                                        /* Information (FILE_EXISTS etc.) */
    15792401                            uint32_t private_flags,     /* Samba specific flags. */
     
    15882410        bool posix_open = False;
    15892411        bool new_file_created = False;
    1590         bool clear_ads = false;
    1591         struct file_id id;
     2412        bool first_open_attempt = true;
    15922413        NTSTATUS fsp_open = NT_STATUS_ACCESS_DENIED;
    15932414        mode_t new_unx_mode = (mode_t)0;
    15942415        mode_t unx_mode = (mode_t)0;
    15952416        int info;
    1596         uint32 existing_dos_attributes = 0;
     2417        uint32_t existing_dos_attributes = 0;
    15972418        struct timeval request_time = timeval_zero();
    15982419        struct share_mode_lock *lck = NULL;
    1599         uint32 open_access_mask = access_mask;
     2420        uint32_t open_access_mask = access_mask;
    16002421        NTSTATUS status;
    16012422        char *parent_dir;
    1602 
    1603         ZERO_STRUCT(id);
     2423        SMB_STRUCT_STAT saved_stat = smb_fname->st;
     2424        struct timespec old_write_time;
     2425        struct file_id id;
    16042426
    16052427        if (conn->printer) {
     
    16572479                   (unsigned int)private_flags));
    16582480
    1659         if ((req == NULL) && ((oplock_request & INTERNAL_OPEN_ONLY) == 0)) {
    1660                 DEBUG(0, ("No smb request but not an internal only open!\n"));
    1661                 return NT_STATUS_INTERNAL_ERROR;
     2481        if (req == NULL) {
     2482                /* Ensure req == NULL means INTERNAL_OPEN_ONLY */
     2483                SMB_ASSERT(((oplock_request & INTERNAL_OPEN_ONLY) != 0));
     2484        } else {
     2485                /* And req != NULL means no INTERNAL_OPEN_ONLY */
     2486                SMB_ASSERT(((oplock_request & INTERNAL_OPEN_ONLY) == 0));
    16622487        }
    16632488
     
    16672492
    16682493        if (req) {
    1669                 void *ptr;
     2494                struct deferred_open_record *open_rec;
    16702495                if (get_deferred_open_message_state(req,
    16712496                                &request_time,
    1672                                 &ptr)) {
    1673 
    1674                         struct deferred_open_record *state = (struct deferred_open_record *)ptr;
     2497                                &open_rec)) {
    16752498                        /* Remember the absolute time of the original
    16762499                           request with this mid. We'll use it later to
    16772500                           see if this has timed out. */
    16782501
    1679                         /* Remove the deferred open entry under lock. */
    1680                         remove_deferred_open_entry(
    1681                                 state->id, req->mid,
    1682                                 sconn_server_id(req->sconn));
     2502                        /* If it was an async create retry, the file
     2503                           didn't exist. */
     2504
     2505                        if (is_deferred_open_async(open_rec)) {
     2506                                SET_STAT_INVALID(smb_fname->st);
     2507                                file_existed = false;
     2508                        }
    16832509
    16842510                        /* Ensure we don't reprocess this message. */
    1685                         remove_deferred_open_message_smb(req->mid);
     2511                        remove_deferred_open_message_smb(req->xconn, req->mid);
     2512
     2513                        first_open_attempt = false;
    16862514                }
    16872515        }
     
    17022530
    17032531        /* this is for OS/2 long file names - say we don't support them */
    1704         if (!lp_posix_pathnames() && strstr(smb_fname->base_name,".+,;=[].")) {
     2532        if (req != NULL && !req->posix_pathnames &&
     2533                        strstr(smb_fname->base_name,".+,;=[].")) {
    17052534                /* OS/2 Workplace shell fix may be main code stream in a later
    17062535                 * release. */
     
    17142543
    17152544        switch( create_disposition ) {
    1716                 /*
    1717                  * Currently we're using FILE_SUPERSEDE as the same as
    1718                  * FILE_OVERWRITE_IF but they really are
    1719                  * different. FILE_SUPERSEDE deletes an existing file
    1720                  * (requiring delete access) then recreates it.
    1721                  */
    1722                 case FILE_SUPERSEDE:
    1723                         /* If file exists replace/overwrite. If file doesn't
    1724                          * exist create. */
    1725                         flags2 |= (O_CREAT | O_TRUNC);
    1726                         clear_ads = true;
    1727                         break;
    1728 
    1729                 case FILE_OVERWRITE_IF:
    1730                         /* If file exists replace/overwrite. If file doesn't
    1731                          * exist create. */
    1732                         flags2 |= (O_CREAT | O_TRUNC);
    1733                         clear_ads = true;
    1734                         break;
    1735 
    17362545                case FILE_OPEN:
    17372546                        /* If file exists open. If file doesn't exist error. */
     
    17572566                                return NT_STATUS_OBJECT_NAME_NOT_FOUND;
    17582567                        }
    1759                         flags2 |= O_TRUNC;
    1760                         clear_ads = true;
    17612568                        break;
    17622569
     
    17762583                                return map_nt_error_from_unix(errno);
    17772584                        }
    1778                         flags2 |= (O_CREAT|O_EXCL);
    17792585                        break;
    17802586
     2587                case FILE_SUPERSEDE:
     2588                case FILE_OVERWRITE_IF:
    17812589                case FILE_OPEN_IF:
    1782                         /* If file exists open. If file doesn't exist
    1783                          * create. */
    1784                         flags2 |= O_CREAT;
    17852590                        break;
    1786 
    17872591                default:
    17882592                        return NT_STATUS_INVALID_PARAMETER;
    17892593        }
    17902594
     2595        flags2 = disposition_to_open_flags(create_disposition);
     2596
    17912597        /* We only care about matching attributes on file exists and
    17922598         * overwrite. */
    17932599
    1794         if (!posix_open && file_existed && ((create_disposition == FILE_OVERWRITE) ||
    1795                              (create_disposition == FILE_OVERWRITE_IF))) {
     2600        if (!posix_open && file_existed &&
     2601            ((create_disposition == FILE_OVERWRITE) ||
     2602             (create_disposition == FILE_OVERWRITE_IF))) {
    17962603                if (!open_match_attributes(conn, existing_dos_attributes,
    17972604                                           new_dos_attributes,
     
    18102617        }
    18112618
    1812         status = smbd_calculate_access_mask(conn, smb_fname, file_existed,
     2619        status = smbd_calculate_access_mask(conn, smb_fname,
     2620                                        false,
    18132621                                        access_mask,
    18142622                                        &access_mask);
     
    18222630        open_access_mask = access_mask;
    18232631
    1824         if ((flags2 & O_TRUNC) || (oplock_request & FORCE_OPLOCK_BREAK_TO_NONE)) {
     2632        if (flags2 & O_TRUNC) {
    18252633                open_access_mask |= FILE_WRITE_DATA; /* This will cause oplock breaks. */
    18262634        }
     
    18352643         */
    18362644
    1837         if ((access_mask & (FILE_WRITE_DATA | FILE_APPEND_DATA)) ||
    1838                         (oplock_request & FORCE_OPLOCK_BREAK_TO_NONE)) {
    1839                 /* DENY_DOS opens are always underlying read-write on the
    1840                    file handle, no matter what the requested access mask
    1841                     says. */
    1842                 if ((private_flags & NTCREATEX_OPTIONS_PRIVATE_DENY_DOS) ||
    1843                         access_mask & (FILE_READ_ATTRIBUTES|FILE_READ_DATA|FILE_READ_EA|FILE_EXECUTE)) {
    1844                         flags = O_RDWR;
    1845                 } else {
    1846                         flags = O_WRONLY;
    1847                 }
    1848         } else {
    1849                 flags = O_RDONLY;
    1850         }
     2645        flags = calculate_open_access_flags(access_mask, private_flags);
    18512646
    18522647        /*
     
    18712666                 */
    18722667                flags2 &= ~(O_CREAT|O_TRUNC);
     2668        }
     2669
     2670        if (first_open_attempt && lp_kernel_oplocks(SNUM(conn))) {
     2671                /*
     2672                 * With kernel oplocks the open breaking an oplock
     2673                 * blocks until the oplock holder has given up the
     2674                 * oplock or closed the file. We prevent this by first
     2675                 * trying to open the file with O_NONBLOCK (see "man
     2676                 * fcntl" on Linux). For the second try, triggered by
     2677                 * an oplock break response, we do not need this
     2678                 * anymore.
     2679                 *
     2680                 * This is true under the assumption that only Samba
     2681                 * requests kernel oplocks. Once someone else like
     2682                 * NFSv4 starts to use that API, we will have to
     2683                 * modify this by communicating with the NFSv4 server.
     2684                 */
     2685                flags2 |= O_NONBLOCK;
    18732686        }
    18742687
     
    18932706                                              * requested access_mask after
    18942707                                              * the open is done. */
    1895         fsp->posix_open = posix_open;
    1896 
    1897         /* Ensure no SAMBA_PRIVATE bits can be set. */
    1898         fsp->oplock_type = (oplock_request & ~SAMBA_PRIVATE_OPLOCK_MASK);
     2708        if (posix_open) {
     2709                fsp->posix_flags |= FSP_POSIX_FLAGS_ALL;
     2710        }
    18992711
    19002712        if (timeval_is_zero(&request_time)) {
    19012713                request_time = fsp->open_time;
    19022714        }
    1903 
    1904         if (file_existed) {
    1905                 struct byte_range_lock *br_lck = NULL;
    1906                 struct share_mode_entry *batch_entry = NULL;
    1907                 struct share_mode_entry *exclusive_entry = NULL;
    1908                 bool got_level2_oplock = false;
    1909                 bool got_a_none_oplock = false;
    1910 
    1911                 struct timespec old_write_time = smb_fname->st.st_ex_mtime;
    1912                 id = vfs_file_id_from_sbuf(conn, &smb_fname->st);
    1913 
    1914                 if (!acquire_ordered_locks(talloc_tos(),
    1915                                         fsp,
    1916                                         id,
    1917                                         conn->connectpath,
    1918                                         smb_fname,
    1919                                         &old_write_time,
    1920                                         &lck,
    1921                                         &br_lck)) {
    1922                         return NT_STATUS_SHARING_VIOLATION;
    1923                 }
    1924 
    1925                 /* Get the types we need to examine. */
    1926                 find_oplock_types(fsp,
    1927                                 oplock_request,
    1928                                 lck,
    1929                                 &batch_entry,
    1930                                 &exclusive_entry,
    1931                                 &got_level2_oplock,
    1932                                 &got_a_none_oplock);
    1933 
    1934                 /* First pass - send break only on batch oplocks. */
    1935                 if ((req != NULL) &&
    1936                                 delay_for_batch_oplocks(fsp,
    1937                                         req->mid,
    1938                                         oplock_request,
    1939                                         batch_entry)) {
    1940                         schedule_defer_open(lck, request_time, req);
    1941                         TALLOC_FREE(lck);
    1942                         return NT_STATUS_SHARING_VIOLATION;
    1943                 }
    1944 
    1945                 /* Use the client requested access mask here, not the one we
    1946                  * open with. */
    1947                 status = open_mode_check(conn, lck, fsp->name_hash,
    1948                                         access_mask, share_access,
    1949                                          create_options, &file_existed);
    1950 
    1951                 if (NT_STATUS_IS_OK(status)) {
    1952                         /* We might be going to allow this open. Check oplock
    1953                          * status again. */
    1954                         /* Second pass - send break for both batch or
    1955                          * exclusive oplocks. */
    1956                         if ((req != NULL) &&
    1957                                         delay_for_exclusive_oplocks(
    1958                                                 fsp,
    1959                                                 req->mid,
    1960                                                 oplock_request,
    1961                                                 exclusive_entry)) {
    1962                                 schedule_defer_open(lck, request_time, req);
    1963                                 TALLOC_FREE(lck);
    1964                                 return NT_STATUS_SHARING_VIOLATION;
    1965                         }
    1966                 }
    1967 
    1968                 if (NT_STATUS_EQUAL(status, NT_STATUS_DELETE_PENDING)) {
    1969                         /* DELETE_PENDING is not deferred for a second */
    1970                         TALLOC_FREE(lck);
    1971                         return status;
    1972                 }
    1973 
    1974                 grant_fsp_oplock_type(fsp,
    1975                                 br_lck,
    1976                                 oplock_request,
    1977                                 got_level2_oplock,
    1978                                 got_a_none_oplock);
    1979 
    1980                 if (!NT_STATUS_IS_OK(status)) {
    1981                         uint32 can_access_mask;
    1982                         bool can_access = True;
    1983 
    1984                         SMB_ASSERT(NT_STATUS_EQUAL(status, NT_STATUS_SHARING_VIOLATION));
    1985 
    1986                         /* Check if this can be done with the deny_dos and fcb
    1987                          * calls. */
    1988                         if (private_flags &
    1989                             (NTCREATEX_OPTIONS_PRIVATE_DENY_DOS|
    1990                              NTCREATEX_OPTIONS_PRIVATE_DENY_FCB)) {
    1991                                 if (req == NULL) {
    1992                                         DEBUG(0, ("DOS open without an SMB "
    1993                                                   "request!\n"));
    1994                                         TALLOC_FREE(lck);
    1995                                         return NT_STATUS_INTERNAL_ERROR;
    1996                                 }
    1997 
    1998                                 /* Use the client requested access mask here,
    1999                                  * not the one we open with. */
    2000                                 status = fcb_or_dos_open(req,
    2001                                                         conn,
    2002                                                         fsp,
    2003                                                         smb_fname,
    2004                                                         id,
    2005                                                         req->smbpid,
    2006                                                         req->vuid,
    2007                                                         access_mask,
    2008                                                         share_access,
    2009                                                         create_options);
    2010 
    2011                                 if (NT_STATUS_IS_OK(status)) {
    2012                                         TALLOC_FREE(lck);
    2013                                         if (pinfo) {
    2014                                                 *pinfo = FILE_WAS_OPENED;
    2015                                         }
    2016                                         return NT_STATUS_OK;
    2017                                 }
    2018                         }
    2019 
    2020                         /*
    2021                          * This next line is a subtlety we need for
    2022                          * MS-Access. If a file open will fail due to share
    2023                          * permissions and also for security (access) reasons,
    2024                          * we need to return the access failed error, not the
    2025                          * share error. We can't open the file due to kernel
    2026                          * oplock deadlock (it's possible we failed above on
    2027                          * the open_mode_check()) so use a userspace check.
    2028                          */
    2029 
    2030                         if (flags & O_RDWR) {
    2031                                 can_access_mask = FILE_READ_DATA|FILE_WRITE_DATA;
    2032                         } else if (flags & O_WRONLY) {
    2033                                 can_access_mask = FILE_WRITE_DATA;
    2034                         } else {
    2035                                 can_access_mask = FILE_READ_DATA;
    2036                         }
    2037 
    2038                         if (((can_access_mask & FILE_WRITE_DATA) &&
    2039                                 !CAN_WRITE(conn)) ||
    2040                             !can_access_file_data(conn, smb_fname,
    2041                                                   can_access_mask)) {
    2042                                 can_access = False;
    2043                         }
    2044 
    2045                         /*
    2046                          * If we're returning a share violation, ensure we
    2047                          * cope with the braindead 1 second delay (SMB1 only).
    2048                          */
    2049 
    2050                         if (!(oplock_request & INTERNAL_OPEN_ONLY) &&
    2051                             !conn->sconn->using_smb2 &&
    2052                             lp_defer_sharing_violations()) {
    2053                                 struct timeval timeout;
    2054                                 struct deferred_open_record state;
    2055                                 int timeout_usecs;
    2056 
    2057                                 /* this is a hack to speed up torture tests
    2058                                    in 'make test' */
    2059                                 timeout_usecs = lp_parm_int(SNUM(conn),
    2060                                                             "smbd","sharedelay",
    2061                                                             SHARING_VIOLATION_USEC_WAIT);
    2062 
    2063                                 /* This is a relative time, added to the absolute
    2064                                    request_time value to get the absolute timeout time.
    2065                                    Note that if this is the second or greater time we enter
    2066                                    this codepath for this particular request mid then
    2067                                    request_time is left as the absolute time of the *first*
    2068                                    time this request mid was processed. This is what allows
    2069                                    the request to eventually time out. */
    2070 
    2071                                 timeout = timeval_set(0, timeout_usecs);
    2072 
    2073                                 /* Nothing actually uses state.delayed_for_oplocks
    2074                                    but it's handy to differentiate in debug messages
    2075                                    between a 30 second delay due to oplock break, and
    2076                                    a 1 second delay for share mode conflicts. */
    2077 
    2078                                 state.delayed_for_oplocks = False;
    2079                                 state.id = id;
    2080 
    2081                                 if ((req != NULL)
    2082                                     && !request_timed_out(request_time,
    2083                                                           timeout)) {
    2084                                         defer_open(lck, request_time, timeout,
    2085                                                    req, &state);
    2086                                 }
    2087                         }
    2088 
    2089                         TALLOC_FREE(lck);
    2090                         if (can_access) {
    2091                                 /*
    2092                                  * We have detected a sharing violation here
    2093                                  * so return the correct error code
    2094                                  */
    2095                                 status = NT_STATUS_SHARING_VIOLATION;
    2096                         } else {
    2097                                 status = NT_STATUS_ACCESS_DENIED;
    2098                         }
    2099                         return status;
    2100                 }
    2101 
    2102                 /*
    2103                  * We exit this block with the share entry *locked*.....
    2104                  */
    2105         }
    2106 
    2107         SMB_ASSERT(!file_existed || (lck != NULL));
    21082715
    21092716        /*
     
    21222729                 (unsigned int)open_access_mask));
    21232730
    2124         /*
    2125          * open_file strips any O_TRUNC flags itself.
    2126          */
    2127 
    21282731        fsp_open = open_file(fsp, conn, req, parent_dir,
    21292732                             flags|flags2, unx_mode, access_mask,
    2130                              open_access_mask);
     2733                             open_access_mask, &new_file_created);
     2734
     2735        if (NT_STATUS_EQUAL(fsp_open, NT_STATUS_NETWORK_BUSY)) {
     2736                struct deferred_open_record state;
     2737
     2738                /*
     2739                 * EWOULDBLOCK/EAGAIN maps to NETWORK_BUSY.
     2740                 */
     2741                if (file_existed && S_ISFIFO(fsp->fsp_name->st.st_ex_mode)) {
     2742                        DEBUG(10, ("FIFO busy\n"));
     2743                        return NT_STATUS_NETWORK_BUSY;
     2744                }
     2745                if (req == NULL) {
     2746                        DEBUG(10, ("Internal open busy\n"));
     2747                        return NT_STATUS_NETWORK_BUSY;
     2748                }
     2749
     2750                /*
     2751                 * From here on we assume this is an oplock break triggered
     2752                 */
     2753
     2754                lck = get_existing_share_mode_lock(talloc_tos(), fsp->file_id);
     2755                if (lck == NULL) {
     2756                        state.delayed_for_oplocks = false;
     2757                        state.async_open = false;
     2758                        state.id = fsp->file_id;
     2759                        defer_open(NULL, request_time, timeval_set(0, 0),
     2760                                   req, &state);
     2761                        DEBUG(10, ("No share mode lock found after "
     2762                                   "EWOULDBLOCK, retrying sync\n"));
     2763                        return NT_STATUS_SHARING_VIOLATION;
     2764                }
     2765
     2766                if (!validate_oplock_types(lck)) {
     2767                        smb_panic("validate_oplock_types failed");
     2768                }
     2769
     2770                if (delay_for_oplock(fsp, 0, lease, lck, false,
     2771                                     create_disposition, first_open_attempt)) {
     2772                        schedule_defer_open(lck, fsp->file_id, request_time,
     2773                                            req);
     2774                        TALLOC_FREE(lck);
     2775                        DEBUG(10, ("Sent oplock break request to kernel "
     2776                                   "oplock holder\n"));
     2777                        return NT_STATUS_SHARING_VIOLATION;
     2778                }
     2779
     2780                /*
     2781                 * No oplock from Samba around. Immediately retry with
     2782                 * a blocking open.
     2783                 */
     2784                state.delayed_for_oplocks = false;
     2785                state.async_open = false;
     2786                state.id = fsp->file_id;
     2787                defer_open(lck, request_time, timeval_set(0, 0), req, &state);
     2788                TALLOC_FREE(lck);
     2789                DEBUG(10, ("No Samba oplock around after EWOULDBLOCK. "
     2790                           "Retrying sync\n"));
     2791                return NT_STATUS_SHARING_VIOLATION;
     2792        }
    21312793
    21322794        if (!NT_STATUS_IS_OK(fsp_open)) {
    2133                 if (lck != NULL) {
    2134                         TALLOC_FREE(lck);
     2795                if (NT_STATUS_EQUAL(fsp_open, NT_STATUS_RETRY)) {
     2796                        schedule_async_open(request_time, req);
    21352797                }
    21362798                return fsp_open;
    21372799        }
    21382800
    2139         if (!file_existed) {
    2140                 struct byte_range_lock *br_lck = NULL;
    2141                 struct share_mode_entry *batch_entry = NULL;
    2142                 struct share_mode_entry *exclusive_entry = NULL;
    2143                 bool got_level2_oplock = false;
    2144                 bool got_a_none_oplock = false;
    2145                 struct timespec old_write_time = smb_fname->st.st_ex_mtime;
     2801        if (new_file_created) {
    21462802                /*
    2147                  * Deal with the race condition where two smbd's detect the
    2148                  * file doesn't exist and do the create at the same time. One
    2149                  * of them will win and set a share mode, the other (ie. this
    2150                  * one) should check if the requested share mode for this
    2151                  * create is allowed.
     2803                 * As we atomically create using O_CREAT|O_EXCL,
     2804                 * then if new_file_created is true, then
     2805                 * file_existed *MUST* have been false (even
     2806                 * if the file was previously detected as being
     2807                 * there).
    21522808                 */
    2153 
     2809                file_existed = false;
     2810        }
     2811
     2812        if (file_existed && !check_same_dev_ino(&saved_stat, &smb_fname->st)) {
    21542813                /*
    2155                  * Now the file exists and fsp is successfully opened,
    2156                  * fsp->dev and fsp->inode are valid and should replace the
    2157                  * dev=0,inode=0 from a non existent file. Spotted by
    2158                  * Nadav Danieli <nadavd@exanet.com>. JRA.
     2814                 * The file did exist, but some other (local or NFS)
     2815                 * process either renamed/unlinked and re-created the
     2816                 * file with different dev/ino after we walked the path,
     2817                 * but before we did the open. We could retry the
     2818                 * open but it's a rare enough case it's easier to
     2819                 * just fail the open to prevent creating any problems
     2820                 * in the open file db having the wrong dev/ino key.
    21592821                 */
    2160 
    2161                 id = fsp->file_id;
    2162 
    2163                 if (!acquire_ordered_locks(talloc_tos(),
    2164                                         fsp,
    2165                                         id,
    2166                                         conn->connectpath,
    2167                                         smb_fname,
    2168                                         &old_write_time,
    2169                                         &lck,
    2170                                         &br_lck)) {
    2171                         return NT_STATUS_SHARING_VIOLATION;
    2172                 }
    2173 
    2174                 /* Get the types we need to examine. */
    2175                 find_oplock_types(fsp,
    2176                                 oplock_request,
    2177                                 lck,
    2178                                 &batch_entry,
    2179                                 &exclusive_entry,
    2180                                 &got_level2_oplock,
    2181                                 &got_a_none_oplock);
    2182 
    2183                 /* First pass - send break only on batch oplocks. */
    2184                 if ((req != NULL) &&
    2185                                 delay_for_batch_oplocks(fsp,
    2186                                         req->mid,
    2187                                         oplock_request,
    2188                                         batch_entry)) {
    2189                         schedule_defer_open(lck, request_time, req);
     2822                fd_close(fsp);
     2823                DEBUG(1,("open_file_ntcreate: file %s - dev/ino mismatch. "
     2824                        "Old (dev=0x%llu, ino =0x%llu). "
     2825                        "New (dev=0x%llu, ino=0x%llu). Failing open "
     2826                        " with NT_STATUS_ACCESS_DENIED.\n",
     2827                         smb_fname_str_dbg(smb_fname),
     2828                         (unsigned long long)saved_stat.st_ex_dev,
     2829                         (unsigned long long)saved_stat.st_ex_ino,
     2830                         (unsigned long long)smb_fname->st.st_ex_dev,
     2831                         (unsigned long long)smb_fname->st.st_ex_ino));
     2832                return NT_STATUS_ACCESS_DENIED;
     2833        }
     2834
     2835        old_write_time = smb_fname->st.st_ex_mtime;
     2836
     2837        /*
     2838         * Deal with the race condition where two smbd's detect the
     2839         * file doesn't exist and do the create at the same time. One
     2840         * of them will win and set a share mode, the other (ie. this
     2841         * one) should check if the requested share mode for this
     2842         * create is allowed.
     2843         */
     2844
     2845        /*
     2846         * Now the file exists and fsp is successfully opened,
     2847         * fsp->dev and fsp->inode are valid and should replace the
     2848         * dev=0,inode=0 from a non existent file. Spotted by
     2849         * Nadav Danieli <nadavd@exanet.com>. JRA.
     2850         */
     2851
     2852        id = fsp->file_id;
     2853
     2854        lck = get_share_mode_lock(talloc_tos(), id,
     2855                                  conn->connectpath,
     2856                                  smb_fname, &old_write_time);
     2857
     2858        if (lck == NULL) {
     2859                DEBUG(0, ("open_file_ntcreate: Could not get share "
     2860                          "mode lock for %s\n",
     2861                          smb_fname_str_dbg(smb_fname)));
     2862                fd_close(fsp);
     2863                return NT_STATUS_SHARING_VIOLATION;
     2864        }
     2865
     2866        /* Get the types we need to examine. */
     2867        if (!validate_oplock_types(lck)) {
     2868                smb_panic("validate_oplock_types failed");
     2869        }
     2870
     2871        if (has_delete_on_close(lck, fsp->name_hash)) {
     2872                TALLOC_FREE(lck);
     2873                fd_close(fsp);
     2874                return NT_STATUS_DELETE_PENDING;
     2875        }
     2876
     2877        status = open_mode_check(conn, lck,
     2878                                 access_mask, share_access);
     2879
     2880        if (NT_STATUS_EQUAL(status, NT_STATUS_SHARING_VIOLATION) ||
     2881            (lck->data->num_share_modes > 0)) {
     2882                /*
     2883                 * This comes from ancient times out of open_mode_check. I
     2884                 * have no clue whether this is still necessary. I can't think
     2885                 * of a case where this would actually matter further down in
     2886                 * this function. I leave it here for further investigation
     2887                 * :-)
     2888                 */
     2889                file_existed = true;
     2890        }
     2891
     2892        if ((req != NULL) &&
     2893            delay_for_oplock(
     2894                    fsp, oplock_request, lease, lck,
     2895                    NT_STATUS_EQUAL(status, NT_STATUS_SHARING_VIOLATION),
     2896                    create_disposition, first_open_attempt)) {
     2897                schedule_defer_open(lck, fsp->file_id, request_time, req);
     2898                TALLOC_FREE(lck);
     2899                fd_close(fsp);
     2900                return NT_STATUS_SHARING_VIOLATION;
     2901        }
     2902
     2903        if (!NT_STATUS_IS_OK(status)) {
     2904                uint32_t can_access_mask;
     2905                bool can_access = True;
     2906
     2907                SMB_ASSERT(NT_STATUS_EQUAL(status, NT_STATUS_SHARING_VIOLATION));
     2908
     2909                /* Check if this can be done with the deny_dos and fcb
     2910                 * calls. */
     2911                if (private_flags &
     2912                    (NTCREATEX_OPTIONS_PRIVATE_DENY_DOS|
     2913                     NTCREATEX_OPTIONS_PRIVATE_DENY_FCB)) {
     2914                        if (req == NULL) {
     2915                                DEBUG(0, ("DOS open without an SMB "
     2916                                          "request!\n"));
     2917                                TALLOC_FREE(lck);
     2918                                fd_close(fsp);
     2919                                return NT_STATUS_INTERNAL_ERROR;
     2920                        }
     2921
     2922                        /* Use the client requested access mask here,
     2923                         * not the one we open with. */
     2924                        status = fcb_or_dos_open(req,
     2925                                                 conn,
     2926                                                 fsp,
     2927                                                 smb_fname,
     2928                                                 id,
     2929                                                 req->smbpid,
     2930                                                 req->vuid,
     2931                                                 access_mask,
     2932                                                 share_access,
     2933                                                 create_options);
     2934
     2935                        if (NT_STATUS_IS_OK(status)) {
     2936                                TALLOC_FREE(lck);
     2937                                if (pinfo) {
     2938                                        *pinfo = FILE_WAS_OPENED;
     2939                                }
     2940                                return NT_STATUS_OK;
     2941                        }
     2942                }
     2943
     2944                /*
     2945                 * This next line is a subtlety we need for
     2946                 * MS-Access. If a file open will fail due to share
     2947                 * permissions and also for security (access) reasons,
     2948                 * we need to return the access failed error, not the
     2949                 * share error. We can't open the file due to kernel
     2950                 * oplock deadlock (it's possible we failed above on
     2951                 * the open_mode_check()) so use a userspace check.
     2952                 */
     2953
     2954                if (flags & O_RDWR) {
     2955                        can_access_mask = FILE_READ_DATA|FILE_WRITE_DATA;
     2956                } else if (flags & O_WRONLY) {
     2957                        can_access_mask = FILE_WRITE_DATA;
     2958                } else {
     2959                        can_access_mask = FILE_READ_DATA;
     2960                }
     2961
     2962                if (((can_access_mask & FILE_WRITE_DATA) &&
     2963                     !CAN_WRITE(conn)) ||
     2964                    !NT_STATUS_IS_OK(smbd_check_access_rights(conn,
     2965                                                              smb_fname,
     2966                                                              false,
     2967                                                              can_access_mask))) {
     2968                        can_access = False;
     2969                }
     2970
     2971                /*
     2972                 * If we're returning a share violation, ensure we
     2973                 * cope with the braindead 1 second delay (SMB1 only).
     2974                 */
     2975
     2976                if (!(oplock_request & INTERNAL_OPEN_ONLY) &&
     2977                    !conn->sconn->using_smb2 &&
     2978                    lp_defer_sharing_violations()) {
     2979                        struct timeval timeout;
     2980                        struct deferred_open_record state;
     2981                        int timeout_usecs;
     2982
     2983                        /* this is a hack to speed up torture tests
     2984                           in 'make test' */
     2985                        timeout_usecs = lp_parm_int(SNUM(conn),
     2986                                                    "smbd","sharedelay",
     2987                                                    SHARING_VIOLATION_USEC_WAIT);
     2988
     2989                        /* This is a relative time, added to the absolute
     2990                           request_time value to get the absolute timeout time.
     2991                           Note that if this is the second or greater time we enter
     2992                           this codepath for this particular request mid then
     2993                           request_time is left as the absolute time of the *first*
     2994                           time this request mid was processed. This is what allows
     2995                           the request to eventually time out. */
     2996
     2997                        timeout = timeval_set(0, timeout_usecs);
     2998
     2999                        /* Nothing actually uses state.delayed_for_oplocks
     3000                           but it's handy to differentiate in debug messages
     3001                           between a 30 second delay due to oplock break, and
     3002                           a 1 second delay for share mode conflicts. */
     3003
     3004                        state.delayed_for_oplocks = False;
     3005                        state.async_open = false;
     3006                        state.id = id;
     3007
     3008                        if ((req != NULL)
     3009                            && !request_timed_out(request_time,
     3010                                                  timeout)) {
     3011                                defer_open(lck, request_time, timeout,
     3012                                           req, &state);
     3013                        }
     3014                }
     3015
     3016                TALLOC_FREE(lck);
     3017                fd_close(fsp);
     3018                if (can_access) {
     3019                        /*
     3020                         * We have detected a sharing violation here
     3021                         * so return the correct error code
     3022                         */
     3023                        status = NT_STATUS_SHARING_VIOLATION;
     3024                } else {
     3025                        status = NT_STATUS_ACCESS_DENIED;
     3026                }
     3027                return status;
     3028        }
     3029
     3030        /* Should we atomically (to the client at least) truncate ? */
     3031        if ((!new_file_created) &&
     3032            (flags2 & O_TRUNC) &&
     3033            (!S_ISFIFO(fsp->fsp_name->st.st_ex_mode))) {
     3034                int ret;
     3035
     3036                ret = vfs_set_filelen(fsp, 0);
     3037                if (ret != 0) {
     3038                        status = map_nt_error_from_unix(errno);
    21903039                        TALLOC_FREE(lck);
    21913040                        fd_close(fsp);
    2192                         return NT_STATUS_SHARING_VIOLATION;
    2193                 }
    2194 
    2195                 status = open_mode_check(conn, lck, fsp->name_hash,
    2196                                         access_mask, share_access,
    2197                                          create_options, &file_existed);
    2198 
    2199                 if (NT_STATUS_IS_OK(status)) {
    2200                         /* We might be going to allow this open. Check oplock
    2201                          * status again. */
    2202                         /* Second pass - send break for both batch or
    2203                          * exclusive oplocks. */
    2204                         if ((req != NULL) &&
    2205                                         delay_for_exclusive_oplocks(
    2206                                                 fsp,
    2207                                                 req->mid,
    2208                                                 oplock_request,
    2209                                                 exclusive_entry)) {
    2210                                 schedule_defer_open(lck, request_time, req);
    2211                                 TALLOC_FREE(lck);
    2212                                 fd_close(fsp);
    2213                                 return NT_STATUS_SHARING_VIOLATION;
    2214                         }
    2215                 }
    2216 
    2217                 if (!NT_STATUS_IS_OK(status)) {
    2218                         struct deferred_open_record state;
    2219 
    2220                         fd_close(fsp);
    2221 
    2222                         state.delayed_for_oplocks = False;
    2223                         state.id = id;
    2224 
    2225                         /* Do it all over again immediately. In the second
    2226                          * round we will find that the file existed and handle
    2227                          * the DELETE_PENDING and FCB cases correctly. No need
    2228                          * to duplicate the code here. Essentially this is a
    2229                          * "goto top of this function", but don't tell
    2230                          * anybody... */
    2231 
    2232                         if (req != NULL) {
    2233                                 defer_open(lck, request_time, timeval_zero(),
    2234                                            req, &state);
    2235                         }
    2236                         TALLOC_FREE(lck);
    22373041                        return status;
    22383042                }
    2239 
    2240                 grant_fsp_oplock_type(fsp,
    2241                                 br_lck,
    2242                                 oplock_request,
    2243                                 got_level2_oplock,
    2244                                 got_a_none_oplock);
    2245 
    2246                 /*
    2247                  * We exit this block with the share entry *locked*.....
    2248                  */
    2249 
    2250         }
    2251 
    2252         SMB_ASSERT(lck != NULL);
     3043        }
     3044
     3045        /*
     3046         * We have the share entry *locked*.....
     3047         */
    22533048
    22543049        /* Delete streams if create_disposition requires it */
    2255         if (file_existed && clear_ads &&
     3050        if (!new_file_created && clear_ads(create_disposition) &&
    22563051            !is_ntfs_stream_smb_fname(smb_fname)) {
    22573052                status = delete_all_streams(conn, smb_fname->base_name);
     
    22713066           note that GPFS supports it as well - jmcd */
    22723067
    2273         if (fsp->fh->fd != -1) {
     3068        if (fsp->fh->fd != -1 && lp_kernel_share_modes(SNUM(conn))) {
    22743069                int ret_flock;
     3070                /*
     3071                 * Beware: streams implementing VFS modules may
     3072                 * implement streams in a way that fsp will have the
     3073                 * basefile open in the fsp fd, so lacking a distinct
     3074                 * fd for the stream kernel_flock will apply on the
     3075                 * basefile which is wrong. The actual check is
     3076                 * deffered to the VFS module implementing the
     3077                 * kernel_flock call.
     3078                 */
    22753079                ret_flock = SMB_VFS_KERNEL_FLOCK(fsp, share_access, access_mask);
    22763080                if(ret_flock == -1 ){
     
    22843088
    22853089        /*
    2286          * At this point onwards, we can guarentee that the share entry
     3090         * At this point onwards, we can guarantee that the share entry
    22873091         * is locked, whether we created the file or not, and that the
    22883092         * deny mode is compatible with all current opens.
    22893093         */
    2290 
    2291         /*
    2292          * If requested, truncate the file.
    2293          */
    2294 
    2295         if (file_existed && (flags2&O_TRUNC)) {
    2296                 /*
    2297                  * We are modifing the file after open - update the stat
    2298                  * struct..
    2299                  */
    2300                 if ((SMB_VFS_FTRUNCATE(fsp, 0) == -1) ||
    2301                     (SMB_VFS_FSTAT(fsp, &smb_fname->st)==-1)) {
    2302                         status = map_nt_error_from_unix(errno);
    2303                         TALLOC_FREE(lck);
    2304                         fd_close(fsp);
    2305                         return status;
    2306                 }
    2307         }
    23083094
    23093095        /*
     
    23253111
    23263112        if (file_existed) {
    2327                 /* stat opens on existing files don't get oplocks. */
    2328                 if (is_stat_open(open_access_mask)) {
    2329                         fsp->oplock_type = NO_OPLOCK;
    2330                 }
    2331 
    2332                 if (!(flags2 & O_TRUNC)) {
     3113                /*
     3114                 * stat opens on existing files don't get oplocks.
     3115                 * They can get leases.
     3116                 *
     3117                 * Note that we check for stat open on the *open_access_mask*,
     3118                 * i.e. the access mask we actually used to do the open,
     3119                 * not the one the client asked for (which is in
     3120                 * fsp->access_mask). This is due to the fact that
     3121                 * FILE_OVERWRITE and FILE_OVERWRITE_IF add in O_TRUNC,
     3122                 * which adds FILE_WRITE_DATA to open_access_mask.
     3123                 */
     3124                if (is_stat_open(open_access_mask) && lease == NULL) {
     3125                        oplock_request = NO_OPLOCK;
     3126                }
     3127        }
     3128
     3129        if (new_file_created) {
     3130                info = FILE_WAS_CREATED;
     3131        } else {
     3132                if (flags2 & O_TRUNC) {
     3133                        info = FILE_WAS_OVERWRITTEN;
     3134                } else {
    23333135                        info = FILE_WAS_OPENED;
    2334                 } else {
    2335                         info = FILE_WAS_OVERWRITTEN;
    2336                 }
    2337         } else {
    2338                 info = FILE_WAS_CREATED;
     3136                }
    23393137        }
    23403138
     
    23473145         * file structs.
    23483146         */
    2349 
    2350         if (!set_file_oplock(fsp, fsp->oplock_type)) {
    2351                 /*
    2352                  * Could not get the kernel oplock or there are byte-range
    2353                  * locks on the file.
    2354                  */
    2355                 fsp->oplock_type = NO_OPLOCK;
    2356         }
    2357 
    2358         if (info == FILE_WAS_OVERWRITTEN || info == FILE_WAS_CREATED || info == FILE_WAS_SUPERSEDED) {
    2359                 new_file_created = True;
    2360         }
    2361 
    2362         set_share_mode(lck, fsp, get_current_uid(conn),
    2363                         req ? req->mid : 0,
    2364                        fsp->oplock_type);
     3147        status = grant_fsp_oplock_type(req, fsp, lck, oplock_request, lease);
     3148        if (!NT_STATUS_IS_OK(status)) {
     3149                TALLOC_FREE(lck);
     3150                fd_close(fsp);
     3151                return status;
     3152        }
    23653153
    23663154        /* Handle strange delete on close create semantics. */
     
    23813169        }
    23823170
    2383         if (new_file_created) {
    2384                 /* Files should be initially set as archive */
    2385                 if (lp_map_archive(SNUM(conn)) ||
     3171        if (info != FILE_WAS_OPENED) {
     3172                /* Overwritten files should be initially set as archive */
     3173                if ((info == FILE_WAS_OVERWRITTEN && lp_map_archive(SNUM(conn))) ||
    23863174                    lp_store_dos_attributes(SNUM(conn))) {
    23873175                        if (!posix_open) {
     
    24093197         */
    24103198
    2411         if (!posix_open && !file_existed && !def_acl) {
     3199        if (!posix_open && new_file_created && !def_acl) {
    24123200
    24133201                int saved_errno = errno; /* We might get ENOSYS in the next
     
    24493237        }
    24503238
    2451         /* If this is a successful open, we must remove any deferred open
    2452          * records. */
    2453         if (req != NULL) {
    2454                 del_deferred_open_entry(lck, req->mid,
    2455                                         sconn_server_id(req->sconn));
    2456         }
     3239        {
     3240                /*
     3241                 * Deal with other opens having a modified write time.
     3242                 */
     3243                struct timespec write_time = get_share_mode_write_time(lck);
     3244
     3245                if (!null_timespec(write_time)) {
     3246                        update_stat_ex_mtime(&fsp->fsp_name->st, write_time);
     3247                }
     3248        }
     3249
    24573250        TALLOC_FREE(lck);
    24583251
     
    24603253}
    24613254
    2462 
    2463 /****************************************************************************
    2464  Open a file for for write to ensure that we can fchmod it.
    2465 ****************************************************************************/
    2466 
    2467 NTSTATUS open_file_fchmod(connection_struct *conn,
    2468                           struct smb_filename *smb_fname,
    2469                           files_struct **result)
    2470 {
    2471         if (!VALID_STAT(smb_fname->st)) {
    2472                 return NT_STATUS_INVALID_PARAMETER;
    2473         }
    2474 
    2475         return SMB_VFS_CREATE_FILE(
    2476                 conn,                                   /* conn */
    2477                 NULL,                                   /* req */
    2478                 0,                                      /* root_dir_fid */
    2479                 smb_fname,                              /* fname */
    2480                 FILE_WRITE_DATA,                        /* access_mask */
    2481                 (FILE_SHARE_READ | FILE_SHARE_WRITE |   /* share_access */
    2482                     FILE_SHARE_DELETE),
    2483                 FILE_OPEN,                              /* create_disposition*/
    2484                 0,                                      /* create_options */
    2485                 0,                                      /* file_attributes */
    2486                 INTERNAL_OPEN_ONLY,                     /* oplock_request */
    2487                 0,                                      /* allocation_size */
    2488                 0,                                      /* private_flags */
    2489                 NULL,                                   /* sd */
    2490                 NULL,                                   /* ea_list */
    2491                 result,                                 /* result */
    2492                 NULL);                                  /* pinfo */
    2493 }
    2494 
    24953255static NTSTATUS mkdir_internal(connection_struct *conn,
    24963256                               struct smb_filename *smb_dname,
    2497                                uint32 file_attributes)
     3257                               uint32_t file_attributes)
    24983258{
    24993259        mode_t mode;
    2500         char *parent_dir;
     3260        char *parent_dir = NULL;
    25013261        NTSTATUS status;
    25023262        bool posix_open = false;
    25033263        bool need_re_stat = false;
    2504 
    2505         if(!CAN_WRITE(conn)) {
    2506                 DEBUG(5,("mkdir_internal: failing create on read-only share "
    2507                          "%s\n", lp_servicename(SNUM(conn))));
     3264        uint32_t access_mask = SEC_DIR_ADD_SUBDIR;
     3265
     3266        if (!CAN_WRITE(conn) || (access_mask & ~(conn->share_access))) {
     3267                DEBUG(5,("mkdir_internal: failing share access "
     3268                         "%s\n", lp_servicename(talloc_tos(), SNUM(conn))));
    25083269                return NT_STATUS_ACCESS_DENIED;
    2509         }
    2510 
    2511         status = check_name(conn, smb_dname->base_name);
    2512         if (!NT_STATUS_IS_OK(status)) {
    2513                 return status;
    25143270        }
    25153271
     
    25263282        }
    25273283
     3284        status = check_parent_access(conn,
     3285                                        smb_dname,
     3286                                        access_mask);
     3287        if(!NT_STATUS_IS_OK(status)) {
     3288                DEBUG(5,("mkdir_internal: check_parent_access "
     3289                        "on directory %s for path %s returned %s\n",
     3290                        parent_dir,
     3291                        smb_dname->base_name,
     3292                        nt_errstr(status) ));
     3293                return status;
     3294        }
     3295
    25283296        if (SMB_VFS_MKDIR(conn, smb_dname->base_name, mode) != 0) {
    25293297                return map_nt_error_from_unix(errno);
     
    25403308
    25413309        if (!S_ISDIR(smb_dname->st.st_ex_mode)) {
    2542                 DEBUG(0, ("Directory just '%s' created is not a directory\n",
     3310                DEBUG(0, ("Directory '%s' just created is not a directory !\n",
    25433311                          smb_fname_str_dbg(smb_dname)));
    2544                 return NT_STATUS_ACCESS_DENIED;
     3312                return NT_STATUS_NOT_A_DIRECTORY;
    25453313        }
    25463314
     
    25533321        }
    25543322
    2555         if (lp_inherit_perms(SNUM(conn))) {
     3323        if (lp_inherit_permissions(SNUM(conn))) {
    25563324                inherit_access_posix_acl(conn, parent_dir,
    25573325                                         smb_dname->base_name, mode);
     
    25983366
    25993367/****************************************************************************
    2600  Ensure we didn't get symlink raced on opening a directory.
    2601 ****************************************************************************/
    2602 
    2603 bool check_same_stat(const SMB_STRUCT_STAT *sbuf1,
    2604                         const SMB_STRUCT_STAT *sbuf2)
    2605 {
    2606         if (sbuf1->st_ex_uid != sbuf2->st_ex_uid ||
    2607                         sbuf1->st_ex_gid != sbuf2->st_ex_gid ||
    2608                         sbuf1->st_ex_dev != sbuf2->st_ex_dev ||
    2609                         sbuf1->st_ex_ino != sbuf2->st_ex_ino) {
    2610                 return false;
    2611         }
    2612         return true;
    2613 }
    2614 
    2615 /****************************************************************************
    26163368 Open a directory from an NT SMB call.
    26173369****************************************************************************/
     
    26203372                               struct smb_request *req,
    26213373                               struct smb_filename *smb_dname,
    2622                                uint32 access_mask,
    2623                                uint32 share_access,
    2624                                uint32 create_disposition,
    2625                                uint32 create_options,
    2626                                uint32 file_attributes,
     3374                               uint32_t access_mask,
     3375                               uint32_t share_access,
     3376                               uint32_t create_disposition,
     3377                               uint32_t create_options,
     3378                               uint32_t file_attributes,
    26273379                               int *pinfo,
    26283380                               files_struct **result)
     
    26343386        struct timespec mtimespec;
    26353387        int info = 0;
    2636 
    2637         SMB_ASSERT(!is_ntfs_stream_smb_fname(smb_dname));
     3388        bool ok;
     3389
     3390        if (is_ntfs_stream_smb_fname(smb_dname)) {
     3391                DEBUG(2, ("open_directory: %s is a stream name!\n",
     3392                          smb_fname_str_dbg(smb_dname)));
     3393                return NT_STATUS_NOT_A_DIRECTORY;
     3394        }
    26383395
    26393396        if (!(file_attributes & FILE_FLAG_POSIX_SEMANTICS)) {
     
    26523409                 (unsigned int)file_attributes));
    26533410
    2654         if (!(file_attributes & FILE_FLAG_POSIX_SEMANTICS) &&
    2655                         (conn->fs_capabilities & FILE_NAMED_STREAMS) &&
    2656                         is_ntfs_stream_smb_fname(smb_dname)) {
    2657                 DEBUG(2, ("open_directory: %s is a stream name!\n",
    2658                           smb_fname_str_dbg(smb_dname)));
    2659                 return NT_STATUS_NOT_A_DIRECTORY;
    2660         }
    2661 
    2662         status = smbd_calculate_access_mask(conn, smb_dname, dir_existed,
     3411        status = smbd_calculate_access_mask(conn, smb_dname, false,
    26633412                                            access_mask, &access_mask);
    26643413        if (!NT_STATUS_IS_OK(status)) {
     
    26943443                         * exist create. */
    26953444
     3445                        if (dir_existed) {
     3446                                status = NT_STATUS_OBJECT_NAME_COLLISION;
     3447                                DEBUG(2, ("open_directory: unable to create "
     3448                                          "%s. Error was %s\n",
     3449                                          smb_fname_str_dbg(smb_dname),
     3450                                          nt_errstr(status)));
     3451                                return status;
     3452                        }
     3453
    26963454                        status = mkdir_internal(conn, smb_dname,
    26973455                                                file_attributes);
     
    27143472                         */
    27153473
    2716                         status = mkdir_internal(conn, smb_dname,
     3474                        if (dir_existed) {
     3475                                status = NT_STATUS_OK;
     3476                                info = FILE_WAS_OPENED;
     3477                        } else {
     3478                                status = mkdir_internal(conn, smb_dname,
    27173479                                                file_attributes);
    27183480
    2719                         if (NT_STATUS_IS_OK(status)) {
    2720                                 info = FILE_WAS_CREATED;
     3481                                if (NT_STATUS_IS_OK(status)) {
     3482                                        info = FILE_WAS_CREATED;
     3483                                } else {
     3484                                        /* Cope with create race. */
     3485                                        if (!NT_STATUS_EQUAL(status,
     3486                                                        NT_STATUS_OBJECT_NAME_COLLISION)) {
     3487                                                DEBUG(2, ("open_directory: unable to create "
     3488                                                        "%s. Error was %s\n",
     3489                                                        smb_fname_str_dbg(smb_dname),
     3490                                                        nt_errstr(status)));
     3491                                                return status;
     3492                                        }
     3493
     3494                                        /*
     3495                                         * If mkdir_internal() returned
     3496                                         * NT_STATUS_OBJECT_NAME_COLLISION
     3497                                         * we still must lstat the path.
     3498                                         */
     3499
     3500                                        if (SMB_VFS_LSTAT(conn, smb_dname)
     3501                                                        == -1) {
     3502                                                DEBUG(2, ("Could not stat "
     3503                                                        "directory '%s' just "
     3504                                                        "opened: %s\n",
     3505                                                        smb_fname_str_dbg(
     3506                                                                smb_dname),
     3507                                                        strerror(errno)));
     3508                                                return map_nt_error_from_unix(
     3509                                                                errno);
     3510                                        }
     3511
     3512                                        info = FILE_WAS_OPENED;
     3513                                }
    27213514                        }
    27223515
    2723                         if (NT_STATUS_EQUAL(status,
    2724                                             NT_STATUS_OBJECT_NAME_COLLISION)) {
    2725                                 info = FILE_WAS_OPENED;
    2726                                 status = NT_STATUS_OK;
    2727                         }
    27283516                        break;
    27293517
     
    27463534
    27473535        if (info == FILE_WAS_OPENED) {
    2748                 uint32_t access_granted = 0;
    2749                 status = smbd_check_open_rights(conn, smb_dname, access_mask,
    2750                                                 &access_granted);
    2751 
    2752                 /* Were we trying to do a directory open
    2753                  * for delete and didn't get DELETE
    2754                  * access (only) ? Check if the
    2755                  * directory allows DELETE_CHILD.
    2756                  * See here:
    2757                  * http://blogs.msdn.com/oldnewthing/archive/2004/06/04/148426.aspx
    2758                  * for details. */
    2759 
    2760                 if ((NT_STATUS_EQUAL(status, NT_STATUS_ACCESS_DENIED) &&
    2761                         (access_mask & DELETE_ACCESS) &&
    2762                         (access_granted == DELETE_ACCESS) &&
    2763                         can_delete_file_in_directory(conn, smb_dname))) {
    2764                         DEBUG(10,("open_directory: overrode ACCESS_DENIED "
    2765                                 "on directory %s\n",
    2766                                 smb_fname_str_dbg(smb_dname)));
    2767                         status = NT_STATUS_OK;
    2768                 }
    2769 
     3536                status = smbd_check_access_rights(conn,
     3537                                                smb_dname,
     3538                                                false,
     3539                                                access_mask);
    27703540                if (!NT_STATUS_IS_OK(status)) {
    2771                         DEBUG(10, ("open_directory: smbd_check_open_rights on "
     3541                        DEBUG(10, ("open_directory: smbd_check_access_rights on "
    27723542                                "file %s failed with %s\n",
    27733543                                smb_fname_str_dbg(smb_dname),
     
    27863556         */
    27873557
    2788         fsp->mode = smb_dname->st.st_ex_mode;
    27893558        fsp->file_id = vfs_file_id_from_sbuf(conn, &smb_dname->st);
    27903559        fsp->vuid = req ? req->vuid : UID_FIELD_INVALID;
     
    27963565        fsp->share_access = share_access;
    27973566        fsp->fh->private_options = 0;
     3567        /*
     3568         * According to Samba4, SEC_FILE_READ_ATTRIBUTE is always granted,
     3569         */
     3570        fsp->access_mask = access_mask | FILE_READ_ATTRIBUTES;
    27983571        fsp->print_file = NULL;
    27993572        fsp->modified = False;
     
    28013574        fsp->sent_oplock_break = NO_BREAK_SENT;
    28023575        fsp->is_directory = True;
    2803         fsp->posix_open = (file_attributes & FILE_FLAG_POSIX_SEMANTICS) ? True : False;
     3576        if (file_attributes & FILE_FLAG_POSIX_SEMANTICS) {
     3577                fsp->posix_flags |= FSP_POSIX_FLAGS_ALL;
     3578        }
    28043579        status = fsp_set_smb_fname(fsp, smb_dname);
    28053580        if (!NT_STATUS_IS_OK(status)) {
     
    28083583        }
    28093584
    2810         mtimespec = smb_dname->st.st_ex_mtime;
    2811 
    2812         fsp->access_mask = access_mask;
    2813 
     3585        /* Don't store old timestamps for directory
     3586           handles in the internal database. We don't
     3587           update them in there if new objects
     3588           are creaded in the directory. Currently
     3589           we only update timestamps on file writes.
     3590           See bug #9870.
     3591        */
     3592        ZERO_STRUCT(mtimespec);
     3593
     3594        if (access_mask & (FILE_LIST_DIRECTORY|
     3595                           FILE_ADD_FILE|
     3596                           FILE_ADD_SUBDIRECTORY|
     3597                           FILE_TRAVERSE|
     3598                           DELETE_ACCESS|
     3599                           FILE_DELETE_CHILD)) {
    28143600#ifdef O_DIRECTORY
    2815         status = fd_open(conn, fsp, O_RDONLY|O_DIRECTORY, 0);
     3601                status = fd_open(conn, fsp, O_RDONLY|O_DIRECTORY, 0);
    28163602#else
    2817         /* POSIX allows us to open a directory with O_RDONLY. */
    2818         status = fd_open(conn, fsp, O_RDONLY, 0);
     3603                /* POSIX allows us to open a directory with O_RDONLY. */
     3604                status = fd_open(conn, fsp, O_RDONLY, 0);
    28193605#endif
    2820         if (!NT_STATUS_IS_OK(status)) {
    2821                 DEBUG(5, ("open_directory: Could not open fd for "
    2822                         "%s (%s)\n",
    2823                         smb_fname_str_dbg(smb_dname),
    2824                         nt_errstr(status)));
    2825                 file_free(req, fsp);
    2826                 return status;
    2827         }
    2828 
    2829         /*
    2830          * According to Samba4, SEC_FILE_READ_ATTRIBUTE is always granted,
    2831          * Set the real access mask for later access (possibly delete).
    2832          */
    2833         fsp->access_mask = access_mask | FILE_READ_ATTRIBUTES;
     3606                if (!NT_STATUS_IS_OK(status)) {
     3607                        DEBUG(5, ("open_directory: Could not open fd for "
     3608                                "%s (%s)\n",
     3609                                smb_fname_str_dbg(smb_dname),
     3610                                nt_errstr(status)));
     3611                        file_free(req, fsp);
     3612                        return status;
     3613                }
     3614        } else {
     3615                fsp->fh->fd = -1;
     3616                DEBUG(10, ("Not opening Directory %s\n",
     3617                        smb_fname_str_dbg(smb_dname)));
     3618        }
    28343619
    28353620        status = vfs_stat_fsp(fsp);
     
    28403625        }
    28413626
    2842         /* Ensure there was no race condition. */
    2843         if (!check_same_stat(&smb_dname->st, &fsp->fsp_name->st)) {
     3627        if(!S_ISDIR(fsp->fsp_name->st.st_ex_mode)) {
     3628                DEBUG(5,("open_directory: %s is not a directory !\n",
     3629                         smb_fname_str_dbg(smb_dname)));
     3630                fd_close(fsp);
     3631                file_free(req, fsp);
     3632                return NT_STATUS_NOT_A_DIRECTORY;
     3633        }
     3634
     3635        /* Ensure there was no race condition.  We need to check
     3636         * dev/inode but not permissions, as these can change
     3637         * legitimately */
     3638        if (!check_same_dev_ino(&smb_dname->st, &fsp->fsp_name->st)) {
    28443639                DEBUG(5,("open_directory: stat struct differs for "
    28453640                        "directory %s.\n",
     
    28513646
    28523647        lck = get_share_mode_lock(talloc_tos(), fsp->file_id,
    2853                                   conn->connectpath, smb_dname, &mtimespec);
     3648                                  conn->connectpath, smb_dname,
     3649                                  &mtimespec);
    28543650
    28553651        if (lck == NULL) {
     
    28613657        }
    28623658
    2863         status = open_mode_check(conn, lck, fsp->name_hash,
    2864                                 access_mask, share_access,
    2865                                  create_options, &dir_existed);
     3659        if (has_delete_on_close(lck, fsp->name_hash)) {
     3660                TALLOC_FREE(lck);
     3661                fd_close(fsp);
     3662                file_free(req, fsp);
     3663                return NT_STATUS_DELETE_PENDING;
     3664        }
     3665
     3666        status = open_mode_check(conn, lck,
     3667                                 access_mask, share_access);
    28663668
    28673669        if (!NT_STATUS_IS_OK(status)) {
     
    28723674        }
    28733675
    2874         set_share_mode(lck, fsp, get_current_uid(conn),
    2875                         req ? req->mid : 0, NO_OPLOCK);
     3676        ok = set_share_mode(lck, fsp, get_current_uid(conn),
     3677                            req ? req->mid : 0, NO_OPLOCK,
     3678                            UINT32_MAX);
     3679        if (!ok) {
     3680                TALLOC_FREE(lck);
     3681                fd_close(fsp);
     3682                file_free(req, fsp);
     3683                return NT_STATUS_NO_MEMORY;
     3684        }
    28763685
    28773686        /* For directories the delete on close bit at open time seems
     
    28803689                status = can_set_delete_on_close(fsp, 0);
    28813690                if (!NT_STATUS_IS_OK(status) && !NT_STATUS_EQUAL(status, NT_STATUS_DIRECTORY_NOT_EMPTY)) {
     3691                        del_share_mode(lck, fsp);
    28823692                        TALLOC_FREE(lck);
    28833693                        fd_close(fsp);
     
    28903700                           not the regular one. The magic gets handled in close. */
    28913701                        fsp->initial_delete_on_close = True;
     3702                }
     3703        }
     3704
     3705        {
     3706                /*
     3707                 * Deal with other opens having a modified write time. Is this
     3708                 * possible for directories?
     3709                 */
     3710                struct timespec write_time = get_share_mode_write_time(lck);
     3711
     3712                if (!null_timespec(write_time)) {
     3713                        update_stat_ex_mtime(&fsp->fsp_name->st, write_time);
    28923714                }
    28933715        }
     
    29203742                FILE_ATTRIBUTE_DIRECTORY,               /* file_attributes */
    29213743                0,                                      /* oplock_request */
     3744                NULL,                                   /* lease */
    29223745                0,                                      /* allocation_size */
    29233746                0,                                      /* private_flags */
     
    29253748                NULL,                                   /* ea_list */
    29263749                &fsp,                                   /* result */
    2927                 NULL);                                  /* pinfo */
     3750                NULL,                                   /* pinfo */
     3751                NULL, NULL);                            /* create context */
    29283752
    29293753        if (NT_STATUS_IS_OK(status)) {
     
    29453769                          DATA_BLOB *data)
    29463770{
    2947         struct smbd_server_connection *sconn;
    29483771        files_struct *fsp;
    29493772        char *frm = (char *)data->data;
     
    29553778        size_t sp_len, bn_len;
    29563779        NTSTATUS status;
    2957 
    2958         sconn = msg_ctx_to_sconn(msg);
    2959         if (sconn == NULL) {
    2960                 DEBUG(1, ("could not find sconn\n"));
    2961                 return;
    2962         }
     3780        struct smbd_server_connection *sconn =
     3781                talloc_get_type_abort(private_data,
     3782                struct smbd_server_connection);
    29633783
    29643784        if (data->data == NULL
     
    29823802        }
    29833803
    2984         status = create_synthetic_smb_fname(talloc_tos(), base_name,
    2985                                             stream_name, NULL, &smb_fname);
    2986         if (!NT_STATUS_IS_OK(status)) {
     3804        smb_fname = synthetic_smb_fname(talloc_tos(), base_name,
     3805                                        stream_name, NULL);
     3806        if (smb_fname == NULL) {
    29873807                return;
    29883808        }
     
    29973817                if (memcmp(fsp->conn->connectpath, sharepath, sp_len) == 0) {
    29983818
    2999                         DEBUG(10,("msg_file_was_renamed: renaming file fnum %d from %s -> %s\n",
    3000                                 fsp->fnum, fsp_str_dbg(fsp),
     3819                        DEBUG(10,("msg_file_was_renamed: renaming file %s from %s -> %s\n",
     3820                                fsp_fnum_dbg(fsp), fsp_str_dbg(fsp),
    30013821                                smb_fname_str_dbg(smb_fname)));
    30023822                        status = fsp_set_smb_fname(fsp, smb_fname);
     
    30103830                        DEBUG(10,("msg_file_was_renamed: share mismatch (sharepath %s "
    30113831                                "not sharepath %s) "
    3012                                 "fnum %d from %s -> %s\n",
     3832                                "%s from %s -> %s\n",
    30133833                                fsp->conn->connectpath,
    30143834                                sharepath,
    3015                                 fsp->fnum,
     3835                                fsp_fnum_dbg(fsp),
    30163836                                fsp_str_dbg(fsp),
    30173837                                smb_fname_str_dbg(smb_fname)));
     
    30633883        }
    30643884
    3065         streams = TALLOC_ARRAY(talloc_tos(), files_struct *, num_streams);
     3885        streams = talloc_array(talloc_tos(), files_struct *, num_streams);
    30663886        if (streams == NULL) {
    30673887                DEBUG(0, ("talloc failed\n"));
     
    30713891
    30723892        for (i=0; i<num_streams; i++) {
    3073                 struct smb_filename *smb_fname = NULL;
     3893                struct smb_filename *smb_fname;
    30743894
    30753895                if (strequal(stream_info[i].name, "::$DATA")) {
     
    30783898                }
    30793899
    3080                 status = create_synthetic_smb_fname(talloc_tos(), fname,
    3081                                                     stream_info[i].name,
    3082                                                     NULL, &smb_fname);
    3083                 if (!NT_STATUS_IS_OK(status)) {
     3900                smb_fname = synthetic_smb_fname(
     3901                        talloc_tos(), fname, stream_info[i].name, NULL);
     3902                if (smb_fname == NULL) {
     3903                        status = NT_STATUS_NO_MEMORY;
    30843904                        goto fail;
    30853905                }
     
    31023922                         FILE_ATTRIBUTE_NORMAL, /* file_attributes */
    31033923                         0,                     /* oplock_request */
     3924                         NULL,                  /* lease */
    31043925                         0,                     /* allocation_size */
    31053926                         NTCREATEX_OPTIONS_PRIVATE_STREAM_DELETE, /* private_flags */
     
    31073928                         NULL,                  /* ea_list */
    31083929                         &streams[i],           /* result */
    3109                          NULL);                 /* pinfo */
     3930                         NULL,                  /* pinfo */
     3931                         NULL, NULL);           /* create context */
    31103932
    31113933                if (!NT_STATUS_IS_OK(status)) {
     
    31373959        TALLOC_FREE(frame);
    31383960        return status;
     3961}
     3962
     3963/*********************************************************************
     3964 Create a default ACL by inheriting from the parent. If no inheritance
     3965 from the parent available, don't set anything. This will leave the actual
     3966 permissions the new file or directory already got from the filesystem
     3967 as the NT ACL when read.
     3968*********************************************************************/
     3969
     3970static NTSTATUS inherit_new_acl(files_struct *fsp)
     3971{
     3972        TALLOC_CTX *frame = talloc_stackframe();
     3973        char *parent_name = NULL;
     3974        struct security_descriptor *parent_desc = NULL;
     3975        NTSTATUS status = NT_STATUS_OK;
     3976        struct security_descriptor *psd = NULL;
     3977        const struct dom_sid *owner_sid = NULL;
     3978        const struct dom_sid *group_sid = NULL;
     3979        uint32_t security_info_sent = (SECINFO_OWNER | SECINFO_GROUP | SECINFO_DACL);
     3980        struct security_token *token = fsp->conn->session_info->security_token;
     3981        bool inherit_owner = lp_inherit_owner(SNUM(fsp->conn));
     3982        bool inheritable_components = false;
     3983        bool try_builtin_administrators = false;
     3984        const struct dom_sid *BA_U_sid = NULL;
     3985        const struct dom_sid *BA_G_sid = NULL;
     3986        bool try_system = false;
     3987        const struct dom_sid *SY_U_sid = NULL;
     3988        const struct dom_sid *SY_G_sid = NULL;
     3989        size_t size = 0;
     3990
     3991        if (!parent_dirname(frame, fsp->fsp_name->base_name, &parent_name, NULL)) {
     3992                TALLOC_FREE(frame);
     3993                return NT_STATUS_NO_MEMORY;
     3994        }
     3995
     3996        status = SMB_VFS_GET_NT_ACL(fsp->conn,
     3997                                    parent_name,
     3998                                    (SECINFO_OWNER | SECINFO_GROUP | SECINFO_DACL),
     3999                                    frame,
     4000                                    &parent_desc);
     4001        if (!NT_STATUS_IS_OK(status)) {
     4002                TALLOC_FREE(frame);
     4003                return status;
     4004        }
     4005
     4006        inheritable_components = sd_has_inheritable_components(parent_desc,
     4007                                        fsp->is_directory);
     4008
     4009        if (!inheritable_components && !inherit_owner) {
     4010                TALLOC_FREE(frame);
     4011                /* Nothing to inherit and not setting owner. */
     4012                return NT_STATUS_OK;
     4013        }
     4014
     4015        /* Create an inherited descriptor from the parent. */
     4016
     4017        if (DEBUGLEVEL >= 10) {
     4018                DEBUG(10,("inherit_new_acl: parent acl for %s is:\n",
     4019                        fsp_str_dbg(fsp) ));
     4020                NDR_PRINT_DEBUG(security_descriptor, parent_desc);
     4021        }
     4022
     4023        /* Inherit from parent descriptor if "inherit owner" set. */
     4024        if (inherit_owner) {
     4025                owner_sid = parent_desc->owner_sid;
     4026                group_sid = parent_desc->group_sid;
     4027        }
     4028
     4029        if (owner_sid == NULL) {
     4030                if (security_token_has_builtin_administrators(token)) {
     4031                        try_builtin_administrators = true;
     4032                } else if (security_token_is_system(token)) {
     4033                        try_builtin_administrators = true;
     4034                        try_system = true;
     4035                }
     4036        }
     4037
     4038        if (group_sid == NULL &&
     4039            token->num_sids == PRIMARY_GROUP_SID_INDEX)
     4040        {
     4041                if (security_token_is_system(token)) {
     4042                        try_builtin_administrators = true;
     4043                        try_system = true;
     4044                }
     4045        }
     4046
     4047        if (try_builtin_administrators) {
     4048                struct unixid ids;
     4049                bool ok;
     4050
     4051                ZERO_STRUCT(ids);
     4052                ok = sids_to_unixids(&global_sid_Builtin_Administrators, 1, &ids);
     4053                if (ok) {
     4054                        switch (ids.type) {
     4055                        case ID_TYPE_BOTH:
     4056                                BA_U_sid = &global_sid_Builtin_Administrators;
     4057                                BA_G_sid = &global_sid_Builtin_Administrators;
     4058                                break;
     4059                        case ID_TYPE_UID:
     4060                                BA_U_sid = &global_sid_Builtin_Administrators;
     4061                                break;
     4062                        case ID_TYPE_GID:
     4063                                BA_G_sid = &global_sid_Builtin_Administrators;
     4064                                break;
     4065                        default:
     4066                                break;
     4067                        }
     4068                }
     4069        }
     4070
     4071        if (try_system) {
     4072                struct unixid ids;
     4073                bool ok;
     4074
     4075                ZERO_STRUCT(ids);
     4076                ok = sids_to_unixids(&global_sid_System, 1, &ids);
     4077                if (ok) {
     4078                        switch (ids.type) {
     4079                        case ID_TYPE_BOTH:
     4080                                SY_U_sid = &global_sid_System;
     4081                                SY_G_sid = &global_sid_System;
     4082                                break;
     4083                        case ID_TYPE_UID:
     4084                                SY_U_sid = &global_sid_System;
     4085                                break;
     4086                        case ID_TYPE_GID:
     4087                                SY_G_sid = &global_sid_System;
     4088                                break;
     4089                        default:
     4090                                break;
     4091                        }
     4092                }
     4093        }
     4094
     4095        if (owner_sid == NULL) {
     4096                owner_sid = BA_U_sid;
     4097        }
     4098
     4099        if (owner_sid == NULL) {
     4100                owner_sid = SY_U_sid;
     4101        }
     4102
     4103        if (group_sid == NULL) {
     4104                group_sid = SY_G_sid;
     4105        }
     4106
     4107        if (try_system && group_sid == NULL) {
     4108                group_sid = BA_G_sid;
     4109        }
     4110
     4111        if (owner_sid == NULL) {
     4112                owner_sid = &token->sids[PRIMARY_USER_SID_INDEX];
     4113        }
     4114        if (group_sid == NULL) {
     4115                if (token->num_sids == PRIMARY_GROUP_SID_INDEX) {
     4116                        group_sid = &token->sids[PRIMARY_USER_SID_INDEX];
     4117                } else {
     4118                        group_sid = &token->sids[PRIMARY_GROUP_SID_INDEX];
     4119                }
     4120        }
     4121
     4122        status = se_create_child_secdesc(frame,
     4123                        &psd,
     4124                        &size,
     4125                        parent_desc,
     4126                        owner_sid,
     4127                        group_sid,
     4128                        fsp->is_directory);
     4129        if (!NT_STATUS_IS_OK(status)) {
     4130                TALLOC_FREE(frame);
     4131                return status;
     4132        }
     4133
     4134        /* If inheritable_components == false,
     4135           se_create_child_secdesc()
     4136           creates a security desriptor with a NULL dacl
     4137           entry, but with SEC_DESC_DACL_PRESENT. We need
     4138           to remove that flag. */
     4139
     4140        if (!inheritable_components) {
     4141                security_info_sent &= ~SECINFO_DACL;
     4142                psd->type &= ~SEC_DESC_DACL_PRESENT;
     4143        }
     4144
     4145        if (DEBUGLEVEL >= 10) {
     4146                DEBUG(10,("inherit_new_acl: child acl for %s is:\n",
     4147                        fsp_str_dbg(fsp) ));
     4148                NDR_PRINT_DEBUG(security_descriptor, psd);
     4149        }
     4150
     4151        if (inherit_owner) {
     4152                /* We need to be root to force this. */
     4153                become_root();
     4154        }
     4155        status = SMB_VFS_FSET_NT_ACL(fsp,
     4156                        security_info_sent,
     4157                        psd);
     4158        if (inherit_owner) {
     4159                unbecome_root();
     4160        }
     4161        TALLOC_FREE(frame);
     4162        return status;
     4163}
     4164
     4165/*
     4166 * If we already have a lease, it must match the new file id. [MS-SMB2]
     4167 * 3.3.5.9.8 speaks about INVALID_PARAMETER if an already used lease key is
     4168 * used for a different file name.
     4169 */
     4170
     4171struct lease_match_state {
     4172        /* Input parameters. */
     4173        TALLOC_CTX *mem_ctx;
     4174        const char *servicepath;
     4175        const struct smb_filename *fname;
     4176        bool file_existed;
     4177        struct file_id id;
     4178        /* Return parameters. */
     4179        uint32_t num_file_ids;
     4180        struct file_id *ids;
     4181        NTSTATUS match_status;
     4182};
     4183
     4184/*************************************************************
     4185 File doesn't exist but this lease key+guid is already in use.
     4186
     4187 This is only allowable in the dynamic share case where the
     4188 service path must be different.
     4189
     4190 There is a small race condition here in the multi-connection
     4191 case where a client sends two create calls on different connections,
     4192 where the file doesn't exist and one smbd creates the leases_db
     4193 entry first, but this will get fixed by the multichannel cleanup
     4194 when all identical client_guids get handled by a single smbd.
     4195**************************************************************/
     4196
     4197static void lease_match_parser_new_file(
     4198        uint32_t num_files,
     4199        const struct leases_db_file *files,
     4200        struct lease_match_state *state)
     4201{
     4202        uint32_t i;
     4203
     4204        for (i = 0; i < num_files; i++) {
     4205                const struct leases_db_file *f = &files[i];
     4206                if (strequal(state->servicepath, f->servicepath)) {
     4207                        state->match_status = NT_STATUS_INVALID_PARAMETER;
     4208                        return;
     4209                }
     4210        }
     4211
     4212        /* Dynamic share case. Break leases on all other files. */
     4213        state->match_status = leases_db_copy_file_ids(state->mem_ctx,
     4214                                        num_files,
     4215                                        files,
     4216                                        &state->ids);
     4217        if (!NT_STATUS_IS_OK(state->match_status)) {
     4218                return;
     4219        }
     4220
     4221        state->num_file_ids = num_files;
     4222        state->match_status = NT_STATUS_OPLOCK_NOT_GRANTED;
     4223        return;
     4224}
     4225
     4226static void lease_match_parser(
     4227        uint32_t num_files,
     4228        const struct leases_db_file *files,
     4229        void *private_data)
     4230{
     4231        struct lease_match_state *state =
     4232                (struct lease_match_state *)private_data;
     4233        uint32_t i;
     4234
     4235        if (!state->file_existed) {
     4236                /*
     4237                 * Deal with name mismatch or
     4238                 * possible dynamic share case separately
     4239                 * to make code clearer.
     4240                 */
     4241                lease_match_parser_new_file(num_files,
     4242                                                files,
     4243                                                state);
     4244                return;
     4245        }
     4246
     4247        /* File existed. */
     4248        state->match_status = NT_STATUS_OK;
     4249
     4250        for (i = 0; i < num_files; i++) {
     4251                const struct leases_db_file *f = &files[i];
     4252
     4253                /* Everything should be the same. */
     4254                if (!file_id_equal(&state->id, &f->id)) {
     4255                        /* This should catch all dynamic share cases. */
     4256                        state->match_status = NT_STATUS_OPLOCK_NOT_GRANTED;
     4257                        break;
     4258                }
     4259                if (!strequal(f->servicepath, state->servicepath)) {
     4260                        state->match_status = NT_STATUS_INVALID_PARAMETER;
     4261                        break;
     4262                }
     4263                if (!strequal(f->base_name, state->fname->base_name)) {
     4264                        state->match_status = NT_STATUS_INVALID_PARAMETER;
     4265                        break;
     4266                }
     4267                if (!strequal(f->stream_name, state->fname->stream_name)) {
     4268                        state->match_status = NT_STATUS_INVALID_PARAMETER;
     4269                        break;
     4270                }
     4271        }
     4272
     4273        if (NT_STATUS_IS_OK(state->match_status)) {
     4274                /*
     4275                 * Common case - just opening another handle on a
     4276                 * file on a non-dynamic share.
     4277                 */
     4278                return;
     4279        }
     4280
     4281        if (NT_STATUS_EQUAL(state->match_status, NT_STATUS_INVALID_PARAMETER)) {
     4282                /* Mismatched path. Error back to client. */
     4283                return;
     4284        }
     4285
     4286        /*
     4287         * File id mismatch. Dynamic share case NT_STATUS_OPLOCK_NOT_GRANTED.
     4288         * Don't allow leases.
     4289         */
     4290
     4291        state->match_status = leases_db_copy_file_ids(state->mem_ctx,
     4292                                        num_files,
     4293                                        files,
     4294                                        &state->ids);
     4295        if (!NT_STATUS_IS_OK(state->match_status)) {
     4296                return;
     4297        }
     4298
     4299        state->num_file_ids = num_files;
     4300        state->match_status = NT_STATUS_OPLOCK_NOT_GRANTED;
     4301        return;
     4302}
     4303
     4304static NTSTATUS lease_match(connection_struct *conn,
     4305                            struct smb_request *req,
     4306                            struct smb2_lease_key *lease_key,
     4307                            const char *servicepath,
     4308                            const struct smb_filename *fname,
     4309                            uint16_t *p_version,
     4310                            uint16_t *p_epoch)
     4311{
     4312        struct smbd_server_connection *sconn = req->sconn;
     4313        TALLOC_CTX *tos = talloc_tos();
     4314        struct lease_match_state state = {
     4315                .mem_ctx = tos,
     4316                .servicepath = servicepath,
     4317                .fname = fname,
     4318                .match_status = NT_STATUS_OK
     4319        };
     4320        uint32_t i;
     4321        NTSTATUS status;
     4322
     4323        state.file_existed = VALID_STAT(fname->st);
     4324        if (state.file_existed) {
     4325                state.id = vfs_file_id_from_sbuf(conn, &fname->st);
     4326        } else {
     4327                memset(&state.id, '\0', sizeof(state.id));
     4328        }
     4329
     4330        status = leases_db_parse(&sconn->client->connections->smb2.client.guid,
     4331                                 lease_key, lease_match_parser, &state);
     4332        if (!NT_STATUS_IS_OK(status)) {
     4333                /*
     4334                 * Not found or error means okay: We can make the lease pass
     4335                 */
     4336                return NT_STATUS_OK;
     4337        }
     4338        if (!NT_STATUS_EQUAL(state.match_status, NT_STATUS_OPLOCK_NOT_GRANTED)) {
     4339                /*
     4340                 * Anything but NT_STATUS_OPLOCK_NOT_GRANTED, let the caller
     4341                 * deal with it.
     4342                 */
     4343                return state.match_status;
     4344        }
     4345
     4346        /* We have to break all existing leases. */
     4347        for (i = 0; i < state.num_file_ids; i++) {
     4348                struct share_mode_lock *lck;
     4349                struct share_mode_data *d;
     4350                uint32_t j;
     4351
     4352                if (file_id_equal(&state.ids[i], &state.id)) {
     4353                        /* Don't need to break our own file. */
     4354                        continue;
     4355                }
     4356
     4357                lck = get_existing_share_mode_lock(talloc_tos(), state.ids[i]);
     4358                if (lck == NULL) {
     4359                        /* Race condition - file already closed. */
     4360                        continue;
     4361                }
     4362                d = lck->data;
     4363                for (j=0; j<d->num_share_modes; j++) {
     4364                        struct share_mode_entry *e = &d->share_modes[j];
     4365                        uint32_t e_lease_type = get_lease_type(d, e);
     4366                        struct share_mode_lease *l = NULL;
     4367
     4368                        if (share_mode_stale_pid(d, j)) {
     4369                                continue;
     4370                        }
     4371
     4372                        if (e->op_type == LEASE_OPLOCK) {
     4373                                l = &lck->data->leases[e->lease_idx];
     4374                                if (!smb2_lease_key_equal(&l->lease_key,
     4375                                                          lease_key)) {
     4376                                        continue;
     4377                                }
     4378                                *p_epoch = l->epoch;
     4379                                *p_version = l->lease_version;
     4380                        }
     4381
     4382                        if (e_lease_type == SMB2_LEASE_NONE) {
     4383                                continue;
     4384                        }
     4385
     4386                        send_break_message(conn->sconn->msg_ctx, e,
     4387                                           SMB2_LEASE_NONE);
     4388
     4389                        /*
     4390                         * Windows 7 and 8 lease clients
     4391                         * are broken in that they will not
     4392                         * respond to lease break requests
     4393                         * whilst waiting for an outstanding
     4394                         * open request on that lease handle
     4395                         * on the same TCP connection, due
     4396                         * to holding an internal inode lock.
     4397                         *
     4398                         * This means we can't reschedule
     4399                         * ourselves here, but must return
     4400                         * from the create.
     4401                         *
     4402                         * Work around:
     4403                         *
     4404                         * Send the breaks and then return
     4405                         * SMB2_LEASE_NONE in the lease handle
     4406                         * to cause them to acknowledge the
     4407                         * lease break. Consulatation with
     4408                         * Microsoft engineering confirmed
     4409                         * this approach is safe.
     4410                         */
     4411
     4412                }
     4413                TALLOC_FREE(lck);
     4414        }
     4415        /*
     4416         * Ensure we don't grant anything more so we
     4417         * never upgrade.
     4418         */
     4419        return NT_STATUS_OPLOCK_NOT_GRANTED;
    31394420}
    31404421
     
    31524433                                     uint32_t file_attributes,
    31534434                                     uint32_t oplock_request,
     4435                                     struct smb2_lease *lease,
    31544436                                     uint64_t allocation_size,
    31554437                                     uint32_t private_flags,
     
    31944476        }
    31954477
     4478        if (lease != NULL) {
     4479                uint16_t epoch = lease->lease_epoch;
     4480                uint16_t version = lease->lease_version;
     4481                status = lease_match(conn,
     4482                                req,
     4483                                &lease->lease_key,
     4484                                conn->connectpath,
     4485                                smb_fname,
     4486                                &version,
     4487                                &epoch);
     4488                if (NT_STATUS_EQUAL(status, NT_STATUS_OPLOCK_NOT_GRANTED)) {
     4489                        /* Dynamic share file. No leases and update epoch... */
     4490                        lease->lease_state = SMB2_LEASE_NONE;
     4491                        lease->lease_epoch = epoch;
     4492                        lease->lease_version = version;
     4493                } else if (!NT_STATUS_IS_OK(status)) {
     4494                        goto fail;
     4495                }
     4496        }
     4497
    31964498        if ((conn->fs_capabilities & FILE_NAMED_STREAMS)
    31974499            && (access_mask & DELETE_ACCESS)
     
    32084510        }
    32094511
    3210         /* This is the correct thing to do (check every time) but can_delete
    3211          * is expensive (it may have to read the parent directory
    3212          * permissions). So for now we're not doing it unless we have a strong
    3213          * hint the client is really going to delete this file. If the client
    3214          * is forcing FILE_CREATE let the filesystem take care of the
    3215          * permissions. */
    3216 
    3217         /* Setting FILE_SHARE_DELETE is the hint. */
    3218 
    3219         if ((create_disposition != FILE_CREATE)
    3220             && (access_mask & DELETE_ACCESS)
    3221             && (!(can_delete_file_in_directory(conn, smb_fname) ||
    3222                  can_access_file_acl(conn, smb_fname, DELETE_ACCESS)))) {
    3223                 status = NT_STATUS_ACCESS_DENIED;
    3224                 DEBUG(10,("create_file_unixpath: open file %s "
    3225                           "for delete ACCESS_DENIED\n",
    3226                           smb_fname_str_dbg(smb_fname)));
    3227                 goto fail;
    3228         }
    3229 
    32304512        if ((access_mask & SEC_FLAG_SYSTEM_SECURITY) &&
    32314513                        !security_token_has_privilege(get_current_nttok(conn),
     
    32414523            && is_ntfs_stream_smb_fname(smb_fname)
    32424524            && (!(private_flags & NTCREATEX_OPTIONS_PRIVATE_STREAM_DELETE))) {
    3243                 uint32 base_create_disposition;
     4525                uint32_t base_create_disposition;
    32444526                struct smb_filename *smb_fname_base = NULL;
    32454527
     
    32594541
    32604542                /* Create an smb_filename with stream_name == NULL. */
    3261                 status = create_synthetic_smb_fname(talloc_tos(),
    3262                                                     smb_fname->base_name,
    3263                                                     NULL, NULL,
    3264                                                     &smb_fname_base);
    3265                 if (!NT_STATUS_IS_OK(status)) {
     4543                smb_fname_base = synthetic_smb_fname(talloc_tos(),
     4544                                                     smb_fname->base_name,
     4545                                                     NULL, NULL);
     4546                if (smb_fname_base == NULL) {
     4547                        status = NT_STATUS_NO_MEMORY;
    32664548                        goto fail;
    32674549                }
     
    32974579                                              | FILE_SHARE_DELETE,
    32984580                                              base_create_disposition,
    3299                                               0, 0, 0, 0, 0, NULL, NULL,
     4581                                              0, 0, 0, NULL, 0, 0, NULL, NULL,
    33004582                                              &base_fsp, NULL);
    33014583                TALLOC_FREE(smb_fname_base);
     
    33074589                        goto fail;
    33084590                }
    3309                 /* we don't need to low level fd */
     4591                /* we don't need the low level fd */
    33104592                fd_close(base_fsp);
    33114593        }
     
    33564638                }
    33574639
    3358                 /*
    3359                  * We're opening the stream element of a base_fsp
    3360                  * we already opened. Set up the base_fsp pointer.
    3361                  */
    33624640                if (base_fsp) {
     4641                        /*
     4642                         * We're opening the stream element of a
     4643                         * base_fsp we already opened. Set up the
     4644                         * base_fsp pointer.
     4645                         */
    33634646                        fsp->base_fsp = base_fsp;
     4647                }
     4648
     4649                if (allocation_size) {
     4650                        fsp->initial_allocation_size = smb_roundup(fsp->conn,
     4651                                                        allocation_size);
    33644652                }
    33654653
     
    33724660                                            file_attributes,
    33734661                                            oplock_request,
     4662                                            lease,
    33744663                                            private_flags,
    33754664                                            &info,
     
    34154704        fsp->base_fsp = base_fsp;
    34164705
    3417         /*
    3418          * According to the MS documentation, the only time the security
    3419          * descriptor is applied to the opened file is iff we *created* the
    3420          * file; an existing file stays the same.
    3421          *
    3422          * Also, it seems (from observation) that you can open the file with
    3423          * any access mask but you can still write the sd. We need to override
    3424          * the granted access before we call set_sd
    3425          * Patch for bug #2242 from Tom Lackemann <cessnatomny@yahoo.com>.
    3426          */
    3427 
    3428         if ((sd != NULL) && (info == FILE_WAS_CREATED)
    3429             && lp_nt_acl_support(SNUM(conn))) {
    3430 
    3431                 uint32_t sec_info_sent;
    3432                 uint32_t saved_access_mask = fsp->access_mask;
    3433 
    3434                 sec_info_sent = get_sec_info(sd);
    3435 
    3436                 fsp->access_mask = FILE_GENERIC_ALL;
    3437 
    3438                 if (sec_info_sent & (SECINFO_OWNER|
    3439                                         SECINFO_GROUP|
    3440                                         SECINFO_DACL|
    3441                                         SECINFO_SACL)) {
    3442                         status = set_sd(fsp, sd, sec_info_sent);
    3443                 }
    3444 
    3445                 fsp->access_mask = saved_access_mask;
    3446 
    3447                 if (!NT_STATUS_IS_OK(status)) {
    3448                         goto fail;
    3449                 }
    3450         }
    3451 
    34524706        if ((ea_list != NULL) &&
    34534707            ((info == FILE_WAS_CREATED) || (info == FILE_WAS_OVERWRITTEN))) {
     
    34654719        /* Save the requested allocation size. */
    34664720        if ((info == FILE_WAS_CREATED) || (info == FILE_WAS_OVERWRITTEN)) {
    3467                 if (allocation_size
    3468                     && (allocation_size > fsp->fsp_name->st.st_ex_size)) {
     4721                if ((allocation_size > fsp->fsp_name->st.st_ex_size)
     4722                    && !(fsp->is_directory))
     4723                {
    34694724                        fsp->initial_allocation_size = smb_roundup(
    34704725                                fsp->conn, allocation_size);
    3471                         if (fsp->is_directory) {
    3472                                 /* Can't set allocation size on a directory. */
    3473                                 status = NT_STATUS_ACCESS_DENIED;
    3474                                 goto fail;
    3475                         }
    34764726                        if (vfs_allocate_file_space(
    34774727                                    fsp, fsp->initial_allocation_size) == -1) {
     
    34824732                        fsp->initial_allocation_size = smb_roundup(
    34834733                                fsp->conn, (uint64_t)fsp->fsp_name->st.st_ex_size);
     4734                }
     4735        } else {
     4736                fsp->initial_allocation_size = 0;
     4737        }
     4738
     4739        if ((info == FILE_WAS_CREATED) && lp_nt_acl_support(SNUM(conn)) &&
     4740                                fsp->base_fsp == NULL) {
     4741                if (sd != NULL) {
     4742                        /*
     4743                         * According to the MS documentation, the only time the security
     4744                         * descriptor is applied to the opened file is iff we *created* the
     4745                         * file; an existing file stays the same.
     4746                         *
     4747                         * Also, it seems (from observation) that you can open the file with
     4748                         * any access mask but you can still write the sd. We need to override
     4749                         * the granted access before we call set_sd
     4750                         * Patch for bug #2242 from Tom Lackemann <cessnatomny@yahoo.com>.
     4751                         */
     4752
     4753                        uint32_t sec_info_sent;
     4754                        uint32_t saved_access_mask = fsp->access_mask;
     4755
     4756                        sec_info_sent = get_sec_info(sd);
     4757
     4758                        fsp->access_mask = FILE_GENERIC_ALL;
     4759
     4760                        if (sec_info_sent & (SECINFO_OWNER|
     4761                                                SECINFO_GROUP|
     4762                                                SECINFO_DACL|
     4763                                                SECINFO_SACL)) {
     4764                                status = set_sd(fsp, sd, sec_info_sent);
     4765                        }
     4766
     4767                        fsp->access_mask = saved_access_mask;
     4768
     4769                        if (!NT_STATUS_IS_OK(status)) {
     4770                                goto fail;
     4771                        }
     4772                } else if (lp_inherit_acls(SNUM(conn))) {
     4773                        /* Inherit from parent. Errors here are not fatal. */
     4774                        status = inherit_new_acl(fsp);
     4775                        if (!NT_STATUS_IS_OK(status)) {
     4776                                DEBUG(10,("inherit_new_acl: failed for %s with %s\n",
     4777                                        fsp_str_dbg(fsp),
     4778                                        nt_errstr(status) ));
     4779                        }
     4780                }
     4781        }
     4782
     4783        if ((conn->fs_capabilities & FILE_FILE_COMPRESSION)
     4784         && (create_options & FILE_NO_COMPRESSION)
     4785         && (info == FILE_WAS_CREATED)) {
     4786                status = SMB_VFS_SET_COMPRESSION(conn, fsp, fsp,
     4787                                                 COMPRESSION_FORMAT_NONE);
     4788                if (!NT_STATUS_IS_OK(status)) {
     4789                        DEBUG(1, ("failed to disable compression: %s\n",
     4790                                  nt_errstr(status)));
    34844791                }
    34854792        }
     
    35294836        char *parent_fname = NULL;
    35304837        char *new_base_name = NULL;
     4838        uint32_t ucf_flags = ((req != NULL && req->posix_pathnames) ?
     4839                        UCF_POSIX_PATHNAMES : 0);
    35314840        NTSTATUS status;
    35324841
     
    35904899                 */
    35914900
    3592                 parent_fname = TALLOC_ARRAY(talloc_tos(), char,
     4901                parent_fname = talloc_array(talloc_tos(), char,
    35934902                    dir_name_len+2);
    35944903                if (parent_fname == NULL) {
     
    36234932                                req->flags2 & FLAGS2_DFS_PATHNAMES,
    36244933                                new_base_name,
    3625                                 0,
     4934                                ucf_flags,
    36264935                                NULL,
    36274936                                smb_fname_out);
     
    36464955                             uint32_t file_attributes,
    36474956                             uint32_t oplock_request,
     4957                             struct smb2_lease *lease,
    36484958                             uint64_t allocation_size,
    36494959                             uint32_t private_flags,
     
    36514961                             struct ea_list *ea_list,
    36524962                             files_struct **result,
    3653                              int *pinfo)
     4963                             int *pinfo,
     4964                             const struct smb2_create_blobs *in_context_blobs,
     4965                             struct smb2_create_blobs *out_context_blobs)
    36544966{
    36554967        int info = FILE_WAS_OPENED;
     
    37295041        }
    37305042
    3731         if (stream_name && is_ntfs_default_stream_smb_fname(smb_fname)) {
     5043        if (is_ntfs_default_stream_smb_fname(smb_fname)) {
    37325044                int ret;
    37335045                smb_fname->stream_name = NULL;
     
    37375049                        goto fail;
    37385050                }
    3739                 if (lp_posix_pathnames()) {
     5051                if (req != NULL && req->posix_pathnames) {
    37405052                        ret = SMB_VFS_LSTAT(conn, smb_fname);
    37415053                } else {
     
    37525064                conn, req, smb_fname, access_mask, share_access,
    37535065                create_disposition, create_options, file_attributes,
    3754                 oplock_request, allocation_size, private_flags,
     5066                oplock_request, lease, allocation_size, private_flags,
    37555067                sd, ea_list,
    37565068                &fsp, &info);
Note: See TracChangeset for help on using the changeset viewer.