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