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