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