Make mkdir_internal() check the parent ACL for SEC_DIR_ADD_SUBDIR rights.
[metze/samba/wip.git] / source3 / smbd / open.c
1 /* 
2    Unix SMB/CIFS implementation.
3    file opening and share modes
4    Copyright (C) Andrew Tridgell 1992-1998
5    Copyright (C) Jeremy Allison 2001-2004
6    Copyright (C) Volker Lendecke 2005
7
8    This program is free software; you can redistribute it and/or modify
9    it under the terms of the GNU General Public License as published by
10    the Free Software Foundation; either version 3 of the License, or
11    (at your option) any later version.
12
13    This program is distributed in the hope that it will be useful,
14    but WITHOUT ANY WARRANTY; without even the implied warranty of
15    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16    GNU General Public License for more details.
17
18    You should have received a copy of the GNU General Public License
19    along with this program.  If not, see <http://www.gnu.org/licenses/>.
20 */
21
22 #include "includes.h"
23 #include "system/filesys.h"
24 #include "printing.h"
25 #include "smbd/smbd.h"
26 #include "smbd/globals.h"
27 #include "fake_file.h"
28 #include "../libcli/security/security.h"
29 #include "../librpc/gen_ndr/ndr_security.h"
30 #include "auth.h"
31 #include "messages.h"
32
33 extern const struct generic_mapping file_generic_mapping;
34
35 struct deferred_open_record {
36         bool delayed_for_oplocks;
37         struct file_id id;
38 };
39
40 /****************************************************************************
41  SMB1 file varient of se_access_check. Never test FILE_READ_ATTRIBUTES.
42 ****************************************************************************/
43
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)
49 {
50         *access_granted = 0;
51
52         if (get_current_uid(conn) == (uid_t)0) {
53                 /* 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                 }
58                 return NT_STATUS_OK;
59         }
60
61         return se_access_check(sd,
62                                 token,
63                                 (access_desired & ~FILE_READ_ATTRIBUTES),
64                                 access_granted);
65 }
66
67 /****************************************************************************
68  Check if we have open rights.
69 ****************************************************************************/
70
71 NTSTATUS smbd_check_open_rights(struct connection_struct *conn,
72                                 const struct smb_filename *smb_fname,
73                                 uint32_t access_mask,
74                                 uint32_t *access_granted)
75 {
76         /* Check if we have rights to open. */
77         NTSTATUS status;
78         struct security_descriptor *sd = NULL;
79         uint32_t rejected_share_access;
80
81         rejected_share_access = access_mask & ~(conn->share_access);
82
83         if (rejected_share_access) {
84                 *access_granted = rejected_share_access;
85                 return NT_STATUS_ACCESS_DENIED;
86         }
87
88         if ((access_mask & DELETE_ACCESS) && !lp_acl_check_permissions(SNUM(conn))) {
89                 *access_granted = access_mask;
90
91                 DEBUG(10,("smbd_check_open_rights: not checking ACL "
92                         "on DELETE_ACCESS on file %s. Granting 0x%x\n",
93                         smb_fname_str_dbg(smb_fname),
94                         (unsigned int)*access_granted ));
95                 return NT_STATUS_OK;
96         }
97
98         status = SMB_VFS_GET_NT_ACL(conn, smb_fname->base_name,
99                         (SECINFO_OWNER |
100                         SECINFO_GROUP |
101                         SECINFO_DACL),&sd);
102
103         if (!NT_STATUS_IS_OK(status)) {
104                 DEBUG(10, ("smbd_check_open_rights: Could not get acl "
105                         "on %s: %s\n",
106                         smb_fname_str_dbg(smb_fname),
107                         nt_errstr(status)));
108                 return status;
109         }
110
111         status = smb1_file_se_access_check(conn,
112                                 sd,
113                                 get_current_nttok(conn),
114                                 access_mask,
115                                 access_granted);
116
117         DEBUG(10,("smbd_check_open_rights: file %s requesting "
118                 "0x%x returning 0x%x (%s)\n",
119                 smb_fname_str_dbg(smb_fname),
120                 (unsigned int)access_mask,
121                 (unsigned int)*access_granted,
122                 nt_errstr(status) ));
123
124         if (!NT_STATUS_IS_OK(status)) {
125                 if (DEBUGLEVEL >= 10) {
126                         DEBUG(10,("smbd_check_open_rights: acl for %s is:\n",
127                                 smb_fname_str_dbg(smb_fname) ));
128                         NDR_PRINT_DEBUG(security_descriptor, sd);
129                 }
130         }
131
132         TALLOC_FREE(sd);
133
134         return status;
135 }
136
137 /****************************************************************************
138  fd support routines - attempt to do a dos_open.
139 ****************************************************************************/
140
141 static NTSTATUS fd_open(struct connection_struct *conn,
142                     files_struct *fsp,
143                     int flags,
144                     mode_t mode)
145 {
146         struct smb_filename *smb_fname = fsp->fsp_name;
147         NTSTATUS status = NT_STATUS_OK;
148
149 #ifdef O_NOFOLLOW
150         /* 
151          * Never follow symlinks on a POSIX client. The
152          * client should be doing this.
153          */
154
155         if (fsp->posix_open || !lp_symlinks(SNUM(conn))) {
156                 flags |= O_NOFOLLOW;
157         }
158 #endif
159
160         fsp->fh->fd = SMB_VFS_OPEN(conn, smb_fname, fsp, flags, mode);
161         if (fsp->fh->fd == -1) {
162                 status = map_nt_error_from_unix(errno);
163                 if (errno == EMFILE) {
164                         static time_t last_warned = 0L;
165
166                         if (time((time_t *) NULL) > last_warned) {
167                                 DEBUG(0,("Too many open files, unable "
168                                         "to open more!  smbd's max "
169                                         "open files = %d\n",
170                                         lp_max_open_files()));
171                                 last_warned = time((time_t *) NULL);
172                         }
173                 }
174
175         }
176
177         DEBUG(10,("fd_open: name %s, flags = 0%o mode = 0%o, fd = %d. %s\n",
178                   smb_fname_str_dbg(smb_fname), flags, (int)mode, fsp->fh->fd,
179                 (fsp->fh->fd == -1) ? strerror(errno) : "" ));
180
181         return status;
182 }
183
184 /****************************************************************************
185  Close the file associated with a fsp.
186 ****************************************************************************/
187
188 NTSTATUS fd_close(files_struct *fsp)
189 {
190         int ret;
191
192         if (fsp->dptr) {
193                 dptr_CloseDir(fsp);
194         }
195         if (fsp->fh->fd == -1) {
196                 return NT_STATUS_OK; /* What we used to call a stat open. */
197         }
198         if (fsp->fh->ref_count > 1) {
199                 return NT_STATUS_OK; /* Shared handle. Only close last reference. */
200         }
201
202         ret = SMB_VFS_CLOSE(fsp);
203         fsp->fh->fd = -1;
204         if (ret == -1) {
205                 return map_nt_error_from_unix(errno);
206         }
207         return NT_STATUS_OK;
208 }
209
210 /****************************************************************************
211  Change the ownership of a file to that of the parent directory.
212  Do this by fd if possible.
213 ****************************************************************************/
214
215 void change_file_owner_to_parent(connection_struct *conn,
216                                         const char *inherit_from_dir,
217                                         files_struct *fsp)
218 {
219         struct smb_filename *smb_fname_parent = NULL;
220         NTSTATUS status;
221         int ret;
222
223         status = create_synthetic_smb_fname(talloc_tos(), inherit_from_dir,
224                                             NULL, NULL, &smb_fname_parent);
225         if (!NT_STATUS_IS_OK(status)) {
226                 return;
227         }
228
229         ret = SMB_VFS_STAT(conn, smb_fname_parent);
230         if (ret == -1) {
231                 DEBUG(0,("change_file_owner_to_parent: failed to stat parent "
232                          "directory %s. Error was %s\n",
233                          smb_fname_str_dbg(smb_fname_parent),
234                          strerror(errno)));
235                 TALLOC_FREE(smb_fname_parent);
236                 return;
237         }
238
239         if (smb_fname_parent->st.st_ex_uid == fsp->fsp_name->st.st_ex_uid) {
240                 /* Already this uid - no need to change. */
241                 DEBUG(10,("change_file_owner_to_parent: file %s "
242                         "is already owned by uid %d\n",
243                         fsp_str_dbg(fsp),
244                         (int)fsp->fsp_name->st.st_ex_uid ));
245                 TALLOC_FREE(smb_fname_parent);
246                 return;
247         }
248
249         become_root();
250         ret = SMB_VFS_FCHOWN(fsp, smb_fname_parent->st.st_ex_uid, (gid_t)-1);
251         unbecome_root();
252         if (ret == -1) {
253                 DEBUG(0,("change_file_owner_to_parent: failed to fchown "
254                          "file %s to parent directory uid %u. Error "
255                          "was %s\n", fsp_str_dbg(fsp),
256                          (unsigned int)smb_fname_parent->st.st_ex_uid,
257                          strerror(errno) ));
258         } else {
259                 DEBUG(10,("change_file_owner_to_parent: changed new file %s to "
260                         "parent directory uid %u.\n", fsp_str_dbg(fsp),
261                         (unsigned int)smb_fname_parent->st.st_ex_uid));
262                 /* Ensure the uid entry is updated. */
263                 fsp->fsp_name->st.st_ex_uid = smb_fname_parent->st.st_ex_uid;
264         }
265
266         TALLOC_FREE(smb_fname_parent);
267 }
268
269 NTSTATUS change_dir_owner_to_parent(connection_struct *conn,
270                                        const char *inherit_from_dir,
271                                        const char *fname,
272                                        SMB_STRUCT_STAT *psbuf)
273 {
274         struct smb_filename *smb_fname_parent = NULL;
275         struct smb_filename *smb_fname_cwd = NULL;
276         char *saved_dir = NULL;
277         TALLOC_CTX *ctx = talloc_tos();
278         NTSTATUS status = NT_STATUS_OK;
279         int ret;
280
281         status = create_synthetic_smb_fname(ctx, inherit_from_dir, NULL, NULL,
282                                             &smb_fname_parent);
283         if (!NT_STATUS_IS_OK(status)) {
284                 return status;
285         }
286
287         ret = SMB_VFS_STAT(conn, smb_fname_parent);
288         if (ret == -1) {
289                 status = map_nt_error_from_unix(errno);
290                 DEBUG(0,("change_dir_owner_to_parent: failed to stat parent "
291                          "directory %s. Error was %s\n",
292                          smb_fname_str_dbg(smb_fname_parent),
293                          strerror(errno)));
294                 goto out;
295         }
296
297         /* We've already done an lstat into psbuf, and we know it's a
298            directory. If we can cd into the directory and the dev/ino
299            are the same then we can safely chown without races as
300            we're locking the directory in place by being in it.  This
301            should work on any UNIX (thanks tridge :-). JRA.
302         */
303
304         saved_dir = vfs_GetWd(ctx,conn);
305         if (!saved_dir) {
306                 status = map_nt_error_from_unix(errno);
307                 DEBUG(0,("change_dir_owner_to_parent: failed to get "
308                          "current working directory. Error was %s\n",
309                          strerror(errno)));
310                 goto out;
311         }
312
313         /* Chdir into the new path. */
314         if (vfs_ChDir(conn, fname) == -1) {
315                 status = map_nt_error_from_unix(errno);
316                 DEBUG(0,("change_dir_owner_to_parent: failed to change "
317                          "current working directory to %s. Error "
318                          "was %s\n", fname, strerror(errno) ));
319                 goto chdir;
320         }
321
322         status = create_synthetic_smb_fname(ctx, ".", NULL, NULL,
323                                             &smb_fname_cwd);
324         if (!NT_STATUS_IS_OK(status)) {
325                 return status;
326         }
327
328         ret = SMB_VFS_STAT(conn, smb_fname_cwd);
329         if (ret == -1) {
330                 status = map_nt_error_from_unix(errno);
331                 DEBUG(0,("change_dir_owner_to_parent: failed to stat "
332                          "directory '.' (%s) Error was %s\n",
333                          fname, strerror(errno)));
334                 goto chdir;
335         }
336
337         /* Ensure we're pointing at the same place. */
338         if (smb_fname_cwd->st.st_ex_dev != psbuf->st_ex_dev ||
339             smb_fname_cwd->st.st_ex_ino != psbuf->st_ex_ino) {
340                 DEBUG(0,("change_dir_owner_to_parent: "
341                          "device/inode on directory %s changed. "
342                          "Refusing to chown !\n", fname ));
343                 status = NT_STATUS_ACCESS_DENIED;
344                 goto chdir;
345         }
346
347         if (smb_fname_parent->st.st_ex_uid == smb_fname_cwd->st.st_ex_uid) {
348                 /* Already this uid - no need to change. */
349                 DEBUG(10,("change_dir_owner_to_parent: directory %s "
350                         "is already owned by uid %d\n",
351                         fname,
352                         (int)smb_fname_cwd->st.st_ex_uid ));
353                 status = NT_STATUS_OK;
354                 goto chdir;
355         }
356
357         become_root();
358         ret = SMB_VFS_LCHOWN(conn, ".", smb_fname_parent->st.st_ex_uid,
359                             (gid_t)-1);
360         unbecome_root();
361         if (ret == -1) {
362                 status = map_nt_error_from_unix(errno);
363                 DEBUG(10,("change_dir_owner_to_parent: failed to chown "
364                           "directory %s to parent directory uid %u. "
365                           "Error was %s\n", fname,
366                           (unsigned int)smb_fname_parent->st.st_ex_uid,
367                           strerror(errno) ));
368         } else {
369                 DEBUG(10,("change_dir_owner_to_parent: changed ownership of new "
370                         "directory %s to parent directory uid %u.\n",
371                         fname, (unsigned int)smb_fname_parent->st.st_ex_uid ));
372                 /* Ensure the uid entry is updated. */
373                 psbuf->st_ex_uid = smb_fname_parent->st.st_ex_uid;
374         }
375
376  chdir:
377         vfs_ChDir(conn,saved_dir);
378  out:
379         TALLOC_FREE(smb_fname_parent);
380         TALLOC_FREE(smb_fname_cwd);
381         return status;
382 }
383
384 /****************************************************************************
385  Open a file.
386 ****************************************************************************/
387
388 static NTSTATUS open_file(files_struct *fsp,
389                           connection_struct *conn,
390                           struct smb_request *req,
391                           const char *parent_dir,
392                           int flags,
393                           mode_t unx_mode,
394                           uint32 access_mask, /* client requested access mask. */
395                           uint32 open_access_mask) /* what we're actually using in the open. */
396 {
397         struct smb_filename *smb_fname = fsp->fsp_name;
398         NTSTATUS status = NT_STATUS_OK;
399         int accmode = (flags & O_ACCMODE);
400         int local_flags = flags;
401         bool file_existed = VALID_STAT(fsp->fsp_name->st);
402         bool file_created = false;
403
404         fsp->fh->fd = -1;
405         errno = EPERM;
406
407         /* Check permissions */
408
409         /*
410          * This code was changed after seeing a client open request 
411          * containing the open mode of (DENY_WRITE/read-only) with
412          * the 'create if not exist' bit set. The previous code
413          * would fail to open the file read only on a read-only share
414          * as it was checking the flags parameter  directly against O_RDONLY,
415          * this was failing as the flags parameter was set to O_RDONLY|O_CREAT.
416          * JRA.
417          */
418
419         if (!CAN_WRITE(conn)) {
420                 /* It's a read-only share - fail if we wanted to write. */
421                 if(accmode != O_RDONLY || (flags & O_TRUNC) || (flags & O_APPEND)) {
422                         DEBUG(3,("Permission denied opening %s\n",
423                                  smb_fname_str_dbg(smb_fname)));
424                         return NT_STATUS_ACCESS_DENIED;
425                 } else if(flags & O_CREAT) {
426                         /* We don't want to write - but we must make sure that
427                            O_CREAT doesn't create the file if we have write
428                            access into the directory.
429                         */
430                         flags &= ~(O_CREAT|O_EXCL);
431                         local_flags &= ~(O_CREAT|O_EXCL);
432                 }
433         }
434
435         /*
436          * This little piece of insanity is inspired by the
437          * fact that an NT client can open a file for O_RDONLY,
438          * but set the create disposition to FILE_EXISTS_TRUNCATE.
439          * If the client *can* write to the file, then it expects to
440          * truncate the file, even though it is opening for readonly.
441          * Quicken uses this stupid trick in backup file creation...
442          * Thanks *greatly* to "David W. Chapman Jr." <dwcjr@inethouston.net>
443          * for helping track this one down. It didn't bite us in 2.0.x
444          * as we always opened files read-write in that release. JRA.
445          */
446
447         if ((accmode == O_RDONLY) && ((flags & O_TRUNC) == O_TRUNC)) {
448                 DEBUG(10,("open_file: truncate requested on read-only open "
449                           "for file %s\n", smb_fname_str_dbg(smb_fname)));
450                 local_flags = (flags & ~O_ACCMODE)|O_RDWR;
451         }
452
453         if ((open_access_mask & (FILE_READ_DATA|FILE_WRITE_DATA|FILE_APPEND_DATA|FILE_EXECUTE)) ||
454             (!file_existed && (local_flags & O_CREAT)) ||
455             ((local_flags & O_TRUNC) == O_TRUNC) ) {
456                 const char *wild;
457
458                 /*
459                  * We can't actually truncate here as the file may be locked.
460                  * open_file_ntcreate will take care of the truncate later. JRA.
461                  */
462
463                 local_flags &= ~O_TRUNC;
464
465 #if defined(O_NONBLOCK) && defined(S_ISFIFO)
466                 /*
467                  * We would block on opening a FIFO with no one else on the
468                  * other end. Do what we used to do and add O_NONBLOCK to the
469                  * open flags. JRA.
470                  */
471
472                 if (file_existed && S_ISFIFO(smb_fname->st.st_ex_mode)) {
473                         local_flags |= O_NONBLOCK;
474                 }
475 #endif
476
477                 /* Don't create files with Microsoft wildcard characters. */
478                 if (fsp->base_fsp) {
479                         /*
480                          * wildcard characters are allowed in stream names
481                          * only test the basefilename
482                          */
483                         wild = fsp->base_fsp->fsp_name->base_name;
484                 } else {
485                         wild = smb_fname->base_name;
486                 }
487                 if ((local_flags & O_CREAT) && !file_existed &&
488                     ms_has_wild(wild))  {
489                         return NT_STATUS_OBJECT_NAME_INVALID;
490                 }
491
492                 /* Actually do the open */
493                 status = fd_open(conn, fsp, local_flags, unx_mode);
494                 if (!NT_STATUS_IS_OK(status)) {
495                         DEBUG(3,("Error opening file %s (%s) (local_flags=%d) "
496                                  "(flags=%d)\n", smb_fname_str_dbg(smb_fname),
497                                  nt_errstr(status),local_flags,flags));
498                         return status;
499                 }
500
501                 if ((local_flags & O_CREAT) && !file_existed) {
502                         file_created = true;
503                 }
504
505         } else {
506                 fsp->fh->fd = -1; /* What we used to call a stat open. */
507                 if (file_existed) {
508                         uint32_t access_granted = 0;
509
510                         status = smbd_check_open_rights(conn,
511                                         smb_fname,
512                                         access_mask,
513                                         &access_granted);
514                         if (!NT_STATUS_IS_OK(status)) {
515                                 if (NT_STATUS_EQUAL(status, NT_STATUS_ACCESS_DENIED)) {
516                                         /*
517                                          * On NT_STATUS_ACCESS_DENIED, access_granted
518                                          * contains the denied bits.
519                                          */
520
521                                         if ((access_mask & FILE_WRITE_ATTRIBUTES) &&
522                                                         (access_granted & FILE_WRITE_ATTRIBUTES) &&
523                                                         (lp_map_readonly(SNUM(conn)) ||
524                                                          lp_map_archive(SNUM(conn)) ||
525                                                          lp_map_hidden(SNUM(conn)) ||
526                                                          lp_map_system(SNUM(conn)))) {
527                                                 access_granted &= ~FILE_WRITE_ATTRIBUTES;
528
529                                                 DEBUG(10,("open_file: "
530                                                           "overrode "
531                                                           "FILE_WRITE_"
532                                                           "ATTRIBUTES "
533                                                           "on file %s\n",
534                                                           smb_fname_str_dbg(
535                                                                   smb_fname)));
536                                         }
537
538                                         if ((access_mask & DELETE_ACCESS) &&
539                                             (access_granted & DELETE_ACCESS) &&
540                                             can_delete_file_in_directory(conn,
541                                                 smb_fname)) {
542                                                 /* Were we trying to do a stat open
543                                                  * for delete and didn't get DELETE
544                                                  * access (only) ? Check if the
545                                                  * directory allows DELETE_CHILD.
546                                                  * See here:
547                                                  * http://blogs.msdn.com/oldnewthing/archive/2004/06/04/148426.aspx
548                                                  * for details. */
549
550                                                 access_granted &= ~DELETE_ACCESS;
551
552                                                 DEBUG(10,("open_file: "
553                                                           "overrode "
554                                                           "DELETE_ACCESS on "
555                                                           "file %s\n",
556                                                           smb_fname_str_dbg(
557                                                                   smb_fname)));
558                                         }
559
560                                         if (access_granted != 0) {
561                                                 DEBUG(10,("open_file: Access "
562                                                           "denied on file "
563                                                           "%s\n",
564                                                           smb_fname_str_dbg(
565                                                                   smb_fname)));
566                                                 return status;
567                                         }
568                                 } else if (NT_STATUS_EQUAL(status, NT_STATUS_OBJECT_NAME_NOT_FOUND) &&
569                                     fsp->posix_open &&
570                                     S_ISLNK(smb_fname->st.st_ex_mode)) {
571                                         /* This is a POSIX stat open for delete
572                                          * or rename on a symlink that points
573                                          * nowhere. Allow. */
574                                         DEBUG(10,("open_file: allowing POSIX "
575                                                   "open on bad symlink %s\n",
576                                                   smb_fname_str_dbg(
577                                                           smb_fname)));
578                                 } else {
579                                         DEBUG(10,("open_file: "
580                                                   "smbd_check_open_rights on file "
581                                                   "%s returned %s\n",
582                                                   smb_fname_str_dbg(smb_fname),
583                                                   nt_errstr(status) ));
584                                         return status;
585                                 }
586                         }
587                 }
588         }
589
590         if (!file_existed) {
591                 int ret;
592
593                 if (fsp->fh->fd == -1) {
594                         ret = SMB_VFS_STAT(conn, smb_fname);
595                 } else {
596                         ret = SMB_VFS_FSTAT(fsp, &smb_fname->st);
597                         /* If we have an fd, this stat should succeed. */
598                         if (ret == -1) {
599                                 DEBUG(0,("Error doing fstat on open file %s "
600                                          "(%s)\n",
601                                          smb_fname_str_dbg(smb_fname),
602                                          strerror(errno) ));
603                         }
604                 }
605
606                 /* For a non-io open, this stat failing means file not found. JRA */
607                 if (ret == -1) {
608                         status = map_nt_error_from_unix(errno);
609                         fd_close(fsp);
610                         return status;
611                 }
612
613                 if (file_created) {
614                         bool need_re_stat = false;
615                         /* Do all inheritance work after we've
616                            done a successful stat call and filled
617                            in the stat struct in fsp->fsp_name. */
618
619                         /* Inherit the ACL if required */
620                         if (lp_inherit_perms(SNUM(conn))) {
621                                 inherit_access_posix_acl(conn, parent_dir,
622                                                          smb_fname->base_name,
623                                                          unx_mode);
624                                 need_re_stat = true;
625                         }
626
627                         /* Change the owner if required. */
628                         if (lp_inherit_owner(SNUM(conn))) {
629                                 change_file_owner_to_parent(conn, parent_dir,
630                                                             fsp);
631                                 need_re_stat = true;
632                         }
633
634                         if (need_re_stat) {
635                                 if (fsp->fh->fd == -1) {
636                                         ret = SMB_VFS_STAT(conn, smb_fname);
637                                 } else {
638                                         ret = SMB_VFS_FSTAT(fsp, &smb_fname->st);
639                                         /* If we have an fd, this stat should succeed. */
640                                         if (ret == -1) {
641                                                 DEBUG(0,("Error doing fstat on open file %s "
642                                                          "(%s)\n",
643                                                          smb_fname_str_dbg(smb_fname),
644                                                          strerror(errno) ));
645                                         }
646                                 }
647                         }
648
649                         notify_fname(conn, NOTIFY_ACTION_ADDED,
650                                      FILE_NOTIFY_CHANGE_FILE_NAME,
651                                      smb_fname->base_name);
652                 }
653         }
654
655         /*
656          * POSIX allows read-only opens of directories. We don't
657          * want to do this (we use a different code path for this)
658          * so catch a directory open and return an EISDIR. JRA.
659          */
660
661         if(S_ISDIR(smb_fname->st.st_ex_mode)) {
662                 fd_close(fsp);
663                 errno = EISDIR;
664                 return NT_STATUS_FILE_IS_A_DIRECTORY;
665         }
666
667         fsp->mode = smb_fname->st.st_ex_mode;
668         fsp->file_id = vfs_file_id_from_sbuf(conn, &smb_fname->st);
669         fsp->vuid = req ? req->vuid : UID_FIELD_INVALID;
670         fsp->file_pid = req ? req->smbpid : 0;
671         fsp->can_lock = True;
672         fsp->can_read = (access_mask & (FILE_READ_DATA)) ? True : False;
673         if (!CAN_WRITE(conn)) {
674                 fsp->can_write = False;
675         } else {
676                 fsp->can_write = (access_mask & (FILE_WRITE_DATA | FILE_APPEND_DATA)) ?
677                         True : False;
678         }
679         fsp->print_file = NULL;
680         fsp->modified = False;
681         fsp->sent_oplock_break = NO_BREAK_SENT;
682         fsp->is_directory = False;
683         if (conn->aio_write_behind_list &&
684             is_in_path(smb_fname->base_name, conn->aio_write_behind_list,
685                        conn->case_sensitive)) {
686                 fsp->aio_write_behind = True;
687         }
688
689         fsp->wcp = NULL; /* Write cache pointer. */
690
691         DEBUG(2,("%s opened file %s read=%s write=%s (numopen=%d)\n",
692                  conn->session_info->unix_info->unix_name,
693                  smb_fname_str_dbg(smb_fname),
694                  BOOLSTR(fsp->can_read), BOOLSTR(fsp->can_write),
695                  conn->num_files_open));
696
697         errno = 0;
698         return NT_STATUS_OK;
699 }
700
701 /****************************************************************************
702  Check if we can open a file with a share mode.
703  Returns True if conflict, False if not.
704 ****************************************************************************/
705
706 static bool share_conflict(struct share_mode_entry *entry,
707                            uint32 access_mask,
708                            uint32 share_access)
709 {
710         DEBUG(10,("share_conflict: entry->access_mask = 0x%x, "
711                   "entry->share_access = 0x%x, "
712                   "entry->private_options = 0x%x\n",
713                   (unsigned int)entry->access_mask,
714                   (unsigned int)entry->share_access,
715                   (unsigned int)entry->private_options));
716
717         DEBUG(10,("share_conflict: access_mask = 0x%x, share_access = 0x%x\n",
718                   (unsigned int)access_mask, (unsigned int)share_access));
719
720         if ((entry->access_mask & (FILE_WRITE_DATA|
721                                    FILE_APPEND_DATA|
722                                    FILE_READ_DATA|
723                                    FILE_EXECUTE|
724                                    DELETE_ACCESS)) == 0) {
725                 DEBUG(10,("share_conflict: No conflict due to "
726                           "entry->access_mask = 0x%x\n",
727                           (unsigned int)entry->access_mask ));
728                 return False;
729         }
730
731         if ((access_mask & (FILE_WRITE_DATA|
732                             FILE_APPEND_DATA|
733                             FILE_READ_DATA|
734                             FILE_EXECUTE|
735                             DELETE_ACCESS)) == 0) {
736                 DEBUG(10,("share_conflict: No conflict due to "
737                           "access_mask = 0x%x\n",
738                           (unsigned int)access_mask ));
739                 return False;
740         }
741
742 #if 1 /* JRA TEST - Superdebug. */
743 #define CHECK_MASK(num, am, right, sa, share) \
744         DEBUG(10,("share_conflict: [%d] am (0x%x) & right (0x%x) = 0x%x\n", \
745                 (unsigned int)(num), (unsigned int)(am), \
746                 (unsigned int)(right), (unsigned int)(am)&(right) )); \
747         DEBUG(10,("share_conflict: [%d] sa (0x%x) & share (0x%x) = 0x%x\n", \
748                 (unsigned int)(num), (unsigned int)(sa), \
749                 (unsigned int)(share), (unsigned int)(sa)&(share) )); \
750         if (((am) & (right)) && !((sa) & (share))) { \
751                 DEBUG(10,("share_conflict: check %d conflict am = 0x%x, right = 0x%x, \
752 sa = 0x%x, share = 0x%x\n", (num), (unsigned int)(am), (unsigned int)(right), (unsigned int)(sa), \
753                         (unsigned int)(share) )); \
754                 return True; \
755         }
756 #else
757 #define CHECK_MASK(num, am, right, sa, share) \
758         if (((am) & (right)) && !((sa) & (share))) { \
759                 DEBUG(10,("share_conflict: check %d conflict am = 0x%x, right = 0x%x, \
760 sa = 0x%x, share = 0x%x\n", (num), (unsigned int)(am), (unsigned int)(right), (unsigned int)(sa), \
761                         (unsigned int)(share) )); \
762                 return True; \
763         }
764 #endif
765
766         CHECK_MASK(1, entry->access_mask, FILE_WRITE_DATA | FILE_APPEND_DATA,
767                    share_access, FILE_SHARE_WRITE);
768         CHECK_MASK(2, access_mask, FILE_WRITE_DATA | FILE_APPEND_DATA,
769                    entry->share_access, FILE_SHARE_WRITE);
770
771         CHECK_MASK(3, entry->access_mask, FILE_READ_DATA | FILE_EXECUTE,
772                    share_access, FILE_SHARE_READ);
773         CHECK_MASK(4, access_mask, FILE_READ_DATA | FILE_EXECUTE,
774                    entry->share_access, FILE_SHARE_READ);
775
776         CHECK_MASK(5, entry->access_mask, DELETE_ACCESS,
777                    share_access, FILE_SHARE_DELETE);
778         CHECK_MASK(6, access_mask, DELETE_ACCESS,
779                    entry->share_access, FILE_SHARE_DELETE);
780
781         DEBUG(10,("share_conflict: No conflict.\n"));
782         return False;
783 }
784
785 #if defined(DEVELOPER)
786 static void validate_my_share_entries(struct smbd_server_connection *sconn,
787                                       int num,
788                                       struct share_mode_entry *share_entry)
789 {
790         files_struct *fsp;
791
792         if (!procid_is_me(&share_entry->pid)) {
793                 return;
794         }
795
796         if (is_deferred_open_entry(share_entry) &&
797             !open_was_deferred(sconn, share_entry->op_mid)) {
798                 char *str = talloc_asprintf(talloc_tos(),
799                         "Got a deferred entry without a request: "
800                         "PANIC: %s\n",
801                         share_mode_str(talloc_tos(), num, share_entry));
802                 smb_panic(str);
803         }
804
805         if (!is_valid_share_mode_entry(share_entry)) {
806                 return;
807         }
808
809         fsp = file_find_dif(sconn, share_entry->id,
810                             share_entry->share_file_id);
811         if (!fsp) {
812                 DEBUG(0,("validate_my_share_entries: PANIC : %s\n",
813                          share_mode_str(talloc_tos(), num, share_entry) ));
814                 smb_panic("validate_my_share_entries: Cannot match a "
815                           "share entry with an open file\n");
816         }
817
818         if (is_deferred_open_entry(share_entry) ||
819             is_unused_share_mode_entry(share_entry)) {
820                 goto panic;
821         }
822
823         if ((share_entry->op_type == NO_OPLOCK) &&
824             (fsp->oplock_type == FAKE_LEVEL_II_OPLOCK)) {
825                 /* Someone has already written to it, but I haven't yet
826                  * noticed */
827                 return;
828         }
829
830         if (((uint16)fsp->oplock_type) != share_entry->op_type) {
831                 goto panic;
832         }
833
834         return;
835
836  panic:
837         {
838                 char *str;
839                 DEBUG(0,("validate_my_share_entries: PANIC : %s\n",
840                          share_mode_str(talloc_tos(), num, share_entry) ));
841                 str = talloc_asprintf(talloc_tos(),
842                         "validate_my_share_entries: "
843                         "file %s, oplock_type = 0x%x, op_type = 0x%x\n",
844                          fsp->fsp_name->base_name,
845                          (unsigned int)fsp->oplock_type,
846                          (unsigned int)share_entry->op_type );
847                 smb_panic(str);
848         }
849 }
850 #endif
851
852 bool is_stat_open(uint32 access_mask)
853 {
854         return (access_mask &&
855                 ((access_mask & ~(SYNCHRONIZE_ACCESS| FILE_READ_ATTRIBUTES|
856                                   FILE_WRITE_ATTRIBUTES))==0) &&
857                 ((access_mask & (SYNCHRONIZE_ACCESS|FILE_READ_ATTRIBUTES|
858                                  FILE_WRITE_ATTRIBUTES)) != 0));
859 }
860
861 /****************************************************************************
862  Deal with share modes
863  Invarient: Share mode must be locked on entry and exit.
864  Returns -1 on error, or number of share modes on success (may be zero).
865 ****************************************************************************/
866
867 static NTSTATUS open_mode_check(connection_struct *conn,
868                                 struct share_mode_lock *lck,
869                                 uint32_t name_hash,
870                                 uint32 access_mask,
871                                 uint32 share_access,
872                                 uint32 create_options,
873                                 bool *file_existed)
874 {
875         int i;
876
877         if(lck->num_share_modes == 0) {
878                 return NT_STATUS_OK;
879         }
880
881         *file_existed = True;
882
883         /* A delete on close prohibits everything */
884
885         if (is_delete_on_close_set(lck, name_hash)) {
886                 return NT_STATUS_DELETE_PENDING;
887         }
888
889         if (is_stat_open(access_mask)) {
890                 /* Stat open that doesn't trigger oplock breaks or share mode
891                  * checks... ! JRA. */
892                 return NT_STATUS_OK;
893         }
894
895         /*
896          * Check if the share modes will give us access.
897          */
898
899 #if defined(DEVELOPER)
900         for(i = 0; i < lck->num_share_modes; i++) {
901                 validate_my_share_entries(conn->sconn, i,
902                                           &lck->share_modes[i]);
903         }
904 #endif
905
906         if (!lp_share_modes(SNUM(conn))) {
907                 return NT_STATUS_OK;
908         }
909
910         /* Now we check the share modes, after any oplock breaks. */
911         for(i = 0; i < lck->num_share_modes; i++) {
912
913                 if (!is_valid_share_mode_entry(&lck->share_modes[i])) {
914                         continue;
915                 }
916
917                 /* someone else has a share lock on it, check to see if we can
918                  * too */
919                 if (share_conflict(&lck->share_modes[i],
920                                    access_mask, share_access)) {
921                         return NT_STATUS_SHARING_VIOLATION;
922                 }
923         }
924
925         return NT_STATUS_OK;
926 }
927
928 static bool is_delete_request(files_struct *fsp) {
929         return ((fsp->access_mask == DELETE_ACCESS) &&
930                 (fsp->oplock_type == NO_OPLOCK));
931 }
932
933 /*
934  * Send a break message to the oplock holder and delay the open for
935  * our client.
936  */
937
938 static NTSTATUS send_break_message(files_struct *fsp,
939                                         struct share_mode_entry *exclusive,
940                                         uint64_t mid,
941                                         int oplock_request)
942 {
943         NTSTATUS status;
944         char msg[MSG_SMB_SHARE_MODE_ENTRY_SIZE];
945
946         DEBUG(10, ("Sending break request to PID %s\n",
947                    procid_str_static(&exclusive->pid)));
948         exclusive->op_mid = mid;
949
950         /* Create the message. */
951         share_mode_entry_to_message(msg, exclusive);
952
953         /* Add in the FORCE_OPLOCK_BREAK_TO_NONE bit in the message if set. We
954            don't want this set in the share mode struct pointed to by lck. */
955
956         if (oplock_request & FORCE_OPLOCK_BREAK_TO_NONE) {
957                 SSVAL(msg,OP_BREAK_MSG_OP_TYPE_OFFSET,
958                         exclusive->op_type | FORCE_OPLOCK_BREAK_TO_NONE);
959         }
960
961         status = messaging_send_buf(fsp->conn->sconn->msg_ctx, exclusive->pid,
962                                     MSG_SMB_BREAK_REQUEST,
963                                     (uint8 *)msg,
964                                     MSG_SMB_SHARE_MODE_ENTRY_SIZE);
965         if (!NT_STATUS_IS_OK(status)) {
966                 DEBUG(3, ("Could not send oplock break message: %s\n",
967                           nt_errstr(status)));
968         }
969
970         return status;
971 }
972
973 /*
974  * Return share_mode_entry pointers for :
975  * 1). Batch oplock entry.
976  * 2). Batch or exclusive oplock entry (may be identical to #1).
977  * bool have_level2_oplock
978  * bool have_no_oplock.
979  * Do internal consistency checks on the share mode for a file.
980  */
981
982 static void find_oplock_types(files_struct *fsp,
983                                 int oplock_request,
984                                 struct share_mode_lock *lck,
985                                 struct share_mode_entry **pp_batch,
986                                 struct share_mode_entry **pp_ex_or_batch,
987                                 bool *got_level2,
988                                 bool *got_no_oplock)
989 {
990         int i;
991
992         *pp_batch = NULL;
993         *pp_ex_or_batch = NULL;
994         *got_level2 = false;
995         *got_no_oplock = false;
996
997         /* Ignore stat or internal opens, as is done in
998                 delay_for_batch_oplocks() and
999                 delay_for_exclusive_oplocks().
1000          */
1001         if ((oplock_request & INTERNAL_OPEN_ONLY) || is_stat_open(fsp->access_mask)) {
1002                 return;
1003         }
1004
1005         for (i=0; i<lck->num_share_modes; i++) {
1006                 if (!is_valid_share_mode_entry(&lck->share_modes[i])) {
1007                         continue;
1008                 }
1009
1010                 if (lck->share_modes[i].op_type == NO_OPLOCK &&
1011                                 is_stat_open(lck->share_modes[i].access_mask)) {
1012                         /* We ignore stat opens in the table - they
1013                            always have NO_OPLOCK and never get or
1014                            cause breaks. JRA. */
1015                         continue;
1016                 }
1017
1018                 if (BATCH_OPLOCK_TYPE(lck->share_modes[i].op_type)) {
1019                         /* batch - can only be one. */
1020                         if (*pp_ex_or_batch || *pp_batch || *got_level2 || *got_no_oplock) {
1021                                 smb_panic("Bad batch oplock entry.");
1022                         }
1023                         *pp_batch = &lck->share_modes[i];
1024                 }
1025
1026                 if (EXCLUSIVE_OPLOCK_TYPE(lck->share_modes[i].op_type)) {
1027                         /* Exclusive or batch - can only be one. */
1028                         if (*pp_ex_or_batch || *got_level2 || *got_no_oplock) {
1029                                 smb_panic("Bad exclusive or batch oplock entry.");
1030                         }
1031                         *pp_ex_or_batch = &lck->share_modes[i];
1032                 }
1033
1034                 if (LEVEL_II_OPLOCK_TYPE(lck->share_modes[i].op_type)) {
1035                         if (*pp_batch || *pp_ex_or_batch) {
1036                                 smb_panic("Bad levelII oplock entry.");
1037                         }
1038                         *got_level2 = true;
1039                 }
1040
1041                 if (lck->share_modes[i].op_type == NO_OPLOCK) {
1042                         if (*pp_batch || *pp_ex_or_batch) {
1043                                 smb_panic("Bad no oplock entry.");
1044                         }
1045                         *got_no_oplock = true;
1046                 }
1047         }
1048 }
1049
1050 static bool delay_for_batch_oplocks(files_struct *fsp,
1051                                         uint64_t mid,
1052                                         int oplock_request,
1053                                         struct share_mode_entry *batch_entry)
1054 {
1055         if ((oplock_request & INTERNAL_OPEN_ONLY) || is_stat_open(fsp->access_mask)) {
1056                 return false;
1057         }
1058
1059         if (batch_entry != NULL) {
1060                 /* Found a batch oplock */
1061                 send_break_message(fsp, batch_entry, mid, oplock_request);
1062                 return true;
1063         }
1064         return false;
1065 }
1066
1067 static bool delay_for_exclusive_oplocks(files_struct *fsp,
1068                                         uint64_t mid,
1069                                         int oplock_request,
1070                                         struct share_mode_entry *ex_entry)
1071 {
1072         if ((oplock_request & INTERNAL_OPEN_ONLY) || is_stat_open(fsp->access_mask)) {
1073                 return false;
1074         }
1075
1076         if (ex_entry != NULL) {
1077                 /* Found an exclusive or batch oplock */
1078                 bool delay_it = is_delete_request(fsp) ?
1079                                 BATCH_OPLOCK_TYPE(ex_entry->op_type) : true;
1080                 if (delay_it) {
1081                         send_break_message(fsp, ex_entry, mid, oplock_request);
1082                         return true;
1083                 }
1084         }
1085         return false;
1086 }
1087
1088 static void grant_fsp_oplock_type(files_struct *fsp,
1089                                 const struct byte_range_lock *br_lck,
1090                                 int oplock_request,
1091                                 bool got_level2_oplock,
1092                                 bool got_a_none_oplock)
1093 {
1094         bool allow_level2 = (global_client_caps & CAP_LEVEL_II_OPLOCKS) &&
1095                             lp_level2_oplocks(SNUM(fsp->conn));
1096
1097         /* Start by granting what the client asked for,
1098            but ensure no SAMBA_PRIVATE bits can be set. */
1099         fsp->oplock_type = (oplock_request & ~SAMBA_PRIVATE_OPLOCK_MASK);
1100
1101         if (oplock_request & INTERNAL_OPEN_ONLY) {
1102                 /* No oplocks on internal open. */
1103                 fsp->oplock_type = NO_OPLOCK;
1104                 DEBUG(10,("grant_fsp_oplock_type: oplock type 0x%x on file %s\n",
1105                         fsp->oplock_type, fsp_str_dbg(fsp)));
1106                 return;
1107         } else if (br_lck && br_lck->num_locks > 0) {
1108                 DEBUG(10,("grant_fsp_oplock_type: file %s has byte range locks\n",
1109                         fsp_str_dbg(fsp)));
1110                 fsp->oplock_type = NO_OPLOCK;
1111         }
1112
1113         if (is_stat_open(fsp->access_mask)) {
1114                 /* Leave the value already set. */
1115                 DEBUG(10,("grant_fsp_oplock_type: oplock type 0x%x on file %s\n",
1116                         fsp->oplock_type, fsp_str_dbg(fsp)));
1117                 return;
1118         }
1119
1120         /*
1121          * Match what was requested (fsp->oplock_type) with
1122          * what was found in the existing share modes.
1123          */
1124
1125         if (got_a_none_oplock) {
1126                 fsp->oplock_type = NO_OPLOCK;
1127         } else if (got_level2_oplock) {
1128                 if (fsp->oplock_type == NO_OPLOCK ||
1129                                 fsp->oplock_type == FAKE_LEVEL_II_OPLOCK) {
1130                         /* Store a level2 oplock, but don't tell the client */
1131                         fsp->oplock_type = FAKE_LEVEL_II_OPLOCK;
1132                 } else {
1133                         fsp->oplock_type = LEVEL_II_OPLOCK;
1134                 }
1135         } else {
1136                 /* All share_mode_entries are placeholders or deferred.
1137                  * Silently upgrade to fake levelII if the client didn't
1138                  * ask for an oplock. */
1139                 if (fsp->oplock_type == NO_OPLOCK) {
1140                         /* Store a level2 oplock, but don't tell the client */
1141                         fsp->oplock_type = FAKE_LEVEL_II_OPLOCK;
1142                 }
1143         }
1144
1145         /*
1146          * Don't grant level2 to clients that don't want them
1147          * or if we've turned them off.
1148          */
1149         if (fsp->oplock_type == LEVEL_II_OPLOCK && !allow_level2) {
1150                 fsp->oplock_type = FAKE_LEVEL_II_OPLOCK;
1151         }
1152
1153         DEBUG(10,("grant_fsp_oplock_type: oplock type 0x%x on file %s\n",
1154                   fsp->oplock_type, fsp_str_dbg(fsp)));
1155 }
1156
1157 bool request_timed_out(struct timeval request_time,
1158                        struct timeval timeout)
1159 {
1160         struct timeval now, end_time;
1161         GetTimeOfDay(&now);
1162         end_time = timeval_sum(&request_time, &timeout);
1163         return (timeval_compare(&end_time, &now) < 0);
1164 }
1165
1166 /****************************************************************************
1167  Handle the 1 second delay in returning a SHARING_VIOLATION error.
1168 ****************************************************************************/
1169
1170 static void defer_open(struct share_mode_lock *lck,
1171                        struct timeval request_time,
1172                        struct timeval timeout,
1173                        struct smb_request *req,
1174                        struct deferred_open_record *state)
1175 {
1176         int i;
1177
1178         /* Paranoia check */
1179
1180         for (i=0; i<lck->num_share_modes; i++) {
1181                 struct share_mode_entry *e = &lck->share_modes[i];
1182
1183                 if (!is_deferred_open_entry(e)) {
1184                         continue;
1185                 }
1186
1187                 if (procid_is_me(&e->pid) && (e->op_mid == req->mid)) {
1188                         DEBUG(0, ("Trying to defer an already deferred "
1189                                 "request: mid=%llu, exiting\n",
1190                                 (unsigned long long)req->mid));
1191                         exit_server("attempt to defer a deferred request");
1192                 }
1193         }
1194
1195         /* End paranoia check */
1196
1197         DEBUG(10,("defer_open_sharing_error: time [%u.%06u] adding deferred "
1198                   "open entry for mid %llu\n",
1199                   (unsigned int)request_time.tv_sec,
1200                   (unsigned int)request_time.tv_usec,
1201                   (unsigned long long)req->mid));
1202
1203         if (!push_deferred_open_message_smb(req, request_time, timeout,
1204                                        state->id, (char *)state, sizeof(*state))) {
1205                 exit_server("push_deferred_open_message_smb failed");
1206         }
1207         add_deferred_open(lck, req->mid, request_time,
1208                           sconn_server_id(req->sconn), state->id);
1209 }
1210
1211
1212 /****************************************************************************
1213  On overwrite open ensure that the attributes match.
1214 ****************************************************************************/
1215
1216 bool open_match_attributes(connection_struct *conn,
1217                            uint32 old_dos_attr,
1218                            uint32 new_dos_attr,
1219                            mode_t existing_unx_mode,
1220                            mode_t new_unx_mode,
1221                            mode_t *returned_unx_mode)
1222 {
1223         uint32 noarch_old_dos_attr, noarch_new_dos_attr;
1224
1225         noarch_old_dos_attr = (old_dos_attr & ~FILE_ATTRIBUTE_ARCHIVE);
1226         noarch_new_dos_attr = (new_dos_attr & ~FILE_ATTRIBUTE_ARCHIVE);
1227
1228         if((noarch_old_dos_attr == 0 && noarch_new_dos_attr != 0) || 
1229            (noarch_old_dos_attr != 0 && ((noarch_old_dos_attr & noarch_new_dos_attr) == noarch_old_dos_attr))) {
1230                 *returned_unx_mode = new_unx_mode;
1231         } else {
1232                 *returned_unx_mode = (mode_t)0;
1233         }
1234
1235         DEBUG(10,("open_match_attributes: old_dos_attr = 0x%x, "
1236                   "existing_unx_mode = 0%o, new_dos_attr = 0x%x "
1237                   "returned_unx_mode = 0%o\n",
1238                   (unsigned int)old_dos_attr,
1239                   (unsigned int)existing_unx_mode,
1240                   (unsigned int)new_dos_attr,
1241                   (unsigned int)*returned_unx_mode ));
1242
1243         /* If we're mapping SYSTEM and HIDDEN ensure they match. */
1244         if (lp_map_system(SNUM(conn)) || lp_store_dos_attributes(SNUM(conn))) {
1245                 if ((old_dos_attr & FILE_ATTRIBUTE_SYSTEM) &&
1246                     !(new_dos_attr & FILE_ATTRIBUTE_SYSTEM)) {
1247                         return False;
1248                 }
1249         }
1250         if (lp_map_hidden(SNUM(conn)) || lp_store_dos_attributes(SNUM(conn))) {
1251                 if ((old_dos_attr & FILE_ATTRIBUTE_HIDDEN) &&
1252                     !(new_dos_attr & FILE_ATTRIBUTE_HIDDEN)) {
1253                         return False;
1254                 }
1255         }
1256         return True;
1257 }
1258
1259 /****************************************************************************
1260  Special FCB or DOS processing in the case of a sharing violation.
1261  Try and find a duplicated file handle.
1262 ****************************************************************************/
1263
1264 NTSTATUS fcb_or_dos_open(struct smb_request *req,
1265                                      connection_struct *conn,
1266                                      files_struct *fsp_to_dup_into,
1267                                      const struct smb_filename *smb_fname,
1268                                      struct file_id id,
1269                                      uint16 file_pid,
1270                                      uint16 vuid,
1271                                      uint32 access_mask,
1272                                      uint32 share_access,
1273                                      uint32 create_options)
1274 {
1275         files_struct *fsp;
1276
1277         DEBUG(5,("fcb_or_dos_open: attempting old open semantics for "
1278                  "file %s.\n", smb_fname_str_dbg(smb_fname)));
1279
1280         for(fsp = file_find_di_first(conn->sconn, id); fsp;
1281             fsp = file_find_di_next(fsp)) {
1282
1283                 DEBUG(10,("fcb_or_dos_open: checking file %s, fd = %d, "
1284                           "vuid = %u, file_pid = %u, private_options = 0x%x "
1285                           "access_mask = 0x%x\n", fsp_str_dbg(fsp),
1286                           fsp->fh->fd, (unsigned int)fsp->vuid,
1287                           (unsigned int)fsp->file_pid,
1288                           (unsigned int)fsp->fh->private_options,
1289                           (unsigned int)fsp->access_mask ));
1290
1291                 if (fsp->fh->fd != -1 &&
1292                     fsp->vuid == vuid &&
1293                     fsp->file_pid == file_pid &&
1294                     (fsp->fh->private_options & (NTCREATEX_OPTIONS_PRIVATE_DENY_DOS |
1295                                                  NTCREATEX_OPTIONS_PRIVATE_DENY_FCB)) &&
1296                     (fsp->access_mask & FILE_WRITE_DATA) &&
1297                     strequal(fsp->fsp_name->base_name, smb_fname->base_name) &&
1298                     strequal(fsp->fsp_name->stream_name,
1299                              smb_fname->stream_name)) {
1300                         DEBUG(10,("fcb_or_dos_open: file match\n"));
1301                         break;
1302                 }
1303         }
1304
1305         if (!fsp) {
1306                 return NT_STATUS_NOT_FOUND;
1307         }
1308
1309         /* quite an insane set of semantics ... */
1310         if (is_executable(smb_fname->base_name) &&
1311             (fsp->fh->private_options & NTCREATEX_OPTIONS_PRIVATE_DENY_DOS)) {
1312                 DEBUG(10,("fcb_or_dos_open: file fail due to is_executable.\n"));
1313                 return NT_STATUS_INVALID_PARAMETER;
1314         }
1315
1316         /* We need to duplicate this fsp. */
1317         return dup_file_fsp(req, fsp, access_mask, share_access,
1318                             create_options, fsp_to_dup_into);
1319 }
1320
1321 static void schedule_defer_open(struct share_mode_lock *lck,
1322                                 struct timeval request_time,
1323                                 struct smb_request *req)
1324 {
1325         struct deferred_open_record state;
1326
1327         /* This is a relative time, added to the absolute
1328            request_time value to get the absolute timeout time.
1329            Note that if this is the second or greater time we enter
1330            this codepath for this particular request mid then
1331            request_time is left as the absolute time of the *first*
1332            time this request mid was processed. This is what allows
1333            the request to eventually time out. */
1334
1335         struct timeval timeout;
1336
1337         /* Normally the smbd we asked should respond within
1338          * OPLOCK_BREAK_TIMEOUT seconds regardless of whether
1339          * the client did, give twice the timeout as a safety
1340          * measure here in case the other smbd is stuck
1341          * somewhere else. */
1342
1343         timeout = timeval_set(OPLOCK_BREAK_TIMEOUT*2, 0);
1344
1345         /* Nothing actually uses state.delayed_for_oplocks
1346            but it's handy to differentiate in debug messages
1347            between a 30 second delay due to oplock break, and
1348            a 1 second delay for share mode conflicts. */
1349
1350         state.delayed_for_oplocks = True;
1351         state.id = lck->id;
1352
1353         if (!request_timed_out(request_time, timeout)) {
1354                 defer_open(lck, request_time, timeout, req, &state);
1355         }
1356 }
1357
1358 /****************************************************************************
1359  Work out what access_mask to use from what the client sent us.
1360 ****************************************************************************/
1361
1362 NTSTATUS smbd_calculate_access_mask(connection_struct *conn,
1363                                     const struct smb_filename *smb_fname,
1364                                     bool file_existed,
1365                                     uint32_t access_mask,
1366                                     uint32_t *access_mask_out)
1367 {
1368         NTSTATUS status;
1369         uint32_t orig_access_mask = access_mask;
1370         uint32_t rejected_share_access;
1371
1372         /*
1373          * Convert GENERIC bits to specific bits.
1374          */
1375
1376         se_map_generic(&access_mask, &file_generic_mapping);
1377
1378         /* Calculate MAXIMUM_ALLOWED_ACCESS if requested. */
1379         if (access_mask & MAXIMUM_ALLOWED_ACCESS) {
1380                 if (file_existed) {
1381
1382                         struct security_descriptor *sd;
1383                         uint32_t access_granted = 0;
1384
1385                         status = SMB_VFS_GET_NT_ACL(conn, smb_fname->base_name,
1386                                         (SECINFO_OWNER |
1387                                         SECINFO_GROUP |
1388                                         SECINFO_DACL),&sd);
1389
1390                         if (!NT_STATUS_IS_OK(status)) {
1391                                 DEBUG(10,("smbd_calculate_access_mask: "
1392                                         "Could not get acl on file %s: %s\n",
1393                                         smb_fname_str_dbg(smb_fname),
1394                                         nt_errstr(status)));
1395                                 return NT_STATUS_ACCESS_DENIED;
1396                         }
1397
1398                         status = smb1_file_se_access_check(conn,
1399                                         sd,
1400                                         get_current_nttok(conn),
1401                                         access_mask,
1402                                         &access_granted);
1403
1404                         TALLOC_FREE(sd);
1405
1406                         if (!NT_STATUS_IS_OK(status)) {
1407                                 DEBUG(10, ("smbd_calculate_access_mask: "
1408                                         "Access denied on file %s: "
1409                                         "when calculating maximum access\n",
1410                                         smb_fname_str_dbg(smb_fname)));
1411                                 return NT_STATUS_ACCESS_DENIED;
1412                         }
1413
1414                         access_mask = access_granted;
1415                 } else {
1416                         access_mask = FILE_GENERIC_ALL;
1417                 }
1418
1419                 access_mask &= conn->share_access;
1420         }
1421
1422         rejected_share_access = access_mask & ~(conn->share_access);
1423
1424         if (rejected_share_access) {
1425                 DEBUG(10, ("smbd_calculate_access_mask: Access denied on "
1426                         "file %s: rejected by share access mask[0x%08X] "
1427                         "orig[0x%08X] mapped[0x%08X] reject[0x%08X]\n",
1428                         smb_fname_str_dbg(smb_fname),
1429                         conn->share_access,
1430                         orig_access_mask, access_mask,
1431                         rejected_share_access));
1432                 return NT_STATUS_ACCESS_DENIED;
1433         }
1434
1435         *access_mask_out = access_mask;
1436         return NT_STATUS_OK;
1437 }
1438
1439 /****************************************************************************
1440  Remove the deferred open entry under lock.
1441 ****************************************************************************/
1442
1443 void remove_deferred_open_entry(struct file_id id, uint64_t mid,
1444                                 struct server_id pid)
1445 {
1446         struct share_mode_lock *lck = get_share_mode_lock(talloc_tos(), id,
1447                         NULL, NULL, NULL);
1448         if (lck == NULL) {
1449                 DEBUG(0, ("could not get share mode lock\n"));
1450         } else {
1451                 del_deferred_open_entry(lck, mid, pid);
1452                 TALLOC_FREE(lck);
1453         }
1454 }
1455
1456 /****************************************************************
1457  Ensure we get the brlock lock followed by the share mode lock
1458  in the correct order to prevent deadlocks if other smbd's are
1459  using the brlock database on this file simultaneously with this open
1460  (that code also gets the locks in brlock -> share mode lock order).
1461 ****************************************************************/
1462
1463 static bool acquire_ordered_locks(TALLOC_CTX *mem_ctx,
1464                                 files_struct *fsp,
1465                                 const struct file_id id,
1466                                 const char *connectpath,
1467                                 const struct smb_filename *smb_fname,
1468                                 const struct timespec *p_old_write_time,
1469                                 struct share_mode_lock **p_lck,
1470                                 struct byte_range_lock **p_br_lck)
1471 {
1472         /* Ordering - we must get the br_lck for this
1473            file before the share mode. */
1474         if (lp_locking(fsp->conn->params)) {
1475                 *p_br_lck = brl_get_locks_readonly(fsp);
1476                 if (*p_br_lck == NULL) {
1477                         DEBUG(0, ("Could not get br_lock\n"));
1478                         return false;
1479                 }
1480                 /* Note - we don't need to free the returned
1481                    br_lck explicitly as it was allocated on talloc_tos()
1482                    and so will be autofreed (and release the lock)
1483                    once the frame context disappears.
1484
1485                    If it was set to fsp->brlock_rec then it was
1486                    talloc_move'd to hang off the fsp pointer and
1487                    in this case is guarenteed to not be holding the
1488                    lock on the brlock database. */
1489         }
1490
1491         *p_lck = get_share_mode_lock(mem_ctx,
1492                                 id,
1493                                 connectpath,
1494                                 smb_fname,
1495                                 p_old_write_time);
1496
1497         if (*p_lck == NULL) {
1498                 DEBUG(0, ("Could not get share mode lock\n"));
1499                 TALLOC_FREE(*p_br_lck);
1500                 return false;
1501         }
1502         return true;
1503 }
1504
1505 /****************************************************************************
1506  Open a file with a share mode. Passed in an already created files_struct *.
1507 ****************************************************************************/
1508
1509 static NTSTATUS open_file_ntcreate(connection_struct *conn,
1510                             struct smb_request *req,
1511                             uint32 access_mask,         /* access bits (FILE_READ_DATA etc.) */
1512                             uint32 share_access,        /* share constants (FILE_SHARE_READ etc) */
1513                             uint32 create_disposition,  /* FILE_OPEN_IF etc. */
1514                             uint32 create_options,      /* options such as delete on close. */
1515                             uint32 new_dos_attributes,  /* attributes used for new file. */
1516                             int oplock_request,         /* internal Samba oplock codes. */
1517                                                         /* Information (FILE_EXISTS etc.) */
1518                             uint32_t private_flags,     /* Samba specific flags. */
1519                             int *pinfo,
1520                             files_struct *fsp)
1521 {
1522         struct smb_filename *smb_fname = fsp->fsp_name;
1523         int flags=0;
1524         int flags2=0;
1525         bool file_existed = VALID_STAT(smb_fname->st);
1526         bool def_acl = False;
1527         bool posix_open = False;
1528         bool new_file_created = False;
1529         bool clear_ads = false;
1530         struct file_id id;
1531         NTSTATUS fsp_open = NT_STATUS_ACCESS_DENIED;
1532         mode_t new_unx_mode = (mode_t)0;
1533         mode_t unx_mode = (mode_t)0;
1534         int info;
1535         uint32 existing_dos_attributes = 0;
1536         struct timeval request_time = timeval_zero();
1537         struct share_mode_lock *lck = NULL;
1538         uint32 open_access_mask = access_mask;
1539         NTSTATUS status;
1540         char *parent_dir;
1541
1542         ZERO_STRUCT(id);
1543
1544         if (conn->printer) {
1545                 /*
1546                  * Printers are handled completely differently.
1547                  * Most of the passed parameters are ignored.
1548                  */
1549
1550                 if (pinfo) {
1551                         *pinfo = FILE_WAS_CREATED;
1552                 }
1553
1554                 DEBUG(10, ("open_file_ntcreate: printer open fname=%s\n",
1555                            smb_fname_str_dbg(smb_fname)));
1556
1557                 if (!req) {
1558                         DEBUG(0,("open_file_ntcreate: printer open without "
1559                                 "an SMB request!\n"));
1560                         return NT_STATUS_INTERNAL_ERROR;
1561                 }
1562
1563                 return print_spool_open(fsp, smb_fname->base_name,
1564                                         req->vuid);
1565         }
1566
1567         if (!parent_dirname(talloc_tos(), smb_fname->base_name, &parent_dir,
1568                             NULL)) {
1569                 return NT_STATUS_NO_MEMORY;
1570         }
1571
1572         if (new_dos_attributes & FILE_FLAG_POSIX_SEMANTICS) {
1573                 posix_open = True;
1574                 unx_mode = (mode_t)(new_dos_attributes & ~FILE_FLAG_POSIX_SEMANTICS);
1575                 new_dos_attributes = 0;
1576         } else {
1577                 /* Windows allows a new file to be created and
1578                    silently removes a FILE_ATTRIBUTE_DIRECTORY
1579                    sent by the client. Do the same. */
1580
1581                 new_dos_attributes &= ~FILE_ATTRIBUTE_DIRECTORY;
1582
1583                 /* We add FILE_ATTRIBUTE_ARCHIVE to this as this mode is only used if the file is
1584                  * created new. */
1585                 unx_mode = unix_mode(conn, new_dos_attributes | FILE_ATTRIBUTE_ARCHIVE,
1586                                      smb_fname, parent_dir);
1587         }
1588
1589         DEBUG(10, ("open_file_ntcreate: fname=%s, dos_attrs=0x%x "
1590                    "access_mask=0x%x share_access=0x%x "
1591                    "create_disposition = 0x%x create_options=0x%x "
1592                    "unix mode=0%o oplock_request=%d private_flags = 0x%x\n",
1593                    smb_fname_str_dbg(smb_fname), new_dos_attributes,
1594                    access_mask, share_access, create_disposition,
1595                    create_options, (unsigned int)unx_mode, oplock_request,
1596                    (unsigned int)private_flags));
1597
1598         if ((req == NULL) && ((oplock_request & INTERNAL_OPEN_ONLY) == 0)) {
1599                 DEBUG(0, ("No smb request but not an internal only open!\n"));
1600                 return NT_STATUS_INTERNAL_ERROR;
1601         }
1602
1603         /*
1604          * Only non-internal opens can be deferred at all
1605          */
1606
1607         if (req) {
1608                 void *ptr;
1609                 if (get_deferred_open_message_state(req,
1610                                 &request_time,
1611                                 &ptr)) {
1612
1613                         struct deferred_open_record *state = (struct deferred_open_record *)ptr;
1614                         /* Remember the absolute time of the original
1615                            request with this mid. We'll use it later to
1616                            see if this has timed out. */
1617
1618                         /* Remove the deferred open entry under lock. */
1619                         remove_deferred_open_entry(
1620                                 state->id, req->mid,
1621                                 sconn_server_id(req->sconn));
1622
1623                         /* Ensure we don't reprocess this message. */
1624                         remove_deferred_open_message_smb(req->sconn, req->mid);
1625                 }
1626         }
1627
1628         status = check_name(conn, smb_fname->base_name);
1629         if (!NT_STATUS_IS_OK(status)) {
1630                 return status;
1631         }
1632
1633         if (!posix_open) {
1634                 new_dos_attributes &= SAMBA_ATTRIBUTES_MASK;
1635                 if (file_existed) {
1636                         existing_dos_attributes = dos_mode(conn, smb_fname);
1637                 }
1638         }
1639
1640         /* ignore any oplock requests if oplocks are disabled */
1641         if (!lp_oplocks(SNUM(conn)) ||
1642             IS_VETO_OPLOCK_PATH(conn, smb_fname->base_name)) {
1643                 /* Mask off everything except the private Samba bits. */
1644                 oplock_request &= SAMBA_PRIVATE_OPLOCK_MASK;
1645         }
1646
1647         /* this is for OS/2 long file names - say we don't support them */
1648         if (!lp_posix_pathnames() && strstr(smb_fname->base_name,".+,;=[].")) {
1649                 /* OS/2 Workplace shell fix may be main code stream in a later
1650                  * release. */
1651                 DEBUG(5,("open_file_ntcreate: OS/2 long filenames are not "
1652                          "supported.\n"));
1653                 if (use_nt_status()) {
1654                         return NT_STATUS_OBJECT_NAME_NOT_FOUND;
1655                 }
1656                 return NT_STATUS_DOS(ERRDOS, ERRcannotopen);
1657         }
1658
1659         switch( create_disposition ) {
1660                 /*
1661                  * Currently we're using FILE_SUPERSEDE as the same as
1662                  * FILE_OVERWRITE_IF but they really are
1663                  * different. FILE_SUPERSEDE deletes an existing file
1664                  * (requiring delete access) then recreates it.
1665                  */
1666                 case FILE_SUPERSEDE:
1667                         /* If file exists replace/overwrite. If file doesn't
1668                          * exist create. */
1669                         flags2 |= (O_CREAT | O_TRUNC);
1670                         clear_ads = true;
1671                         break;
1672
1673                 case FILE_OVERWRITE_IF:
1674                         /* If file exists replace/overwrite. If file doesn't
1675                          * exist create. */
1676                         flags2 |= (O_CREAT | O_TRUNC);
1677                         clear_ads = true;
1678                         break;
1679
1680                 case FILE_OPEN:
1681                         /* If file exists open. If file doesn't exist error. */
1682                         if (!file_existed) {
1683                                 DEBUG(5,("open_file_ntcreate: FILE_OPEN "
1684                                          "requested for file %s and file "
1685                                          "doesn't exist.\n",
1686                                          smb_fname_str_dbg(smb_fname)));
1687                                 errno = ENOENT;
1688                                 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
1689                         }
1690                         break;
1691
1692                 case FILE_OVERWRITE:
1693                         /* If file exists overwrite. If file doesn't exist
1694                          * error. */
1695                         if (!file_existed) {
1696                                 DEBUG(5,("open_file_ntcreate: FILE_OVERWRITE "
1697                                          "requested for file %s and file "
1698                                          "doesn't exist.\n",
1699                                          smb_fname_str_dbg(smb_fname) ));
1700                                 errno = ENOENT;
1701                                 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
1702                         }
1703                         flags2 |= O_TRUNC;
1704                         clear_ads = true;
1705                         break;
1706
1707                 case FILE_CREATE:
1708                         /* If file exists error. If file doesn't exist
1709                          * create. */
1710                         if (file_existed) {
1711                                 DEBUG(5,("open_file_ntcreate: FILE_CREATE "
1712                                          "requested for file %s and file "
1713                                          "already exists.\n",
1714                                          smb_fname_str_dbg(smb_fname)));
1715                                 if (S_ISDIR(smb_fname->st.st_ex_mode)) {
1716                                         errno = EISDIR;
1717                                 } else {
1718                                         errno = EEXIST;
1719                                 }
1720                                 return map_nt_error_from_unix(errno);
1721                         }
1722                         flags2 |= (O_CREAT|O_EXCL);
1723                         break;
1724
1725                 case FILE_OPEN_IF:
1726                         /* If file exists open. If file doesn't exist
1727                          * create. */
1728                         flags2 |= O_CREAT;
1729                         break;
1730
1731                 default:
1732                         return NT_STATUS_INVALID_PARAMETER;
1733         }
1734
1735         /* We only care about matching attributes on file exists and
1736          * overwrite. */
1737
1738         if (!posix_open && file_existed && ((create_disposition == FILE_OVERWRITE) ||
1739                              (create_disposition == FILE_OVERWRITE_IF))) {
1740                 if (!open_match_attributes(conn, existing_dos_attributes,
1741                                            new_dos_attributes,
1742                                            smb_fname->st.st_ex_mode,
1743                                            unx_mode, &new_unx_mode)) {
1744                         DEBUG(5,("open_file_ntcreate: attributes missmatch "
1745                                  "for file %s (%x %x) (0%o, 0%o)\n",
1746                                  smb_fname_str_dbg(smb_fname),
1747                                  existing_dos_attributes,
1748                                  new_dos_attributes,
1749                                  (unsigned int)smb_fname->st.st_ex_mode,
1750                                  (unsigned int)unx_mode ));
1751                         errno = EACCES;
1752                         return NT_STATUS_ACCESS_DENIED;
1753                 }
1754         }
1755
1756         status = smbd_calculate_access_mask(conn, smb_fname, file_existed,
1757                                         access_mask,
1758                                         &access_mask); 
1759         if (!NT_STATUS_IS_OK(status)) {
1760                 DEBUG(10, ("open_file_ntcreate: smbd_calculate_access_mask "
1761                         "on file %s returned %s\n",
1762                         smb_fname_str_dbg(smb_fname), nt_errstr(status)));
1763                 return status;
1764         }
1765
1766         open_access_mask = access_mask;
1767
1768         if ((flags2 & O_TRUNC) || (oplock_request & FORCE_OPLOCK_BREAK_TO_NONE)) {
1769                 open_access_mask |= FILE_WRITE_DATA; /* This will cause oplock breaks. */
1770         }
1771
1772         DEBUG(10, ("open_file_ntcreate: fname=%s, after mapping "
1773                    "access_mask=0x%x\n", smb_fname_str_dbg(smb_fname),
1774                     access_mask));
1775
1776         /*
1777          * Note that we ignore the append flag as append does not
1778          * mean the same thing under DOS and Unix.
1779          */
1780
1781         if ((access_mask & (FILE_WRITE_DATA | FILE_APPEND_DATA)) ||
1782                         (oplock_request & FORCE_OPLOCK_BREAK_TO_NONE)) {
1783                 /* DENY_DOS opens are always underlying read-write on the
1784                    file handle, no matter what the requested access mask
1785                     says. */
1786                 if ((private_flags & NTCREATEX_OPTIONS_PRIVATE_DENY_DOS) ||
1787                         access_mask & (FILE_READ_ATTRIBUTES|FILE_READ_DATA|FILE_READ_EA|FILE_EXECUTE)) {
1788                         flags = O_RDWR;
1789                 } else {
1790                         flags = O_WRONLY;
1791                 }
1792         } else {
1793                 flags = O_RDONLY;
1794         }
1795
1796         /*
1797          * Currently we only look at FILE_WRITE_THROUGH for create options.
1798          */
1799
1800 #if defined(O_SYNC)
1801         if ((create_options & FILE_WRITE_THROUGH) && lp_strict_sync(SNUM(conn))) {
1802                 flags2 |= O_SYNC;
1803         }
1804 #endif /* O_SYNC */
1805
1806         if (posix_open && (access_mask & FILE_APPEND_DATA)) {
1807                 flags2 |= O_APPEND;
1808         }
1809
1810         if (!posix_open && !CAN_WRITE(conn)) {
1811                 /*
1812                  * We should really return a permission denied error if either
1813                  * O_CREAT or O_TRUNC are set, but for compatibility with
1814                  * older versions of Samba we just AND them out.
1815                  */
1816                 flags2 &= ~(O_CREAT|O_TRUNC);
1817         }
1818
1819         /*
1820          * Ensure we can't write on a read-only share or file.
1821          */
1822
1823         if (flags != O_RDONLY && file_existed &&
1824             (!CAN_WRITE(conn) || IS_DOS_READONLY(existing_dos_attributes))) {
1825                 DEBUG(5,("open_file_ntcreate: write access requested for "
1826                          "file %s on read only %s\n",
1827                          smb_fname_str_dbg(smb_fname),
1828                          !CAN_WRITE(conn) ? "share" : "file" ));
1829                 errno = EACCES;
1830                 return NT_STATUS_ACCESS_DENIED;
1831         }
1832
1833         fsp->file_id = vfs_file_id_from_sbuf(conn, &smb_fname->st);
1834         fsp->share_access = share_access;
1835         fsp->fh->private_options = private_flags;
1836         fsp->access_mask = open_access_mask; /* We change this to the
1837                                               * requested access_mask after
1838                                               * the open is done. */
1839         fsp->posix_open = posix_open;
1840
1841         /* Ensure no SAMBA_PRIVATE bits can be set. */
1842         fsp->oplock_type = (oplock_request & ~SAMBA_PRIVATE_OPLOCK_MASK);
1843
1844         if (timeval_is_zero(&request_time)) {
1845                 request_time = fsp->open_time;
1846         }
1847
1848         if (file_existed) {
1849                 struct byte_range_lock *br_lck = NULL;
1850                 struct share_mode_entry *batch_entry = NULL;
1851                 struct share_mode_entry *exclusive_entry = NULL;
1852                 bool got_level2_oplock = false;
1853                 bool got_a_none_oplock = false;
1854
1855                 struct timespec old_write_time = smb_fname->st.st_ex_mtime;
1856                 id = vfs_file_id_from_sbuf(conn, &smb_fname->st);
1857
1858                 if (!acquire_ordered_locks(talloc_tos(),
1859                                         fsp,
1860                                         id,
1861                                         conn->connectpath,
1862                                         smb_fname,
1863                                         &old_write_time,
1864                                         &lck,
1865                                         &br_lck)) {
1866                         return NT_STATUS_SHARING_VIOLATION;
1867                 }
1868
1869                 /* Get the types we need to examine. */
1870                 find_oplock_types(fsp,
1871                                 oplock_request,
1872                                 lck,
1873                                 &batch_entry,
1874                                 &exclusive_entry,
1875                                 &got_level2_oplock,
1876                                 &got_a_none_oplock);
1877
1878                 /* First pass - send break only on batch oplocks. */
1879                 if ((req != NULL) &&
1880                                 delay_for_batch_oplocks(fsp,
1881                                         req->mid,
1882                                         oplock_request,
1883                                         batch_entry)) {
1884                         schedule_defer_open(lck, request_time, req);
1885                         TALLOC_FREE(lck);
1886                         return NT_STATUS_SHARING_VIOLATION;
1887                 }
1888
1889                 /* Use the client requested access mask here, not the one we
1890                  * open with. */
1891                 status = open_mode_check(conn, lck, fsp->name_hash,
1892                                         access_mask, share_access,
1893                                          create_options, &file_existed);
1894
1895                 if (NT_STATUS_IS_OK(status)) {
1896                         /* We might be going to allow this open. Check oplock
1897                          * status again. */
1898                         /* Second pass - send break for both batch or
1899                          * exclusive oplocks. */
1900                         if ((req != NULL) &&
1901                                         delay_for_exclusive_oplocks(
1902                                                 fsp,
1903                                                 req->mid,
1904                                                 oplock_request,
1905                                                 exclusive_entry)) {
1906                                 schedule_defer_open(lck, request_time, req);
1907                                 TALLOC_FREE(lck);
1908                                 return NT_STATUS_SHARING_VIOLATION;
1909                         }
1910                 }
1911
1912                 if (NT_STATUS_EQUAL(status, NT_STATUS_DELETE_PENDING)) {
1913                         /* DELETE_PENDING is not deferred for a second */
1914                         TALLOC_FREE(lck);
1915                         return status;
1916                 }
1917
1918                 grant_fsp_oplock_type(fsp,
1919                                 br_lck,
1920                                 oplock_request,
1921                                 got_level2_oplock,
1922                                 got_a_none_oplock);
1923
1924                 if (!NT_STATUS_IS_OK(status)) {
1925                         uint32 can_access_mask;
1926                         bool can_access = True;
1927
1928                         SMB_ASSERT(NT_STATUS_EQUAL(status, NT_STATUS_SHARING_VIOLATION));
1929
1930                         /* Check if this can be done with the deny_dos and fcb
1931                          * calls. */
1932                         if (private_flags &
1933                             (NTCREATEX_OPTIONS_PRIVATE_DENY_DOS|
1934                              NTCREATEX_OPTIONS_PRIVATE_DENY_FCB)) {
1935                                 if (req == NULL) {
1936                                         DEBUG(0, ("DOS open without an SMB "
1937                                                   "request!\n"));
1938                                         TALLOC_FREE(lck);
1939                                         return NT_STATUS_INTERNAL_ERROR;
1940                                 }
1941
1942                                 /* Use the client requested access mask here,
1943                                  * not the one we open with. */
1944                                 status = fcb_or_dos_open(req,
1945                                                         conn,
1946                                                         fsp,
1947                                                         smb_fname,
1948                                                         id,
1949                                                         req->smbpid,
1950                                                         req->vuid,
1951                                                         access_mask,
1952                                                         share_access,
1953                                                         create_options);
1954
1955                                 if (NT_STATUS_IS_OK(status)) {
1956                                         TALLOC_FREE(lck);
1957                                         if (pinfo) {
1958                                                 *pinfo = FILE_WAS_OPENED;
1959                                         }
1960                                         return NT_STATUS_OK;
1961                                 }
1962                         }
1963
1964                         /*
1965                          * This next line is a subtlety we need for
1966                          * MS-Access. If a file open will fail due to share
1967                          * permissions and also for security (access) reasons,
1968                          * we need to return the access failed error, not the
1969                          * share error. We can't open the file due to kernel
1970                          * oplock deadlock (it's possible we failed above on
1971                          * the open_mode_check()) so use a userspace check.
1972                          */
1973
1974                         if (flags & O_RDWR) {
1975                                 can_access_mask = FILE_READ_DATA|FILE_WRITE_DATA;
1976                         } else if (flags & O_WRONLY) {
1977                                 can_access_mask = FILE_WRITE_DATA;
1978                         } else {
1979                                 can_access_mask = FILE_READ_DATA;
1980                         }
1981
1982                         if (((can_access_mask & FILE_WRITE_DATA) &&
1983                                 !CAN_WRITE(conn)) ||
1984                             !can_access_file_data(conn, smb_fname,
1985                                                   can_access_mask)) {
1986                                 can_access = False;
1987                         }
1988
1989                         /*
1990                          * If we're returning a share violation, ensure we
1991                          * cope with the braindead 1 second delay.
1992                          */
1993
1994                         if (!(oplock_request & INTERNAL_OPEN_ONLY) &&
1995                             lp_defer_sharing_violations()) {
1996                                 struct timeval timeout;
1997                                 struct deferred_open_record state;
1998                                 int timeout_usecs;
1999
2000                                 /* this is a hack to speed up torture tests
2001                                    in 'make test' */
2002                                 timeout_usecs = lp_parm_int(SNUM(conn),
2003                                                             "smbd","sharedelay",
2004                                                             SHARING_VIOLATION_USEC_WAIT);
2005
2006                                 /* This is a relative time, added to the absolute
2007                                    request_time value to get the absolute timeout time.
2008                                    Note that if this is the second or greater time we enter
2009                                    this codepath for this particular request mid then
2010                                    request_time is left as the absolute time of the *first*
2011                                    time this request mid was processed. This is what allows
2012                                    the request to eventually time out. */
2013
2014                                 timeout = timeval_set(0, timeout_usecs);
2015
2016                                 /* Nothing actually uses state.delayed_for_oplocks
2017                                    but it's handy to differentiate in debug messages
2018                                    between a 30 second delay due to oplock break, and
2019                                    a 1 second delay for share mode conflicts. */
2020
2021                                 state.delayed_for_oplocks = False;
2022                                 state.id = id;
2023
2024                                 if ((req != NULL)
2025                                     && !request_timed_out(request_time,
2026                                                           timeout)) {
2027                                         defer_open(lck, request_time, timeout,
2028                                                    req, &state);
2029                                 }
2030                         }
2031
2032                         TALLOC_FREE(lck);
2033                         if (can_access) {
2034                                 /*
2035                                  * We have detected a sharing violation here
2036                                  * so return the correct error code
2037                                  */
2038                                 status = NT_STATUS_SHARING_VIOLATION;
2039                         } else {
2040                                 status = NT_STATUS_ACCESS_DENIED;
2041                         }
2042                         return status;
2043                 }
2044
2045                 /*
2046                  * We exit this block with the share entry *locked*.....
2047                  */
2048         }
2049
2050         SMB_ASSERT(!file_existed || (lck != NULL));
2051
2052         /*
2053          * Ensure we pay attention to default ACLs on directories if required.
2054          */
2055
2056         if ((flags2 & O_CREAT) && lp_inherit_acls(SNUM(conn)) &&
2057             (def_acl = directory_has_default_acl(conn, parent_dir))) {
2058                 unx_mode = (0777 & lp_create_mask(SNUM(conn)));
2059         }
2060
2061         DEBUG(4,("calling open_file with flags=0x%X flags2=0x%X mode=0%o, "
2062                 "access_mask = 0x%x, open_access_mask = 0x%x\n",
2063                  (unsigned int)flags, (unsigned int)flags2,
2064                  (unsigned int)unx_mode, (unsigned int)access_mask,
2065                  (unsigned int)open_access_mask));
2066
2067         /*
2068          * open_file strips any O_TRUNC flags itself.
2069          */
2070
2071         fsp_open = open_file(fsp, conn, req, parent_dir,
2072                              flags|flags2, unx_mode, access_mask,
2073                              open_access_mask);
2074
2075         if (!NT_STATUS_IS_OK(fsp_open)) {
2076                 TALLOC_FREE(lck);
2077                 return fsp_open;
2078         }
2079
2080         if (!file_existed) {
2081                 struct byte_range_lock *br_lck = NULL;
2082                 struct share_mode_entry *batch_entry = NULL;
2083                 struct share_mode_entry *exclusive_entry = NULL;
2084                 bool got_level2_oplock = false;
2085                 bool got_a_none_oplock = false;
2086                 struct timespec old_write_time = smb_fname->st.st_ex_mtime;
2087                 /*
2088                  * Deal with the race condition where two smbd's detect the
2089                  * file doesn't exist and do the create at the same time. One
2090                  * of them will win and set a share mode, the other (ie. this
2091                  * one) should check if the requested share mode for this
2092                  * create is allowed.
2093                  */
2094
2095                 /*
2096                  * Now the file exists and fsp is successfully opened,
2097                  * fsp->dev and fsp->inode are valid and should replace the
2098                  * dev=0,inode=0 from a non existent file. Spotted by
2099                  * Nadav Danieli <nadavd@exanet.com>. JRA.
2100                  */
2101
2102                 id = fsp->file_id;
2103
2104                 if (!acquire_ordered_locks(talloc_tos(),
2105                                         fsp,
2106                                         id,
2107                                         conn->connectpath,
2108                                         smb_fname,
2109                                         &old_write_time,
2110                                         &lck,
2111                                         &br_lck)) {
2112                         return NT_STATUS_SHARING_VIOLATION;
2113                 }
2114
2115                 /* Get the types we need to examine. */
2116                 find_oplock_types(fsp,
2117                                 oplock_request,
2118                                 lck,
2119                                 &batch_entry,
2120                                 &exclusive_entry,
2121                                 &got_level2_oplock,
2122                                 &got_a_none_oplock);
2123
2124                 /* First pass - send break only on batch oplocks. */
2125                 if ((req != NULL) &&
2126                                 delay_for_batch_oplocks(fsp,
2127                                         req->mid,
2128                                         oplock_request,
2129                                         batch_entry)) {
2130                         schedule_defer_open(lck, request_time, req);
2131                         TALLOC_FREE(lck);
2132                         fd_close(fsp);
2133                         return NT_STATUS_SHARING_VIOLATION;
2134                 }
2135
2136                 status = open_mode_check(conn, lck, fsp->name_hash,
2137                                         access_mask, share_access,
2138                                          create_options, &file_existed);
2139
2140                 if (NT_STATUS_IS_OK(status)) {
2141                         /* We might be going to allow this open. Check oplock
2142                          * status again. */
2143                         /* Second pass - send break for both batch or
2144                          * exclusive oplocks. */
2145                         if ((req != NULL) &&
2146                                         delay_for_exclusive_oplocks(
2147                                                 fsp,
2148                                                 req->mid,
2149                                                 oplock_request,
2150                                                 exclusive_entry)) {
2151                                 schedule_defer_open(lck, request_time, req);
2152                                 TALLOC_FREE(lck);
2153                                 fd_close(fsp);
2154                                 return NT_STATUS_SHARING_VIOLATION;
2155                         }
2156                 }
2157
2158                 if (!NT_STATUS_IS_OK(status)) {
2159                         struct deferred_open_record state;
2160
2161                         state.delayed_for_oplocks = False;
2162                         state.id = id;
2163
2164                         /* Do it all over again immediately. In the second
2165                          * round we will find that the file existed and handle
2166                          * the DELETE_PENDING and FCB cases correctly. No need
2167                          * to duplicate the code here. Essentially this is a
2168                          * "goto top of this function", but don't tell
2169                          * anybody... */
2170
2171                         if (req != NULL) {
2172                                 defer_open(lck, request_time, timeval_zero(),
2173                                            req, &state);
2174                         }
2175                         TALLOC_FREE(lck);
2176                         fd_close(fsp);
2177                         return status;
2178                 }
2179
2180                 grant_fsp_oplock_type(fsp,
2181                                 br_lck,
2182                                 oplock_request,
2183                                 got_level2_oplock,
2184                                 got_a_none_oplock);
2185
2186                 /*
2187                  * We exit this block with the share entry *locked*.....
2188                  */
2189
2190         }
2191
2192         SMB_ASSERT(lck != NULL);
2193
2194         /* Delete streams if create_disposition requires it */
2195         if (file_existed && clear_ads &&
2196             !is_ntfs_stream_smb_fname(smb_fname)) {
2197                 status = delete_all_streams(conn, smb_fname->base_name);
2198                 if (!NT_STATUS_IS_OK(status)) {
2199                         TALLOC_FREE(lck);
2200                         fd_close(fsp);
2201                         return status;
2202                 }
2203         }
2204
2205         /* note that we ignore failure for the following. It is
2206            basically a hack for NFS, and NFS will never set one of
2207            these only read them. Nobody but Samba can ever set a deny
2208            mode and we have already checked our more authoritative
2209            locking database for permission to set this deny mode. If
2210            the kernel refuses the operations then the kernel is wrong.
2211            note that GPFS supports it as well - jmcd */
2212
2213         if (fsp->fh->fd != -1) {
2214                 int ret_flock;
2215                 ret_flock = SMB_VFS_KERNEL_FLOCK(fsp, share_access, access_mask);
2216                 if(ret_flock == -1 ){
2217
2218                         TALLOC_FREE(lck);
2219                         fd_close(fsp);
2220
2221                         return NT_STATUS_SHARING_VIOLATION;
2222                 }
2223         }
2224
2225         /*
2226          * At this point onwards, we can guarentee that the share entry
2227          * is locked, whether we created the file or not, and that the
2228          * deny mode is compatible with all current opens.
2229          */
2230
2231         /*
2232          * If requested, truncate the file.
2233          */
2234
2235         if (file_existed && (flags2&O_TRUNC)) {
2236                 /*
2237                  * We are modifing the file after open - update the stat
2238                  * struct..
2239                  */
2240                 if ((SMB_VFS_FTRUNCATE(fsp, 0) == -1) ||
2241                     (SMB_VFS_FSTAT(fsp, &smb_fname->st)==-1)) {
2242                         status = map_nt_error_from_unix(errno);
2243                         TALLOC_FREE(lck);
2244                         fd_close(fsp);
2245                         return status;
2246                 }
2247         }
2248
2249         /*
2250          * According to Samba4, SEC_FILE_READ_ATTRIBUTE is always granted,
2251          * but we don't have to store this - just ignore it on access check.
2252          */
2253         if (conn->sconn->using_smb2) {
2254                 /*
2255                  * SMB2 doesn't return it (according to Microsoft tests).
2256                  * Test Case: TestSuite_ScenarioNo009GrantedAccessTestS0
2257                  * File created with access = 0x7 (Read, Write, Delete)
2258                  * Query Info on file returns 0x87 (Read, Write, Delete, Read Attributes)
2259                  */
2260                 fsp->access_mask = access_mask;
2261         } else {
2262                 /* But SMB1 does. */
2263                 fsp->access_mask = access_mask | FILE_READ_ATTRIBUTES;
2264         }
2265
2266         if (file_existed) {
2267                 /* stat opens on existing files don't get oplocks. */
2268                 if (is_stat_open(open_access_mask)) {
2269                         fsp->oplock_type = NO_OPLOCK;
2270                 }
2271
2272                 if (!(flags2 & O_TRUNC)) {
2273                         info = FILE_WAS_OPENED;
2274                 } else {
2275                         info = FILE_WAS_OVERWRITTEN;
2276                 }
2277         } else {
2278                 info = FILE_WAS_CREATED;
2279         }
2280
2281         if (pinfo) {
2282                 *pinfo = info;
2283         }
2284
2285         /*
2286          * Setup the oplock info in both the shared memory and
2287          * file structs.
2288          */
2289
2290         if (!set_file_oplock(fsp, fsp->oplock_type)) {
2291                 /*
2292                  * Could not get the kernel oplock or there are byte-range
2293                  * locks on the file.
2294                  */
2295                 fsp->oplock_type = NO_OPLOCK;
2296         }
2297
2298         if (info == FILE_WAS_OVERWRITTEN || info == FILE_WAS_CREATED || info == FILE_WAS_SUPERSEDED) {
2299                 new_file_created = True;
2300         }
2301
2302         set_share_mode(lck, fsp, get_current_uid(conn),
2303                         req ? req->mid : 0,
2304                        fsp->oplock_type);
2305
2306         /* Handle strange delete on close create semantics. */
2307         if (create_options & FILE_DELETE_ON_CLOSE) {
2308
2309                 status = can_set_delete_on_close(fsp, new_dos_attributes);
2310
2311                 if (!NT_STATUS_IS_OK(status)) {
2312                         /* Remember to delete the mode we just added. */
2313                         del_share_mode(lck, fsp);
2314                         TALLOC_FREE(lck);
2315                         fd_close(fsp);
2316                         return status;
2317                 }
2318                 /* Note that here we set the *inital* delete on close flag,
2319                    not the regular one. The magic gets handled in close. */
2320                 fsp->initial_delete_on_close = True;
2321         }
2322
2323         if (new_file_created) {
2324                 /* Files should be initially set as archive */
2325                 if (lp_map_archive(SNUM(conn)) ||
2326                     lp_store_dos_attributes(SNUM(conn))) {
2327                         if (!posix_open) {
2328                                 if (file_set_dosmode(conn, smb_fname,
2329                                             new_dos_attributes | FILE_ATTRIBUTE_ARCHIVE,
2330                                             parent_dir, true) == 0) {
2331                                         unx_mode = smb_fname->st.st_ex_mode;
2332                                 }
2333                         }
2334                 }
2335         }
2336
2337         /* Determine sparse flag. */
2338         if (posix_open) {
2339                 /* POSIX opens are sparse by default. */
2340                 fsp->is_sparse = true;
2341         } else {
2342                 fsp->is_sparse = (file_existed &&
2343                         (existing_dos_attributes & FILE_ATTRIBUTE_SPARSE));
2344         }
2345
2346         /*
2347          * Take care of inherited ACLs on created files - if default ACL not
2348          * selected.
2349          */
2350
2351         if (!posix_open && !file_existed && !def_acl) {
2352
2353                 int saved_errno = errno; /* We might get ENOSYS in the next
2354                                           * call.. */
2355
2356                 if (SMB_VFS_FCHMOD_ACL(fsp, unx_mode) == -1 &&
2357                     errno == ENOSYS) {
2358                         errno = saved_errno; /* Ignore ENOSYS */
2359                 }
2360
2361         } else if (new_unx_mode) {
2362
2363                 int ret = -1;
2364
2365                 /* Attributes need changing. File already existed. */
2366
2367                 {
2368                         int saved_errno = errno; /* We might get ENOSYS in the
2369                                                   * next call.. */
2370                         ret = SMB_VFS_FCHMOD_ACL(fsp, new_unx_mode);
2371
2372                         if (ret == -1 && errno == ENOSYS) {
2373                                 errno = saved_errno; /* Ignore ENOSYS */
2374                         } else {
2375                                 DEBUG(5, ("open_file_ntcreate: reset "
2376                                           "attributes of file %s to 0%o\n",
2377                                           smb_fname_str_dbg(smb_fname),
2378                                           (unsigned int)new_unx_mode));
2379                                 ret = 0; /* Don't do the fchmod below. */
2380                         }
2381                 }
2382
2383                 if ((ret == -1) &&
2384                     (SMB_VFS_FCHMOD(fsp, new_unx_mode) == -1))
2385                         DEBUG(5, ("open_file_ntcreate: failed to reset "
2386                                   "attributes of file %s to 0%o\n",
2387                                   smb_fname_str_dbg(smb_fname),
2388                                   (unsigned int)new_unx_mode));
2389         }
2390
2391         /* If this is a successful open, we must remove any deferred open
2392          * records. */
2393         if (req != NULL) {
2394                 del_deferred_open_entry(lck, req->mid,
2395                                         sconn_server_id(req->sconn));
2396         }
2397         TALLOC_FREE(lck);
2398
2399         return NT_STATUS_OK;
2400 }
2401
2402
2403 /****************************************************************************
2404  Open a file for for write to ensure that we can fchmod it.
2405 ****************************************************************************/
2406
2407 NTSTATUS open_file_fchmod(connection_struct *conn,
2408                           struct smb_filename *smb_fname,
2409                           files_struct **result)
2410 {
2411         if (!VALID_STAT(smb_fname->st)) {
2412                 return NT_STATUS_INVALID_PARAMETER;
2413         }
2414
2415         return SMB_VFS_CREATE_FILE(
2416                 conn,                                   /* conn */
2417                 NULL,                                   /* req */
2418                 0,                                      /* root_dir_fid */
2419                 smb_fname,                              /* fname */
2420                 FILE_WRITE_DATA,                        /* access_mask */
2421                 (FILE_SHARE_READ | FILE_SHARE_WRITE |   /* share_access */
2422                     FILE_SHARE_DELETE),
2423                 FILE_OPEN,                              /* create_disposition*/
2424                 0,                                      /* create_options */
2425                 0,                                      /* file_attributes */
2426                 INTERNAL_OPEN_ONLY,                     /* oplock_request */
2427                 0,                                      /* allocation_size */
2428                 0,                                      /* private_flags */
2429                 NULL,                                   /* sd */
2430                 NULL,                                   /* ea_list */
2431                 result,                                 /* result */
2432                 NULL);                                  /* pinfo */
2433 }
2434
2435 static NTSTATUS mkdir_internal(connection_struct *conn,
2436                                struct smb_filename *smb_dname,
2437                                uint32 file_attributes)
2438 {
2439         mode_t mode;
2440         char *parent_dir;
2441         NTSTATUS status;
2442         bool posix_open = false;
2443         bool need_re_stat = false;
2444         struct security_descriptor *parent_sd = NULL;
2445         uint32_t access_mask = SEC_DIR_ADD_SUBDIR;
2446         uint32_t access_granted = 0;
2447
2448         if(access_mask & ~(conn->share_access)) {
2449                 DEBUG(5,("mkdir_internal: failing share access "
2450                          "%s\n", lp_servicename(SNUM(conn))));
2451                 return NT_STATUS_ACCESS_DENIED;
2452         }
2453
2454         status = check_name(conn, smb_dname->base_name);
2455         if (!NT_STATUS_IS_OK(status)) {
2456                 return status;
2457         }
2458
2459         if (!parent_dirname(talloc_tos(), smb_dname->base_name, &parent_dir,
2460                             NULL)) {
2461                 return NT_STATUS_NO_MEMORY;
2462         }
2463
2464         if (file_attributes & FILE_FLAG_POSIX_SEMANTICS) {
2465                 posix_open = true;
2466                 mode = (mode_t)(file_attributes & ~FILE_FLAG_POSIX_SEMANTICS);
2467         } else {
2468                 mode = unix_mode(conn, FILE_ATTRIBUTE_DIRECTORY, smb_dname, parent_dir);
2469         }
2470
2471         status = SMB_VFS_GET_NT_ACL(conn,
2472                                 parent_dir,
2473                                 SECINFO_DACL,
2474                                 &parent_sd);
2475         if (!NT_STATUS_IS_OK(status)) {
2476                 DEBUG(5,("mkdir_internal: SMB_VFS_GET_NT_ACL failed for "
2477                         "%s with error %s\n",
2478                         parent_dir,
2479                         nt_errstr(status)));
2480                 return status;
2481         }
2482
2483         status = smb1_file_se_access_check(conn,
2484                                         parent_sd,
2485                                         get_current_nttok(conn),
2486                                         access_mask,
2487                                         &access_granted);
2488         if(!NT_STATUS_IS_OK(status)) {
2489                 DEBUG(5,("mkdir_internal: access check "
2490                         "on directory %s for "
2491                         "path %s for mask 0x%x returned %s\n",
2492                         parent_dir,
2493                         smb_dname->base_name,
2494                         access_mask,
2495                         nt_errstr(status) ));
2496                 return status;
2497         }
2498
2499         if (SMB_VFS_MKDIR(conn, smb_dname->base_name, mode) != 0) {
2500                 return map_nt_error_from_unix(errno);
2501         }
2502
2503         /* Ensure we're checking for a symlink here.... */
2504         /* We don't want to get caught by a symlink racer. */
2505
2506         if (SMB_VFS_LSTAT(conn, smb_dname) == -1) {
2507                 DEBUG(2, ("Could not stat directory '%s' just created: %s\n",
2508                           smb_fname_str_dbg(smb_dname), strerror(errno)));
2509                 return map_nt_error_from_unix(errno);
2510         }
2511
2512         if (!S_ISDIR(smb_dname->st.st_ex_mode)) {
2513                 DEBUG(0, ("Directory '%s' just created is not a directory !\n",
2514                           smb_fname_str_dbg(smb_dname)));
2515                 return NT_STATUS_NOT_A_DIRECTORY;
2516         }
2517
2518         if (lp_store_dos_attributes(SNUM(conn))) {
2519                 if (!posix_open) {
2520                         file_set_dosmode(conn, smb_dname,
2521                                          file_attributes | FILE_ATTRIBUTE_DIRECTORY,
2522                                          parent_dir, true);
2523                 }
2524         }
2525
2526         if (lp_inherit_perms(SNUM(conn))) {
2527                 inherit_access_posix_acl(conn, parent_dir,
2528                                          smb_dname->base_name, mode);
2529                 need_re_stat = true;
2530         }
2531
2532         if (!posix_open) {
2533                 /*
2534                  * Check if high bits should have been set,
2535                  * then (if bits are missing): add them.
2536                  * Consider bits automagically set by UNIX, i.e. SGID bit from parent
2537                  * dir.
2538                  */
2539                 if ((mode & ~(S_IRWXU|S_IRWXG|S_IRWXO)) &&
2540                     (mode & ~smb_dname->st.st_ex_mode)) {
2541                         SMB_VFS_CHMOD(conn, smb_dname->base_name,
2542                                       (smb_dname->st.st_ex_mode |
2543                                           (mode & ~smb_dname->st.st_ex_mode)));
2544                         need_re_stat = true;
2545                 }
2546         }
2547
2548         /* Change the owner if required. */
2549         if (lp_inherit_owner(SNUM(conn))) {
2550                 change_dir_owner_to_parent(conn, parent_dir,
2551                                            smb_dname->base_name,
2552                                            &smb_dname->st);
2553                 need_re_stat = true;
2554         }
2555
2556         if (need_re_stat) {
2557                 if (SMB_VFS_LSTAT(conn, smb_dname) == -1) {
2558                         DEBUG(2, ("Could not stat directory '%s' just created: %s\n",
2559                           smb_fname_str_dbg(smb_dname), strerror(errno)));
2560                         return map_nt_error_from_unix(errno);
2561                 }
2562         }
2563
2564         notify_fname(conn, NOTIFY_ACTION_ADDED, FILE_NOTIFY_CHANGE_DIR_NAME,
2565                      smb_dname->base_name);
2566
2567         return NT_STATUS_OK;
2568 }
2569
2570 /****************************************************************************
2571  Ensure we didn't get symlink raced on opening a directory.
2572 ****************************************************************************/
2573
2574 bool check_same_stat(const SMB_STRUCT_STAT *sbuf1,
2575                         const SMB_STRUCT_STAT *sbuf2)
2576 {
2577         if (sbuf1->st_ex_uid != sbuf2->st_ex_uid ||
2578                         sbuf1->st_ex_gid != sbuf2->st_ex_gid ||
2579                         sbuf1->st_ex_dev != sbuf2->st_ex_dev ||
2580                         sbuf1->st_ex_ino != sbuf2->st_ex_ino) {
2581                 return false;
2582         }
2583         return true;
2584 }
2585
2586 /****************************************************************************
2587  Open a directory from an NT SMB call.
2588 ****************************************************************************/
2589
2590 static NTSTATUS open_directory(connection_struct *conn,
2591                                struct smb_request *req,
2592                                struct smb_filename *smb_dname,
2593                                uint32 access_mask,
2594                                uint32 share_access,
2595                                uint32 create_disposition,
2596                                uint32 create_options,
2597                                uint32 file_attributes,
2598                                int *pinfo,
2599                                files_struct **result)
2600 {
2601         files_struct *fsp = NULL;
2602         bool dir_existed = VALID_STAT(smb_dname->st) ? True : False;
2603         struct share_mode_lock *lck = NULL;
2604         NTSTATUS status;
2605         struct timespec mtimespec;
2606         int info = 0;
2607
2608         SMB_ASSERT(!is_ntfs_stream_smb_fname(smb_dname));
2609
2610         /* Ensure we have a directory attribute. */
2611         file_attributes |= FILE_ATTRIBUTE_DIRECTORY;
2612
2613         DEBUG(5,("open_directory: opening directory %s, access_mask = 0x%x, "
2614                  "share_access = 0x%x create_options = 0x%x, "
2615                  "create_disposition = 0x%x, file_attributes = 0x%x\n",
2616                  smb_fname_str_dbg(smb_dname),
2617                  (unsigned int)access_mask,
2618                  (unsigned int)share_access,
2619                  (unsigned int)create_options,
2620                  (unsigned int)create_disposition,
2621                  (unsigned int)file_attributes));
2622
2623         if (!(file_attributes & FILE_FLAG_POSIX_SEMANTICS) &&
2624                         (conn->fs_capabilities & FILE_NAMED_STREAMS) &&
2625                         is_ntfs_stream_smb_fname(smb_dname)) {
2626                 DEBUG(2, ("open_directory: %s is a stream name!\n",
2627                           smb_fname_str_dbg(smb_dname)));
2628                 return NT_STATUS_NOT_A_DIRECTORY;
2629         }
2630
2631         status = smbd_calculate_access_mask(conn, smb_dname, dir_existed,
2632                                             access_mask, &access_mask);
2633         if (!NT_STATUS_IS_OK(status)) {
2634                 DEBUG(10, ("open_directory: smbd_calculate_access_mask "
2635                         "on file %s returned %s\n",
2636                         smb_fname_str_dbg(smb_dname),
2637                         nt_errstr(status)));
2638                 return status;
2639         }
2640
2641         if ((access_mask & SEC_FLAG_SYSTEM_SECURITY) &&
2642                         !security_token_has_privilege(get_current_nttok(conn),
2643                                         SEC_PRIV_SECURITY)) {
2644                 DEBUG(10, ("open_directory: open on %s "
2645                         "failed - SEC_FLAG_SYSTEM_SECURITY denied.\n",
2646                         smb_fname_str_dbg(smb_dname)));
2647                 return NT_STATUS_PRIVILEGE_NOT_HELD;
2648         }
2649
2650         switch( create_disposition ) {
2651                 case FILE_OPEN:
2652
2653                         if (!dir_existed) {
2654                                 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
2655                         }
2656
2657                         info = FILE_WAS_OPENED;
2658                         break;
2659
2660                 case FILE_CREATE:
2661
2662                         /* If directory exists error. If directory doesn't
2663                          * exist create. */
2664
2665                         if (dir_existed) {
2666                                 status = NT_STATUS_OBJECT_NAME_COLLISION;
2667                                 DEBUG(2, ("open_directory: unable to create "
2668                                           "%s. Error was %s\n",
2669                                           smb_fname_str_dbg(smb_dname),
2670                                           nt_errstr(status)));
2671                                 return status;
2672                         }
2673
2674                         status = mkdir_internal(conn, smb_dname,
2675                                                 file_attributes);
2676
2677                         if (!NT_STATUS_IS_OK(status)) {
2678                                 DEBUG(2, ("open_directory: unable to create "
2679                                           "%s. Error was %s\n",
2680                                           smb_fname_str_dbg(smb_dname),
2681                                           nt_errstr(status)));
2682                                 return status;
2683                         }
2684
2685                         info = FILE_WAS_CREATED;
2686                         break;
2687
2688                 case FILE_OPEN_IF:
2689                         /*
2690                          * If directory exists open. If directory doesn't
2691                          * exist create.
2692                          */
2693
2694                         if (dir_existed) {
2695                                 status = NT_STATUS_OK;
2696                                 info = FILE_WAS_OPENED;
2697                         } else {
2698                                 status = mkdir_internal(conn, smb_dname,
2699                                                 file_attributes);
2700
2701                                 if (NT_STATUS_IS_OK(status)) {
2702                                         info = FILE_WAS_CREATED;
2703                                 } else {
2704                                         /* Cope with create race. */
2705                                         if (!NT_STATUS_EQUAL(status,
2706                                                         NT_STATUS_OBJECT_NAME_COLLISION)) {
2707                                                 DEBUG(2, ("open_directory: unable to create "
2708                                                         "%s. Error was %s\n",
2709                                                         smb_fname_str_dbg(smb_dname),
2710                                                         nt_errstr(status)));
2711                                                 return status;
2712                                         }
2713                                         info = FILE_WAS_OPENED;
2714                                 }
2715                         }
2716
2717                         break;
2718
2719                 case FILE_SUPERSEDE:
2720                 case FILE_OVERWRITE:
2721                 case FILE_OVERWRITE_IF:
2722                 default:
2723                         DEBUG(5,("open_directory: invalid create_disposition "
2724                                  "0x%x for directory %s\n",
2725                                  (unsigned int)create_disposition,
2726                                  smb_fname_str_dbg(smb_dname)));
2727                         return NT_STATUS_INVALID_PARAMETER;
2728         }
2729
2730         if(!S_ISDIR(smb_dname->st.st_ex_mode)) {
2731                 DEBUG(5,("open_directory: %s is not a directory !\n",
2732                          smb_fname_str_dbg(smb_dname)));
2733                 return NT_STATUS_NOT_A_DIRECTORY;
2734         }
2735
2736         if (info == FILE_WAS_OPENED) {
2737                 uint32_t access_granted = 0;
2738                 status = smbd_check_open_rights(conn, smb_dname, access_mask,
2739                                                 &access_granted);
2740
2741                 /* Were we trying to do a directory open
2742                  * for delete and didn't get DELETE
2743                  * access (only) ? Check if the
2744                  * directory allows DELETE_CHILD.
2745                  * See here:
2746                  * http://blogs.msdn.com/oldnewthing/archive/2004/06/04/148426.aspx
2747                  * for details. */
2748
2749                 if ((NT_STATUS_EQUAL(status, NT_STATUS_ACCESS_DENIED) &&
2750                         (access_mask & DELETE_ACCESS) &&
2751                         (access_granted == DELETE_ACCESS) &&
2752                         can_delete_file_in_directory(conn, smb_dname))) {
2753                         DEBUG(10,("open_directory: overrode ACCESS_DENIED "
2754                                 "on directory %s\n",
2755                                 smb_fname_str_dbg(smb_dname)));
2756                         status = NT_STATUS_OK;
2757                 }
2758
2759                 if (!NT_STATUS_IS_OK(status)) {
2760                         DEBUG(10, ("open_directory: smbd_check_open_rights on "
2761                                 "file %s failed with %s\n",
2762                                 smb_fname_str_dbg(smb_dname),
2763                                 nt_errstr(status)));
2764                         return status;
2765                 }
2766         }
2767
2768         status = file_new(req, conn, &fsp);
2769         if(!NT_STATUS_IS_OK(status)) {
2770                 return status;
2771         }
2772
2773         /*
2774          * Setup the files_struct for it.
2775          */
2776
2777         fsp->mode = smb_dname->st.st_ex_mode;
2778         fsp->file_id = vfs_file_id_from_sbuf(conn, &smb_dname->st);
2779         fsp->vuid = req ? req->vuid : UID_FIELD_INVALID;
2780         fsp->file_pid = req ? req->smbpid : 0;
2781         fsp->can_lock = False;
2782         fsp->can_read = False;
2783         fsp->can_write = False;
2784
2785         fsp->share_access = share_access;
2786         fsp->fh->private_options = 0;
2787         /*
2788          * According to Samba4, SEC_FILE_READ_ATTRIBUTE is always granted,
2789          */
2790         fsp->access_mask = access_mask | FILE_READ_ATTRIBUTES;
2791         fsp->print_file = NULL;
2792         fsp->modified = False;
2793         fsp->oplock_type = NO_OPLOCK;
2794         fsp->sent_oplock_break = NO_BREAK_SENT;
2795         fsp->is_directory = True;
2796         fsp->posix_open = (file_attributes & FILE_FLAG_POSIX_SEMANTICS) ? True : False;
2797         status = fsp_set_smb_fname(fsp, smb_dname);
2798         if (!NT_STATUS_IS_OK(status)) {
2799                 file_free(req, fsp);
2800                 return status;
2801         }
2802
2803         mtimespec = smb_dname->st.st_ex_mtime;
2804
2805 #ifdef O_DIRECTORY
2806         status = fd_open(conn, fsp, O_RDONLY|O_DIRECTORY, 0);
2807 #else
2808         /* POSIX allows us to open a directory with O_RDONLY. */
2809         status = fd_open(conn, fsp, O_RDONLY, 0);
2810 #endif
2811         if (!NT_STATUS_IS_OK(status)) {
2812                 DEBUG(5, ("open_directory: Could not open fd for "
2813                         "%s (%s)\n",
2814                         smb_fname_str_dbg(smb_dname),
2815                         nt_errstr(status)));
2816                 file_free(req, fsp);
2817                 return status;
2818         }
2819
2820         status = vfs_stat_fsp(fsp);
2821         if (!NT_STATUS_IS_OK(status)) {
2822                 fd_close(fsp);
2823                 file_free(req, fsp);
2824                 return status;
2825         }
2826
2827         /* Ensure there was no race condition. */
2828         if (!check_same_stat(&smb_dname->st, &fsp->fsp_name->st)) {
2829                 DEBUG(5,("open_directory: stat struct differs for "
2830                         "directory %s.\n",
2831                         smb_fname_str_dbg(smb_dname)));
2832                 fd_close(fsp);
2833                 file_free(req, fsp);
2834                 return NT_STATUS_ACCESS_DENIED;
2835         }
2836
2837         lck = get_share_mode_lock(talloc_tos(), fsp->file_id,
2838                                   conn->connectpath, smb_dname, &mtimespec);
2839
2840         if (lck == NULL) {
2841                 DEBUG(0, ("open_directory: Could not get share mode lock for "
2842                           "%s\n", smb_fname_str_dbg(smb_dname)));
2843                 fd_close(fsp);
2844                 file_free(req, fsp);
2845                 return NT_STATUS_SHARING_VIOLATION;
2846         }
2847
2848         status = open_mode_check(conn, lck, fsp->name_hash,
2849                                 access_mask, share_access,
2850                                  create_options, &dir_existed);
2851
2852         if (!NT_STATUS_IS_OK(status)) {
2853                 TALLOC_FREE(lck);
2854                 fd_close(fsp);
2855                 file_free(req, fsp);
2856                 return status;
2857         }
2858
2859         set_share_mode(lck, fsp, get_current_uid(conn),
2860                         req ? req->mid : 0, NO_OPLOCK);
2861
2862         /* For directories the delete on close bit at open time seems
2863            always to be honored on close... See test 19 in Samba4 BASE-DELETE. */
2864         if (create_options & FILE_DELETE_ON_CLOSE) {
2865                 status = can_set_delete_on_close(fsp, 0);
2866                 if (!NT_STATUS_IS_OK(status) && !NT_STATUS_EQUAL(status, NT_STATUS_DIRECTORY_NOT_EMPTY)) {
2867                         TALLOC_FREE(lck);
2868                         fd_close(fsp);
2869                         file_free(req, fsp);
2870                         return status;
2871                 }
2872
2873                 if (NT_STATUS_IS_OK(status)) {
2874                         /* Note that here we set the *inital* delete on close flag,
2875                            not the regular one. The magic gets handled in close. */
2876                         fsp->initial_delete_on_close = True;
2877                 }
2878         }
2879
2880         TALLOC_FREE(lck);
2881
2882         if (pinfo) {
2883                 *pinfo = info;
2884         }
2885
2886         *result = fsp;
2887         return NT_STATUS_OK;
2888 }
2889
2890 NTSTATUS create_directory(connection_struct *conn, struct smb_request *req,
2891                           struct smb_filename *smb_dname)
2892 {
2893         NTSTATUS status;
2894         files_struct *fsp;
2895
2896         status = SMB_VFS_CREATE_FILE(
2897                 conn,                                   /* conn */
2898                 req,                                    /* req */
2899                 0,                                      /* root_dir_fid */
2900                 smb_dname,                              /* fname */
2901                 FILE_READ_ATTRIBUTES,                   /* access_mask */
2902                 FILE_SHARE_NONE,                        /* share_access */
2903                 FILE_CREATE,                            /* create_disposition*/
2904                 FILE_DIRECTORY_FILE,                    /* create_options */
2905                 FILE_ATTRIBUTE_DIRECTORY,               /* file_attributes */
2906                 0,                                      /* oplock_request */
2907                 0,                                      /* allocation_size */
2908                 0,                                      /* private_flags */
2909                 NULL,                                   /* sd */
2910                 NULL,                                   /* ea_list */
2911                 &fsp,                                   /* result */
2912                 NULL);                                  /* pinfo */
2913
2914         if (NT_STATUS_IS_OK(status)) {
2915                 close_file(req, fsp, NORMAL_CLOSE);
2916         }
2917
2918         return status;
2919 }
2920
2921 /****************************************************************************
2922  Receive notification that one of our open files has been renamed by another
2923  smbd process.
2924 ****************************************************************************/
2925
2926 void msg_file_was_renamed(struct messaging_context *msg,
2927                           void *private_data,
2928                           uint32_t msg_type,
2929                           struct server_id server_id,
2930                           DATA_BLOB *data)
2931 {
2932         struct smbd_server_connection *sconn;
2933         files_struct *fsp;
2934         char *frm = (char *)data->data;
2935         struct file_id id;
2936         const char *sharepath;
2937         const char *base_name;
2938         const char *stream_name;
2939         struct smb_filename *smb_fname = NULL;
2940         size_t sp_len, bn_len;
2941         NTSTATUS status;
2942
2943         sconn = msg_ctx_to_sconn(msg);
2944         if (sconn == NULL) {
2945                 DEBUG(1, ("could not find sconn\n"));
2946                 return;
2947         }
2948
2949         if (data->data == NULL
2950             || data->length < MSG_FILE_RENAMED_MIN_SIZE + 2) {
2951                 DEBUG(0, ("msg_file_was_renamed: Got invalid msg len %d\n",
2952                           (int)data->length));
2953                 return;
2954         }
2955
2956         /* Unpack the message. */
2957         pull_file_id_24(frm, &id);
2958         sharepath = &frm[24];
2959         sp_len = strlen(sharepath);
2960         base_name = sharepath + sp_len + 1;
2961         bn_len = strlen(base_name);
2962         stream_name = sharepath + sp_len + 1 + bn_len + 1;
2963
2964         /* stream_name must always be NULL if there is no stream. */
2965         if (stream_name[0] == '\0') {
2966                 stream_name = NULL;
2967         }
2968
2969         status = create_synthetic_smb_fname(talloc_tos(), base_name,
2970                                             stream_name, NULL, &smb_fname);
2971         if (!NT_STATUS_IS_OK(status)) {
2972                 return;
2973         }
2974
2975         DEBUG(10,("msg_file_was_renamed: Got rename message for sharepath %s, new name %s, "
2976                 "file_id %s\n",
2977                 sharepath, smb_fname_str_dbg(smb_fname),
2978                 file_id_string_tos(&id)));
2979
2980         for(fsp = file_find_di_first(sconn, id); fsp;
2981             fsp = file_find_di_next(fsp)) {
2982                 if (memcmp(fsp->conn->connectpath, sharepath, sp_len) == 0) {
2983
2984                         DEBUG(10,("msg_file_was_renamed: renaming file fnum %d from %s -> %s\n",
2985                                 fsp->fnum, fsp_str_dbg(fsp),
2986                                 smb_fname_str_dbg(smb_fname)));
2987                         status = fsp_set_smb_fname(fsp, smb_fname);
2988                         if (!NT_STATUS_IS_OK(status)) {
2989                                 goto out;
2990                         }
2991                 } else {
2992                         /* TODO. JRA. */
2993                         /* Now we have the complete path we can work out if this is
2994                            actually within this share and adjust newname accordingly. */
2995                         DEBUG(10,("msg_file_was_renamed: share mismatch (sharepath %s "
2996                                 "not sharepath %s) "
2997                                 "fnum %d from %s -> %s\n",
2998                                 fsp->conn->connectpath,
2999                                 sharepath,
3000                                 fsp->fnum,
3001                                 fsp_str_dbg(fsp),
3002                                 smb_fname_str_dbg(smb_fname)));
3003                 }
3004         }
3005  out:
3006         TALLOC_FREE(smb_fname);
3007         return;
3008 }
3009
3010 /*
3011  * If a main file is opened for delete, all streams need to be checked for
3012  * !FILE_SHARE_DELETE. Do this by opening with DELETE_ACCESS.
3013  * If that works, delete them all by setting the delete on close and close.
3014  */
3015
3016 NTSTATUS open_streams_for_delete(connection_struct *conn,
3017                                         const char *fname)
3018 {
3019         struct stream_struct *stream_info = NULL;
3020         files_struct **streams = NULL;
3021         int i;
3022         unsigned int num_streams = 0;
3023         TALLOC_CTX *frame = talloc_stackframe();
3024         NTSTATUS status;
3025
3026         status = vfs_streaminfo(conn, NULL, fname, talloc_tos(),
3027                                 &num_streams, &stream_info);
3028
3029         if (NT_STATUS_EQUAL(status, NT_STATUS_NOT_IMPLEMENTED)
3030             || NT_STATUS_EQUAL(status, NT_STATUS_OBJECT_NAME_NOT_FOUND)) {
3031                 DEBUG(10, ("no streams around\n"));
3032                 TALLOC_FREE(frame);
3033                 return NT_STATUS_OK;
3034         }
3035
3036         if (!NT_STATUS_IS_OK(status)) {
3037                 DEBUG(10, ("vfs_streaminfo failed: %s\n",
3038                            nt_errstr(status)));
3039                 goto fail;
3040         }
3041
3042         DEBUG(10, ("open_streams_for_delete found %d streams\n",
3043                    num_streams));
3044
3045         if (num_streams == 0) {
3046                 TALLOC_FREE(frame);
3047                 return NT_STATUS_OK;
3048         }
3049
3050         streams = talloc_array(talloc_tos(), files_struct *, num_streams);
3051         if (streams == NULL) {
3052                 DEBUG(0, ("talloc failed\n"));
3053                 status = NT_STATUS_NO_MEMORY;
3054                 goto fail;
3055         }
3056
3057         for (i=0; i<num_streams; i++) {
3058                 struct smb_filename *smb_fname = NULL;
3059
3060                 if (strequal(stream_info[i].name, "::$DATA")) {
3061                         streams[i] = NULL;
3062                         continue;
3063                 }
3064
3065                 status = create_synthetic_smb_fname(talloc_tos(), fname,
3066                                                     stream_info[i].name,
3067                                                     NULL, &smb_fname);
3068                 if (!NT_STATUS_IS_OK(status)) {
3069                         goto fail;
3070                 }
3071
3072                 if (SMB_VFS_STAT(conn, smb_fname) == -1) {
3073                         DEBUG(10, ("Unable to stat stream: %s\n",
3074                                    smb_fname_str_dbg(smb_fname)));
3075                 }
3076
3077                 status = SMB_VFS_CREATE_FILE(
3078                          conn,                  /* conn */
3079                          NULL,                  /* req */
3080                          0,                     /* root_dir_fid */
3081                          smb_fname,             /* fname */
3082                          DELETE_ACCESS,         /* access_mask */
3083                          (FILE_SHARE_READ |     /* share_access */
3084                              FILE_SHARE_WRITE | FILE_SHARE_DELETE),
3085                          FILE_OPEN,             /* create_disposition*/
3086                          0,                     /* create_options */
3087                          FILE_ATTRIBUTE_NORMAL, /* file_attributes */
3088                          0,                     /* oplock_request */
3089                          0,                     /* allocation_size */
3090                          NTCREATEX_OPTIONS_PRIVATE_STREAM_DELETE, /* private_flags */
3091                          NULL,                  /* sd */
3092                          NULL,                  /* ea_list */
3093                          &streams[i],           /* result */
3094                          NULL);                 /* pinfo */
3095
3096                 if (!NT_STATUS_IS_OK(status)) {
3097                         DEBUG(10, ("Could not open stream %s: %s\n",
3098                                    smb_fname_str_dbg(smb_fname),
3099                                    nt_errstr(status)));
3100
3101                         TALLOC_FREE(smb_fname);
3102                         break;
3103                 }
3104                 TALLOC_FREE(smb_fname);
3105         }
3106
3107         /*
3108          * don't touch the variable "status" beyond this point :-)
3109          */
3110
3111         for (i -= 1 ; i >= 0; i--) {
3112                 if (streams[i] == NULL) {
3113                         continue;
3114                 }
3115
3116                 DEBUG(10, ("Closing stream # %d, %s\n", i,
3117                            fsp_str_dbg(streams[i])));
3118                 close_file(NULL, streams[i], NORMAL_CLOSE);
3119         }
3120
3121  fail:
3122         TALLOC_FREE(frame);
3123         return status;
3124 }
3125
3126 /*
3127  * Wrapper around open_file_ntcreate and open_directory
3128  */
3129
3130 static NTSTATUS create_file_unixpath(connection_struct *conn,
3131                                      struct smb_request *req,
3132                                      struct smb_filename *smb_fname,
3133                                      uint32_t access_mask,
3134                                      uint32_t share_access,
3135                                      uint32_t create_disposition,
3136                                      uint32_t create_options,
3137                                      uint32_t file_attributes,
3138                                      uint32_t oplock_request,
3139                                      uint64_t allocation_size,
3140                                      uint32_t private_flags,
3141                                      struct security_descriptor *sd,
3142                                      struct ea_list *ea_list,
3143
3144                                      files_struct **result,
3145                                      int *pinfo)
3146 {
3147         int info = FILE_WAS_OPENED;
3148         files_struct *base_fsp = NULL;
3149         files_struct *fsp = NULL;
3150         NTSTATUS status;
3151
3152         DEBUG(10,("create_file_unixpath: access_mask = 0x%x "
3153                   "file_attributes = 0x%x, share_access = 0x%x, "
3154                   "create_disposition = 0x%x create_options = 0x%x "
3155                   "oplock_request = 0x%x private_flags = 0x%x "
3156                   "ea_list = 0x%p, sd = 0x%p, "
3157                   "fname = %s\n",
3158                   (unsigned int)access_mask,
3159                   (unsigned int)file_attributes,
3160                   (unsigned int)share_access,
3161                   (unsigned int)create_disposition,
3162                   (unsigned int)create_options,
3163                   (unsigned int)oplock_request,
3164                   (unsigned int)private_flags,
3165                   ea_list, sd, smb_fname_str_dbg(smb_fname)));
3166
3167         if (create_options & FILE_OPEN_BY_FILE_ID) {
3168                 status = NT_STATUS_NOT_SUPPORTED;
3169                 goto fail;
3170         }
3171
3172         if (create_options & NTCREATEX_OPTIONS_INVALID_PARAM_MASK) {
3173                 status = NT_STATUS_INVALID_PARAMETER;
3174                 goto fail;
3175         }
3176
3177         if (req == NULL) {
3178                 oplock_request |= INTERNAL_OPEN_ONLY;
3179         }
3180
3181         if ((conn->fs_capabilities & FILE_NAMED_STREAMS)
3182             && (access_mask & DELETE_ACCESS)
3183             && !is_ntfs_stream_smb_fname(smb_fname)) {
3184                 /*
3185                  * We can't open a file with DELETE access if any of the
3186                  * streams is open without FILE_SHARE_DELETE
3187                  */
3188                 status = open_streams_for_delete(conn, smb_fname->base_name);
3189
3190                 if (!NT_STATUS_IS_OK(status)) {
3191                         goto fail;
3192                 }
3193         }
3194
3195         /* This is the correct thing to do (check every time) but can_delete
3196          * is expensive (it may have to read the parent directory
3197          * permissions). So for now we're not doing it unless we have a strong
3198          * hint the client is really going to delete this file. If the client
3199          * is forcing FILE_CREATE let the filesystem take care of the
3200          * permissions. */
3201
3202         /* Setting FILE_SHARE_DELETE is the hint. */
3203
3204         if ((create_disposition != FILE_CREATE)
3205             && (access_mask & DELETE_ACCESS)
3206             && (!(can_delete_file_in_directory(conn, smb_fname) ||
3207                  can_access_file_acl(conn, smb_fname, DELETE_ACCESS)))) {
3208                 status = NT_STATUS_ACCESS_DENIED;
3209                 DEBUG(10,("create_file_unixpath: open file %s "
3210                           "for delete ACCESS_DENIED\n",
3211                           smb_fname_str_dbg(smb_fname)));
3212                 goto fail;
3213         }
3214
3215         if ((access_mask & SEC_FLAG_SYSTEM_SECURITY) &&
3216                         !security_token_has_privilege(get_current_nttok(conn),
3217                                         SEC_PRIV_SECURITY)) {
3218                 DEBUG(10, ("create_file_unixpath: open on %s "
3219                         "failed - SEC_FLAG_SYSTEM_SECURITY denied.\n",
3220                         smb_fname_str_dbg(smb_fname)));
3221                 status = NT_STATUS_PRIVILEGE_NOT_HELD;
3222                 goto fail;
3223         }
3224
3225         if ((conn->fs_capabilities & FILE_NAMED_STREAMS)
3226             && is_ntfs_stream_smb_fname(smb_fname)
3227             && (!(private_flags & NTCREATEX_OPTIONS_PRIVATE_STREAM_DELETE))) {
3228                 uint32 base_create_disposition;
3229                 struct smb_filename *smb_fname_base = NULL;
3230
3231                 if (create_options & FILE_DIRECTORY_FILE) {
3232                         status = NT_STATUS_NOT_A_DIRECTORY;
3233                         goto fail;
3234                 }
3235
3236                 switch (create_disposition) {
3237                 case FILE_OPEN:
3238                         base_create_disposition = FILE_OPEN;
3239                         break;
3240                 default:
3241                         base_create_disposition = FILE_OPEN_IF;
3242                         break;
3243                 }
3244
3245                 /* Create an smb_filename with stream_name == NULL. */
3246                 status = create_synthetic_smb_fname(talloc_tos(),
3247                                                     smb_fname->base_name,
3248                                                     NULL, NULL,
3249                                                     &smb_fname_base);
3250                 if (!NT_STATUS_IS_OK(status)) {
3251                         goto fail;
3252                 }
3253
3254                 if (SMB_VFS_STAT(conn, smb_fname_base) == -1) {
3255                         DEBUG(10, ("Unable to stat stream: %s\n",
3256                                    smb_fname_str_dbg(smb_fname_base)));
3257                 }
3258
3259                 /* Open the base file. */
3260                 status = create_file_unixpath(conn, NULL, smb_fname_base, 0,
3261                                               FILE_SHARE_READ
3262                                               | FILE_SHARE_WRITE
3263                                               | FILE_SHARE_DELETE,
3264                                               base_create_disposition,
3265                                               0, 0, 0, 0, 0, NULL, NULL,
3266                                               &base_fsp, NULL);
3267                 TALLOC_FREE(smb_fname_base);
3268
3269                 if (!NT_STATUS_IS_OK(status)) {
3270                         DEBUG(10, ("create_file_unixpath for base %s failed: "
3271                                    "%s\n", smb_fname->base_name,
3272                                    nt_errstr(status)));
3273                         goto fail;
3274                 }
3275                 /* we don't need to low level fd */
3276                 fd_close(base_fsp);
3277         }
3278
3279         /*
3280          * If it's a request for a directory open, deal with it separately.
3281          */
3282
3283         if (create_options & FILE_DIRECTORY_FILE) {
3284
3285                 if (create_options & FILE_NON_DIRECTORY_FILE) {
3286                         status = NT_STATUS_INVALID_PARAMETER;
3287                         goto fail;
3288                 }
3289
3290                 /* Can't open a temp directory. IFS kit test. */
3291                 if (!(file_attributes & FILE_FLAG_POSIX_SEMANTICS) &&
3292                      (file_attributes & FILE_ATTRIBUTE_TEMPORARY)) {
3293                         status = NT_STATUS_INVALID_PARAMETER;
3294                         goto fail;
3295                 }
3296
3297                 /*
3298                  * We will get a create directory here if the Win32
3299                  * app specified a security descriptor in the
3300                  * CreateDirectory() call.
3301                  */
3302
3303                 oplock_request = 0;
3304                 status = open_directory(
3305                         conn, req, smb_fname, access_mask, share_access,
3306                         create_disposition, create_options, file_attributes,
3307                         &info, &fsp);
3308         } else {
3309
3310                 /*
3311                  * Ordinary file case.
3312                  */
3313
3314                 status = file_new(req, conn, &fsp);
3315                 if(!NT_STATUS_IS_OK(status)) {
3316                         goto fail;
3317                 }
3318
3319                 status = fsp_set_smb_fname(fsp, smb_fname);
3320                 if (!NT_STATUS_IS_OK(status)) {
3321                         goto fail;
3322                 }
3323
3324                 /*
3325                  * We're opening the stream element of a base_fsp
3326                  * we already opened. Set up the base_fsp pointer.
3327                  */
3328                 if (base_fsp) {
3329                         fsp->base_fsp = base_fsp;
3330                 }
3331
3332                 status = open_file_ntcreate(conn,
3333                                             req,
3334                                             access_mask,
3335                                             share_access,
3336                                             create_disposition,
3337                                             create_options,
3338                                             file_attributes,
3339                                             oplock_request,
3340                                             private_flags,
3341                                             &info,
3342                                             fsp);
3343
3344                 if(!NT_STATUS_IS_OK(status)) {
3345                         file_free(req, fsp);
3346                         fsp = NULL;
3347                 }
3348
3349                 if (NT_STATUS_EQUAL(status, NT_STATUS_FILE_IS_A_DIRECTORY)) {
3350
3351                         /* A stream open never opens a directory */
3352
3353                         if (base_fsp) {
3354                                 status = NT_STATUS_FILE_IS_A_DIRECTORY;
3355                                 goto fail;
3356                         }
3357
3358                         /*
3359                          * Fail the open if it was explicitly a non-directory
3360                          * file.
3361                          */
3362
3363                         if (create_options & FILE_NON_DIRECTORY_FILE) {
3364                                 status = NT_STATUS_FILE_IS_A_DIRECTORY;
3365                                 goto fail;
3366                         }
3367
3368                         oplock_request = 0;
3369                         status = open_directory(
3370                                 conn, req, smb_fname, access_mask,
3371                                 share_access, create_disposition,
3372                                 create_options, file_attributes,
3373                                 &info, &fsp);
3374                 }
3375         }
3376
3377         if (!NT_STATUS_IS_OK(status)) {
3378                 goto fail;
3379         }
3380
3381         fsp->base_fsp = base_fsp;
3382
3383         /*
3384          * According to the MS documentation, the only time the security
3385          * descriptor is applied to the opened file is iff we *created* the
3386          * file; an existing file stays the same.
3387          *
3388          * Also, it seems (from observation) that you can open the file with
3389          * any access mask but you can still write the sd. We need to override
3390          * the granted access before we call set_sd
3391          * Patch for bug #2242 from Tom Lackemann <cessnatomny@yahoo.com>.
3392          */
3393
3394         if ((sd != NULL) && (info == FILE_WAS_CREATED)
3395             && lp_nt_acl_support(SNUM(conn))) {
3396
3397                 uint32_t sec_info_sent;
3398                 uint32_t saved_access_mask = fsp->access_mask;
3399
3400                 sec_info_sent = get_sec_info(sd);
3401
3402                 fsp->access_mask = FILE_GENERIC_ALL;
3403
3404                 /* Convert all the generic bits. */
3405                 security_acl_map_generic(sd->dacl, &file_generic_mapping);
3406                 security_acl_map_generic(sd->sacl, &file_generic_mapping);
3407
3408                 if (sec_info_sent & (SECINFO_OWNER|
3409                                         SECINFO_GROUP|
3410                                         SECINFO_DACL|
3411                                         SECINFO_SACL)) {
3412                         status = SMB_VFS_FSET_NT_ACL(fsp, sec_info_sent, sd);
3413                 }
3414
3415                 fsp->access_mask = saved_access_mask;
3416
3417                 if (!NT_STATUS_IS_OK(status)) {
3418                         goto fail;
3419                 }
3420         }
3421
3422         if ((ea_list != NULL) &&
3423             ((info == FILE_WAS_CREATED) || (info == FILE_WAS_OVERWRITTEN))) {
3424                 status = set_ea(conn, fsp, fsp->fsp_name, ea_list);
3425                 if (!NT_STATUS_IS_OK(status)) {
3426                         goto fail;
3427                 }
3428         }
3429
3430         if (!fsp->is_directory && S_ISDIR(fsp->fsp_name->st.st_ex_mode)) {
3431                 status = NT_STATUS_ACCESS_DENIED;
3432                 goto fail;
3433         }
3434
3435         /* Save the requested allocation size. */
3436         if ((info == FILE_WAS_CREATED) || (info == FILE_WAS_OVERWRITTEN)) {
3437                 if (allocation_size
3438                     && (allocation_size > fsp->fsp_name->st.st_ex_size)) {
3439                         fsp->initial_allocation_size = smb_roundup(
3440                                 fsp->conn, allocation_size);
3441                         if (fsp->is_directory) {
3442                                 /* Can't set allocation size on a directory. */
3443                                 status = NT_STATUS_ACCESS_DENIED;
3444                                 goto fail;
3445                         }
3446                         if (vfs_allocate_file_space(
3447                                     fsp, fsp->initial_allocation_size) == -1) {
3448                                 status = NT_STATUS_DISK_FULL;
3449                                 goto fail;
3450                         }
3451                 } else {
3452                         fsp->initial_allocation_size = smb_roundup(
3453                                 fsp->conn, (uint64_t)fsp->fsp_name->st.st_ex_size);
3454                 }
3455         }
3456
3457         DEBUG(10, ("create_file_unixpath: info=%d\n", info));
3458
3459         *result = fsp;
3460         if (pinfo != NULL) {
3461                 *pinfo = info;
3462         }
3463
3464         smb_fname->st = fsp->fsp_name->st;
3465
3466         return NT_STATUS_OK;
3467
3468  fail:
3469         DEBUG(10, ("create_file_unixpath: %s\n", nt_errstr(status)));
3470
3471         if (fsp != NULL) {
3472                 if (base_fsp && fsp->base_fsp == base_fsp) {
3473                         /*
3474                          * The close_file below will close
3475                          * fsp->base_fsp.
3476                          */
3477                         base_fsp = NULL;
3478                 }
3479                 close_file(req, fsp, ERROR_CLOSE);
3480                 fsp = NULL;
3481         }
3482         if (base_fsp != NULL) {
3483                 close_file(req, base_fsp, ERROR_CLOSE);
3484                 base_fsp = NULL;
3485         }
3486         return status;
3487 }
3488
3489 /*
3490  * Calculate the full path name given a relative fid.
3491  */
3492 NTSTATUS get_relative_fid_filename(connection_struct *conn,
3493                                    struct smb_request *req,
3494                                    uint16_t root_dir_fid,
3495                                    const struct smb_filename *smb_fname,
3496                                    struct smb_filename **smb_fname_out)
3497 {
3498         files_struct *dir_fsp;
3499         char *parent_fname = NULL;
3500         char *new_base_name = NULL;
3501         NTSTATUS status;
3502
3503         if (root_dir_fid == 0 || !smb_fname) {
3504                 status = NT_STATUS_INTERNAL_ERROR;
3505                 goto out;
3506         }
3507
3508         dir_fsp = file_fsp(req, root_dir_fid);
3509
3510         if (dir_fsp == NULL) {
3511                 status = NT_STATUS_INVALID_HANDLE;
3512                 goto out;
3513         }
3514
3515         if (is_ntfs_stream_smb_fname(dir_fsp->fsp_name)) {
3516                 status = NT_STATUS_INVALID_HANDLE;
3517                 goto out;
3518         }
3519
3520         if (!dir_fsp->is_directory) {
3521
3522                 /*
3523                  * Check to see if this is a mac fork of some kind.
3524                  */
3525
3526                 if ((conn->fs_capabilities & FILE_NAMED_STREAMS) &&
3527                     is_ntfs_stream_smb_fname(smb_fname)) {
3528                         status = NT_STATUS_OBJECT_PATH_NOT_FOUND;
3529                         goto out;
3530                 }
3531
3532                 /*
3533                   we need to handle the case when we get a
3534                   relative open relative to a file and the
3535                   pathname is blank - this is a reopen!
3536                   (hint from demyn plantenberg)
3537                 */
3538
3539                 status = NT_STATUS_INVALID_HANDLE;
3540                 goto out;
3541         }
3542
3543         if (ISDOT(dir_fsp->fsp_name->base_name)) {
3544                 /*
3545                  * We're at the toplevel dir, the final file name
3546                  * must not contain ./, as this is filtered out
3547                  * normally by srvstr_get_path and unix_convert
3548                  * explicitly rejects paths containing ./.
3549                  */
3550                 parent_fname = talloc_strdup(talloc_tos(), "");
3551                 if (parent_fname == NULL) {
3552                         status = NT_STATUS_NO_MEMORY;
3553                         goto out;
3554                 }
3555         } else {
3556                 size_t dir_name_len = strlen(dir_fsp->fsp_name->base_name);
3557
3558                 /*
3559                  * Copy in the base directory name.
3560                  */
3561
3562                 parent_fname = talloc_array(talloc_tos(), char,
3563                     dir_name_len+2);
3564                 if (parent_fname == NULL) {
3565                         status = NT_STATUS_NO_MEMORY;
3566                         goto out;
3567                 }
3568                 memcpy(parent_fname, dir_fsp->fsp_name->base_name,
3569                     dir_name_len+1);
3570
3571                 /*
3572                  * Ensure it ends in a '/'.
3573                  * We used TALLOC_SIZE +2 to add space for the '/'.
3574                  */
3575
3576                 if(dir_name_len
3577                     && (parent_fname[dir_name_len-1] != '\\')
3578                     && (parent_fname[dir_name_len-1] != '/')) {
3579                         parent_fname[dir_name_len] = '/';
3580                         parent_fname[dir_name_len+1] = '\0';
3581                 }
3582         }
3583
3584         new_base_name = talloc_asprintf(talloc_tos(), "%s%s", parent_fname,
3585                                         smb_fname->base_name);
3586         if (new_base_name == NULL) {
3587                 status = NT_STATUS_NO_MEMORY;
3588                 goto out;
3589         }
3590
3591         status = filename_convert(req,
3592                                 conn,
3593                                 req->flags2 & FLAGS2_DFS_PATHNAMES,
3594                                 new_base_name,
3595                                 0,
3596                                 NULL,
3597                                 smb_fname_out);
3598         if (!NT_STATUS_IS_OK(status)) {
3599                 goto out;
3600         }
3601
3602  out:
3603         TALLOC_FREE(parent_fname);
3604         TALLOC_FREE(new_base_name);
3605         return status;
3606 }
3607
3608 NTSTATUS create_file_default(connection_struct *conn,
3609                              struct smb_request *req,
3610                              uint16_t root_dir_fid,
3611                              struct smb_filename *smb_fname,
3612                              uint32_t access_mask,
3613                              uint32_t share_access,
3614                              uint32_t create_disposition,
3615                              uint32_t create_options,
3616                              uint32_t file_attributes,
3617                              uint32_t oplock_request,
3618                              uint64_t allocation_size,
3619                              uint32_t private_flags,
3620                              struct security_descriptor *sd,
3621                              struct ea_list *ea_list,
3622                              files_struct **result,
3623                              int *pinfo)
3624 {
3625         int info = FILE_WAS_OPENED;
3626         files_struct *fsp = NULL;
3627         NTSTATUS status;
3628         bool stream_name = false;
3629
3630         DEBUG(10,("create_file: access_mask = 0x%x "
3631                   "file_attributes = 0x%x, share_access = 0x%x, "
3632                   "create_disposition = 0x%x create_options = 0x%x "
3633                   "oplock_request = 0x%x "
3634                   "private_flags = 0x%x "
3635                   "root_dir_fid = 0x%x, ea_list = 0x%p, sd = 0x%p, "
3636                   "fname = %s\n",
3637                   (unsigned int)access_mask,
3638                   (unsigned int)file_attributes,
3639                   (unsigned int)share_access,
3640                   (unsigned int)create_disposition,
3641                   (unsigned int)create_options,
3642                   (unsigned int)oplock_request,
3643                   (unsigned int)private_flags,
3644                   (unsigned int)root_dir_fid,
3645                   ea_list, sd, smb_fname_str_dbg(smb_fname)));
3646
3647         /*
3648          * Calculate the filename from the root_dir_if if necessary.
3649          */
3650
3651         if (root_dir_fid != 0) {
3652                 struct smb_filename *smb_fname_out = NULL;
3653                 status = get_relative_fid_filename(conn, req, root_dir_fid,
3654                                                    smb_fname, &smb_fname_out);
3655                 if (!NT_STATUS_IS_OK(status)) {
3656                         goto fail;
3657                 }
3658                 smb_fname = smb_fname_out;
3659         }
3660
3661         /*
3662          * Check to see if this is a mac fork of some kind.
3663          */
3664
3665         stream_name = is_ntfs_stream_smb_fname(smb_fname);
3666         if (stream_name) {
3667                 enum FAKE_FILE_TYPE fake_file_type;
3668
3669                 fake_file_type = is_fake_file(smb_fname);
3670
3671                 if (fake_file_type != FAKE_FILE_TYPE_NONE) {
3672
3673                         /*
3674                          * Here we go! support for changing the disk quotas
3675                          * --metze
3676                          *
3677                          * We need to fake up to open this MAGIC QUOTA file
3678                          * and return a valid FID.
3679                          *
3680                          * w2k close this file directly after openening xp
3681                          * also tries a QUERY_FILE_INFO on the file and then
3682                          * close it
3683                          */
3684                         status = open_fake_file(req, conn, req->vuid,
3685                                                 fake_file_type, smb_fname,
3686                                                 access_mask, &fsp);
3687                         if (!NT_STATUS_IS_OK(status)) {
3688                                 goto fail;
3689                         }
3690
3691                         ZERO_STRUCT(smb_fname->st);
3692                         goto done;
3693                 }
3694
3695                 if (!(conn->fs_capabilities & FILE_NAMED_STREAMS)) {
3696                         status = NT_STATUS_OBJECT_NAME_NOT_FOUND;
3697                         goto fail;
3698                 }
3699         }
3700
3701         /* All file access must go through check_name() */
3702
3703         status = check_name(conn, smb_fname->base_name);
3704         if (!NT_STATUS_IS_OK(status)) {
3705                 goto fail;
3706         }
3707
3708         if (stream_name && is_ntfs_default_stream_smb_fname(smb_fname)) {
3709                 int ret;
3710                 smb_fname->stream_name = NULL;
3711                 /* We have to handle this error here. */
3712                 if (create_options & FILE_DIRECTORY_FILE) {
3713                         status = NT_STATUS_NOT_A_DIRECTORY;
3714                         goto fail;
3715                 }
3716                 if (lp_posix_pathnames()) {
3717                         ret = SMB_VFS_LSTAT(conn, smb_fname);
3718                 } else {
3719                         ret = SMB_VFS_STAT(conn, smb_fname);
3720                 }
3721
3722                 if (ret == 0 && VALID_STAT_OF_DIR(smb_fname->st)) {
3723                         status = NT_STATUS_FILE_IS_A_DIRECTORY;
3724                         goto fail;
3725                 }
3726         }
3727
3728         status = create_file_unixpath(
3729                 conn, req, smb_fname, access_mask, share_access,
3730                 create_disposition, create_options, file_attributes,
3731                 oplock_request, allocation_size, private_flags,
3732                 sd, ea_list,
3733                 &fsp, &info);
3734
3735         if (!NT_STATUS_IS_OK(status)) {
3736                 goto fail;
3737         }
3738
3739  done:
3740         DEBUG(10, ("create_file: info=%d\n", info));
3741
3742         *result = fsp;
3743         if (pinfo != NULL) {
3744                 *pinfo = info;
3745         }
3746         return NT_STATUS_OK;
3747
3748  fail:
3749         DEBUG(10, ("create_file: %s\n", nt_errstr(status)));
3750
3751         if (fsp != NULL) {
3752                 close_file(req, fsp, ERROR_CLOSE);
3753                 fsp = NULL;
3754         }
3755         return status;
3756 }