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