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