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