r20343: Split change_owner_to_parent fd-based (for file opens) and a name-based (for
[samba.git] / source / smbd / open.c
1 /* 
2    Unix SMB/CIFS implementation.
3    file opening and share modes
4    Copyright (C) Andrew Tridgell 1992-1998
5    Copyright (C) Jeremy Allison 2001-2004
6    Copyright (C) Volker Lendecke 2005
7    
8    This program is free software; you can redistribute it and/or modify
9    it under the terms of the GNU General Public License as published by
10    the Free Software Foundation; either version 2 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, write to the Free Software
20    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
21 */
22
23 #include "includes.h"
24
25 extern struct generic_mapping file_generic_mapping;
26 extern struct current_user current_user;
27 extern userdom_struct current_user_info;
28 extern uint16 global_smbpid;
29 extern BOOL global_client_failed_oplock_break;
30
31 struct deferred_open_record {
32         BOOL delayed_for_oplocks;
33         SMB_DEV_T dev;
34         SMB_INO_T inode;
35 };
36
37 /****************************************************************************
38  fd support routines - attempt to do a dos_open.
39 ****************************************************************************/
40
41 static BOOL fd_open(struct connection_struct *conn,
42                     const char *fname, 
43                     files_struct *fsp,
44                     int flags,
45                     mode_t mode)
46 {
47         int sav;
48
49 #ifdef O_NOFOLLOW
50         if (!lp_symlinks(SNUM(conn))) {
51                 flags |= O_NOFOLLOW;
52         }
53 #endif
54
55         fsp->fh->fd = SMB_VFS_OPEN(conn,fname,fsp,flags,mode);
56         sav = errno;
57
58         DEBUG(10,("fd_open: name %s, flags = 0%o mode = 0%o, fd = %d. %s\n",
59                     fname, flags, (int)mode, fsp->fh->fd,
60                 (fsp->fh->fd == -1) ? strerror(errno) : "" ));
61
62         errno = sav;
63         return fsp->fh->fd != -1;
64 }
65
66 /****************************************************************************
67  Close the file associated with a fsp.
68 ****************************************************************************/
69
70 int fd_close(struct connection_struct *conn,
71              files_struct *fsp)
72 {
73         if (fsp->fh->fd == -1) {
74                 return 0; /* What we used to call a stat open. */
75         }
76         if (fsp->fh->ref_count > 1) {
77                 return 0; /* Shared handle. Only close last reference. */
78         }
79         return fd_close_posix(conn, fsp);
80 }
81
82 /****************************************************************************
83  Change the ownership of a file to that of the parent directory.
84  Do this by fd if possible.
85 ****************************************************************************/
86
87 static void change_fd_owner_to_parent(connection_struct *conn,
88                                       files_struct *fsp)
89 {
90         const char *parent_path = parent_dirname(fsp->fsp_name);
91         SMB_STRUCT_STAT parent_st;
92         int ret;
93
94         ret = SMB_VFS_STAT(conn, parent_path, &parent_st);
95         if (ret == -1) {
96                 DEBUG(0,("change_fd_owner_to_parent: failed to stat parent "
97                          "directory %s. Error was %s\n",
98                          parent_path, strerror(errno) ));
99                 return;
100         }
101
102         become_root();
103         ret = SMB_VFS_FCHOWN(fsp, fsp->fh->fd, parent_st.st_uid, (gid_t)-1);
104         unbecome_root();
105         if (ret == -1) {
106                 DEBUG(0,("change_fd_owner_to_parent: failed to fchown "
107                          "file %s to parent directory uid %u. Error "
108                          "was %s\n", fsp->fsp_name,
109                          (unsigned int)parent_st.st_uid,
110                          strerror(errno) ));
111         }
112
113         DEBUG(10,("change_fd_owner_to_parent: changed new file %s to "
114                   "parent directory uid %u.\n", fsp->fsp_name,
115                   (unsigned int)parent_st.st_uid ));
116 }
117
118 static void change_owner_to_parent(connection_struct *conn,
119                                    const char *fname,
120                                    SMB_STRUCT_STAT *psbuf)
121 {
122         pstring saved_dir;
123         SMB_STRUCT_STAT sbuf;
124         const char *parent_path = parent_dirname(fname);
125         SMB_STRUCT_STAT parent_st;
126         int ret;
127
128         ret = SMB_VFS_STAT(conn, parent_path, &parent_st);
129         if (ret == -1) {
130                 DEBUG(0,("change_owner_to_parent: failed to stat parent "
131                          "directory %s. Error was %s\n",
132                          parent_path, strerror(errno) ));
133                 return;
134         }
135
136         /* We've already done an lstat into psbuf, and we know it's a
137            directory. If we can cd into the directory and the dev/ino
138            are the same then we can safely chown without races as
139            we're locking the directory in place by being in it.  This
140            should work on any UNIX (thanks tridge :-). JRA.
141         */
142
143         if (!vfs_GetWd(conn,saved_dir)) {
144                 DEBUG(0,("change_owner_to_parent: failed to get "
145                          "current working directory\n"));
146                 return;
147         }
148
149         /* Chdir into the new path. */
150         if (vfs_ChDir(conn, fname) == -1) {
151                 DEBUG(0,("change_owner_to_parent: failed to change "
152                          "current working directory to %s. Error "
153                          "was %s\n", fname, strerror(errno) ));
154                 goto out;
155         }
156
157         if (SMB_VFS_STAT(conn,".",&sbuf) == -1) {
158                 DEBUG(0,("change_owner_to_parent: failed to stat "
159                          "directory '.' (%s) Error was %s\n",
160                          fname, strerror(errno)));
161                 goto out;
162         }
163
164         /* Ensure we're pointing at the same place. */
165         if (sbuf.st_dev != psbuf->st_dev ||
166             sbuf.st_ino != psbuf->st_ino ||
167             sbuf.st_mode != psbuf->st_mode ) {
168                 DEBUG(0,("change_owner_to_parent: "
169                          "device/inode/mode on directory %s changed. "
170                          "Refusing to chown !\n", fname ));
171                 goto out;
172         }
173
174         become_root();
175         ret = SMB_VFS_CHOWN(conn, ".", parent_st.st_uid, (gid_t)-1);
176         unbecome_root();
177         if (ret == -1) {
178                 DEBUG(10,("change_owner_to_parent: failed to chown "
179                           "directory %s to parent directory uid %u. "
180                           "Error was %s\n", fname,
181                           (unsigned int)parent_st.st_uid, strerror(errno) ));
182                 goto out;
183         }
184
185         DEBUG(10,("change_owner_to_parent: changed ownership of new "
186                   "directory %s to parent directory uid %u.\n",
187                   fname, (unsigned int)parent_st.st_uid ));
188
189  out:
190
191         vfs_ChDir(conn,saved_dir);
192 }
193
194 /****************************************************************************
195  Open a file.
196 ****************************************************************************/
197
198 static NTSTATUS open_file(files_struct *fsp,
199                           connection_struct *conn,
200                           const char *fname,
201                           SMB_STRUCT_STAT *psbuf,
202                           int flags,
203                           mode_t unx_mode,
204                           uint32 access_mask, /* client requested access mask. */
205                           uint32 open_access_mask) /* what we're actually using in the open. */
206 {
207         int accmode = (flags & O_ACCMODE);
208         int local_flags = flags;
209         BOOL file_existed = VALID_STAT(*psbuf);
210
211         fsp->fh->fd = -1;
212         errno = EPERM;
213
214         /* Check permissions */
215
216         /*
217          * This code was changed after seeing a client open request 
218          * containing the open mode of (DENY_WRITE/read-only) with
219          * the 'create if not exist' bit set. The previous code
220          * would fail to open the file read only on a read-only share
221          * as it was checking the flags parameter  directly against O_RDONLY,
222          * this was failing as the flags parameter was set to O_RDONLY|O_CREAT.
223          * JRA.
224          */
225
226         if (!CAN_WRITE(conn)) {
227                 /* It's a read-only share - fail if we wanted to write. */
228                 if(accmode != O_RDONLY) {
229                         DEBUG(3,("Permission denied opening %s\n",fname));
230                         return NT_STATUS_ACCESS_DENIED;
231                 } else if(flags & O_CREAT) {
232                         /* We don't want to write - but we must make sure that
233                            O_CREAT doesn't create the file if we have write
234                            access into the directory.
235                         */
236                         flags &= ~O_CREAT;
237                         local_flags &= ~O_CREAT;
238                 }
239         }
240
241         /*
242          * This little piece of insanity is inspired by the
243          * fact that an NT client can open a file for O_RDONLY,
244          * but set the create disposition to FILE_EXISTS_TRUNCATE.
245          * If the client *can* write to the file, then it expects to
246          * truncate the file, even though it is opening for readonly.
247          * Quicken uses this stupid trick in backup file creation...
248          * Thanks *greatly* to "David W. Chapman Jr." <dwcjr@inethouston.net>
249          * for helping track this one down. It didn't bite us in 2.0.x
250          * as we always opened files read-write in that release. JRA.
251          */
252
253         if ((accmode == O_RDONLY) && ((flags & O_TRUNC) == O_TRUNC)) {
254                 DEBUG(10,("open_file: truncate requested on read-only open "
255                           "for file %s\n",fname ));
256                 local_flags = (flags & ~O_ACCMODE)|O_RDWR;
257         }
258
259         if ((open_access_mask & (FILE_READ_DATA|FILE_WRITE_DATA|FILE_APPEND_DATA|FILE_EXECUTE)) ||
260             (!file_existed && (local_flags & O_CREAT)) ||
261             ((local_flags & O_TRUNC) == O_TRUNC) ) {
262
263                 /*
264                  * We can't actually truncate here as the file may be locked.
265                  * open_file_ntcreate will take care of the truncate later. JRA.
266                  */
267
268                 local_flags &= ~O_TRUNC;
269
270 #if defined(O_NONBLOCK) && defined(S_ISFIFO)
271                 /*
272                  * We would block on opening a FIFO with no one else on the
273                  * other end. Do what we used to do and add O_NONBLOCK to the
274                  * open flags. JRA.
275                  */
276
277                 if (file_existed && S_ISFIFO(psbuf->st_mode)) {
278                         local_flags |= O_NONBLOCK;
279                 }
280 #endif
281
282                 /* Don't create files with Microsoft wildcard characters. */
283                 if ((local_flags & O_CREAT) && !file_existed &&
284                     ms_has_wild(fname))  {
285                         return NT_STATUS_OBJECT_NAME_INVALID;
286                 }
287
288                 /* Actually do the open */
289                 if (!fd_open(conn, fname, fsp, local_flags, unx_mode)) {
290                         DEBUG(3,("Error opening file %s (%s) (local_flags=%d) "
291                                  "(flags=%d)\n",
292                                  fname,strerror(errno),local_flags,flags));
293                         return map_nt_error_from_unix(errno);
294                 }
295
296                 /* Inherit the ACL if the file was created. */
297                 if ((local_flags & O_CREAT)
298                     && !file_existed
299                     && lp_inherit_perms(SNUM(conn))) {
300                         inherit_access_acl(conn, fname, unx_mode);
301                 }
302
303         } else {
304                 fsp->fh->fd = -1; /* What we used to call a stat open. */
305         }
306
307         if (!file_existed) {
308                 int ret;
309
310                 if (fsp->fh->fd == -1) {
311                         ret = SMB_VFS_STAT(conn, fname, psbuf);
312                 } else {
313                         ret = SMB_VFS_FSTAT(fsp,fsp->fh->fd,psbuf);
314                         /* If we have an fd, this stat should succeed. */
315                         if (ret == -1) {
316                                 DEBUG(0,("Error doing fstat on open file %s "
317                                          "(%s)\n", fname,strerror(errno) ));
318                         }
319                 }
320
321                 /* For a non-io open, this stat failing means file not found. JRA */
322                 if (ret == -1) {
323                         NTSTATUS status = map_nt_error_from_unix(errno);
324                         fd_close(conn, fsp);
325                         return status;
326                 }
327         }
328
329         /*
330          * POSIX allows read-only opens of directories. We don't
331          * want to do this (we use a different code path for this)
332          * so catch a directory open and return an EISDIR. JRA.
333          */
334
335         if(S_ISDIR(psbuf->st_mode)) {
336                 fd_close(conn, fsp);
337                 errno = EISDIR;
338                 return NT_STATUS_FILE_IS_A_DIRECTORY;
339         }
340
341         fsp->mode = psbuf->st_mode;
342         fsp->inode = psbuf->st_ino;
343         fsp->dev = psbuf->st_dev;
344         fsp->vuid = current_user.vuid;
345         fsp->file_pid = global_smbpid;
346         fsp->can_lock = True;
347         fsp->can_read = (access_mask & (FILE_READ_DATA)) ? True : False;
348         if (!CAN_WRITE(conn)) {
349                 fsp->can_write = False;
350         } else {
351                 fsp->can_write = (access_mask & (FILE_WRITE_DATA | FILE_APPEND_DATA)) ?
352                         True : False;
353         }
354         fsp->print_file = False;
355         fsp->modified = False;
356         fsp->sent_oplock_break = NO_BREAK_SENT;
357         fsp->is_directory = False;
358         fsp->is_stat = False;
359         if (conn->aio_write_behind_list &&
360             is_in_path(fname, conn->aio_write_behind_list, conn->case_sensitive)) {
361                 fsp->aio_write_behind = True;
362         }
363
364         string_set(&fsp->fsp_name,fname);
365         fsp->wcp = NULL; /* Write cache pointer. */
366
367         DEBUG(2,("%s opened file %s read=%s write=%s (numopen=%d)\n",
368                  *current_user_info.smb_name ?
369                  current_user_info.smb_name : conn->user,fsp->fsp_name,
370                  BOOLSTR(fsp->can_read), BOOLSTR(fsp->can_write),
371                  conn->num_files_open + 1));
372
373         errno = 0;
374         return NT_STATUS_OK;
375 }
376
377 /*******************************************************************
378  Return True if the filename is one of the special executable types.
379 ********************************************************************/
380
381 static BOOL is_executable(const char *fname)
382 {
383         if ((fname = strrchr_m(fname,'.'))) {
384                 if (strequal(fname,".com") ||
385                     strequal(fname,".dll") ||
386                     strequal(fname,".exe") ||
387                     strequal(fname,".sym")) {
388                         return True;
389                 }
390         }
391         return False;
392 }
393
394 /****************************************************************************
395  Check if we can open a file with a share mode.
396  Returns True if conflict, False if not.
397 ****************************************************************************/
398
399 static BOOL share_conflict(struct share_mode_entry *entry,
400                            uint32 access_mask,
401                            uint32 share_access)
402 {
403         DEBUG(10,("share_conflict: entry->access_mask = 0x%x, "
404                   "entry->share_access = 0x%x, "
405                   "entry->private_options = 0x%x\n",
406                   (unsigned int)entry->access_mask,
407                   (unsigned int)entry->share_access,
408                   (unsigned int)entry->private_options));
409
410         DEBUG(10,("share_conflict: access_mask = 0x%x, share_access = 0x%x\n",
411                   (unsigned int)access_mask, (unsigned int)share_access));
412
413         if ((entry->access_mask & (FILE_WRITE_DATA|
414                                    FILE_APPEND_DATA|
415                                    FILE_READ_DATA|
416                                    FILE_EXECUTE|
417                                    DELETE_ACCESS)) == 0) {
418                 DEBUG(10,("share_conflict: No conflict due to "
419                           "entry->access_mask = 0x%x\n",
420                           (unsigned int)entry->access_mask ));
421                 return False;
422         }
423
424         if ((access_mask & (FILE_WRITE_DATA|
425                             FILE_APPEND_DATA|
426                             FILE_READ_DATA|
427                             FILE_EXECUTE|
428                             DELETE_ACCESS)) == 0) {
429                 DEBUG(10,("share_conflict: No conflict due to "
430                           "access_mask = 0x%x\n",
431                           (unsigned int)access_mask ));
432                 return False;
433         }
434
435 #if 1 /* JRA TEST - Superdebug. */
436 #define CHECK_MASK(num, am, right, sa, share) \
437         DEBUG(10,("share_conflict: [%d] am (0x%x) & right (0x%x) = 0x%x\n", \
438                 (unsigned int)(num), (unsigned int)(am), \
439                 (unsigned int)(right), (unsigned int)(am)&(right) )); \
440         DEBUG(10,("share_conflict: [%d] sa (0x%x) & share (0x%x) = 0x%x\n", \
441                 (unsigned int)(num), (unsigned int)(sa), \
442                 (unsigned int)(share), (unsigned int)(sa)&(share) )); \
443         if (((am) & (right)) && !((sa) & (share))) { \
444                 DEBUG(10,("share_conflict: check %d conflict am = 0x%x, right = 0x%x, \
445 sa = 0x%x, share = 0x%x\n", (num), (unsigned int)(am), (unsigned int)(right), (unsigned int)(sa), \
446                         (unsigned int)(share) )); \
447                 return True; \
448         }
449 #else
450 #define CHECK_MASK(num, am, right, sa, share) \
451         if (((am) & (right)) && !((sa) & (share))) { \
452                 DEBUG(10,("share_conflict: check %d conflict am = 0x%x, right = 0x%x, \
453 sa = 0x%x, share = 0x%x\n", (num), (unsigned int)(am), (unsigned int)(right), (unsigned int)(sa), \
454                         (unsigned int)(share) )); \
455                 return True; \
456         }
457 #endif
458
459         CHECK_MASK(1, entry->access_mask, FILE_WRITE_DATA | FILE_APPEND_DATA,
460                    share_access, FILE_SHARE_WRITE);
461         CHECK_MASK(2, access_mask, FILE_WRITE_DATA | FILE_APPEND_DATA,
462                    entry->share_access, FILE_SHARE_WRITE);
463         
464         CHECK_MASK(3, entry->access_mask, FILE_READ_DATA | FILE_EXECUTE,
465                    share_access, FILE_SHARE_READ);
466         CHECK_MASK(4, access_mask, FILE_READ_DATA | FILE_EXECUTE,
467                    entry->share_access, FILE_SHARE_READ);
468
469         CHECK_MASK(5, entry->access_mask, DELETE_ACCESS,
470                    share_access, FILE_SHARE_DELETE);
471         CHECK_MASK(6, access_mask, DELETE_ACCESS,
472                    entry->share_access, FILE_SHARE_DELETE);
473
474         DEBUG(10,("share_conflict: No conflict.\n"));
475         return False;
476 }
477
478 #if defined(DEVELOPER)
479 static void validate_my_share_entries(int num,
480                                       struct share_mode_entry *share_entry)
481 {
482         files_struct *fsp;
483
484         if (!procid_is_me(&share_entry->pid)) {
485                 return;
486         }
487
488         if (is_deferred_open_entry(share_entry) &&
489             !open_was_deferred(share_entry->op_mid)) {
490                 pstring str;
491                 pstr_sprintf(str, "Got a deferred entry without a request: "
492                              "PANIC: %s\n", share_mode_str(num, share_entry));
493                 smb_panic(str);
494         }
495
496         if (!is_valid_share_mode_entry(share_entry)) {
497                 return;
498         }
499
500         fsp = file_find_dif(share_entry->dev, share_entry->inode,
501                             share_entry->share_file_id);
502         if (!fsp) {
503                 DEBUG(0,("validate_my_share_entries: PANIC : %s\n",
504                          share_mode_str(num, share_entry) ));
505                 smb_panic("validate_my_share_entries: Cannot match a "
506                           "share entry with an open file\n");
507         }
508
509         if (is_deferred_open_entry(share_entry) ||
510             is_unused_share_mode_entry(share_entry)) {
511                 goto panic;
512         }
513
514         if ((share_entry->op_type == NO_OPLOCK) &&
515             (fsp->oplock_type == FAKE_LEVEL_II_OPLOCK)) {
516                 /* Someone has already written to it, but I haven't yet
517                  * noticed */
518                 return;
519         }
520
521         if (((uint16)fsp->oplock_type) != share_entry->op_type) {
522                 goto panic;
523         }
524
525         return;
526
527  panic:
528         {
529                 pstring str;
530                 DEBUG(0,("validate_my_share_entries: PANIC : %s\n",
531                          share_mode_str(num, share_entry) ));
532                 slprintf(str, sizeof(str)-1, "validate_my_share_entries: "
533                          "file %s, oplock_type = 0x%x, op_type = 0x%x\n",
534                          fsp->fsp_name, (unsigned int)fsp->oplock_type,
535                          (unsigned int)share_entry->op_type );
536                 smb_panic(str);
537         }
538 }
539 #endif
540
541 static BOOL is_stat_open(uint32 access_mask)
542 {
543         return (access_mask &&
544                 ((access_mask & ~(SYNCHRONIZE_ACCESS| FILE_READ_ATTRIBUTES|
545                                   FILE_WRITE_ATTRIBUTES))==0) &&
546                 ((access_mask & (SYNCHRONIZE_ACCESS|FILE_READ_ATTRIBUTES|
547                                  FILE_WRITE_ATTRIBUTES)) != 0));
548 }
549
550 /****************************************************************************
551  Deal with share modes
552  Invarient: Share mode must be locked on entry and exit.
553  Returns -1 on error, or number of share modes on success (may be zero).
554 ****************************************************************************/
555
556 static NTSTATUS open_mode_check(connection_struct *conn,
557                                 const char *fname,
558                                 struct share_mode_lock *lck,
559                                 uint32 access_mask,
560                                 uint32 share_access,
561                                 uint32 create_options,
562                                 BOOL *file_existed)
563 {
564         int i;
565
566         if(lck->num_share_modes == 0) {
567                 return NT_STATUS_OK;
568         }
569
570         *file_existed = True;
571         
572         if (is_stat_open(access_mask)) {
573                 /* Stat open that doesn't trigger oplock breaks or share mode
574                  * checks... ! JRA. */
575                 return NT_STATUS_OK;
576         }
577
578         /* A delete on close prohibits everything */
579
580         if (lck->delete_on_close) {
581                 return NT_STATUS_DELETE_PENDING;
582         }
583
584         /*
585          * Check if the share modes will give us access.
586          */
587         
588 #if defined(DEVELOPER)
589         for(i = 0; i < lck->num_share_modes; i++) {
590                 validate_my_share_entries(i, &lck->share_modes[i]);
591         }
592 #endif
593
594         if (!lp_share_modes(SNUM(conn))) {
595                 return NT_STATUS_OK;
596         }
597
598         /* Now we check the share modes, after any oplock breaks. */
599         for(i = 0; i < lck->num_share_modes; i++) {
600
601                 if (!is_valid_share_mode_entry(&lck->share_modes[i])) {
602                         continue;
603                 }
604
605                 /* someone else has a share lock on it, check to see if we can
606                  * too */
607                 if (share_conflict(&lck->share_modes[i],
608                                    access_mask, share_access)) {
609                         return NT_STATUS_SHARING_VIOLATION;
610                 }
611         }
612         
613         return NT_STATUS_OK;
614 }
615
616 static BOOL is_delete_request(files_struct *fsp) {
617         return ((fsp->access_mask == DELETE_ACCESS) &&
618                 (fsp->oplock_type == NO_OPLOCK));
619 }
620
621 /*
622  * 1) No files open at all or internal open: Grant whatever the client wants.
623  *
624  * 2) Exclusive (or batch) oplock around: If the requested access is a delete
625  *    request, break if the oplock around is a batch oplock. If it's another
626  *    requested access type, break.
627  * 
628  * 3) Only level2 around: Grant level2 and do nothing else.
629  */
630
631 static BOOL delay_for_oplocks(struct share_mode_lock *lck,
632                               files_struct *fsp,
633                               int pass_number,
634                               int oplock_request)
635 {
636         int i;
637         struct share_mode_entry *exclusive = NULL;
638         BOOL valid_entry = False;
639         BOOL delay_it = False;
640         BOOL have_level2 = False;
641         BOOL ret;
642         char msg[MSG_SMB_SHARE_MODE_ENTRY_SIZE];
643
644         if (oplock_request & INTERNAL_OPEN_ONLY) {
645                 fsp->oplock_type = NO_OPLOCK;
646         }
647
648         if ((oplock_request & INTERNAL_OPEN_ONLY) || is_stat_open(fsp->access_mask)) {
649                 return False;
650         }
651
652         for (i=0; i<lck->num_share_modes; i++) {
653
654                 if (!is_valid_share_mode_entry(&lck->share_modes[i])) {
655                         continue;
656                 }
657
658                 /* At least one entry is not an invalid or deferred entry. */
659                 valid_entry = True;
660
661                 if (pass_number == 1) {
662                         if (BATCH_OPLOCK_TYPE(lck->share_modes[i].op_type)) {
663                                 SMB_ASSERT(exclusive == NULL);                  
664                                 exclusive = &lck->share_modes[i];
665                         }
666                 } else {
667                         if (EXCLUSIVE_OPLOCK_TYPE(lck->share_modes[i].op_type)) {
668                                 SMB_ASSERT(exclusive == NULL);                  
669                                 exclusive = &lck->share_modes[i];
670                         }
671                 }
672
673                 if (lck->share_modes[i].op_type == LEVEL_II_OPLOCK) {
674                         SMB_ASSERT(exclusive == NULL);                  
675                         have_level2 = True;
676                 }
677         }
678
679         if (!valid_entry) {
680                 /* All entries are placeholders or deferred.
681                  * Directly grant whatever the client wants. */
682                 if (fsp->oplock_type == NO_OPLOCK) {
683                         /* Store a level2 oplock, but don't tell the client */
684                         fsp->oplock_type = FAKE_LEVEL_II_OPLOCK;
685                 }
686                 return False;
687         }
688
689         if (exclusive != NULL) { /* Found an exclusive oplock */
690                 SMB_ASSERT(!have_level2);
691                 delay_it = is_delete_request(fsp) ?
692                         BATCH_OPLOCK_TYPE(exclusive->op_type) : True;
693         }
694
695         if (EXCLUSIVE_OPLOCK_TYPE(fsp->oplock_type)) {
696                 /* We can at most grant level2 as there are other
697                  * level2 or NO_OPLOCK entries. */
698                 fsp->oplock_type = LEVEL_II_OPLOCK;
699         }
700
701         if ((fsp->oplock_type == NO_OPLOCK) && have_level2) {
702                 /* Store a level2 oplock, but don't tell the client */
703                 fsp->oplock_type = FAKE_LEVEL_II_OPLOCK;
704         }
705
706         if (!delay_it) {
707                 return False;
708         }
709
710         /*
711          * Send a break message to the oplock holder and delay the open for
712          * our client.
713          */
714
715         DEBUG(10, ("Sending break request to PID %s\n",
716                    procid_str_static(&exclusive->pid)));
717         exclusive->op_mid = get_current_mid();
718
719         /* Create the message. */
720         share_mode_entry_to_message(msg, exclusive);
721
722         /* Add in the FORCE_OPLOCK_BREAK_TO_NONE bit in the message if set. We
723            don't want this set in the share mode struct pointed to by lck. */
724
725         if (oplock_request & FORCE_OPLOCK_BREAK_TO_NONE) {
726                 SSVAL(msg,6,exclusive->op_type | FORCE_OPLOCK_BREAK_TO_NONE);
727         }
728
729         ret = message_send_pid(exclusive->pid, MSG_SMB_BREAK_REQUEST,
730                                msg, MSG_SMB_SHARE_MODE_ENTRY_SIZE, True);
731         if (!ret) {
732                 DEBUG(3, ("Could not send oplock break message\n"));
733         }
734
735         return True;
736 }
737
738 static BOOL request_timed_out(struct timeval request_time,
739                               struct timeval timeout)
740 {
741         struct timeval now, end_time;
742         GetTimeOfDay(&now);
743         end_time = timeval_sum(&request_time, &timeout);
744         return (timeval_compare(&end_time, &now) < 0);
745 }
746
747 /****************************************************************************
748  Handle the 1 second delay in returning a SHARING_VIOLATION error.
749 ****************************************************************************/
750
751 static void defer_open(struct share_mode_lock *lck,
752                        struct timeval request_time,
753                        struct timeval timeout,
754                        struct deferred_open_record *state)
755 {
756         uint16 mid = get_current_mid();
757         int i;
758
759         /* Paranoia check */
760
761         for (i=0; i<lck->num_share_modes; i++) {
762                 struct share_mode_entry *e = &lck->share_modes[i];
763
764                 if (!is_deferred_open_entry(e)) {
765                         continue;
766                 }
767
768                 if (procid_is_me(&e->pid) && (e->op_mid == mid)) {
769                         DEBUG(0, ("Trying to defer an already deferred "
770                                   "request: mid=%d, exiting\n", mid));
771                         exit_server("attempt to defer a deferred request");
772                 }
773         }
774
775         /* End paranoia check */
776
777         DEBUG(10,("defer_open_sharing_error: time [%u.%06u] adding deferred "
778                   "open entry for mid %u\n",
779                   (unsigned int)request_time.tv_sec,
780                   (unsigned int)request_time.tv_usec,
781                   (unsigned int)mid));
782
783         if (!push_deferred_smb_message(mid, request_time, timeout,
784                                        (char *)state, sizeof(*state))) {
785                 exit_server("push_deferred_smb_message failed");
786         }
787         add_deferred_open(lck, mid, request_time, state->dev, state->inode);
788
789         /*
790          * Push the MID of this packet on the signing queue.
791          * We only do this once, the first time we push the packet
792          * onto the deferred open queue, as this has a side effect
793          * of incrementing the response sequence number.
794          */
795
796         srv_defer_sign_response(mid);
797 }
798
799
800 /****************************************************************************
801  On overwrite open ensure that the attributes match.
802 ****************************************************************************/
803
804 static BOOL open_match_attributes(connection_struct *conn,
805                                   const char *path,
806                                   uint32 old_dos_attr,
807                                   uint32 new_dos_attr,
808                                   mode_t existing_unx_mode,
809                                   mode_t new_unx_mode,
810                                   mode_t *returned_unx_mode)
811 {
812         uint32 noarch_old_dos_attr, noarch_new_dos_attr;
813
814         noarch_old_dos_attr = (old_dos_attr & ~FILE_ATTRIBUTE_ARCHIVE);
815         noarch_new_dos_attr = (new_dos_attr & ~FILE_ATTRIBUTE_ARCHIVE);
816
817         if((noarch_old_dos_attr == 0 && noarch_new_dos_attr != 0) || 
818            (noarch_old_dos_attr != 0 && ((noarch_old_dos_attr & noarch_new_dos_attr) == noarch_old_dos_attr))) {
819                 *returned_unx_mode = new_unx_mode;
820         } else {
821                 *returned_unx_mode = (mode_t)0;
822         }
823
824         DEBUG(10,("open_match_attributes: file %s old_dos_attr = 0x%x, "
825                   "existing_unx_mode = 0%o, new_dos_attr = 0x%x "
826                   "returned_unx_mode = 0%o\n",
827                   path,
828                   (unsigned int)old_dos_attr,
829                   (unsigned int)existing_unx_mode,
830                   (unsigned int)new_dos_attr,
831                   (unsigned int)*returned_unx_mode ));
832
833         /* If we're mapping SYSTEM and HIDDEN ensure they match. */
834         if (lp_map_system(SNUM(conn)) || lp_store_dos_attributes(SNUM(conn))) {
835                 if ((old_dos_attr & FILE_ATTRIBUTE_SYSTEM) &&
836                     !(new_dos_attr & FILE_ATTRIBUTE_SYSTEM)) {
837                         return False;
838                 }
839         }
840         if (lp_map_hidden(SNUM(conn)) || lp_store_dos_attributes(SNUM(conn))) {
841                 if ((old_dos_attr & FILE_ATTRIBUTE_HIDDEN) &&
842                     !(new_dos_attr & FILE_ATTRIBUTE_HIDDEN)) {
843                         return False;
844                 }
845         }
846         return True;
847 }
848
849 /****************************************************************************
850  Special FCB or DOS processing in the case of a sharing violation.
851  Try and find a duplicated file handle.
852 ****************************************************************************/
853
854 static files_struct *fcb_or_dos_open(connection_struct *conn,
855                                      const char *fname, SMB_DEV_T dev,
856                                      SMB_INO_T inode,
857                                      uint32 access_mask,
858                                      uint32 share_access,
859                                      uint32 create_options)
860 {
861         files_struct *fsp;
862         files_struct *dup_fsp;
863
864         DEBUG(5,("fcb_or_dos_open: attempting old open semantics for "
865                  "file %s.\n", fname ));
866
867         for(fsp = file_find_di_first(dev, inode); fsp;
868             fsp = file_find_di_next(fsp)) {
869
870                 DEBUG(10,("fcb_or_dos_open: checking file %s, fd = %d, "
871                           "vuid = %u, file_pid = %u, private_options = 0x%x "
872                           "access_mask = 0x%x\n", fsp->fsp_name,
873                           fsp->fh->fd, (unsigned int)fsp->vuid,
874                           (unsigned int)fsp->file_pid,
875                           (unsigned int)fsp->fh->private_options,
876                           (unsigned int)fsp->access_mask ));
877
878                 if (fsp->fh->fd != -1 &&
879                     fsp->vuid == current_user.vuid &&
880                     fsp->file_pid == global_smbpid &&
881                     (fsp->fh->private_options & (NTCREATEX_OPTIONS_PRIVATE_DENY_DOS |
882                                                  NTCREATEX_OPTIONS_PRIVATE_DENY_FCB)) &&
883                     (fsp->access_mask & FILE_WRITE_DATA) &&
884                     strequal(fsp->fsp_name, fname)) {
885                         DEBUG(10,("fcb_or_dos_open: file match\n"));
886                         break;
887                 }
888         }
889
890         if (!fsp) {
891                 return NULL;
892         }
893
894         /* quite an insane set of semantics ... */
895         if (is_executable(fname) &&
896             (fsp->fh->private_options & NTCREATEX_OPTIONS_PRIVATE_DENY_DOS)) {
897                 DEBUG(10,("fcb_or_dos_open: file fail due to is_executable.\n"));
898                 return NULL;
899         }
900
901         /* We need to duplicate this fsp. */
902         if (!NT_STATUS_IS_OK(dup_file_fsp(fsp, access_mask, share_access,
903                                           create_options, &dup_fsp))) {
904                 return NULL;
905         }
906
907         return dup_fsp;
908 }
909
910 /****************************************************************************
911  Open a file with a share mode - old openX method - map into NTCreate.
912 ****************************************************************************/
913
914 BOOL map_open_params_to_ntcreate(const char *fname, int deny_mode, int open_func,
915                                  uint32 *paccess_mask,
916                                  uint32 *pshare_mode,
917                                  uint32 *pcreate_disposition,
918                                  uint32 *pcreate_options)
919 {
920         uint32 access_mask;
921         uint32 share_mode;
922         uint32 create_disposition;
923         uint32 create_options = 0;
924
925         DEBUG(10,("map_open_params_to_ntcreate: fname = %s, deny_mode = 0x%x, "
926                   "open_func = 0x%x\n",
927                   fname, (unsigned int)deny_mode, (unsigned int)open_func ));
928
929         /* Create the NT compatible access_mask. */
930         switch (GET_OPENX_MODE(deny_mode)) {
931                 case DOS_OPEN_EXEC: /* Implies read-only - used to be FILE_READ_DATA */
932                 case DOS_OPEN_RDONLY:
933                         access_mask = FILE_GENERIC_READ;
934                         break;
935                 case DOS_OPEN_WRONLY:
936                         access_mask = FILE_GENERIC_WRITE;
937                         break;
938                 case DOS_OPEN_RDWR:
939                 case DOS_OPEN_FCB:
940                         access_mask = FILE_GENERIC_READ|FILE_GENERIC_WRITE;
941                         break;
942                 default:
943                         DEBUG(10,("map_open_params_to_ntcreate: bad open mode = 0x%x\n",
944                                   (unsigned int)GET_OPENX_MODE(deny_mode)));
945                         return False;
946         }
947
948         /* Create the NT compatible create_disposition. */
949         switch (open_func) {
950                 case OPENX_FILE_EXISTS_FAIL|OPENX_FILE_CREATE_IF_NOT_EXIST:
951                         create_disposition = FILE_CREATE;
952                         break;
953
954                 case OPENX_FILE_EXISTS_OPEN:
955                         create_disposition = FILE_OPEN;
956                         break;
957
958                 case OPENX_FILE_EXISTS_OPEN|OPENX_FILE_CREATE_IF_NOT_EXIST:
959                         create_disposition = FILE_OPEN_IF;
960                         break;
961        
962                 case OPENX_FILE_EXISTS_TRUNCATE:
963                         create_disposition = FILE_OVERWRITE;
964                         break;
965
966                 case OPENX_FILE_EXISTS_TRUNCATE|OPENX_FILE_CREATE_IF_NOT_EXIST:
967                         create_disposition = FILE_OVERWRITE_IF;
968                         break;
969
970                 default:
971                         /* From samba4 - to be confirmed. */
972                         if (GET_OPENX_MODE(deny_mode) == DOS_OPEN_EXEC) {
973                                 create_disposition = FILE_CREATE;
974                                 break;
975                         }
976                         DEBUG(10,("map_open_params_to_ntcreate: bad "
977                                   "open_func 0x%x\n", (unsigned int)open_func));
978                         return False;
979         }
980  
981         /* Create the NT compatible share modes. */
982         switch (GET_DENY_MODE(deny_mode)) {
983                 case DENY_ALL:
984                         share_mode = FILE_SHARE_NONE;
985                         break;
986
987                 case DENY_WRITE:
988                         share_mode = FILE_SHARE_READ;
989                         break;
990
991                 case DENY_READ:
992                         share_mode = FILE_SHARE_WRITE;
993                         break;
994
995                 case DENY_NONE:
996                         share_mode = FILE_SHARE_READ|FILE_SHARE_WRITE;
997                         break;
998
999                 case DENY_DOS:
1000                         create_options |= NTCREATEX_OPTIONS_PRIVATE_DENY_DOS;
1001                         if (is_executable(fname)) {
1002                                 share_mode = FILE_SHARE_READ|FILE_SHARE_WRITE;
1003                         } else {
1004                                 if (GET_OPENX_MODE(deny_mode) == DOS_OPEN_RDONLY) {
1005                                         share_mode = FILE_SHARE_READ;
1006                                 } else {
1007                                         share_mode = FILE_SHARE_NONE;
1008                                 }
1009                         }
1010                         break;
1011
1012                 case DENY_FCB:
1013                         create_options |= NTCREATEX_OPTIONS_PRIVATE_DENY_FCB;
1014                         share_mode = FILE_SHARE_NONE;
1015                         break;
1016
1017                 default:
1018                         DEBUG(10,("map_open_params_to_ntcreate: bad deny_mode 0x%x\n",
1019                                 (unsigned int)GET_DENY_MODE(deny_mode) ));
1020                         return False;
1021         }
1022
1023         DEBUG(10,("map_open_params_to_ntcreate: file %s, access_mask = 0x%x, "
1024                   "share_mode = 0x%x, create_disposition = 0x%x, "
1025                   "create_options = 0x%x\n",
1026                   fname,
1027                   (unsigned int)access_mask,
1028                   (unsigned int)share_mode,
1029                   (unsigned int)create_disposition,
1030                   (unsigned int)create_options ));
1031
1032         if (paccess_mask) {
1033                 *paccess_mask = access_mask;
1034         }
1035         if (pshare_mode) {
1036                 *pshare_mode = share_mode;
1037         }
1038         if (pcreate_disposition) {
1039                 *pcreate_disposition = create_disposition;
1040         }
1041         if (pcreate_options) {
1042                 *pcreate_options = create_options;
1043         }
1044
1045         return True;
1046
1047 }
1048
1049 static void schedule_defer_open(struct share_mode_lock *lck, struct timeval request_time)
1050 {
1051         struct deferred_open_record state;
1052
1053         /* This is a relative time, added to the absolute
1054            request_time value to get the absolute timeout time.
1055            Note that if this is the second or greater time we enter
1056            this codepath for this particular request mid then
1057            request_time is left as the absolute time of the *first*
1058            time this request mid was processed. This is what allows
1059            the request to eventually time out. */
1060
1061         struct timeval timeout;
1062
1063         /* Normally the smbd we asked should respond within
1064          * OPLOCK_BREAK_TIMEOUT seconds regardless of whether
1065          * the client did, give twice the timeout as a safety
1066          * measure here in case the other smbd is stuck
1067          * somewhere else. */
1068
1069         timeout = timeval_set(OPLOCK_BREAK_TIMEOUT*2, 0);
1070
1071         /* Nothing actually uses state.delayed_for_oplocks
1072            but it's handy to differentiate in debug messages
1073            between a 30 second delay due to oplock break, and
1074            a 1 second delay for share mode conflicts. */
1075
1076         state.delayed_for_oplocks = True;
1077         state.dev = lck->dev;
1078         state.inode = lck->ino;
1079
1080         if (!request_timed_out(request_time, timeout)) {
1081                 defer_open(lck, request_time, timeout, &state);
1082         }
1083 }
1084
1085 /****************************************************************************
1086  Open a file with a share mode.
1087 ****************************************************************************/
1088
1089 NTSTATUS open_file_ntcreate(connection_struct *conn,
1090                             const char *fname,
1091                             SMB_STRUCT_STAT *psbuf,
1092                             uint32 access_mask,         /* access bits (FILE_READ_DATA etc.) */
1093                             uint32 share_access,        /* share constants (FILE_SHARE_READ etc) */
1094                             uint32 create_disposition,  /* FILE_OPEN_IF etc. */
1095                             uint32 create_options,      /* options such as delete on close. */
1096                             uint32 new_dos_attributes,  /* attributes used for new file. */
1097                             int oplock_request,         /* internal Samba oplock codes. */
1098                                                         /* Information (FILE_EXISTS etc.) */
1099                             int *pinfo,
1100                             files_struct **result)
1101 {
1102         int flags=0;
1103         int flags2=0;
1104         BOOL file_existed = VALID_STAT(*psbuf);
1105         BOOL def_acl = False;
1106         SMB_DEV_T dev = 0;
1107         SMB_INO_T inode = 0;
1108         NTSTATUS fsp_open = NT_STATUS_ACCESS_DENIED;
1109         files_struct *fsp = NULL;
1110         mode_t new_unx_mode = (mode_t)0;
1111         mode_t unx_mode = (mode_t)0;
1112         int info;
1113         uint32 existing_dos_attributes = 0;
1114         struct pending_message_list *pml = NULL;
1115         uint16 mid = get_current_mid();
1116         struct timeval request_time = timeval_zero();
1117         struct share_mode_lock *lck = NULL;
1118         uint32 open_access_mask = access_mask;
1119         NTSTATUS status;
1120         int ret_flock;
1121
1122         if (conn->printer) {
1123                 /* 
1124                  * Printers are handled completely differently.
1125                  * Most of the passed parameters are ignored.
1126                  */
1127
1128                 if (pinfo) {
1129                         *pinfo = FILE_WAS_CREATED;
1130                 }
1131
1132                 DEBUG(10, ("open_file_ntcreate: printer open fname=%s\n", fname));
1133
1134                 return print_fsp_open(conn, fname, result);
1135         }
1136
1137         /* We add aARCH to this as this mode is only used if the file is
1138          * created new. */
1139         unx_mode = unix_mode(conn, new_dos_attributes | aARCH,fname, True);
1140
1141         DEBUG(10, ("open_file_ntcreate: fname=%s, dos_attrs=0x%x "
1142                    "access_mask=0x%x share_access=0x%x "
1143                    "create_disposition = 0x%x create_options=0x%x "
1144                    "unix mode=0%o oplock_request=%d\n",
1145                    fname, new_dos_attributes, access_mask, share_access,
1146                    create_disposition, create_options, unx_mode,
1147                    oplock_request));
1148
1149         if ((pml = get_open_deferred_message(mid)) != NULL) {
1150                 struct deferred_open_record *state =
1151                         (struct deferred_open_record *)pml->private_data.data;
1152
1153                 /* Remember the absolute time of the original
1154                    request with this mid. We'll use it later to
1155                    see if this has timed out. */
1156
1157                 request_time = pml->request_time;
1158
1159                 /* Remove the deferred open entry under lock. */
1160                 lck = get_share_mode_lock(NULL, state->dev, state->inode, NULL, NULL);
1161                 if (lck == NULL) {
1162                         DEBUG(0, ("could not get share mode lock\n"));
1163                 } else {
1164                         del_deferred_open_entry(lck, mid);
1165                         TALLOC_FREE(lck);
1166                 }
1167
1168                 /* Ensure we don't reprocess this message. */
1169                 remove_deferred_open_smb_message(mid);
1170         }
1171
1172         if (!check_name(fname,conn)) {
1173                 return map_nt_error_from_unix(errno);
1174         } 
1175
1176         new_dos_attributes &= SAMBA_ATTRIBUTES_MASK;
1177         if (file_existed) {
1178                 existing_dos_attributes = dos_mode(conn, fname, psbuf);
1179         }
1180
1181         /* ignore any oplock requests if oplocks are disabled */
1182         if (!lp_oplocks(SNUM(conn)) || global_client_failed_oplock_break ||
1183             IS_VETO_OPLOCK_PATH(conn, fname)) {
1184                 /* Mask off everything except the private Samba bits. */
1185                 oplock_request &= SAMBA_PRIVATE_OPLOCK_MASK;
1186         }
1187
1188         /* this is for OS/2 long file names - say we don't support them */
1189         if (!lp_posix_pathnames() && strstr(fname,".+,;=[].")) {
1190                 /* OS/2 Workplace shell fix may be main code stream in a later
1191                  * release. */ 
1192                 DEBUG(5,("open_file_ntcreate: OS/2 long filenames are not "
1193                          "supported.\n"));
1194                 if (use_nt_status()) {
1195                         return NT_STATUS_OBJECT_NAME_NOT_FOUND;
1196                 }
1197                 return NT_STATUS_DOS(ERRDOS, ERRcannotopen);
1198         }
1199
1200         switch( create_disposition ) {
1201                 /*
1202                  * Currently we're using FILE_SUPERSEDE as the same as
1203                  * FILE_OVERWRITE_IF but they really are
1204                  * different. FILE_SUPERSEDE deletes an existing file
1205                  * (requiring delete access) then recreates it.
1206                  */
1207                 case FILE_SUPERSEDE:
1208                         /* If file exists replace/overwrite. If file doesn't
1209                          * exist create. */
1210                         flags2 |= (O_CREAT | O_TRUNC);
1211                         break;
1212
1213                 case FILE_OVERWRITE_IF:
1214                         /* If file exists replace/overwrite. If file doesn't
1215                          * exist create. */
1216                         flags2 |= (O_CREAT | O_TRUNC);
1217                         break;
1218
1219                 case FILE_OPEN:
1220                         /* If file exists open. If file doesn't exist error. */
1221                         if (!file_existed) {
1222                                 DEBUG(5,("open_file_ntcreate: FILE_OPEN "
1223                                          "requested for file %s and file "
1224                                          "doesn't exist.\n", fname ));
1225                                 errno = ENOENT;
1226                                 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
1227                         }
1228                         break;
1229
1230                 case FILE_OVERWRITE:
1231                         /* If file exists overwrite. If file doesn't exist
1232                          * error. */
1233                         if (!file_existed) {
1234                                 DEBUG(5,("open_file_ntcreate: FILE_OVERWRITE "
1235                                          "requested for file %s and file "
1236                                          "doesn't exist.\n", fname ));
1237                                 errno = ENOENT;
1238                                 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
1239                         }
1240                         flags2 |= O_TRUNC;
1241                         break;
1242
1243                 case FILE_CREATE:
1244                         /* If file exists error. If file doesn't exist
1245                          * create. */
1246                         if (file_existed) {
1247                                 DEBUG(5,("open_file_ntcreate: FILE_CREATE "
1248                                          "requested for file %s and file "
1249                                          "already exists.\n", fname ));
1250                                 if (S_ISDIR(psbuf->st_mode)) {
1251                                         errno = EISDIR;
1252                                 } else {
1253                                         errno = EEXIST;
1254                                 }
1255                                 return map_nt_error_from_unix(errno);
1256                         }
1257                         flags2 |= (O_CREAT|O_EXCL);
1258                         break;
1259
1260                 case FILE_OPEN_IF:
1261                         /* If file exists open. If file doesn't exist
1262                          * create. */
1263                         flags2 |= O_CREAT;
1264                         break;
1265
1266                 default:
1267                         return NT_STATUS_INVALID_PARAMETER;
1268         }
1269
1270         /* We only care about matching attributes on file exists and
1271          * overwrite. */
1272
1273         if (file_existed && ((create_disposition == FILE_OVERWRITE) ||
1274                              (create_disposition == FILE_OVERWRITE_IF))) {
1275                 if (!open_match_attributes(conn, fname,
1276                                            existing_dos_attributes,
1277                                            new_dos_attributes, psbuf->st_mode,
1278                                            unx_mode, &new_unx_mode)) {
1279                         DEBUG(5,("open_file_ntcreate: attributes missmatch "
1280                                  "for file %s (%x %x) (0%o, 0%o)\n",
1281                                  fname, existing_dos_attributes,
1282                                  new_dos_attributes,
1283                                  (unsigned int)psbuf->st_mode,
1284                                  (unsigned int)unx_mode ));
1285                         errno = EACCES;
1286                         return NT_STATUS_ACCESS_DENIED;
1287                 }
1288         }
1289
1290         /* This is a nasty hack - must fix... JRA. */
1291         if (access_mask == MAXIMUM_ALLOWED_ACCESS) {
1292                 open_access_mask = access_mask = FILE_GENERIC_ALL;
1293         }
1294
1295         /*
1296          * Convert GENERIC bits to specific bits.
1297          */
1298
1299         se_map_generic(&access_mask, &file_generic_mapping);
1300         open_access_mask = access_mask;
1301
1302         if (flags2 & O_TRUNC) {
1303                 open_access_mask |= FILE_WRITE_DATA; /* This will cause oplock breaks. */
1304         }
1305
1306         DEBUG(10, ("open_file_ntcreate: fname=%s, after mapping "
1307                    "access_mask=0x%x\n", fname, access_mask ));
1308
1309         /*
1310          * Note that we ignore the append flag as append does not
1311          * mean the same thing under DOS and Unix.
1312          */
1313
1314         if (access_mask & (FILE_WRITE_DATA | FILE_APPEND_DATA)) {
1315                 /* DENY_DOS opens are always underlying read-write on the
1316                    file handle, no matter what the requested access mask
1317                     says. */
1318                 if ((create_options & NTCREATEX_OPTIONS_PRIVATE_DENY_DOS) ||
1319                         access_mask & (FILE_READ_ATTRIBUTES|FILE_READ_DATA|FILE_READ_EA|FILE_EXECUTE)) {
1320                         flags = O_RDWR;
1321                 } else {
1322                         flags = O_WRONLY;
1323                 }
1324         } else {
1325                 flags = O_RDONLY;
1326         }
1327
1328         /*
1329          * Currently we only look at FILE_WRITE_THROUGH for create options.
1330          */
1331
1332 #if defined(O_SYNC)
1333         if ((create_options & FILE_WRITE_THROUGH) && lp_strict_sync(SNUM(conn))) {
1334                 flags2 |= O_SYNC;
1335         }
1336 #endif /* O_SYNC */
1337   
1338         if (!CAN_WRITE(conn)) {
1339                 /*
1340                  * We should really return a permission denied error if either
1341                  * O_CREAT or O_TRUNC are set, but for compatibility with
1342                  * older versions of Samba we just AND them out.
1343                  */
1344                 flags2 &= ~(O_CREAT|O_TRUNC);
1345         }
1346
1347         /*
1348          * Ensure we can't write on a read-only share or file.
1349          */
1350
1351         if (flags != O_RDONLY && file_existed &&
1352             (!CAN_WRITE(conn) || IS_DOS_READONLY(existing_dos_attributes))) {
1353                 DEBUG(5,("open_file_ntcreate: write access requested for "
1354                          "file %s on read only %s\n",
1355                          fname, !CAN_WRITE(conn) ? "share" : "file" ));
1356                 errno = EACCES;
1357                 return NT_STATUS_ACCESS_DENIED;
1358         }
1359
1360         status = file_new(conn, &fsp);
1361         if(!NT_STATUS_IS_OK(status)) {
1362                 return status;
1363         }
1364
1365         fsp->dev = psbuf->st_dev;
1366         fsp->inode = psbuf->st_ino;
1367         fsp->share_access = share_access;
1368         fsp->fh->private_options = create_options;
1369         fsp->access_mask = open_access_mask; /* We change this to the
1370                                               * requested access_mask after
1371                                               * the open is done. */
1372         /* Ensure no SAMBA_PRIVATE bits can be set. */
1373         fsp->oplock_type = (oplock_request & ~SAMBA_PRIVATE_OPLOCK_MASK);
1374
1375         if (timeval_is_zero(&request_time)) {
1376                 request_time = fsp->open_time;
1377         }
1378
1379         if (file_existed) {
1380                 dev = psbuf->st_dev;
1381                 inode = psbuf->st_ino;
1382
1383                 lck = get_share_mode_lock(NULL, dev, inode,
1384                                           conn->connectpath,
1385                                           fname);
1386
1387                 if (lck == NULL) {
1388                         file_free(fsp);
1389                         DEBUG(0, ("Could not get share mode lock\n"));
1390                         return NT_STATUS_SHARING_VIOLATION;
1391                 }
1392
1393                 /* First pass - send break only on batch oplocks. */
1394                 if (delay_for_oplocks(lck, fsp, 1, oplock_request)) {
1395                         schedule_defer_open(lck, request_time);
1396                         TALLOC_FREE(lck);
1397                         file_free(fsp);
1398                         return NT_STATUS_SHARING_VIOLATION;
1399                 }
1400
1401                 /* Use the client requested access mask here, not the one we
1402                  * open with. */
1403                 status = open_mode_check(conn, fname, lck,
1404                                          access_mask, share_access,
1405                                          create_options, &file_existed);
1406
1407                 if (NT_STATUS_IS_OK(status)) {
1408                         /* We might be going to allow this open. Check oplock
1409                          * status again. */
1410                         /* Second pass - send break for both batch or
1411                          * exclusive oplocks. */
1412                         if (delay_for_oplocks(lck, fsp, 2, oplock_request)) {
1413                                 schedule_defer_open(lck, request_time);
1414                                 TALLOC_FREE(lck);
1415                                 file_free(fsp);
1416                                 return NT_STATUS_SHARING_VIOLATION;
1417                         }
1418                 }
1419
1420                 if (NT_STATUS_EQUAL(status, NT_STATUS_DELETE_PENDING)) {
1421                         /* DELETE_PENDING is not deferred for a second */
1422                         TALLOC_FREE(lck);
1423                         file_free(fsp);
1424                         return status;
1425                 }
1426
1427                 if (!NT_STATUS_IS_OK(status)) {
1428                         uint32 can_access_mask;
1429                         BOOL can_access = True;
1430
1431                         SMB_ASSERT(NT_STATUS_EQUAL(status, NT_STATUS_SHARING_VIOLATION));
1432
1433                         /* Check if this can be done with the deny_dos and fcb
1434                          * calls. */
1435                         if (create_options &
1436                             (NTCREATEX_OPTIONS_PRIVATE_DENY_DOS|
1437                              NTCREATEX_OPTIONS_PRIVATE_DENY_FCB)) {
1438                                 files_struct *fsp_dup;
1439
1440                                 /* Use the client requested access mask here,
1441                                  * not the one we open with. */
1442                                 fsp_dup = fcb_or_dos_open(conn, fname, dev,
1443                                                           inode, access_mask,
1444                                                           share_access,
1445                                                           create_options);
1446
1447                                 if (fsp_dup) {
1448                                         TALLOC_FREE(lck);
1449                                         file_free(fsp);
1450                                         if (pinfo) {
1451                                                 *pinfo = FILE_WAS_OPENED;
1452                                         }
1453                                         conn->num_files_open++;
1454                                         *result = fsp_dup;
1455                                         return NT_STATUS_OK;
1456                                 }
1457                         }
1458
1459                         /*
1460                          * This next line is a subtlety we need for
1461                          * MS-Access. If a file open will fail due to share
1462                          * permissions and also for security (access) reasons,
1463                          * we need to return the access failed error, not the
1464                          * share error. We can't open the file due to kernel
1465                          * oplock deadlock (it's possible we failed above on
1466                          * the open_mode_check()) so use a userspace check.
1467                          */
1468
1469                         if (flags & O_RDWR) {
1470                                 can_access_mask = FILE_READ_DATA|FILE_WRITE_DATA;
1471                         } else if (flags & O_WRONLY) {
1472                                 can_access_mask = FILE_WRITE_DATA;
1473                         } else {
1474                                 can_access_mask = FILE_READ_DATA;
1475                         }
1476
1477                         if (((can_access_mask & FILE_WRITE_DATA) && !CAN_WRITE(conn)) ||
1478                             !can_access_file(conn,fname,psbuf,can_access_mask)) {
1479                                 can_access = False;
1480                         }
1481
1482                         /* 
1483                          * If we're returning a share violation, ensure we
1484                          * cope with the braindead 1 second delay.
1485                          */
1486
1487                         if (!(oplock_request & INTERNAL_OPEN_ONLY) &&
1488                             lp_defer_sharing_violations()) {
1489                                 struct timeval timeout;
1490                                 struct deferred_open_record state;
1491                                 int timeout_usecs;
1492
1493                                 /* this is a hack to speed up torture tests
1494                                    in 'make test' */
1495                                 timeout_usecs = lp_parm_int(SNUM(conn),
1496                                                             "smbd","sharedelay",
1497                                                             SHARING_VIOLATION_USEC_WAIT);
1498
1499                                 /* This is a relative time, added to the absolute
1500                                    request_time value to get the absolute timeout time.
1501                                    Note that if this is the second or greater time we enter
1502                                    this codepath for this particular request mid then
1503                                    request_time is left as the absolute time of the *first*
1504                                    time this request mid was processed. This is what allows
1505                                    the request to eventually time out. */
1506
1507                                 timeout = timeval_set(0, timeout_usecs);
1508
1509                                 /* Nothing actually uses state.delayed_for_oplocks
1510                                    but it's handy to differentiate in debug messages
1511                                    between a 30 second delay due to oplock break, and
1512                                    a 1 second delay for share mode conflicts. */
1513
1514                                 state.delayed_for_oplocks = False;
1515                                 state.dev = dev;
1516                                 state.inode = inode;
1517
1518                                 if (!request_timed_out(request_time,
1519                                                        timeout)) {
1520                                         defer_open(lck, request_time, timeout,
1521                                                    &state);
1522                                 }
1523                         }
1524
1525                         TALLOC_FREE(lck);
1526                         if (can_access) {
1527                                 /*
1528                                  * We have detected a sharing violation here
1529                                  * so return the correct error code
1530                                  */
1531                                 status = NT_STATUS_SHARING_VIOLATION;
1532                         } else {
1533                                 status = NT_STATUS_ACCESS_DENIED;
1534                         }
1535                         file_free(fsp);
1536                         return status;
1537                 }
1538
1539                 /*
1540                  * We exit this block with the share entry *locked*.....
1541                  */
1542         }
1543
1544         SMB_ASSERT(!file_existed || (lck != NULL));
1545
1546         /*
1547          * Ensure we pay attention to default ACLs on directories if required.
1548          */
1549
1550         if ((flags2 & O_CREAT) && lp_inherit_acls(SNUM(conn)) &&
1551             (def_acl = directory_has_default_acl(conn,
1552                                                  parent_dirname(fname)))) {
1553                 unx_mode = 0777;
1554         }
1555
1556         DEBUG(4,("calling open_file with flags=0x%X flags2=0x%X mode=0%o, "
1557                 "access_mask = 0x%x, open_access_mask = 0x%x\n",
1558                  (unsigned int)flags, (unsigned int)flags2,
1559                  (unsigned int)unx_mode, (unsigned int)access_mask,
1560                  (unsigned int)open_access_mask));
1561
1562         /*
1563          * open_file strips any O_TRUNC flags itself.
1564          */
1565
1566         fsp_open = open_file(fsp,conn,fname,psbuf,flags|flags2,unx_mode,
1567                              access_mask, open_access_mask);
1568
1569         if (!NT_STATUS_IS_OK(fsp_open)) {
1570                 if (lck != NULL) {
1571                         TALLOC_FREE(lck);
1572                 }
1573                 file_free(fsp);
1574                 return fsp_open;
1575         }
1576
1577         if (!file_existed) {
1578
1579                 /*
1580                  * Deal with the race condition where two smbd's detect the
1581                  * file doesn't exist and do the create at the same time. One
1582                  * of them will win and set a share mode, the other (ie. this
1583                  * one) should check if the requested share mode for this
1584                  * create is allowed.
1585                  */
1586
1587                 /*
1588                  * Now the file exists and fsp is successfully opened,
1589                  * fsp->dev and fsp->inode are valid and should replace the
1590                  * dev=0,inode=0 from a non existent file. Spotted by
1591                  * Nadav Danieli <nadavd@exanet.com>. JRA.
1592                  */
1593
1594                 dev = fsp->dev;
1595                 inode = fsp->inode;
1596
1597                 lck = get_share_mode_lock(NULL, dev, inode,
1598                                           conn->connectpath,
1599                                           fname);
1600
1601                 if (lck == NULL) {
1602                         DEBUG(0, ("open_file_ntcreate: Could not get share "
1603                                   "mode lock for %s\n", fname));
1604                         fd_close(conn, fsp);
1605                         file_free(fsp);
1606                         return NT_STATUS_SHARING_VIOLATION;
1607                 }
1608
1609                 status = open_mode_check(conn, fname, lck,
1610                                          access_mask, share_access,
1611                                          create_options, &file_existed);
1612
1613                 if (!NT_STATUS_IS_OK(status)) {
1614                         struct deferred_open_record state;
1615
1616                         fd_close(conn, fsp);
1617                         file_free(fsp);
1618
1619                         state.delayed_for_oplocks = False;
1620                         state.dev = dev;
1621                         state.inode = inode;
1622
1623                         /* Do it all over again immediately. In the second
1624                          * round we will find that the file existed and handle
1625                          * the DELETE_PENDING and FCB cases correctly. No need
1626                          * to duplicate the code here. Essentially this is a
1627                          * "goto top of this function", but don't tell
1628                          * anybody... */
1629
1630                         defer_open(lck, request_time, timeval_zero(),
1631                                    &state);
1632                         TALLOC_FREE(lck);
1633                         return status;
1634                 }
1635
1636                 /*
1637                  * We exit this block with the share entry *locked*.....
1638                  */
1639
1640         }
1641
1642         SMB_ASSERT(lck != NULL);
1643
1644         /* note that we ignore failure for the following. It is
1645            basically a hack for NFS, and NFS will never set one of
1646            these only read them. Nobody but Samba can ever set a deny
1647            mode and we have already checked our more authoritative
1648            locking database for permission to set this deny mode. If
1649            the kernel refuses the operations then the kernel is wrong.
1650            note that GPFS supports it as well - jmcd */
1651
1652         ret_flock = SMB_VFS_KERNEL_FLOCK(fsp, fsp->fh->fd, share_access);
1653         if(ret_flock == -1 ){
1654
1655                 talloc_free(lck);
1656                 fd_close(conn, fsp);
1657                 file_free(fsp);
1658                 
1659                 return NT_STATUS_SHARING_VIOLATION;
1660         }
1661
1662         /*
1663          * At this point onwards, we can guarentee that the share entry
1664          * is locked, whether we created the file or not, and that the
1665          * deny mode is compatible with all current opens.
1666          */
1667
1668         /*
1669          * If requested, truncate the file.
1670          */
1671
1672         if (flags2&O_TRUNC) {
1673                 /*
1674                  * We are modifing the file after open - update the stat
1675                  * struct..
1676                  */
1677                 if ((SMB_VFS_FTRUNCATE(fsp,fsp->fh->fd,0) == -1) ||
1678                     (SMB_VFS_FSTAT(fsp,fsp->fh->fd,psbuf)==-1)) {
1679                         status = map_nt_error_from_unix(errno);
1680                         TALLOC_FREE(lck);
1681                         fd_close(conn,fsp);
1682                         file_free(fsp);
1683                         return status;
1684                 }
1685         }
1686
1687         /* Record the options we were opened with. */
1688         fsp->share_access = share_access;
1689         fsp->fh->private_options = create_options;
1690         fsp->access_mask = access_mask;
1691
1692         if (file_existed) {
1693                 /* stat opens on existing files don't get oplocks. */
1694                 if (is_stat_open(open_access_mask)) {
1695                         fsp->oplock_type = NO_OPLOCK;
1696                 }
1697
1698                 if (!(flags2 & O_TRUNC)) {
1699                         info = FILE_WAS_OPENED;
1700                 } else {
1701                         info = FILE_WAS_OVERWRITTEN;
1702                 }
1703         } else {
1704                 info = FILE_WAS_CREATED;
1705                 /* Change the owner if required. */
1706                 if (lp_inherit_owner(SNUM(conn))) {
1707                         change_fd_owner_to_parent(conn, fsp);
1708                 }
1709         }
1710
1711         if (pinfo) {
1712                 *pinfo = info;
1713         }
1714
1715         /* 
1716          * Setup the oplock info in both the shared memory and
1717          * file structs.
1718          */
1719
1720         if ((fsp->oplock_type != NO_OPLOCK) &&
1721             (fsp->oplock_type != FAKE_LEVEL_II_OPLOCK)) {
1722                 if (!set_file_oplock(fsp, fsp->oplock_type)) {
1723                         /* Could not get the kernel oplock */
1724                         fsp->oplock_type = NO_OPLOCK;
1725                 }
1726         }
1727         set_share_mode(lck, fsp, current_user.ut.uid, 0, fsp->oplock_type);
1728
1729         if (info == FILE_WAS_OVERWRITTEN || info == FILE_WAS_CREATED ||
1730             info == FILE_WAS_SUPERSEDED) {
1731
1732                 /* Handle strange delete on close create semantics. */
1733                 if (create_options & FILE_DELETE_ON_CLOSE) {
1734                         status = can_set_delete_on_close(fsp, True, new_dos_attributes);
1735
1736                         if (!NT_STATUS_IS_OK(status)) {
1737                                 /* Remember to delete the mode we just added. */
1738                                 del_share_mode(lck, fsp);
1739                                 TALLOC_FREE(lck);
1740                                 fd_close(conn,fsp);
1741                                 file_free(fsp);
1742                                 return status;
1743                         }
1744                         /* Note that here we set the *inital* delete on close flag,
1745                            not the regular one. */
1746                         set_delete_on_close_token(lck, &current_user.ut);
1747                         lck->initial_delete_on_close = True;
1748                         lck->modified = True;
1749                 }
1750         
1751                 /* Files should be initially set as archive */
1752                 if (lp_map_archive(SNUM(conn)) ||
1753                     lp_store_dos_attributes(SNUM(conn))) {
1754                         file_set_dosmode(conn, fname,
1755                                          new_dos_attributes | aARCH, NULL,
1756                                          True);
1757                 }
1758         }
1759
1760         /*
1761          * Take care of inherited ACLs on created files - if default ACL not
1762          * selected.
1763          */
1764
1765         if (!file_existed && !def_acl) {
1766
1767                 int saved_errno = errno; /* We might get ENOSYS in the next
1768                                           * call.. */
1769
1770                 if (SMB_VFS_FCHMOD_ACL(fsp, fsp->fh->fd, unx_mode) == -1 &&
1771                     errno == ENOSYS) {
1772                         errno = saved_errno; /* Ignore ENOSYS */
1773                 }
1774
1775         } else if (new_unx_mode) {
1776
1777                 int ret = -1;
1778
1779                 /* Attributes need changing. File already existed. */
1780
1781                 {
1782                         int saved_errno = errno; /* We might get ENOSYS in the
1783                                                   * next call.. */
1784                         ret = SMB_VFS_FCHMOD_ACL(fsp, fsp->fh->fd,
1785                                                  new_unx_mode);
1786
1787                         if (ret == -1 && errno == ENOSYS) {
1788                                 errno = saved_errno; /* Ignore ENOSYS */
1789                         } else {
1790                                 DEBUG(5, ("open_file_ntcreate: reset "
1791                                           "attributes of file %s to 0%o\n",
1792                                           fname, (unsigned int)new_unx_mode));
1793                                 ret = 0; /* Don't do the fchmod below. */
1794                         }
1795                 }
1796
1797                 if ((ret == -1) &&
1798                     (SMB_VFS_FCHMOD(fsp, fsp->fh->fd, new_unx_mode) == -1))
1799                         DEBUG(5, ("open_file_ntcreate: failed to reset "
1800                                   "attributes of file %s to 0%o\n",
1801                                   fname, (unsigned int)new_unx_mode));
1802         }
1803
1804         /* If this is a successful open, we must remove any deferred open
1805          * records. */
1806         del_deferred_open_entry(lck, mid);
1807         TALLOC_FREE(lck);
1808
1809         conn->num_files_open++;
1810
1811         *result = fsp;
1812         return NT_STATUS_OK;
1813 }
1814
1815 /****************************************************************************
1816  Open a file for for write to ensure that we can fchmod it.
1817 ****************************************************************************/
1818
1819 NTSTATUS open_file_fchmod(connection_struct *conn, const char *fname,
1820                           SMB_STRUCT_STAT *psbuf, files_struct **result)
1821 {
1822         files_struct *fsp = NULL;
1823         NTSTATUS status;
1824
1825         if (!VALID_STAT(*psbuf)) {
1826                 return NT_STATUS_INVALID_PARAMETER;
1827         }
1828
1829         status = file_new(conn, &fsp);
1830         if(!NT_STATUS_IS_OK(status)) {
1831                 return status;
1832         }
1833
1834         /* note! we must use a non-zero desired access or we don't get
1835            a real file descriptor. Oh what a twisted web we weave. */
1836         status = open_file(fsp,conn,fname,psbuf,O_WRONLY,0,FILE_WRITE_DATA,FILE_WRITE_DATA);
1837
1838         /* 
1839          * This is not a user visible file open.
1840          * Don't set a share mode and don't increment
1841          * the conn->num_files_open.
1842          */
1843
1844         if (!NT_STATUS_IS_OK(status)) {
1845                 file_free(fsp);
1846                 return status;
1847         }
1848
1849         *result = fsp;
1850         return NT_STATUS_OK;
1851 }
1852
1853 /****************************************************************************
1854  Close the fchmod file fd - ensure no locks are lost.
1855 ****************************************************************************/
1856
1857 int close_file_fchmod(files_struct *fsp)
1858 {
1859         int ret = fd_close(fsp->conn, fsp);
1860         file_free(fsp);
1861         return ret;
1862 }
1863
1864 static NTSTATUS mkdir_internal(connection_struct *conn, const char *name,
1865                                SMB_STRUCT_STAT *psbuf)
1866 {
1867         int ret= -1;
1868         mode_t mode;
1869
1870         if(!CAN_WRITE(conn)) {
1871                 DEBUG(5,("mkdir_internal: failing create on read-only share "
1872                          "%s\n", lp_servicename(SNUM(conn))));
1873                 return NT_STATUS_ACCESS_DENIED;
1874         }
1875
1876         if (!check_name(name, conn)) {
1877                 return map_nt_error_from_unix(errno);
1878         }
1879
1880         mode = unix_mode(conn, aDIR, name, True);
1881
1882         if ((ret=SMB_VFS_MKDIR(conn, name, mode)) != 0) {
1883                 return map_nt_error_from_unix(errno);
1884         }
1885
1886         /* Ensure we're checking for a symlink here.... */
1887         /* We don't want to get caught by a symlink racer. */
1888
1889         if (SMB_VFS_LSTAT(conn, name, psbuf) == -1) {
1890                 DEBUG(2, ("Could not stat directory '%s' just created: %s\n",
1891                           name, strerror(errno)));
1892                 return map_nt_error_from_unix(errno);
1893         }
1894
1895         if (!S_ISDIR(psbuf->st_mode)) {
1896                 DEBUG(0, ("Directory just '%s' created is not a directory\n",
1897                           name));
1898                 return NT_STATUS_ACCESS_DENIED;
1899         }
1900
1901         if (lp_inherit_perms(SNUM(conn))) {
1902                 inherit_access_acl(conn, name, mode);
1903         }
1904
1905         /*
1906          * Check if high bits should have been set,
1907          * then (if bits are missing): add them.
1908          * Consider bits automagically set by UNIX, i.e. SGID bit from parent
1909          * dir.
1910          */
1911         if (mode & ~(S_IRWXU|S_IRWXG|S_IRWXO) && (mode & ~psbuf->st_mode)) {
1912                 SMB_VFS_CHMOD(conn, name,
1913                               psbuf->st_mode | (mode & ~psbuf->st_mode));
1914         }
1915
1916         return NT_STATUS_OK;
1917 }
1918
1919 /****************************************************************************
1920  Open a directory from an NT SMB call.
1921 ****************************************************************************/
1922
1923 NTSTATUS open_directory(connection_struct *conn,
1924                         const char *fname,
1925                         SMB_STRUCT_STAT *psbuf,
1926                         uint32 access_mask,
1927                         uint32 share_access,
1928                         uint32 create_disposition,
1929                         uint32 create_options,
1930                         int *pinfo,
1931                         files_struct **result)
1932 {
1933         files_struct *fsp = NULL;
1934         BOOL dir_existed = VALID_STAT(*psbuf) ? True : False;
1935         struct share_mode_lock *lck = NULL;
1936         NTSTATUS status;
1937         int info = 0;
1938
1939         DEBUG(5,("open_directory: opening directory %s, access_mask = 0x%x, "
1940                  "share_access = 0x%x create_options = 0x%x, "
1941                  "create_disposition = 0x%x\n",
1942                  fname,
1943                  (unsigned int)access_mask,
1944                  (unsigned int)share_access,
1945                  (unsigned int)create_options,
1946                  (unsigned int)create_disposition));
1947
1948         if (is_ntfs_stream_name(fname)) {
1949                 DEBUG(0,("open_directory: %s is a stream name!\n", fname ));
1950                 return NT_STATUS_NOT_A_DIRECTORY;
1951         }
1952
1953         switch( create_disposition ) {
1954                 case FILE_OPEN:
1955
1956                         info = FILE_WAS_OPENED;
1957
1958                         /*
1959                          * We want to follow symlinks here.
1960                          */
1961
1962                         if (SMB_VFS_STAT(conn, fname, psbuf) != 0) {
1963                                 return map_nt_error_from_unix(errno);
1964                         }
1965                                 
1966                         break;
1967
1968                 case FILE_CREATE:
1969
1970                         /* If directory exists error. If directory doesn't
1971                          * exist create. */
1972
1973                         status = mkdir_internal(conn, fname, psbuf);
1974                         if (!NT_STATUS_IS_OK(status)) {
1975                                 DEBUG(2, ("open_directory: unable to create "
1976                                           "%s. Error was %s\n", fname,
1977                                           nt_errstr(status)));
1978                                 return status;
1979                         }
1980
1981                         info = FILE_WAS_CREATED;
1982                         break;
1983
1984                 case FILE_OPEN_IF:
1985                         /*
1986                          * If directory exists open. If directory doesn't
1987                          * exist create.
1988                          */
1989
1990                         status = mkdir_internal(conn, fname, psbuf);
1991
1992                         if (NT_STATUS_IS_OK(status)) {
1993                                 info = FILE_WAS_CREATED;
1994                         }
1995
1996                         if (NT_STATUS_EQUAL(status,
1997                                             NT_STATUS_OBJECT_NAME_COLLISION)) {
1998                                 info = FILE_WAS_OPENED;
1999                                 status = NT_STATUS_OK;
2000                         }
2001                                 
2002                         break;
2003
2004                 case FILE_SUPERSEDE:
2005                 case FILE_OVERWRITE:
2006                 case FILE_OVERWRITE_IF:
2007                 default:
2008                         DEBUG(5,("open_directory: invalid create_disposition "
2009                                  "0x%x for directory %s\n",
2010                                  (unsigned int)create_disposition, fname));
2011                         return NT_STATUS_INVALID_PARAMETER;
2012         }
2013
2014         if(!S_ISDIR(psbuf->st_mode)) {
2015                 DEBUG(5,("open_directory: %s is not a directory !\n",
2016                          fname ));
2017                 return NT_STATUS_NOT_A_DIRECTORY;
2018         }
2019
2020         status = file_new(conn, &fsp);
2021         if(!NT_STATUS_IS_OK(status)) {
2022                 return status;
2023         }
2024
2025         /*
2026          * Setup the files_struct for it.
2027          */
2028         
2029         fsp->mode = psbuf->st_mode;
2030         fsp->inode = psbuf->st_ino;
2031         fsp->dev = psbuf->st_dev;
2032         fsp->vuid = current_user.vuid;
2033         fsp->file_pid = global_smbpid;
2034         fsp->can_lock = False;
2035         fsp->can_read = False;
2036         fsp->can_write = False;
2037
2038         fsp->share_access = share_access;
2039         fsp->fh->private_options = create_options;
2040         fsp->access_mask = access_mask;
2041
2042         fsp->print_file = False;
2043         fsp->modified = False;
2044         fsp->oplock_type = NO_OPLOCK;
2045         fsp->sent_oplock_break = NO_BREAK_SENT;
2046         fsp->is_directory = True;
2047         fsp->is_stat = False;
2048         string_set(&fsp->fsp_name,fname);
2049
2050         lck = get_share_mode_lock(NULL, fsp->dev, fsp->inode,
2051                                   conn->connectpath,
2052                                   fname);
2053
2054         if (lck == NULL) {
2055                 DEBUG(0, ("open_directory: Could not get share mode lock for %s\n", fname));
2056                 file_free(fsp);
2057                 return NT_STATUS_SHARING_VIOLATION;
2058         }
2059
2060         status = open_mode_check(conn, fname, lck,
2061                                 access_mask, share_access,
2062                                 create_options, &dir_existed);
2063
2064         if (!NT_STATUS_IS_OK(status)) {
2065                 TALLOC_FREE(lck);
2066                 file_free(fsp);
2067                 return status;
2068         }
2069
2070         set_share_mode(lck, fsp, current_user.ut.uid, 0, NO_OPLOCK);
2071
2072         /* For directories the delete on close bit at open time seems
2073            always to be honored on close... See test 19 in Samba4 BASE-DELETE. */
2074         if (create_options & FILE_DELETE_ON_CLOSE) {
2075                 status = can_set_delete_on_close(fsp, True, 0);
2076                 if (!NT_STATUS_IS_OK(status)) {
2077                         TALLOC_FREE(lck);
2078                         file_free(fsp);
2079                         return status;
2080                 }
2081
2082                 set_delete_on_close_token(lck, &current_user.ut);
2083                 lck->initial_delete_on_close = True;
2084                 lck->modified = True;
2085         }
2086
2087         TALLOC_FREE(lck);
2088
2089         /* Change the owner if required. */
2090         if ((info == FILE_WAS_CREATED) && lp_inherit_owner(SNUM(conn))) {
2091                 change_owner_to_parent(conn, fsp->fsp_name, psbuf);
2092         }
2093
2094         if (pinfo) {
2095                 *pinfo = info;
2096         }
2097
2098         conn->num_files_open++;
2099
2100         *result = fsp;
2101         return NT_STATUS_OK;
2102 }
2103
2104 NTSTATUS create_directory(connection_struct *conn, const char *directory)
2105 {
2106         NTSTATUS status;
2107         SMB_STRUCT_STAT sbuf;
2108         files_struct *fsp;
2109
2110         SET_STAT_INVALID(sbuf);
2111         
2112         status = open_directory(conn, directory, &sbuf,
2113                                 FILE_READ_ATTRIBUTES, /* Just a stat open */
2114                                 FILE_SHARE_NONE, /* Ignored for stat opens */
2115                                 FILE_CREATE, 0, NULL, &fsp);
2116
2117         if (NT_STATUS_IS_OK(status)) {
2118                 close_file(fsp, NORMAL_CLOSE);
2119         }
2120
2121         return status;
2122 }
2123
2124 /****************************************************************************
2125  Open a pseudo-file (no locking checks - a 'stat' open).
2126 ****************************************************************************/
2127
2128 NTSTATUS open_file_stat(connection_struct *conn, const char *fname,
2129                         SMB_STRUCT_STAT *psbuf, files_struct **result)
2130 {
2131         files_struct *fsp = NULL;
2132         NTSTATUS status;
2133
2134         if (!VALID_STAT(*psbuf)) {
2135                 return NT_STATUS_INVALID_PARAMETER;
2136         }
2137
2138         /* Can't 'stat' open directories. */
2139         if(S_ISDIR(psbuf->st_mode)) {
2140                 return NT_STATUS_FILE_IS_A_DIRECTORY;
2141         }
2142
2143         status = file_new(conn, &fsp);
2144         if(!NT_STATUS_IS_OK(status)) {
2145                 return status;
2146         }
2147
2148         DEBUG(5,("open_file_stat: 'opening' file %s\n", fname));
2149
2150         /*
2151          * Setup the files_struct for it.
2152          */
2153         
2154         fsp->mode = psbuf->st_mode;
2155         fsp->inode = psbuf->st_ino;
2156         fsp->dev = psbuf->st_dev;
2157         fsp->vuid = current_user.vuid;
2158         fsp->file_pid = global_smbpid;
2159         fsp->can_lock = False;
2160         fsp->can_read = False;
2161         fsp->can_write = False;
2162         fsp->print_file = False;
2163         fsp->modified = False;
2164         fsp->oplock_type = NO_OPLOCK;
2165         fsp->sent_oplock_break = NO_BREAK_SENT;
2166         fsp->is_directory = False;
2167         fsp->is_stat = True;
2168         string_set(&fsp->fsp_name,fname);
2169
2170         conn->num_files_open++;
2171
2172         *result = fsp;
2173         return NT_STATUS_OK;
2174 }
2175
2176 /****************************************************************************
2177  Receive notification that one of our open files has been renamed by another
2178  smbd process.
2179 ****************************************************************************/
2180
2181 void msg_file_was_renamed(int msg_type, struct process_id src, void *buf, size_t len)
2182 {
2183         files_struct *fsp;
2184         char *frm = (char *)buf;
2185         SMB_DEV_T dev;
2186         SMB_INO_T inode;
2187         const char *sharepath;
2188         const char *newname;
2189         size_t sp_len;
2190
2191         if (buf == NULL || len < MSG_FILE_RENAMED_MIN_SIZE + 2) {
2192                 DEBUG(0, ("msg_file_was_renamed: Got invalid msg len %d\n", (int)len));
2193                 return;
2194         }
2195
2196         /* Unpack the message. */
2197         dev = DEV_T_VAL(frm,0);
2198         inode = INO_T_VAL(frm,8);
2199         sharepath = &frm[16];
2200         newname = sharepath + strlen(sharepath) + 1;
2201         sp_len = strlen(sharepath);
2202
2203         DEBUG(10,("msg_file_was_renamed: Got rename message for sharepath %s, new name %s, "
2204                 "dev %x, inode  %.0f\n",
2205                 sharepath, newname, (unsigned int)dev, (double)inode ));
2206
2207         for(fsp = file_find_di_first(dev, inode); fsp; fsp = file_find_di_next(fsp)) {
2208                 if (memcmp(fsp->conn->connectpath, sharepath, sp_len) == 0) {
2209                         DEBUG(10,("msg_file_was_renamed: renaming file fnum %d from %s -> %s\n",
2210                                 fsp->fnum, fsp->fsp_name, newname ));
2211                         string_set(&fsp->fsp_name, newname);
2212                 } else {
2213                         /* TODO. JRA. */
2214                         /* Now we have the complete path we can work out if this is
2215                            actually within this share and adjust newname accordingly. */
2216                         DEBUG(10,("msg_file_was_renamed: share mismatch (sharepath %s "
2217                                 "not sharepath %s) "
2218                                 "fnum %d from %s -> %s\n",
2219                                 fsp->conn->connectpath,
2220                                 sharepath,
2221                                 fsp->fnum,
2222                                 fsp->fsp_name,
2223                                 newname ));
2224                 }
2225         }
2226 }