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