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