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