r12460: Fixes for bug 3349
[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                 DEBUG(10, ("Sending break request to PID %s\n",
687                            procid_str_static(&exclusive->pid)));
688                 exclusive->op_mid = get_current_mid();
689                 become_root();
690                 ret = message_send_pid(exclusive->pid, MSG_SMB_BREAK_REQUEST,
691                                        exclusive, sizeof(*exclusive), True);
692                 unbecome_root();
693                 if (!ret) {
694                         DEBUG(3, ("Could not send oplock break message\n"));
695                 }
696                 file_free(fsp);
697         }
698
699         return delay_it;
700 }
701
702 static BOOL request_timed_out(struct timeval request_time,
703                               struct timeval timeout)
704 {
705         struct timeval now, end_time;
706         GetTimeOfDay(&now);
707         end_time = timeval_sum(&request_time, &timeout);
708         return (timeval_compare(&end_time, &now) < 0);
709 }
710
711 /****************************************************************************
712  Handle the 1 second delay in returning a SHARING_VIOLATION error.
713 ****************************************************************************/
714
715 static void defer_open(struct share_mode_lock *lck,
716                        struct timeval request_time,
717                        struct timeval timeout,
718                        struct deferred_open_record *state)
719 {
720         uint16 mid = get_current_mid();
721         int i;
722
723         /* Paranoia check */
724
725         for (i=0; i<lck->num_share_modes; i++) {
726                 struct share_mode_entry *e = &lck->share_modes[i];
727
728                 if (!is_deferred_open_entry(e)) {
729                         continue;
730                 }
731
732                 if (procid_is_me(&e->pid) && (e->op_mid == mid)) {
733                         DEBUG(0, ("Trying to defer an already deferred "
734                                   "request: mid=%d, exiting\n", mid));
735                         exit_server("exiting");
736                 }
737         }
738
739         /* End paranoia check */
740
741         DEBUG(10,("defer_open_sharing_error: time [%u.%06u] adding deferred "
742                   "open entry for mid %u\n",
743                   (unsigned int)request_time.tv_sec,
744                   (unsigned int)request_time.tv_usec,
745                   (unsigned int)mid));
746
747         if (!push_deferred_smb_message(mid, request_time, timeout,
748                                        (char *)state, sizeof(*state))) {
749                 exit_server("push_deferred_smb_message failed\n");
750         }
751         add_deferred_open(lck, mid, request_time, state->dev, state->inode);
752
753         /*
754          * Push the MID of this packet on the signing queue.
755          * We only do this once, the first time we push the packet
756          * onto the deferred open queue, as this has a side effect
757          * of incrementing the response sequence number.
758          */
759
760         srv_defer_sign_response(mid);
761 }
762
763 /****************************************************************************
764  Set a kernel flock on a file for NFS interoperability.
765  This requires a patch to Linux.
766 ****************************************************************************/
767
768 static void kernel_flock(files_struct *fsp, uint32 share_mode)
769 {
770 #if HAVE_KERNEL_SHARE_MODES
771         int kernel_mode = 0;
772         if (share_mode == FILE_SHARE_WRITE) {
773                 kernel_mode = LOCK_MAND|LOCK_WRITE;
774         } else if (share_mode == FILE_SHARE_READ) {
775                 kernel_mode = LOCK_MAND|LOCK_READ;
776         } else if (share_mode == FILE_SHARE_NONE) {
777                 kernel_mode = LOCK_MAND;
778         }
779         if (kernel_mode) {
780                 flock(fsp->fh->fd, kernel_mode);
781         }
782 #endif
783         ;
784 }
785
786 /****************************************************************************
787  On overwrite open ensure that the attributes match.
788 ****************************************************************************/
789
790 static BOOL open_match_attributes(connection_struct *conn,
791                                 const char *path,
792                                 uint32 old_dos_attr,
793                                 uint32 new_dos_attr,
794                                 mode_t existing_unx_mode,
795                                 mode_t new_unx_mode,
796                                 mode_t *returned_unx_mode)
797 {
798         uint32 noarch_old_dos_attr, noarch_new_dos_attr;
799
800         noarch_old_dos_attr = (old_dos_attr & ~FILE_ATTRIBUTE_ARCHIVE);
801         noarch_new_dos_attr = (new_dos_attr & ~FILE_ATTRIBUTE_ARCHIVE);
802
803         if((noarch_old_dos_attr == 0 && noarch_new_dos_attr != 0) || 
804            (noarch_old_dos_attr != 0 && ((noarch_old_dos_attr & noarch_new_dos_attr) == noarch_old_dos_attr))) {
805                 *returned_unx_mode = new_unx_mode;
806         } else {
807                 *returned_unx_mode = (mode_t)0;
808         }
809
810         DEBUG(10,("open_match_attributes: file %s old_dos_attr = 0x%x, "
811                   "existing_unx_mode = 0%o, new_dos_attr = 0x%x "
812                   "returned_unx_mode = 0%o\n",
813                   path,
814                   (unsigned int)old_dos_attr,
815                   (unsigned int)existing_unx_mode,
816                   (unsigned int)new_dos_attr,
817                   (unsigned int)*returned_unx_mode ));
818
819         /* If we're mapping SYSTEM and HIDDEN ensure they match. */
820         if (lp_map_system(SNUM(conn)) || lp_store_dos_attributes(SNUM(conn))) {
821                 if ((old_dos_attr & FILE_ATTRIBUTE_SYSTEM) &&
822                     !(new_dos_attr & FILE_ATTRIBUTE_SYSTEM)) {
823                         return False;
824                 }
825         }
826         if (lp_map_hidden(SNUM(conn)) || lp_store_dos_attributes(SNUM(conn))) {
827                 if ((old_dos_attr & FILE_ATTRIBUTE_HIDDEN) &&
828                     !(new_dos_attr & FILE_ATTRIBUTE_HIDDEN)) {
829                         return False;
830                 }
831         }
832         return True;
833 }
834
835 /****************************************************************************
836  Special FCB or DOS processing in the case of a sharing violation.
837  Try and find a duplicated file handle.
838 ****************************************************************************/
839
840 static files_struct *fcb_or_dos_open(connection_struct *conn,
841                                      const char *fname, SMB_DEV_T dev,
842                                      SMB_INO_T inode,
843                                      uint32 access_mask,
844                                      uint32 share_access,
845                                      uint32 create_options)
846 {
847         files_struct *fsp;
848         files_struct *dup_fsp;
849
850         DEBUG(5,("fcb_or_dos_open: attempting old open semantics for "
851                  "file %s.\n", fname ));
852
853         for(fsp = file_find_di_first(dev, inode); fsp;
854             fsp = file_find_di_next(fsp)) {
855
856                 DEBUG(10,("fcb_or_dos_open: checking file %s, fd = %d, "
857                           "vuid = %u, file_pid = %u, private_options = 0x%x "
858                           "access_mask = 0x%x\n", fsp->fsp_name,
859                           fsp->fh->fd, (unsigned int)fsp->vuid,
860                           (unsigned int)fsp->file_pid,
861                           (unsigned int)fsp->fh->private_options,
862                           (unsigned int)fsp->access_mask ));
863
864                 if (fsp->fh->fd != -1 &&
865                     fsp->vuid == current_user.vuid &&
866                     fsp->file_pid == global_smbpid &&
867                     (fsp->fh->private_options & (NTCREATEX_OPTIONS_PRIVATE_DENY_DOS |
868                                                  NTCREATEX_OPTIONS_PRIVATE_DENY_FCB)) &&
869                     (fsp->access_mask & FILE_WRITE_DATA) &&
870                     strequal(fsp->fsp_name, fname)) {
871                         DEBUG(10,("fcb_or_dos_open: file match\n"));
872                         break;
873                 }
874         }
875
876         if (!fsp) {
877                 return NULL;
878         }
879
880         /* quite an insane set of semantics ... */
881         if (is_executable(fname) &&
882             (fsp->fh->private_options & NTCREATEX_OPTIONS_PRIVATE_DENY_DOS)) {
883                 DEBUG(10,("fcb_or_dos_open: file fail due to is_executable.\n"));
884                 return NULL;
885         }
886
887         /* We need to duplicate this fsp. */
888         dup_fsp = dup_file_fsp(fsp, access_mask, share_access, create_options);
889         if (!dup_fsp) {
890                 return NULL;
891         }
892
893         return dup_fsp;
894 }
895
896 /****************************************************************************
897  Open a file with a share mode - old openX method - map into NTCreate.
898 ****************************************************************************/
899
900 BOOL map_open_params_to_ntcreate(const char *fname, int deny_mode, int open_func,
901                                 uint32 *paccess_mask,
902                                 uint32 *pshare_mode,
903                                 uint32 *pcreate_disposition,
904                                 uint32 *pcreate_options)
905 {
906         uint32 access_mask;
907         uint32 share_mode;
908         uint32 create_disposition;
909         uint32 create_options = 0;
910
911         DEBUG(10,("map_open_params_to_ntcreate: fname = %s, deny_mode = 0x%x, "
912                   "open_func = 0x%x\n",
913                   fname, (unsigned int)deny_mode, (unsigned int)open_func ));
914
915         /* Create the NT compatible access_mask. */
916         switch (GET_OPENX_MODE(deny_mode)) {
917                 case DOS_OPEN_EXEC: /* Implies read-only - used to be FILE_READ_DATA */
918                 case DOS_OPEN_RDONLY:
919                         access_mask = FILE_GENERIC_READ;
920                         break;
921                 case DOS_OPEN_WRONLY:
922                         access_mask = FILE_GENERIC_WRITE;
923                         break;
924                 case DOS_OPEN_RDWR:
925                 case DOS_OPEN_FCB:
926                         access_mask = FILE_GENERIC_READ|FILE_GENERIC_WRITE;
927                         break;
928                 default:
929                         DEBUG(10,("map_open_params_to_ntcreate: bad open mode = 0x%x\n",
930                                   (unsigned int)GET_OPENX_MODE(deny_mode)));
931                         return False;
932         }
933
934         /* Create the NT compatible create_disposition. */
935         switch (open_func) {
936                 case OPENX_FILE_EXISTS_FAIL|OPENX_FILE_CREATE_IF_NOT_EXIST:
937                         create_disposition = FILE_CREATE;
938                         break;
939
940                 case OPENX_FILE_EXISTS_OPEN:
941                         create_disposition = FILE_OPEN;
942                         break;
943
944                 case OPENX_FILE_EXISTS_OPEN|OPENX_FILE_CREATE_IF_NOT_EXIST:
945                         create_disposition = FILE_OPEN_IF;
946                         break;
947        
948                 case OPENX_FILE_EXISTS_TRUNCATE:
949                         create_disposition = FILE_OVERWRITE;
950                         break;
951
952                 case OPENX_FILE_EXISTS_TRUNCATE|OPENX_FILE_CREATE_IF_NOT_EXIST:
953                         create_disposition = FILE_OVERWRITE_IF;
954                         break;
955
956                 default:
957                         /* From samba4 - to be confirmed. */
958                         if (GET_OPENX_MODE(deny_mode) == DOS_OPEN_EXEC) {
959                                 create_disposition = FILE_CREATE;
960                                 break;
961                         }
962                         DEBUG(10,("map_open_params_to_ntcreate: bad "
963                                   "open_func 0x%x\n", (unsigned int)open_func));
964                         return False;
965         }
966  
967         /* Create the NT compatible share modes. */
968         switch (GET_DENY_MODE(deny_mode)) {
969                 case DENY_ALL:
970                         share_mode = FILE_SHARE_NONE;
971                         break;
972
973                 case DENY_WRITE:
974                         share_mode = FILE_SHARE_READ;
975                         break;
976
977                 case DENY_READ:
978                         share_mode = FILE_SHARE_WRITE;
979                         break;
980
981                 case DENY_NONE:
982                         share_mode = FILE_SHARE_READ|FILE_SHARE_WRITE;
983                         break;
984
985                 case DENY_DOS:
986                         create_options |= NTCREATEX_OPTIONS_PRIVATE_DENY_DOS;
987                         if (is_executable(fname)) {
988                                 share_mode = FILE_SHARE_READ|FILE_SHARE_WRITE;
989                         } else {
990                                 if (GET_OPENX_MODE(deny_mode) == DOS_OPEN_RDONLY) {
991                                         share_mode = FILE_SHARE_READ;
992                                 } else {
993                                         share_mode = FILE_SHARE_NONE;
994                                 }
995                         }
996                         break;
997
998                 case DENY_FCB:
999                         create_options |= NTCREATEX_OPTIONS_PRIVATE_DENY_FCB;
1000                         share_mode = FILE_SHARE_NONE;
1001                         break;
1002
1003                 default:
1004                         DEBUG(10,("map_open_params_to_ntcreate: bad deny_mode 0x%x\n",
1005                                 (unsigned int)GET_DENY_MODE(deny_mode) ));
1006                         return False;
1007         }
1008
1009         DEBUG(10,("map_open_params_to_ntcreate: file %s, access_mask = 0x%x, "
1010                   "share_mode = 0x%x, create_disposition = 0x%x, "
1011                   "create_options = 0x%x\n",
1012                   fname,
1013                   (unsigned int)access_mask,
1014                   (unsigned int)share_mode,
1015                   (unsigned int)create_disposition,
1016                   (unsigned int)create_options ));
1017
1018         if (paccess_mask) {
1019                 *paccess_mask = access_mask;
1020         }
1021         if (pshare_mode) {
1022                 *pshare_mode = share_mode;
1023         }
1024         if (pcreate_disposition) {
1025                 *pcreate_disposition = create_disposition;
1026         }
1027         if (pcreate_options) {
1028                 *pcreate_options = create_options;
1029         }
1030
1031         return True;
1032
1033 }
1034
1035 /* Map generic permissions to file object specific permissions */
1036                                                                                                                
1037 struct generic_mapping file_generic_mapping = {
1038         FILE_GENERIC_READ,
1039         FILE_GENERIC_WRITE,
1040         FILE_GENERIC_EXECUTE,
1041         FILE_GENERIC_ALL
1042 };
1043
1044 /****************************************************************************
1045  Open a file with a share mode.
1046 ****************************************************************************/
1047
1048 files_struct *open_file_ntcreate(connection_struct *conn,
1049                                  const char *fname,
1050                                  SMB_STRUCT_STAT *psbuf,
1051                                  uint32 access_mask,            /* access bits (FILE_READ_DATA etc.) */
1052                                  uint32 share_access,           /* share constants (FILE_SHARE_READ etc). */
1053                                  uint32 create_disposition,     /* FILE_OPEN_IF etc. */
1054                                  uint32 create_options,         /* options such as delete on close. */
1055                                  uint32 new_dos_attributes,     /* attributes used for new file. */
1056                                  int oplock_request,            /* internal Samba oplock codes. */
1057                                                                 /* Information (FILE_EXISTS etc.) */
1058                                  int *pinfo)
1059 {
1060         int flags=0;
1061         int flags2=0;
1062         BOOL file_existed = VALID_STAT(*psbuf);
1063         BOOL def_acl = False;
1064         BOOL internal_only_open = False;
1065         SMB_DEV_T dev = 0;
1066         SMB_INO_T inode = 0;
1067         BOOL fsp_open = False;
1068         files_struct *fsp = NULL;
1069         mode_t new_unx_mode = (mode_t)0;
1070         mode_t unx_mode = (mode_t)0;
1071         int info;
1072         uint32 existing_dos_attributes = 0;
1073         struct pending_message_list *pml = NULL;
1074         uint16 mid = get_current_mid();
1075         BOOL delayed_for_oplocks = False;
1076         struct timeval request_time = timeval_zero();
1077         struct share_mode_lock *lck = NULL;
1078         NTSTATUS status;
1079
1080         if (conn->printer) {
1081                 /* 
1082                  * Printers are handled completely differently.
1083                  * Most of the passed parameters are ignored.
1084                  */
1085
1086                 if (pinfo) {
1087                         *pinfo = FILE_WAS_CREATED;
1088                 }
1089
1090                 DEBUG(10, ("open_file_ntcreate: printer open fname=%s\n", fname));
1091
1092                 return print_fsp_open(conn, fname);
1093         }
1094
1095         /* We add aARCH to this as this mode is only used if the file is
1096          * created new. */
1097         unx_mode = unix_mode(conn, new_dos_attributes | aARCH,fname, True);
1098
1099         DEBUG(10, ("open_file_ntcreate: fname=%s, dos_attrs=0x%x "
1100                    "access_mask=0x%x share_access=0x%x "
1101                    "create_disposition = 0x%x create_options=0x%x "
1102                    "unix mode=0%o oplock_request=%d\n",
1103                    fname, new_dos_attributes, access_mask, share_access,
1104                    create_disposition, create_options, unx_mode,
1105                    oplock_request));
1106
1107         if (oplock_request == INTERNAL_OPEN_ONLY) {
1108                 internal_only_open = True;
1109                 oplock_request = 0;
1110         }
1111
1112         if ((pml = get_open_deferred_message(mid)) != NULL) {
1113                 struct deferred_open_record *state =
1114                         (struct deferred_open_record *)pml->private_data.data;
1115
1116                 request_time = pml->request_time;
1117                 delayed_for_oplocks = state->delayed_for_oplocks;
1118
1119                 /* There could be a race condition where the dev/inode pair
1120                    has changed since we deferred the message. If so, just
1121                    remove the deferred open entry and return sharing
1122                    violation. */
1123
1124                 /* If the timeout value is non-zero, we need to just return
1125                    sharing violation. Don't retry the open as we were not
1126                    notified of a close and we don't want to trigger another
1127                    spurious oplock break. */
1128
1129                 /* Now remove the deferred open entry under lock. */
1130                 lck = get_share_mode_lock(NULL, state->dev, state->inode, NULL, NULL);
1131                 if (lck == NULL) {
1132                         DEBUG(0, ("could not get share mode lock\n"));
1133                 } else {
1134                         del_deferred_open_entry(lck, mid);
1135                         talloc_destroy(lck);
1136                 }
1137
1138                 /* Ensure we don't reprocess this message. */
1139                 remove_deferred_open_smb_message(mid);
1140         }
1141
1142         if (!check_name(fname,conn)) {
1143                 return NULL;
1144         } 
1145
1146         new_dos_attributes &= SAMBA_ATTRIBUTES_MASK;
1147         if (file_existed) {
1148                 existing_dos_attributes = dos_mode(conn, fname, psbuf);
1149         }
1150
1151         /* ignore any oplock requests if oplocks are disabled */
1152         if (!lp_oplocks(SNUM(conn)) || global_client_failed_oplock_break ||
1153             IS_VETO_OPLOCK_PATH(conn, fname)) {
1154                 oplock_request = 0;
1155         }
1156
1157         /* this is for OS/2 long file names - say we don't support them */
1158         if (!lp_posix_pathnames() && strstr(fname,".+,;=[].")) {
1159                 /* OS/2 Workplace shell fix may be main code stream in a later
1160                  * release. */ 
1161                 set_saved_error_triple(ERRDOS, ERRcannotopen,
1162                                        NT_STATUS_OBJECT_NAME_NOT_FOUND);
1163                 DEBUG(5,("open_file_ntcreate: OS/2 long filenames are not "
1164                          "supported.\n"));
1165                 return NULL;
1166         }
1167
1168         switch( create_disposition ) {
1169                 /*
1170                  * Currently we're using FILE_SUPERSEDE as the same as
1171                  * FILE_OVERWRITE_IF but they really are
1172                  * different. FILE_SUPERSEDE deletes an existing file
1173                  * (requiring delete access) then recreates it.
1174                  */
1175                 case FILE_SUPERSEDE:
1176                         /* If file exists replace/overwrite. If file doesn't
1177                          * exist create. */
1178                         flags2 |= (O_CREAT | O_TRUNC);
1179                         break;
1180
1181                 case FILE_OVERWRITE_IF:
1182                         /* If file exists replace/overwrite. If file doesn't
1183                          * exist create. */
1184                         flags2 |= (O_CREAT | O_TRUNC);
1185                         break;
1186
1187                 case FILE_OPEN:
1188                         /* If file exists open. If file doesn't exist error. */
1189                         if (!file_existed) {
1190                                 DEBUG(5,("open_file_ntcreate: FILE_OPEN "
1191                                          "requested for file %s and file "
1192                                          "doesn't exist.\n", fname ));
1193                                 set_saved_ntstatus(NT_STATUS_OBJECT_NAME_NOT_FOUND);
1194                                 errno = ENOENT;
1195                                 return NULL;
1196                         }
1197                         break;
1198
1199                 case FILE_OVERWRITE:
1200                         /* If file exists overwrite. If file doesn't exist
1201                          * error. */
1202                         if (!file_existed) {
1203                                 DEBUG(5,("open_file_ntcreate: FILE_OVERWRITE "
1204                                          "requested for file %s and file "
1205                                          "doesn't exist.\n", fname ));
1206                                 set_saved_ntstatus(NT_STATUS_OBJECT_NAME_NOT_FOUND);
1207                                 errno = ENOENT;
1208                                 return NULL;
1209                         }
1210                         flags2 |= O_TRUNC;
1211                         break;
1212
1213                 case FILE_CREATE:
1214                         /* If file exists error. If file doesn't exist
1215                          * create. */
1216                         if (file_existed) {
1217                                 DEBUG(5,("open_file_ntcreate: FILE_CREATE "
1218                                          "requested for file %s and file "
1219                                          "already exists.\n", fname ));
1220                                 if (S_ISDIR(psbuf->st_mode)) {
1221                                         errno = EISDIR;
1222                                 } else {
1223                                         errno = EEXIST;
1224                                 }
1225                                 return NULL;
1226                         }
1227                         flags2 |= (O_CREAT|O_EXCL);
1228                         break;
1229
1230                 case FILE_OPEN_IF:
1231                         /* If file exists open. If file doesn't exist
1232                          * create. */
1233                         flags2 |= O_CREAT;
1234                         break;
1235
1236                 default:
1237                         set_saved_ntstatus(NT_STATUS_INVALID_PARAMETER);
1238                         return NULL;
1239         }
1240
1241         /* We only care about matching attributes on file exists and
1242          * overwrite. */
1243
1244         if (file_existed && ((create_disposition == FILE_OVERWRITE) ||
1245                              (create_disposition == FILE_OVERWRITE_IF))) {
1246                 if (!open_match_attributes(conn, fname,
1247                                            existing_dos_attributes,
1248                                            new_dos_attributes, psbuf->st_mode,
1249                                            unx_mode, &new_unx_mode)) {
1250                         DEBUG(5,("open_file_ntcreate: attributes missmatch "
1251                                  "for file %s (%x %x) (0%o, 0%o)\n",
1252                                  fname, existing_dos_attributes,
1253                                  new_dos_attributes,
1254                                  (unsigned int)psbuf->st_mode,
1255                                  (unsigned int)unx_mode ));
1256                         errno = EACCES;
1257                         return NULL;
1258                 }
1259         }
1260
1261         /* This is a nasty hack - must fix... JRA. */
1262         if (access_mask == MAXIMUM_ALLOWED_ACCESS) {
1263                 access_mask = FILE_GENERIC_ALL;
1264         }
1265
1266         /*
1267          * Convert GENERIC bits to specific bits.
1268          */
1269
1270         se_map_generic(&access_mask, &file_generic_mapping);
1271
1272         DEBUG(10, ("open_file_ntcreate: fname=%s, after mapping "
1273                    "access_mask=0x%x\n", fname, access_mask ));
1274
1275         /*
1276          * Note that we ignore the append flag as append does not
1277          * mean the same thing under DOS and Unix.
1278          */
1279
1280         if (access_mask & (FILE_WRITE_DATA | FILE_APPEND_DATA)) {
1281                 flags = O_RDWR;
1282         } else {
1283                 flags = O_RDONLY;
1284         }
1285
1286         /*
1287          * Currently we only look at FILE_WRITE_THROUGH for create options.
1288          */
1289
1290 #if defined(O_SYNC)
1291         if (create_options & FILE_WRITE_THROUGH) {
1292                 flags2 |= O_SYNC;
1293         }
1294 #endif /* O_SYNC */
1295   
1296         if (!CAN_WRITE(conn)) {
1297                 /*
1298                  * We should really return a permission denied error if either
1299                  * O_CREAT or O_TRUNC are set, but for compatibility with
1300                  * older versions of Samba we just AND them out.
1301                  */
1302                 flags2 &= ~(O_CREAT|O_TRUNC);
1303         }
1304
1305         /*
1306          * Ensure we can't write on a read-only share or file.
1307          */
1308
1309         if (flags != O_RDONLY && file_existed &&
1310             (!CAN_WRITE(conn) || IS_DOS_READONLY(existing_dos_attributes))) {
1311                 DEBUG(5,("open_file_ntcreate: write access requested for "
1312                          "file %s on read only %s\n",
1313                          fname, !CAN_WRITE(conn) ? "share" : "file" ));
1314                 set_saved_ntstatus(NT_STATUS_ACCESS_DENIED);
1315                 errno = EACCES;
1316                 return NULL;
1317         }
1318
1319         fsp = file_new(conn);
1320         if(!fsp) {
1321                 return NULL;
1322         }
1323
1324         fsp->dev = psbuf->st_dev;
1325         fsp->inode = psbuf->st_ino;
1326         fsp->share_access = share_access;
1327         fsp->fh->private_options = create_options;
1328         fsp->access_mask = access_mask;
1329         fsp->oplock_type = oplock_request;
1330
1331         if (timeval_is_zero(&request_time)) {
1332                 request_time = fsp->open_time;
1333         }
1334
1335         if (file_existed) {
1336
1337                 dev = psbuf->st_dev;
1338                 inode = psbuf->st_ino;
1339
1340                 lck = get_share_mode_lock(NULL, dev, inode,
1341                                         conn->connectpath,
1342                                         fname);
1343
1344                 if (lck == NULL) {
1345                         DEBUG(0, ("Could not get share mode lock\n"));
1346                         set_saved_ntstatus(NT_STATUS_SHARING_VIOLATION);
1347                         return NULL;
1348                 }
1349
1350                 if (delay_for_oplocks(lck, fsp)) {
1351                         struct deferred_open_record state;
1352                         struct timeval timeout;
1353
1354                         if (delayed_for_oplocks) {
1355                                 DEBUG(0, ("Trying to delay for oplocks "
1356                                           "twice\n"));
1357                                 exit_server("exiting");
1358                         }
1359
1360                         timeout = timeval_set(OPLOCK_BREAK_TIMEOUT*2, 0);
1361
1362                         /* Normally the smbd we asked should respond within
1363                          * OPLOCK_BREAK_TIMEOUT seconds regardless of whether
1364                          * the client did, give twice the timeout as a safety
1365                          * measure here in case the other smbd is stuck
1366                          * somewhere else. */
1367
1368                         state.delayed_for_oplocks = True;
1369                         state.dev = dev;
1370                         state.inode = inode;
1371
1372                         if (!request_timed_out(request_time, timeout)) {
1373                                 defer_open(lck, request_time, timeout,
1374                                            &state);
1375                         }
1376
1377                         talloc_free(lck);
1378                         return NULL;
1379                 }
1380
1381                 status = open_mode_check(conn, fname, lck,
1382                                          access_mask, share_access,
1383                                          create_options, &file_existed);
1384
1385                 if (NT_STATUS_EQUAL(status, NT_STATUS_DELETE_PENDING)) {
1386                         /* DELETE_PENDING is not deferred for a second */
1387                         set_saved_ntstatus(status);
1388                         talloc_free(lck);
1389                         file_free(fsp);
1390                         return NULL;
1391                 }
1392
1393                 if (!NT_STATUS_IS_OK(status)) {
1394
1395                         SMB_ASSERT(NT_STATUS_EQUAL(status, NT_STATUS_SHARING_VIOLATION));
1396
1397                         /* Check if this can be done with the deny_dos and fcb
1398                          * calls. */
1399                         if (create_options &
1400                             (NTCREATEX_OPTIONS_PRIVATE_DENY_DOS|
1401                              NTCREATEX_OPTIONS_PRIVATE_DENY_FCB)) {
1402                                 files_struct *fsp_dup;
1403                                 fsp_dup = fcb_or_dos_open(conn, fname, dev,
1404                                                           inode, access_mask,
1405                                                           share_access,
1406                                                           create_options);
1407
1408                                 if (fsp_dup) {
1409                                         talloc_free(lck);
1410                                         file_free(fsp);
1411                                         if (pinfo) {
1412                                                 *pinfo = FILE_WAS_OPENED;
1413                                         }
1414                                         conn->num_files_open++;
1415                                         return fsp_dup;
1416                                 }
1417                         }
1418
1419                         /*
1420                          * This next line is a subtlety we need for
1421                          * MS-Access. If a file open will fail due to share
1422                          * permissions and also for security (access) reasons,
1423                          * we need to return the access failed error, not the
1424                          * share error. This means we must attempt to open the
1425                          * file anyway in order to get the UNIX access error -
1426                          * even if we're going to fail the open for share
1427                          * reasons. This is bad, as we're burning another fd
1428                          * if there are existing locks but there's nothing
1429                          * else we can do. We also ensure we're not going to
1430                          * create or tuncate the file as we only want an
1431                          * access decision at this stage. JRA.
1432                          */
1433                         errno = 0;
1434                         fsp_open = open_file(fsp,conn,fname,psbuf,
1435                                              flags|(flags2&~(O_TRUNC|O_CREAT)),
1436                                              unx_mode,access_mask);
1437
1438                         DEBUG(4,("open_file_ntcreate : share_mode deny - "
1439                                  "calling open_file with flags=0x%X "
1440                                  "flags2=0x%X mode=0%o returned %d\n",
1441                                  flags, (flags2&~(O_TRUNC|O_CREAT)),
1442                                  (unsigned int)unx_mode, (int)fsp_open ));
1443
1444                         if (!fsp_open && errno) {
1445                                 /* Default error. */
1446                                 set_saved_ntstatus(NT_STATUS_ACCESS_DENIED);
1447                         }
1448
1449                         /* 
1450                          * If we're returning a share violation, ensure we
1451                          * cope with the braindead 1 second delay.
1452                          */
1453
1454                         if (!internal_only_open &&
1455                             lp_defer_sharing_violations()) {
1456                                 struct timeval timeout;
1457                                 struct deferred_open_record state;
1458
1459                                 timeout = timeval_set(0, SHARING_VIOLATION_USEC_WAIT);
1460
1461                                 state.delayed_for_oplocks = False;
1462                                 state.dev = dev;
1463                                 state.inode = inode;
1464
1465                                 if (!request_timed_out(request_time,
1466                                                        timeout)) {
1467                                         defer_open(lck, request_time, timeout,
1468                                                    &state);
1469                                 }
1470                         }
1471
1472                         talloc_free(lck);
1473                         if (fsp_open) {
1474                                 fd_close(conn, fsp);
1475                                 /*
1476                                  * We have detected a sharing violation here
1477                                  * so return the correct error code
1478                                  */
1479                                 set_saved_ntstatus(NT_STATUS_SHARING_VIOLATION);
1480                         }
1481                         file_free(fsp);
1482                         return NULL;
1483                 }
1484
1485                 /*
1486                  * We exit this block with the share entry *locked*.....
1487                  */
1488         }
1489
1490         SMB_ASSERT(!file_existed || (lck != NULL));
1491
1492         /*
1493          * Ensure we pay attention to default ACLs on directories if required.
1494          */
1495
1496         if ((flags2 & O_CREAT) && lp_inherit_acls(SNUM(conn)) &&
1497             (def_acl = directory_has_default_acl(conn,
1498                                                  parent_dirname(fname)))) {
1499                 unx_mode = 0777;
1500         }
1501
1502         DEBUG(4,("calling open_file with flags=0x%X flags2=0x%X mode=0%o\n",
1503                  (unsigned int)flags, (unsigned int)flags2,
1504                  (unsigned int)unx_mode));
1505
1506         /*
1507          * open_file strips any O_TRUNC flags itself.
1508          */
1509
1510         fsp_open = open_file(fsp,conn,fname,psbuf,flags|flags2,unx_mode,
1511                              access_mask);
1512
1513         if (!fsp_open) {
1514                 if (lck != NULL) {
1515                         talloc_free(lck);
1516                 }
1517                 file_free(fsp);
1518                 return NULL;
1519         }
1520
1521         if (!file_existed) { 
1522
1523                 /*
1524                  * Deal with the race condition where two smbd's detect the
1525                  * file doesn't exist and do the create at the same time. One
1526                  * of them will win and set a share mode, the other (ie. this
1527                  * one) should check if the requested share mode for this
1528                  * create is allowed.
1529                  */
1530
1531                 /*
1532                  * Now the file exists and fsp is successfully opened,
1533                  * fsp->dev and fsp->inode are valid and should replace the
1534                  * dev=0,inode=0 from a non existent file. Spotted by
1535                  * Nadav Danieli <nadavd@exanet.com>. JRA.
1536                  */
1537
1538                 dev = fsp->dev;
1539                 inode = fsp->inode;
1540
1541                 lck = get_share_mode_lock(NULL, dev, inode,
1542                                         conn->connectpath,
1543                                         fname);
1544
1545                 if (lck == NULL) {
1546                         DEBUG(0, ("open_file_ntcreate: Could not get share mode lock for %s\n", fname));
1547                         fd_close(conn, fsp);
1548                         file_free(fsp);
1549                         set_saved_ntstatus(NT_STATUS_SHARING_VIOLATION);
1550                         return NULL;
1551                 }
1552
1553                 status = open_mode_check(conn, fname, lck,
1554                                          access_mask, share_access,
1555                                          create_options, &file_existed);
1556
1557                 if (!NT_STATUS_IS_OK(status)) {
1558                         struct deferred_open_record state;
1559
1560                         fd_close(conn, fsp);
1561                         file_free(fsp);
1562
1563                         state.delayed_for_oplocks = False;
1564                         state.dev = dev;
1565                         state.inode = inode;
1566
1567                         /* Do it all over again immediately. In the second
1568                          * round we will find that the file existed and handle
1569                          * the DELETE_PENDING and FCB cases correctly. No need
1570                          * to duplicate the code here. Essentially this is a
1571                          * "goto top of this function", but don't tell
1572                          * anybody... */
1573
1574                         defer_open(lck, request_time, timeval_zero(),
1575                                    &state);
1576                         talloc_free(lck);
1577                         return NULL;
1578                 }
1579
1580                 /*
1581                  * We exit this block with the share entry *locked*.....
1582                  */
1583         }
1584
1585         SMB_ASSERT(lck != NULL);
1586
1587         /* note that we ignore failure for the following. It is
1588            basically a hack for NFS, and NFS will never set one of
1589            these only read them. Nobody but Samba can ever set a deny
1590            mode and we have already checked our more authoritative
1591            locking database for permission to set this deny mode. If
1592            the kernel refuses the operations then the kernel is wrong */
1593
1594         kernel_flock(fsp, share_access);
1595
1596         /*
1597          * At this point onwards, we can guarentee that the share entry
1598          * is locked, whether we created the file or not, and that the
1599          * deny mode is compatible with all current opens.
1600          */
1601
1602         /*
1603          * If requested, truncate the file.
1604          */
1605
1606         if (flags2&O_TRUNC) {
1607                 /*
1608                  * We are modifing the file after open - update the stat
1609                  * struct..
1610                  */
1611                 if ((SMB_VFS_FTRUNCATE(fsp,fsp->fh->fd,0) == -1) ||
1612                     (SMB_VFS_FSTAT(fsp,fsp->fh->fd,psbuf)==-1)) {
1613                         talloc_free(lck);
1614                         fd_close(conn,fsp);
1615                         file_free(fsp);
1616                         return NULL;
1617                 }
1618         }
1619
1620         /* Record the options we were opened with. */
1621         fsp->share_access = share_access;
1622         fsp->fh->private_options = create_options;
1623         fsp->access_mask = access_mask;
1624
1625         if (file_existed) {
1626                 if (!(flags2 & O_TRUNC)) {
1627                         info = FILE_WAS_OPENED;
1628                 } else {
1629                         info = FILE_WAS_OVERWRITTEN;
1630                 }
1631         } else {
1632                 info = FILE_WAS_CREATED;
1633                 /* Change the owner if required. */
1634                 if (lp_inherit_owner(SNUM(conn))) {
1635                         change_owner_to_parent(conn, fsp, fsp->fsp_name,
1636                                                psbuf);
1637                 }
1638         }
1639
1640         if (pinfo) {
1641                 *pinfo = info;
1642         }
1643
1644         /* 
1645          * Setup the oplock info in both the shared memory and
1646          * file structs.
1647          */
1648
1649         if ((fsp->oplock_type != NO_OPLOCK) &&
1650             (fsp->oplock_type != FAKE_LEVEL_II_OPLOCK)) {
1651                 if (!set_file_oplock(fsp, fsp->oplock_type)) {
1652                         /* Could not get the kernel oplock */
1653                         fsp->oplock_type = NO_OPLOCK;
1654                 }
1655         }
1656         set_share_mode(lck, fsp, 0, fsp->oplock_type);
1657
1658         if (create_options & FILE_DELETE_ON_CLOSE) {
1659                 uint32 dosattr= existing_dos_attributes;
1660                 NTSTATUS result;
1661
1662                 if (info == FILE_WAS_OVERWRITTEN || info == FILE_WAS_CREATED ||
1663                                 info == FILE_WAS_SUPERSEDED) {
1664                         dosattr = new_dos_attributes;
1665                 }
1666
1667                 result = can_set_delete_on_close(fsp, True, dosattr);
1668
1669                 if (!NT_STATUS_IS_OK(result)) {
1670                         /* Remember to delete the mode we just added. */
1671                         del_share_mode(lck, fsp);
1672                         talloc_free(lck);
1673                         fd_close(conn,fsp);
1674                         file_free(fsp);
1675                         set_saved_ntstatus(result);
1676                         return NULL;
1677                 }
1678                 lck->delete_on_close = True;
1679                 lck->modified = True;
1680         }
1681         
1682         if (info == FILE_WAS_OVERWRITTEN || info == FILE_WAS_CREATED ||
1683                                 info == FILE_WAS_SUPERSEDED) {
1684                 /* Files should be initially set as archive */
1685                 if (lp_map_archive(SNUM(conn)) ||
1686                     lp_store_dos_attributes(SNUM(conn))) {
1687                         file_set_dosmode(conn, fname,
1688                                          new_dos_attributes | aARCH, NULL,
1689                                          True);
1690                 }
1691         }
1692
1693         /*
1694          * Take care of inherited ACLs on created files - if default ACL not
1695          * selected.
1696          */
1697
1698         if (!file_existed && !def_acl) {
1699
1700                 int saved_errno = errno; /* We might get ENOSYS in the next
1701                                           * call.. */
1702
1703                 if (SMB_VFS_FCHMOD_ACL(fsp, fsp->fh->fd, unx_mode) == -1
1704                     && errno == ENOSYS) {
1705                         errno = saved_errno; /* Ignore ENOSYS */
1706                 }
1707
1708         } else if (new_unx_mode) {
1709
1710                 int ret = -1;
1711
1712                 /* Attributes need changing. File already existed. */
1713
1714                 {
1715                         int saved_errno = errno; /* We might get ENOSYS in the
1716                                                   * next call.. */
1717                         ret = SMB_VFS_FCHMOD_ACL(fsp, fsp->fh->fd,
1718                                                  new_unx_mode);
1719
1720                         if (ret == -1 && errno == ENOSYS) {
1721                                 errno = saved_errno; /* Ignore ENOSYS */
1722                         } else {
1723                                 DEBUG(5, ("open_file_shared: reset "
1724                                           "attributes of file %s to 0%o\n",
1725                                         fname, (unsigned int)new_unx_mode));
1726                                 ret = 0; /* Don't do the fchmod below. */
1727                         }
1728                 }
1729
1730                 if ((ret == -1) &&
1731                     (SMB_VFS_FCHMOD(fsp, fsp->fh->fd, new_unx_mode) == -1))
1732                         DEBUG(5, ("open_file_shared: failed to reset "
1733                                   "attributes of file %s to 0%o\n",
1734                                 fname, (unsigned int)new_unx_mode));
1735         }
1736
1737         /* If this is a successful open, we must remove any deferred open
1738          * records. */
1739         del_deferred_open_entry(lck, mid);
1740         talloc_free(lck);
1741
1742         conn->num_files_open++;
1743
1744         return fsp;
1745 }
1746
1747 /****************************************************************************
1748  Open a file for for write to ensure that we can fchmod it.
1749 ****************************************************************************/
1750
1751 files_struct *open_file_fchmod(connection_struct *conn, const char *fname,
1752                                SMB_STRUCT_STAT *psbuf)
1753 {
1754         files_struct *fsp = NULL;
1755         BOOL fsp_open;
1756
1757         if (!VALID_STAT(*psbuf)) {
1758                 return NULL;
1759         }
1760
1761         fsp = file_new(conn);
1762         if(!fsp) {
1763                 return NULL;
1764         }
1765
1766         /* note! we must use a non-zero desired access or we don't get
1767            a real file descriptor. Oh what a twisted web we weave. */
1768         fsp_open = open_file(fsp,conn,fname,psbuf,O_WRONLY,0,FILE_WRITE_DATA);
1769
1770         /* 
1771          * This is not a user visible file open.
1772          * Don't set a share mode and don't increment
1773          * the conn->num_files_open.
1774          */
1775
1776         if (!fsp_open) {
1777                 file_free(fsp);
1778                 return NULL;
1779         }
1780
1781         return fsp;
1782 }
1783
1784 /****************************************************************************
1785  Close the fchmod file fd - ensure no locks are lost.
1786 ****************************************************************************/
1787
1788 int close_file_fchmod(files_struct *fsp)
1789 {
1790         int ret = fd_close(fsp->conn, fsp);
1791         file_free(fsp);
1792         return ret;
1793 }
1794
1795 /****************************************************************************
1796  Open a directory from an NT SMB call.
1797 ****************************************************************************/
1798
1799 files_struct *open_directory(connection_struct *conn,
1800                                 const char *fname,
1801                                 SMB_STRUCT_STAT *psbuf,
1802                                 uint32 access_mask,
1803                                 uint32 share_access,
1804                                 uint32 create_disposition,
1805                                 uint32 create_options,
1806                                 int *pinfo)
1807 {
1808         files_struct *fsp = NULL;
1809         BOOL dir_existed = VALID_STAT(*psbuf) ? True : False;
1810         BOOL create_dir = False;
1811         struct share_mode_lock *lck = NULL;
1812         NTSTATUS status;
1813         int info = 0;
1814
1815         DEBUG(5,("open_directory: opening directory %s, access_mask = 0x%x, "
1816                  "share_access = 0x%x create_options = 0x%x, "
1817                  "create_disposition = 0x%x\n",
1818                  fname,
1819                  (unsigned int)access_mask,
1820                  (unsigned int)share_access,
1821                  (unsigned int)create_options,
1822                  (unsigned int)create_disposition));
1823
1824         if (is_ntfs_stream_name(fname)) {
1825                 DEBUG(0,("open_directory: %s is a stream name!\n", fname ));
1826                 set_saved_ntstatus(NT_STATUS_NOT_A_DIRECTORY);
1827                 return NULL;
1828         }
1829
1830         if (dir_existed && !S_ISDIR(psbuf->st_mode)) {
1831                 DEBUG(0,("open_directory: %s is not a directory !\n", fname ));
1832                 set_saved_ntstatus(NT_STATUS_NOT_A_DIRECTORY);
1833                 return NULL;
1834         }
1835
1836         switch( create_disposition ) {
1837                 case FILE_OPEN:
1838                         /* If directory exists open. If directory doesn't
1839                          * exist error. */
1840                         if (!dir_existed) {
1841                                 DEBUG(5,("open_directory: FILE_OPEN requested "
1842                                          "for directory %s and it doesn't "
1843                                          "exist.\n", fname ));
1844                                 set_saved_ntstatus(NT_STATUS_OBJECT_NAME_NOT_FOUND);
1845                                 return NULL;
1846                         }
1847                         info = FILE_WAS_OPENED;
1848                         break;
1849
1850                 case FILE_CREATE:
1851                         /* If directory exists error. If directory doesn't
1852                          * exist create. */
1853                         if (dir_existed) {
1854                                 DEBUG(5,("open_directory: FILE_CREATE "
1855                                          "requested for directory %s and it "
1856                                          "already exists.\n", fname ));
1857                                 set_saved_error_triple(ERRDOS, ERRfilexists,
1858                                                        NT_STATUS_OBJECT_NAME_COLLISION);
1859                                 return NULL;
1860                         }
1861                         create_dir = True;
1862                         info = FILE_WAS_CREATED;
1863                         break;
1864
1865                 case FILE_OPEN_IF:
1866                         /* If directory exists open. If directory doesn't
1867                          * exist create. */
1868                         if (!dir_existed) {
1869                                 create_dir = True;
1870                                 info = FILE_WAS_CREATED;
1871                         } else {
1872                                 info = FILE_WAS_OPENED;
1873                         }
1874                         break;
1875
1876                 case FILE_SUPERSEDE:
1877                 case FILE_OVERWRITE:
1878                 case FILE_OVERWRITE_IF:
1879                 default:
1880                         DEBUG(5,("open_directory: invalid create_disposition "
1881                                  "0x%x for directory %s\n",
1882                                  (unsigned int)create_disposition, fname));
1883                         file_free(fsp);
1884                         set_saved_ntstatus(NT_STATUS_INVALID_PARAMETER);
1885                         return NULL;
1886         }
1887
1888         if (create_dir) {
1889                 /*
1890                  * Try and create the directory.
1891                  */
1892
1893                 /* We know bad_path is false as it's caught earlier. */
1894
1895                 status = mkdir_internal(conn, fname, False);
1896
1897                 if (!NT_STATUS_IS_OK(status)) {
1898                         DEBUG(2,("open_directory: unable to create %s. "
1899                                  "Error was %s\n", fname, strerror(errno) ));
1900                         /* Ensure we return the correct NT status to the
1901                          * client. */
1902                         set_saved_error_triple(0, 0, status);
1903                         return NULL;
1904                 }
1905
1906                 /* Ensure we're checking for a symlink here.... */
1907                 /* We don't want to get caught by a symlink racer. */
1908
1909                 if(SMB_VFS_LSTAT(conn,fname, psbuf) != 0) {
1910                         return NULL;
1911                 }
1912
1913                 if(!S_ISDIR(psbuf->st_mode)) {
1914                         DEBUG(0,("open_directory: %s is not a directory !\n",
1915                                  fname ));
1916                         return NULL;
1917                 }
1918         }
1919
1920         fsp = file_new(conn);
1921         if(!fsp) {
1922                 return NULL;
1923         }
1924
1925         /*
1926          * Setup the files_struct for it.
1927          */
1928         
1929         fsp->mode = psbuf->st_mode;
1930         fsp->inode = psbuf->st_ino;
1931         fsp->dev = psbuf->st_dev;
1932         fsp->vuid = current_user.vuid;
1933         fsp->file_pid = global_smbpid;
1934         fsp->can_lock = True;
1935         fsp->can_read = False;
1936         fsp->can_write = False;
1937
1938         fsp->share_access = share_access;
1939         fsp->fh->private_options = create_options;
1940         fsp->access_mask = access_mask;
1941
1942         fsp->print_file = False;
1943         fsp->modified = False;
1944         fsp->oplock_type = NO_OPLOCK;
1945         fsp->sent_oplock_break = NO_BREAK_SENT;
1946         fsp->is_directory = True;
1947         fsp->is_stat = False;
1948         string_set(&fsp->fsp_name,fname);
1949
1950         lck = get_share_mode_lock(NULL, fsp->dev, fsp->inode,
1951                                 conn->connectpath,
1952                                 fname);
1953
1954         if (lck == NULL) {
1955                 DEBUG(0, ("open_directory: Could not get share mode lock for %s\n", fname));
1956                 file_free(fsp);
1957                 set_saved_ntstatus(NT_STATUS_SHARING_VIOLATION);
1958                 return NULL;
1959         }
1960
1961         status = open_mode_check(conn, fname, lck,
1962                                 access_mask, share_access,
1963                                 create_options, &dir_existed);
1964
1965         if (!NT_STATUS_IS_OK(status)) {
1966                 set_saved_ntstatus(status);
1967                 talloc_free(lck);
1968                 file_free(fsp);
1969                 return NULL;
1970         }
1971
1972         set_share_mode(lck, fsp, 0, NO_OPLOCK);
1973
1974         if (create_options & FILE_DELETE_ON_CLOSE) {
1975                 status = can_set_delete_on_close(fsp, True, 0);
1976                 if (!NT_STATUS_IS_OK(status)) {
1977                         set_saved_ntstatus(status);
1978                         talloc_free(lck);
1979                         file_free(fsp);
1980                         return NULL;
1981                 }
1982
1983                 lck->delete_on_close = True;
1984                 lck->modified = True;
1985         }
1986
1987         talloc_free(lck);
1988
1989         /* Change the owner if required. */
1990         if ((info == FILE_WAS_CREATED) && lp_inherit_owner(SNUM(conn))) {
1991                 change_owner_to_parent(conn, fsp, fsp->fsp_name, psbuf);
1992         }
1993
1994         if (pinfo) {
1995                 *pinfo = info;
1996         }
1997
1998         conn->num_files_open++;
1999
2000         return fsp;
2001 }
2002
2003 /****************************************************************************
2004  Open a pseudo-file (no locking checks - a 'stat' open).
2005 ****************************************************************************/
2006
2007 files_struct *open_file_stat(connection_struct *conn, char *fname,
2008                              SMB_STRUCT_STAT *psbuf)
2009 {
2010         files_struct *fsp = NULL;
2011
2012         if (!VALID_STAT(*psbuf))
2013                 return NULL;
2014
2015         /* Can't 'stat' open directories. */
2016         if(S_ISDIR(psbuf->st_mode))
2017                 return NULL;
2018
2019         fsp = file_new(conn);
2020         if(!fsp)
2021                 return NULL;
2022
2023         DEBUG(5,("open_file_stat: 'opening' file %s\n", fname));
2024
2025         /*
2026          * Setup the files_struct for it.
2027          */
2028         
2029         fsp->mode = psbuf->st_mode;
2030         fsp->inode = psbuf->st_ino;
2031         fsp->dev = psbuf->st_dev;
2032         fsp->vuid = current_user.vuid;
2033         fsp->file_pid = global_smbpid;
2034         fsp->can_lock = False;
2035         fsp->can_read = False;
2036         fsp->can_write = False;
2037         fsp->print_file = False;
2038         fsp->modified = False;
2039         fsp->oplock_type = NO_OPLOCK;
2040         fsp->sent_oplock_break = NO_BREAK_SENT;
2041         fsp->is_directory = False;
2042         fsp->is_stat = True;
2043         string_set(&fsp->fsp_name,fname);
2044
2045         conn->num_files_open++;
2046
2047         return fsp;
2048 }
2049
2050 /****************************************************************************
2051  Receive notification that one of our open files has been renamed by another
2052  smbd process.
2053 ****************************************************************************/
2054
2055 void msg_file_was_renamed(int msg_type, struct process_id src, void *buf, size_t len)
2056 {
2057         files_struct *fsp;
2058         struct file_renamed_message *frm = (struct file_renamed_message *)buf;
2059         const char *sharepath;
2060         const char *newname;
2061         size_t sp_len;
2062
2063         if (buf == NULL || len < sizeof(*frm)) {
2064                 DEBUG(0, ("msg_file_was_renamed: Got invalid msg len %d\n", (int)len));
2065                 return;
2066         }
2067
2068         sharepath = &frm->names[0];
2069         newname = sharepath + strlen(sharepath) + 1;
2070         sp_len = strlen(sharepath);
2071
2072         DEBUG(10,("msg_file_was_renamed: Got rename message for sharepath %s, new name %s, "
2073                 "dev %x, inode  %.0f\n",
2074                 sharepath, newname, (unsigned int)frm->dev, (double)frm->inode ));
2075
2076         for(fsp = file_find_di_first(frm->dev, frm->inode); fsp; fsp = file_find_di_next(fsp)) {
2077                 if (memcmp(fsp->conn->connectpath, sharepath, sp_len) == 0) {
2078                         DEBUG(10,("msg_file_was_renamed: renaming file fnum %d from %s -> %s\n",
2079                                 fsp->fnum, fsp->fsp_name, newname ));
2080                         string_set(&fsp->fsp_name, newname);
2081                 } else {
2082                         /* TODO. JRA. */
2083                         /* Now we have the complete path we can work out if this is
2084                            actually within this share and adjust newname accordingly. */
2085                         DEBUG(10,("msg_file_was_renamed: share mismatch (sharepath %s "
2086                                 "not sharepath %s) "
2087                                 "fnum %d from %s -> %s\n",
2088                                 fsp->conn->connectpath,
2089                                 sharepath,
2090                                 fsp->fnum,
2091                                 fsp->fsp_name,
2092                                 newname ));
2093                 }
2094         }
2095 }