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