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