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