r6673: Fix the write cache based on some VERY good detective work
[kai/samba.git] / source3 / smbd / open.c
1 /* 
2    Unix SMB/CIFS implementation.
3    file opening and share modes
4    Copyright (C) Andrew Tridgell 1992-1998
5    Copyright (C) Jeremy Allison 2001-2004
6    
7    This program is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 2 of the License, or
10    (at your option) any later version.
11    
12    This program is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16    
17    You should have received a copy of the GNU General Public License
18    along with this program; if not, write to the Free Software
19    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
20 */
21
22 #include "includes.h"
23
24 extern struct current_user current_user;
25 extern userdom_struct current_user_info;
26 extern uint16 global_oplock_port;
27 extern uint16 global_smbpid;
28 extern BOOL global_client_failed_oplock_break;
29
30 struct dev_inode_bundle {
31         SMB_DEV_T dev;
32         SMB_INO_T inode;
33 };
34
35 /****************************************************************************
36  fd support routines - attempt to do a dos_open.
37 ****************************************************************************/
38
39 static int fd_open(struct connection_struct *conn, const char *fname, 
40                    int flags, mode_t mode)
41 {
42         int fd;
43 #ifdef O_NOFOLLOW
44         if (!lp_symlinks(SNUM(conn)))
45                 flags |= O_NOFOLLOW;
46 #endif
47
48         fd = SMB_VFS_OPEN(conn,fname,flags,mode);
49
50         DEBUG(10,("fd_open: name %s, flags = 0%o mode = 0%o, fd = %d. %s\n", fname,
51                 flags, (int)mode, fd, (fd == -1) ? strerror(errno) : "" ));
52
53         return fd;
54 }
55
56 /****************************************************************************
57  Close the file associated with a fsp.
58 ****************************************************************************/
59
60 int fd_close(struct connection_struct *conn, files_struct *fsp)
61 {
62         if (fsp->fd == -1)
63                 return 0; /* what we used to call a stat open. */
64         return fd_close_posix(conn, fsp);
65 }
66
67
68 /****************************************************************************
69  Check a filename for the pipe string.
70 ****************************************************************************/
71
72 static void check_for_pipe(const char *fname)
73 {
74         /* special case of pipe opens */
75         char s[10];
76         StrnCpy(s,fname,sizeof(s)-1);
77         strlower_m(s);
78         if (strstr(s,"pipe/")) {
79                 DEBUG(3,("Rejecting named pipe open for %s\n",fname));
80                 set_saved_error_triple(ERRSRV, ERRaccess, NT_STATUS_ACCESS_DENIED);
81         }
82 }
83
84 /****************************************************************************
85  Change the ownership of a file to that of the parent directory.
86  Do this by fd if possible.
87 ****************************************************************************/
88
89 void change_owner_to_parent(connection_struct *conn, files_struct *fsp, const char *fname, SMB_STRUCT_STAT *psbuf)
90 {
91         const char *parent_path = parent_dirname(fname);
92         SMB_STRUCT_STAT parent_st;
93         int ret;
94
95         ret = SMB_VFS_STAT(conn, parent_path, &parent_st);
96         if (ret == -1) {
97                 DEBUG(0,("change_owner_to_parent: failed to stat parent directory %s. Error was %s\n",
98                         parent_path, strerror(errno) ));
99                 return;
100         }
101
102         if (fsp && fsp->fd != -1) {
103                 become_root();
104                 ret = SMB_VFS_FCHOWN(fsp, fsp->fd, parent_st.st_uid, (gid_t)-1);
105                 unbecome_root();
106                 if (ret == -1) {
107                         DEBUG(0,("change_owner_to_parent: failed to fchown file %s to parent directory uid %u. \
108 Error was %s\n",
109                                 fname, (unsigned int)parent_st.st_uid, strerror(errno) ));
110                 }
111
112                 DEBUG(10,("change_owner_to_parent: changed new file %s to parent directory uid %u.\n",
113                         fname, (unsigned int)parent_st.st_uid ));
114
115         } else {
116                 /* We've already done an lstat into psbuf, and we know it's a directory. If
117                    we can cd into the directory and the dev/ino are the same then we can safely
118                    chown without races as we're locking the directory in place by being in it.
119                    This should work on any UNIX (thanks tridge :-). JRA.
120                 */
121
122                 pstring saved_dir;
123                 SMB_STRUCT_STAT sbuf;
124
125                 if (!vfs_GetWd(conn,saved_dir)) {
126                         DEBUG(0,("change_owner_to_parent: failed to get current working directory\n"));
127                         return;
128                 }
129
130                 /* Chdir into the new path. */
131                 if (vfs_ChDir(conn, fname) == -1) {
132                         DEBUG(0,("change_owner_to_parent: failed to change current working directory to %s. \
133 Error was %s\n", fname, strerror(errno) ));
134                         goto out;
135                 }
136
137                 if (SMB_VFS_STAT(conn,".",&sbuf) == -1) {
138                         DEBUG(0,("change_owner_to_parent: failed to stat directory '.' (%s) \
139 Error was %s\n", fname, strerror(errno)));
140                         goto out;
141                 }
142
143                 /* Ensure we're pointing at the same place. */
144                 if (sbuf.st_dev != psbuf->st_dev || sbuf.st_ino != psbuf->st_ino || sbuf.st_mode != psbuf->st_mode ) {
145                         DEBUG(0,("change_owner_to_parent: device/inode/mode on directory %s changed. Refusing to chown !\n",
146                                 fname ));
147                         goto out;
148                 }
149
150                 become_root();
151                 ret = SMB_VFS_CHOWN(conn, ".", parent_st.st_uid, (gid_t)-1);
152                 unbecome_root();
153                 if (ret == -1) {
154                         DEBUG(10,("change_owner_to_parent: failed to chown directory %s to parent directory uid %u. \
155 Error was %s\n",
156                                 fname, (unsigned int)parent_st.st_uid, strerror(errno) ));
157                         goto out;
158                 }
159
160                 DEBUG(10,("change_owner_to_parent: changed ownership of new directory %s to parent directory uid %u.\n",
161                         fname, (unsigned int)parent_st.st_uid ));
162
163   out:
164
165                 vfs_ChDir(conn,saved_dir);
166         }
167 }
168
169 /****************************************************************************
170  Open a file.
171 ****************************************************************************/
172
173 static BOOL open_file(files_struct *fsp,connection_struct *conn,
174                       const char *fname,SMB_STRUCT_STAT *psbuf,int flags,mode_t mode, uint32 desired_access)
175 {
176         int accmode = (flags & O_ACCMODE);
177         int local_flags = flags;
178
179         fsp->fd = -1;
180         fsp->oplock_type = NO_OPLOCK;
181         errno = EPERM;
182
183         /* Check permissions */
184
185         /*
186          * This code was changed after seeing a client open request 
187          * containing the open mode of (DENY_WRITE/read-only) with
188          * the 'create if not exist' bit set. The previous code
189          * would fail to open the file read only on a read-only share
190          * as it was checking the flags parameter  directly against O_RDONLY,
191          * this was failing as the flags parameter was set to O_RDONLY|O_CREAT.
192          * JRA.
193          */
194
195         if (!CAN_WRITE(conn)) {
196                 /* It's a read-only share - fail if we wanted to write. */
197                 if(accmode != O_RDONLY) {
198                         DEBUG(3,("Permission denied opening %s\n",fname));
199                         check_for_pipe(fname);
200                         return False;
201                 } else if(flags & O_CREAT) {
202                         /* We don't want to write - but we must make sure that O_CREAT
203                            doesn't create the file if we have write access into the
204                            directory.
205                         */
206                         flags &= ~O_CREAT;
207                         local_flags &= ~O_CREAT;
208                 }
209         }
210
211         /*
212          * This little piece of insanity is inspired by the
213          * fact that an NT client can open a file for O_RDONLY,
214          * but set the create disposition to FILE_EXISTS_TRUNCATE.
215          * If the client *can* write to the file, then it expects to
216          * truncate the file, even though it is opening for readonly.
217          * Quicken uses this stupid trick in backup file creation...
218          * Thanks *greatly* to "David W. Chapman Jr." <dwcjr@inethouston.net>
219          * for helping track this one down. It didn't bite us in 2.0.x
220          * as we always opened files read-write in that release. JRA.
221          */
222
223         if ((accmode == O_RDONLY) && ((flags & O_TRUNC) == O_TRUNC)) {
224                 DEBUG(10,("open_file: truncate requested on read-only open for file %s\n",fname ));
225                 local_flags = (flags & ~O_ACCMODE)|O_RDWR;
226         }
227
228         if ((desired_access & (FILE_READ_DATA|FILE_WRITE_DATA|FILE_APPEND_DATA|FILE_EXECUTE)) ||
229                         (local_flags & O_CREAT) || ((local_flags & O_TRUNC) == O_TRUNC) ) {
230
231                 /*
232                  * We can't actually truncate here as the file may be locked.
233                  * open_file_shared will take care of the truncate later. JRA.
234                  */
235
236                 local_flags &= ~O_TRUNC;
237
238 #if defined(O_NONBLOCK) && defined(S_ISFIFO)
239                 /*
240                  * We would block on opening a FIFO with no one else on the
241                  * other end. Do what we used to do and add O_NONBLOCK to the
242                  * open flags. JRA.
243                  */
244
245                 if (VALID_STAT(*psbuf) && S_ISFIFO(psbuf->st_mode))
246                         local_flags |= O_NONBLOCK;
247 #endif
248
249                 /* Don't create files with Microsoft wildcard characters. */
250                 if ((local_flags & O_CREAT) && !VALID_STAT(*psbuf) && ms_has_wild(fname))  {
251                         set_saved_error_triple(ERRDOS, ERRinvalidname, NT_STATUS_OBJECT_NAME_INVALID);
252                         return False;
253                 }
254
255                 /* Actually do the open */
256                 fsp->fd = fd_open(conn, fname, local_flags, mode);
257                 if (fsp->fd == -1)  {
258                         DEBUG(3,("Error opening file %s (%s) (local_flags=%d) (flags=%d)\n",
259                                  fname,strerror(errno),local_flags,flags));
260                         check_for_pipe(fname);
261                         return False;
262                 }
263
264                 /* Inherit the ACL if the file was created. */
265                 if ((local_flags & O_CREAT) && !VALID_STAT(*psbuf))
266                         inherit_access_acl(conn, fname, mode);
267
268         } else
269                 fsp->fd = -1; /* What we used to call a stat open. */
270
271         if (!VALID_STAT(*psbuf)) {
272                 int ret;
273
274                 if (fsp->fd == -1)
275                         ret = SMB_VFS_STAT(conn, fname, psbuf);
276                 else {
277                         ret = SMB_VFS_FSTAT(fsp,fsp->fd,psbuf);
278                         /* If we have an fd, this stat should succeed. */
279                         if (ret == -1)
280                                 DEBUG(0,("Error doing fstat on open file %s (%s)\n", fname,strerror(errno) ));
281                 }
282
283                 /* For a non-io open, this stat failing means file not found. JRA */
284                 if (ret == -1) {
285                         fd_close(conn, fsp);
286                         return False;
287                 }
288         }
289
290         /*
291          * POSIX allows read-only opens of directories. We don't
292          * want to do this (we use a different code path for this)
293          * so catch a directory open and return an EISDIR. JRA.
294          */
295
296         if(S_ISDIR(psbuf->st_mode)) {
297                 fd_close(conn, fsp);
298                 errno = EISDIR;
299                 return False;
300         }
301
302         fsp->mode = psbuf->st_mode;
303         fsp->inode = psbuf->st_ino;
304         fsp->dev = psbuf->st_dev;
305         fsp->vuid = current_user.vuid;
306         fsp->file_pid = global_smbpid;
307         fsp->can_lock = True;
308         fsp->can_read = ((flags & O_WRONLY)==0);
309         fsp->can_write = ((flags & (O_WRONLY|O_RDWR))!=0);
310         fsp->share_mode = 0;
311         fsp->desired_access = desired_access;
312         fsp->print_file = False;
313         fsp->modified = False;
314         fsp->oplock_type = NO_OPLOCK;
315         fsp->sent_oplock_break = NO_BREAK_SENT;
316         fsp->is_directory = False;
317         fsp->is_stat = False;
318         fsp->directory_delete_on_close = False;
319         string_set(&fsp->fsp_name,fname);
320         fsp->wcp = NULL; /* Write cache pointer. */
321
322         DEBUG(2,("%s opened file %s read=%s write=%s (numopen=%d)\n",
323                  *current_user_info.smb_name ? current_user_info.smb_name : conn->user,fsp->fsp_name,
324                  BOOLSTR(fsp->can_read), BOOLSTR(fsp->can_write),
325                  conn->num_files_open + 1));
326
327         errno = 0;
328         return True;
329 }
330
331 /*******************************************************************
332  Return True if the filename is one of the special executable types.
333 ********************************************************************/
334
335 static BOOL is_executable(const char *fname)
336 {
337         if ((fname = strrchr_m(fname,'.'))) {
338                 if (strequal(fname,".com") ||
339                     strequal(fname,".dll") ||
340                     strequal(fname,".exe") ||
341                     strequal(fname,".sym")) {
342                         return True;
343                 }
344         }
345         return False;
346 }
347
348 enum {AFAIL,AREAD,AWRITE,AALL};
349
350 /*******************************************************************
351  Reproduce the share mode access table.
352  This is horrendoously complex, and really can't be justified on any
353  rational grounds except that this is _exactly_ what NT does. See
354  the DENY1 and DENY2 tests in smbtorture for a comprehensive set of
355  test routines.
356 ********************************************************************/
357
358 static int access_table(int new_deny,int old_deny,int old_mode,
359                         BOOL same_pid, BOOL isexe)
360 {
361           if (new_deny == DENY_ALL || old_deny == DENY_ALL) return(AFAIL);
362
363           if (same_pid) {
364                   if (isexe && old_mode == DOS_OPEN_RDONLY && 
365                       old_deny == DENY_DOS && new_deny == DENY_READ) {
366                           return AFAIL;
367                   }
368                   if (!isexe && old_mode == DOS_OPEN_RDONLY && 
369                       old_deny == DENY_DOS && new_deny == DENY_DOS) {
370                           return AREAD;
371                   }
372                   if (new_deny == DENY_FCB && old_deny == DENY_DOS) {
373                           if (isexe) return AFAIL;
374                           if (old_mode == DOS_OPEN_RDONLY) return AFAIL;
375                           return AALL;
376                   }
377                   if (old_mode == DOS_OPEN_RDONLY && old_deny == DENY_DOS) {
378                           if (new_deny == DENY_FCB || new_deny == DENY_READ) {
379                                   if (isexe) return AREAD;
380                                   return AFAIL;
381                           }
382                   }
383                   if (old_deny == DENY_FCB) {
384                           if (new_deny == DENY_DOS || new_deny == DENY_FCB) return AALL;
385                           return AFAIL;
386                   }
387           }
388
389           if (old_deny == DENY_DOS || new_deny == DENY_DOS || 
390               old_deny == DENY_FCB || new_deny == DENY_FCB) {
391                   if (isexe) {
392                           if (old_deny == DENY_FCB || new_deny == DENY_FCB) {
393                                   return AFAIL;
394                           }
395                           if (old_deny == DENY_DOS) {
396                                   if (new_deny == DENY_READ && 
397                                       (old_mode == DOS_OPEN_RDONLY || 
398                                        old_mode == DOS_OPEN_RDWR)) {
399                                           return AFAIL;
400                                   }
401                                   if (new_deny == DENY_WRITE && 
402                                       (old_mode == DOS_OPEN_WRONLY || 
403                                        old_mode == DOS_OPEN_RDWR)) {
404                                           return AFAIL;
405                                   }
406                                   return AALL;
407                           }
408                           if (old_deny == DENY_NONE) return AALL;
409                           if (old_deny == DENY_READ) return AWRITE;
410                           if (old_deny == DENY_WRITE) return AREAD;
411                   }
412                   /* it isn't a exe, dll, sym or com file */
413                   if (old_deny == new_deny && same_pid)
414                           return(AALL);    
415
416                   if (old_deny == DENY_READ || new_deny == DENY_READ) return AFAIL;
417                   if (old_mode == DOS_OPEN_RDONLY) return(AREAD);
418                   
419                   return(AFAIL);
420           }
421           
422           switch (new_deny) 
423                   {
424                   case DENY_WRITE:
425                           if (old_deny==DENY_WRITE && old_mode==DOS_OPEN_RDONLY) return(AREAD);
426                           if (old_deny==DENY_READ && old_mode==DOS_OPEN_RDONLY) return(AWRITE);
427                           if (old_deny==DENY_NONE && old_mode==DOS_OPEN_RDONLY) return(AALL);
428                           return(AFAIL);
429                   case DENY_READ:
430                           if (old_deny==DENY_WRITE && old_mode==DOS_OPEN_WRONLY) return(AREAD);
431                           if (old_deny==DENY_READ && old_mode==DOS_OPEN_WRONLY) return(AWRITE);
432                           if (old_deny==DENY_NONE && old_mode==DOS_OPEN_WRONLY) return(AALL);
433                           return(AFAIL);
434                   case DENY_NONE:
435                           if (old_deny==DENY_WRITE) return(AREAD);
436                           if (old_deny==DENY_READ) return(AWRITE);
437                           if (old_deny==DENY_NONE) return(AALL);
438                           return(AFAIL);      
439                   }
440           return(AFAIL);      
441 }
442
443 /****************************************************************************
444  Check if we can open a file with a share mode.
445 ****************************************************************************/
446
447 static BOOL check_share_mode(connection_struct *conn, share_mode_entry *share, int share_mode, uint32 desired_access,
448                              const char *fname, BOOL fcbopen, int *flags)
449 {
450         int deny_mode = GET_DENY_MODE(share_mode);
451         int old_open_mode = GET_OPEN_MODE(share->share_mode);
452         int old_deny_mode = GET_DENY_MODE(share->share_mode);
453         BOOL non_io_open_request;
454         BOOL non_io_open_existing;
455
456         /*
457          * share modes = false means don't bother to check for
458          * DENY mode conflict. This is a *really* bad idea :-). JRA.
459          */
460
461         if(!lp_share_modes(SNUM(conn)))
462                 return True;
463
464         if (desired_access & ~(SYNCHRONIZE_ACCESS|READ_CONTROL_ACCESS|FILE_READ_ATTRIBUTES|FILE_WRITE_ATTRIBUTES)) {
465                 non_io_open_request = False;
466         } else {
467                 non_io_open_request = True;
468         }
469
470         if (share->desired_access & ~(SYNCHRONIZE_ACCESS|READ_CONTROL_ACCESS|FILE_READ_ATTRIBUTES|FILE_WRITE_ATTRIBUTES)) {
471                 non_io_open_existing = False;
472         } else {
473                 non_io_open_existing = True;
474         }
475
476         /*
477          * Don't allow any opens once the delete on close flag has been
478          * set.
479          */
480
481         if (GET_DELETE_ON_CLOSE_FLAG(share->share_mode)) {
482                 DEBUG(5,("check_share_mode: Failing open on file %s as delete on close flag is set.\n",
483                         fname ));
484                 /* Use errno to map to correct error. */
485                 set_saved_error_triple(SMB_SUCCESS, 0, NT_STATUS_OK);
486                 return False;
487         }
488
489         /* this is a nasty hack, but necessary until we rewrite our open
490            handling to use a NTCreateX call as the basic call.
491            NT may open a file with neither read nor write access, and in
492                    this case it expects the open not to conflict with any
493                    existing deny modes. This happens (for example) during a
494                    "xcopy /o" where the second file descriptor is used for
495                    ACL sets
496                    (tridge)
497         */
498
499         /*
500          * This is a bit wierd - the test for desired access not having the
501          * critical bits seems seems odd. Firstly, if both opens have no
502          * critical bits then always ignore. Then check the "allow delete"
503          * then check for either. This probably isn't quite right yet but
504          * gets us much closer. JRA.
505          */
506
507         /*
508          * If desired_access doesn't contain READ_DATA,WRITE_DATA,APPEND_DATA or EXECUTE
509          * and the existing desired_acces then share modes don't conflict.
510          */
511
512         if (non_io_open_request && non_io_open_existing) {
513
514                 /*
515                  * Wrinkle discovered by smbtorture....
516                  * If both are non-io open and requester is asking for delete and current open has delete access
517                  * but neither open has allowed file share delete then deny.... this is very strange and
518                  * seems to be the only case in which non-io opens conflict. JRA.
519                  */
520
521                 if ((desired_access & DELETE_ACCESS) && (share->desired_access & DELETE_ACCESS) && 
522                                 (!GET_ALLOW_SHARE_DELETE(share->share_mode) || !GET_ALLOW_SHARE_DELETE(share_mode))) {
523                         DEBUG(5,("check_share_mode: Failing open on file %s as delete access requests conflict.\n",
524                                 fname ));
525                         set_saved_error_triple(ERRDOS, ERRbadshare, NT_STATUS_SHARING_VIOLATION);
526                         return False;
527                 }
528
529                 DEBUG(5,("check_share_mode: Allowing open on file %s as both desired access (0x%x) \
530 and existing desired access (0x%x) are non-data opens\n", 
531                         fname, (unsigned int)desired_access, (unsigned int)share->desired_access ));
532                 return True;
533         } else if (non_io_open_request || non_io_open_existing) {
534                 /*
535                  * If either are non-io opens then share modes don't conflict.
536                  */
537                 DEBUG(5,("check_share_mode: One non-io open. Allowing open on file %s as desired access (0x%x) doesn't conflict with\
538 existing desired access (0x%x).\n", fname, (unsigned int)desired_access, (unsigned int)share->desired_access ));
539                 return True;
540         }
541
542         /*
543          * If delete access was requested and the existing share mode doesn't have
544          * ALLOW_SHARE_DELETE then deny.
545          */
546
547         if ((desired_access & DELETE_ACCESS) && !GET_ALLOW_SHARE_DELETE(share->share_mode)) {
548                 DEBUG(5,("check_share_mode: Failing open on file %s as delete access requested and allow share delete not set.\n",
549                         fname ));
550                 set_saved_error_triple(ERRDOS, ERRbadshare, NT_STATUS_SHARING_VIOLATION);
551                 return False;
552         }
553
554         /*
555          * The inverse of the above.
556          * If delete access was granted and the new share mode doesn't have
557          * ALLOW_SHARE_DELETE then deny.
558          */
559
560         if ((share->desired_access & DELETE_ACCESS) && !GET_ALLOW_SHARE_DELETE(share_mode)) {
561                 DEBUG(5,("check_share_mode: Failing open on file %s as delete access granted and allow share delete not requested.\n",
562                         fname ));
563                 set_saved_error_triple(ERRDOS, ERRbadshare, NT_STATUS_SHARING_VIOLATION);
564                 return False;
565         }
566
567 #if 0
568         /* Bluarc test may need this ... needs further investigation. */
569         if (deny_mode == DENY_ALL || old_deny_mode == DENY_ALL) {
570                 set_saved_error_triple(ERRDOS, ERRbadshare, NT_STATUS_SHARING_VIOLATION);
571                 return False;
572         }
573 #endif
574
575         /*
576          * If desired_access doesn't contain READ_DATA,WRITE_DATA,APPEND_DATA or EXECUTE
577          * then share modes don't conflict. Likewise with existing desired access.
578          */
579
580         if ( !(desired_access & (FILE_READ_DATA|FILE_WRITE_DATA|FILE_APPEND_DATA|FILE_EXECUTE)) ||
581                 !(share->desired_access & (FILE_READ_DATA|FILE_WRITE_DATA|FILE_APPEND_DATA|FILE_EXECUTE)) ) {
582                 DEBUG(5,("check_share_mode: Allowing open on file %s as desired access (0x%x) doesn't conflict with \
583 existing desired access (0x%x).\n", fname, (unsigned int)desired_access, (unsigned int)share->desired_access ));
584                 return True;
585         }
586
587         {
588                 int access_allowed = access_table(deny_mode,old_deny_mode,old_open_mode,
589                                                 (share->pid == sys_getpid()),is_executable(fname));
590
591                 if ((access_allowed == AFAIL) ||
592                         (!fcbopen && (access_allowed == AREAD && *flags == O_RDWR)) ||
593                         (access_allowed == AREAD && *flags != O_RDONLY) ||
594                         (access_allowed == AWRITE && *flags != O_WRONLY)) {
595
596                         DEBUG(2,("Share violation on file (%d,%d,%d,%d,%s,fcbopen = %d, flags = %d) = %d\n",
597                                 deny_mode,old_deny_mode,old_open_mode,
598                                 (int)share->pid,fname, fcbopen, *flags, access_allowed));
599
600                         set_saved_error_triple(ERRDOS, ERRbadshare, NT_STATUS_SHARING_VIOLATION);
601                         return False;
602                 }
603
604                 if (access_allowed == AREAD)
605                         *flags = O_RDONLY;
606
607                 if (access_allowed == AWRITE)
608                         *flags = O_WRONLY;
609
610         }
611
612         return True;
613 }
614
615
616 #if defined(DEVELOPER)
617 static void validate_my_share_entries(int num, share_mode_entry *share_entry)
618 {
619         files_struct *fsp;
620
621         if (share_entry->pid != sys_getpid())
622                 return;
623
624         fsp = file_find_dif(share_entry->dev, share_entry->inode, share_entry->share_file_id);
625         if (!fsp) {
626                 DEBUG(0,("validate_my_share_entries: PANIC : %s\n", share_mode_str(num, share_entry) ));
627                 smb_panic("validate_my_share_entries: Cannot match a share entry with an open file\n");
628         }
629
630         if (((uint16)fsp->oplock_type) != share_entry->op_type) {
631                 pstring str;
632                 DEBUG(0,("validate_my_share_entries: PANIC : %s\n", share_mode_str(num, share_entry) ));
633                 slprintf(str, sizeof(str)-1, "validate_my_share_entries: file %s, oplock_type = 0x%x, op_type = 0x%x\n",
634                                 fsp->fsp_name, (unsigned int)fsp->oplock_type, (unsigned int)share_entry->op_type );
635                 smb_panic(str);
636         }
637 }
638 #endif
639
640 struct share_mode_entry_list {
641         struct share_mode_entry_list *next, *prev;
642         share_mode_entry entry;
643 };
644
645 static void free_broken_entry_list(struct share_mode_entry_list *broken_entry_list)
646 {
647         while (broken_entry_list) {
648                 struct share_mode_entry_list *broken_entry = broken_entry_list;
649                 DLIST_REMOVE(broken_entry_list, broken_entry);
650                 SAFE_FREE(broken_entry);
651         }
652 }
653
654 /****************************************************************************
655  Deal with open deny mode and oplock break processing.
656  Invarient: Share mode must be locked on entry and exit.
657  Returns -1 on error, or number of share modes on success (may be zero).
658 ****************************************************************************/
659
660 static int open_mode_check(connection_struct *conn, const char *fname, SMB_DEV_T dev,
661                            SMB_INO_T inode, 
662                            uint32 desired_access,
663                            int share_mode, int *p_flags, int *p_oplock_request,
664                            BOOL *p_all_current_opens_are_level_II)
665 {
666         int i;
667         int num_share_modes;
668         int oplock_contention_count = 0;
669         share_mode_entry *old_shares = NULL;
670         BOOL fcbopen = False;
671         BOOL broke_oplock;
672
673         if(GET_OPEN_MODE(share_mode) == DOS_OPEN_FCB)
674                 fcbopen = True;
675         
676         num_share_modes = get_share_modes(conn, dev, inode, &old_shares);
677         
678         if(num_share_modes == 0) {
679                 SAFE_FREE(old_shares);
680                 return 0;
681         }
682         
683         if (desired_access && ((desired_access & ~(SYNCHRONIZE_ACCESS|FILE_READ_ATTRIBUTES|FILE_WRITE_ATTRIBUTES))==0) &&
684                 ((desired_access & (SYNCHRONIZE_ACCESS|FILE_READ_ATTRIBUTES|FILE_WRITE_ATTRIBUTES)) != 0)) {
685                 /* Stat open that doesn't trigger oplock breaks or share mode checks... ! JRA. */
686                 SAFE_FREE(old_shares);
687                 return num_share_modes;
688         }
689
690         /*
691          * Check if the share modes will give us access.
692          */
693         
694         do {
695                 struct share_mode_entry_list *broken_entry_list = NULL;
696                 struct share_mode_entry_list *broken_entry = NULL;
697
698                 broke_oplock = False;
699                 *p_all_current_opens_are_level_II = True;
700                 
701                 for(i = 0; i < num_share_modes; i++) {
702                         BOOL cause_oplock_break = False;
703                         share_mode_entry *share_entry = &old_shares[i];
704                         
705 #if defined(DEVELOPER)
706                         validate_my_share_entries(i, share_entry);
707 #endif
708
709                         /* 
710                          * By observation of NetBench, oplocks are broken *before* share
711                          * modes are checked. This allows a file to be closed by the client
712                          * if the share mode would deny access and the client has an oplock. 
713                          * Check if someone has an oplock on this file. If so we must break 
714                          * it before continuing. 
715                          */
716                         
717                         /* Was this a delete this file request ? */
718                         if (!*p_oplock_request && desired_access == DELETE_ACCESS &&
719                                         !BATCH_OPLOCK_TYPE(share_entry->op_type)) {
720                                 /* Don't break the oplock in this case. */
721                                 cause_oplock_break = False;
722                         } else if((*p_oplock_request && EXCLUSIVE_OPLOCK_TYPE(share_entry->op_type)) ||
723                            (!*p_oplock_request && (share_entry->op_type != NO_OPLOCK))) {
724                                 cause_oplock_break = True;
725                         }
726
727                         if(cause_oplock_break) {
728                                 BOOL opb_ret;
729
730                                 DEBUG(5,("open_mode_check: oplock_request = %d, breaking oplock (%x) on file %s, \
731 dev = %x, inode = %.0f\n", *p_oplock_request, share_entry->op_type, fname, (unsigned int)dev, (double)inode));
732                                 
733                                 /* Ensure the reply for the open uses the correct sequence number. */
734                                 /* This isn't a real deferred packet as it's response will also increment
735                                  * the sequence.
736                                  */
737                                 srv_defer_sign_response(get_current_mid());
738
739                                 /* Oplock break - unlock to request it. */
740                                 unlock_share_entry(conn, dev, inode);
741                                 
742                                 opb_ret = request_oplock_break(share_entry);
743                                 
744                                 /* Now relock. */
745                                 lock_share_entry(conn, dev, inode);
746                                 
747                                 if(opb_ret == False) {
748                                         DEBUG(0,("open_mode_check: FAILED when breaking oplock (%x) on file %s, \
749 dev = %x, inode = %.0f\n", old_shares[i].op_type, fname, (unsigned int)dev, (double)inode));
750                                         SAFE_FREE(old_shares);
751                                         set_saved_error_triple(ERRDOS, ERRbadshare, NT_STATUS_SHARING_VIOLATION);
752                                         return -1;
753                                 }
754                                 
755                                 broken_entry = SMB_MALLOC_P(struct share_mode_entry_list);
756                                 if (!broken_entry) {
757                                         smb_panic("open_mode_check: malloc fail.\n");
758                                 }
759                                 broken_entry->entry = *share_entry;
760                                 DLIST_ADD(broken_entry_list, broken_entry);
761                                 broke_oplock = True;
762                                 
763                         } else if (!LEVEL_II_OPLOCK_TYPE(share_entry->op_type)) {
764                                 *p_all_current_opens_are_level_II = False;
765                         }
766                 } /* end for */
767                 
768                 if (broke_oplock) {
769                         /* Update the current open table. */
770                         SAFE_FREE(old_shares);
771                         num_share_modes = get_share_modes(conn, dev, inode, &old_shares);
772                 }
773
774                 /* Now we check the share modes, after any oplock breaks. */
775                 for(i = 0; i < num_share_modes; i++) {
776                         share_mode_entry *share_entry = &old_shares[i];
777
778                         /* someone else has a share lock on it, check to see if we can too */
779                         if (!check_share_mode(conn, share_entry, share_mode, desired_access,
780                                                 fname, fcbopen, p_flags)) {
781                                 SAFE_FREE(old_shares);
782                                 free_broken_entry_list(broken_entry_list);
783                                 errno = EACCES;
784                                 return -1;
785                         }
786                 }
787
788                 for(broken_entry = broken_entry_list; broken_entry; broken_entry = broken_entry->next) {
789                         oplock_contention_count++;
790                         
791                         /* Paranoia check that this is no longer an exlusive entry. */
792                         for(i = 0; i < num_share_modes; i++) {
793                                 share_mode_entry *share_entry = &old_shares[i];
794                                 
795                                 if (share_modes_identical(&broken_entry->entry, share_entry) && 
796                                             EXCLUSIVE_OPLOCK_TYPE(share_entry->op_type) ) {
797                                         
798                                         /*
799                                          * This should not happen. The target left this oplock
800                                          * as exlusive.... The process *must* be dead.... 
801                                          */
802                                         
803                                         DEBUG(0,("open_mode_check: exlusive oplock left by process %d \
804 after break ! For file %s, dev = %x, inode = %.0f. Deleting it to continue...\n",
805                                                 (int)broken_entry->entry.pid, fname, (unsigned int)dev, (double)inode));
806                                         
807                                         if (process_exists(broken_entry->entry.pid)) {
808                                                 DEBUG(0,("open_mode_check: Existent process %lu left active oplock.\n",
809                                                          (unsigned long)broken_entry->entry.pid ));
810                                         }
811                                         
812                                         if (del_share_entry(dev, inode, &broken_entry->entry, NULL) == -1) {
813                                                 free_broken_entry_list(broken_entry_list);
814                                                 errno = EACCES;
815                                                 set_saved_error_triple(ERRDOS, ERRbadshare, NT_STATUS_SHARING_VIOLATION);
816                                                 return -1;
817                                         }
818                                         
819                                         /*
820                                          * We must reload the share modes after deleting the 
821                                          * other process's entry.
822                                          */
823                                         
824                                         SAFE_FREE(old_shares);
825                                         num_share_modes = get_share_modes(conn, dev, inode, &old_shares);
826                                         break;
827                                 }
828                         } /* end for paranoia... */
829                 } /* end for broken_entry */
830                 free_broken_entry_list(broken_entry_list);
831         } while(broke_oplock);
832         
833         /*
834          * Refuse to grant an oplock in case the contention limit is
835          * reached when going through the lock list multiple times.
836          */
837         
838         if(oplock_contention_count >= lp_oplock_contention_limit(SNUM(conn))) {
839                 *p_oplock_request = 0;
840                 DEBUG(4,("open_mode_check: oplock contention = %d. Not granting oplock.\n",
841                          oplock_contention_count ));
842         }
843         
844         SAFE_FREE(old_shares);
845         return num_share_modes;
846 }
847
848 /****************************************************************************
849  Delete the record for a handled deferred open entry.
850 ****************************************************************************/
851
852 static void delete_defered_open_entry_record(connection_struct *conn, SMB_DEV_T dev, SMB_INO_T inode)
853 {
854         uint16 mid = get_current_mid();
855         pid_t mypid = sys_getpid();
856         deferred_open_entry *de_array = NULL;
857         int num_de_entries, i;
858
859         if (!lp_defer_sharing_violations()) {
860                 return;
861         }
862
863         num_de_entries = get_deferred_opens(conn, dev, inode, &de_array);
864         for (i = 0; i < num_de_entries; i++) {
865                 deferred_open_entry *entry = &de_array[i];
866                 if (entry->pid == mypid && entry->mid == mid && entry->dev == dev &&
867                         entry->inode == inode) {
868
869                         /* Remove the deferred open entry from the array. */
870                         delete_deferred_open_entry(entry);
871                         SAFE_FREE(de_array);
872                         return;
873                 }
874         }
875         SAFE_FREE(de_array);
876 }
877
878 /****************************************************************************
879  Handle the 1 second delay in returning a SHARING_VIOLATION error.
880 ****************************************************************************/
881
882 void defer_open_sharing_error(connection_struct *conn, struct timeval *ptv,
883                 char *fname, SMB_DEV_T dev, SMB_INO_T inode)
884 {
885         uint16 mid = get_current_mid();
886         pid_t mypid = sys_getpid();
887         deferred_open_entry *de_array = NULL;
888         int num_de_entries, i;
889         struct dev_inode_bundle dib;
890
891         if (!lp_defer_sharing_violations()) {
892                 return;
893         }
894
895         dib.dev = dev;
896         dib.inode = inode;
897
898         num_de_entries = get_deferred_opens(conn, dev, inode, &de_array);
899         for (i = 0; i < num_de_entries; i++) {
900                 deferred_open_entry *entry = &de_array[i];
901                 if (entry->pid == mypid && entry->mid == mid) {
902                         /*
903                          * Check if a 1 second timeout has expired.
904                          */
905                         if (usec_time_diff(ptv, &entry->time) > SHARING_VIOLATION_USEC_WAIT) {
906                                 DEBUG(10,("defer_open_sharing_error: Deleting deferred open entry for mid %u, \
907 file %s\n",
908                                         (unsigned int)mid, fname ));
909
910                                 /* Expired, return a real error. */
911                                 /* Remove the deferred open entry from the array. */
912
913                                 delete_deferred_open_entry(entry);
914                                 SAFE_FREE(de_array);
915                                 return;
916                         }
917                         /*
918                          * If the timeout hasn't expired yet and we still have a sharing violation,
919                          * just leave the entry in the deferred open array alone. We do need to
920                          * reschedule this open call though (with the original created time).
921                          */
922                         DEBUG(10,("defer_open_sharing_error: time [%u.%06u] updating \
923 deferred open entry for mid %u, file %s\n",
924                                 (unsigned int)entry->time.tv_sec,
925                                 (unsigned int)entry->time.tv_usec,
926                                 (unsigned int)mid, fname ));
927
928                         push_sharing_violation_open_smb_message(&entry->time, (char *)&dib, sizeof(dib));
929                         SAFE_FREE(de_array);
930                         return;
931                 }
932         }
933
934         DEBUG(10,("defer_open_sharing_error: time [%u.%06u] adding deferred open entry for mid %u, file %s\n",
935                 (unsigned int)ptv->tv_sec, (unsigned int)ptv->tv_usec, (unsigned int)mid, fname ));
936
937         if (!push_sharing_violation_open_smb_message(ptv, (char *)&dib, sizeof(dib))) {
938                 SAFE_FREE(de_array);
939                 return;
940         }
941         if (!add_deferred_open(mid, ptv, dev, inode, global_oplock_port, fname)) {
942                 remove_sharing_violation_open_smb_message(mid);
943         }
944
945         /*
946          * Push the MID of this packet on the signing queue.
947          * We only do this once, the first time we push the packet
948          * onto the deferred open queue, as this has a side effect
949          * of incrementing the response sequence number.
950          */
951
952         srv_defer_sign_response(mid);
953
954         SAFE_FREE(de_array);
955 }
956
957 /****************************************************************************
958  Set a kernel flock on a file for NFS interoperability.
959  This requires a patch to Linux.
960 ****************************************************************************/
961
962 static void kernel_flock(files_struct *fsp, int deny_mode)
963 {
964 #if HAVE_KERNEL_SHARE_MODES
965         int kernel_mode = 0;
966         if (deny_mode == DENY_READ) kernel_mode = LOCK_MAND|LOCK_WRITE;
967         else if (deny_mode == DENY_WRITE) kernel_mode = LOCK_MAND|LOCK_READ;
968         else if (deny_mode == DENY_ALL) kernel_mode = LOCK_MAND;
969         if (kernel_mode) flock(fsp->fd, kernel_mode);
970 #endif
971         ;;
972 }
973
974
975 static BOOL open_match_attributes(connection_struct *conn, const char *path, uint32 old_dos_mode, uint32 new_dos_mode,
976                 mode_t existing_mode, mode_t new_mode, mode_t *returned_mode)
977 {
978         uint32 noarch_old_dos_mode, noarch_new_dos_mode;
979
980         noarch_old_dos_mode = (old_dos_mode & ~FILE_ATTRIBUTE_ARCHIVE);
981         noarch_new_dos_mode = (new_dos_mode & ~FILE_ATTRIBUTE_ARCHIVE);
982
983         if((noarch_old_dos_mode == 0 && noarch_new_dos_mode != 0) || 
984            (noarch_old_dos_mode != 0 && ((noarch_old_dos_mode & noarch_new_dos_mode) == noarch_old_dos_mode)))
985                 *returned_mode = new_mode;
986         else
987                 *returned_mode = (mode_t)0;
988
989         DEBUG(10,("open_match_attributes: file %s old_dos_mode = 0x%x, existing_mode = 0%o, new_dos_mode = 0x%x returned_mode = 0%o\n",
990                 path,
991                 old_dos_mode, (unsigned int)existing_mode, new_dos_mode, (unsigned int)*returned_mode ));
992
993         /* If we're mapping SYSTEM and HIDDEN ensure they match. */
994         if (lp_map_system(SNUM(conn)) || lp_store_dos_attributes(SNUM(conn))) {
995                 if ((old_dos_mode & FILE_ATTRIBUTE_SYSTEM) && !(new_dos_mode & FILE_ATTRIBUTE_SYSTEM))
996                         return False;
997         }
998         if (lp_map_hidden(SNUM(conn)) || lp_store_dos_attributes(SNUM(conn))) {
999                 if ((old_dos_mode & FILE_ATTRIBUTE_HIDDEN) && !(new_dos_mode & FILE_ATTRIBUTE_HIDDEN))
1000                         return False;
1001         }
1002         return True;
1003 }
1004
1005 /****************************************************************************
1006  Open a file with a share mode.
1007 ****************************************************************************/
1008
1009 files_struct *open_file_shared(connection_struct *conn,char *fname, SMB_STRUCT_STAT *psbuf, 
1010                                int share_mode,int ofun, uint32 new_dos_mode, int oplock_request, 
1011                                int *Access,int *action)
1012 {
1013         return open_file_shared1(conn, fname, psbuf, 0, share_mode, ofun, new_dos_mode,
1014                                  oplock_request, Access, action);
1015 }
1016
1017 /****************************************************************************
1018  Open a file with a share mode.
1019 ****************************************************************************/
1020
1021 files_struct *open_file_shared1(connection_struct *conn,char *fname, SMB_STRUCT_STAT *psbuf, 
1022                                 uint32 desired_access, 
1023                                 int share_mode,int ofun, uint32 new_dos_mode,
1024                                 int oplock_request, 
1025                                 int *Access,int *paction)
1026 {
1027         int flags=0;
1028         int flags2=0;
1029         int deny_mode = GET_DENY_MODE(share_mode);
1030         BOOL allow_share_delete = GET_ALLOW_SHARE_DELETE(share_mode);
1031         BOOL delete_on_close = GET_DELETE_ON_CLOSE_FLAG(share_mode);
1032         BOOL file_existed = VALID_STAT(*psbuf);
1033         BOOL fcbopen = False;
1034         BOOL def_acl = False;
1035         BOOL add_share_mode = True;
1036         BOOL internal_only_open = False;
1037         SMB_DEV_T dev = 0;
1038         SMB_INO_T inode = 0;
1039         int num_share_modes = 0;
1040         BOOL all_current_opens_are_level_II = False;
1041         BOOL fsp_open = False;
1042         files_struct *fsp = NULL;
1043         int open_mode=0;
1044         uint16 port = 0;
1045         mode_t new_mode = (mode_t)0;
1046         int action;
1047         uint32 existing_dos_mode = 0;
1048         struct pending_message_list *pml = NULL;
1049         uint16 mid = get_current_mid();
1050         /* We add aARCH to this as this mode is only used if the file is created new. */
1051         mode_t mode = unix_mode(conn,new_dos_mode | aARCH,fname, True);
1052
1053         if (oplock_request == INTERNAL_OPEN_ONLY) {
1054                 internal_only_open = True;
1055                 oplock_request = 0;
1056         }
1057
1058         if ((pml = get_open_deferred_message(mid)) != NULL) {
1059                 struct dev_inode_bundle dib;
1060
1061                 memcpy(&dib, pml->private_data.data, sizeof(dib));
1062
1063                 /* There could be a race condition where the dev/inode pair
1064                         has changed since we deferred the message. If so, just
1065                         remove the deferred open entry and return sharing violation. */
1066
1067                 /* If the timeout value is non-zero, we need to just
1068                         return sharing violation. Don't retry the open
1069                         as we were not notified of a close and we don't want to
1070                         trigger another spurious oplock break. */
1071
1072                 if (!file_existed || dib.dev != psbuf->st_dev || dib.inode != psbuf->st_ino ||
1073                                 pml->msg_time.tv_sec || pml->msg_time.tv_usec) {
1074                         /* Ensure we don't reprocess this message. */
1075                         remove_sharing_violation_open_smb_message(mid);
1076
1077                         /* Now remove the deferred open entry under lock. */
1078                         lock_share_entry(conn, dib.dev, dib.inode);
1079                         delete_defered_open_entry_record(conn, dib.dev, dib.inode);
1080                         unlock_share_entry(conn, dib.dev, dib.inode);
1081
1082                         set_saved_error_triple(ERRDOS, ERRbadshare, NT_STATUS_SHARING_VIOLATION);
1083                         return NULL;
1084                 }
1085                 /* Ensure we don't reprocess this message. */
1086                 remove_sharing_violation_open_smb_message(mid);
1087
1088         }
1089
1090         if (conn->printer) {
1091                 /* printers are handled completely differently. Most of the passed parameters are
1092                         ignored */
1093                 if (Access)
1094                         *Access = DOS_OPEN_WRONLY;
1095                 if (paction)
1096                         *paction = FILE_WAS_CREATED;
1097                 return print_fsp_open(conn, fname);
1098         }
1099
1100         DEBUG(10,("open_file_shared: fname = %s, dos_attrs = %x, share_mode = %x, ofun = %x, mode = %o, oplock request = %d\n",
1101                 fname, new_dos_mode, share_mode, ofun, (int)mode,  oplock_request ));
1102
1103         if (!check_name(fname,conn)) {
1104                 return NULL;
1105         } 
1106
1107         new_dos_mode &= SAMBA_ATTRIBUTES_MASK;
1108         if (file_existed) {
1109                 existing_dos_mode = dos_mode(conn, fname, psbuf);
1110         }
1111
1112         /* ignore any oplock requests if oplocks are disabled */
1113         if (!lp_oplocks(SNUM(conn)) || global_client_failed_oplock_break) {
1114                 oplock_request = 0;
1115         }
1116
1117         /* this is for OS/2 long file names - say we don't support them */
1118         if (strstr(fname,".+,;=[].")) {
1119                 /* OS/2 Workplace shell fix may be main code stream in a later release. */ 
1120                 set_saved_error_triple(ERRDOS, ERRcannotopen, NT_STATUS_OBJECT_NAME_NOT_FOUND);
1121                 DEBUG(5,("open_file_shared: OS/2 long filenames are not supported.\n"));
1122                 return NULL;
1123         }
1124
1125         if ((GET_FILE_OPEN_DISPOSITION(ofun) == FILE_EXISTS_FAIL) && file_existed)  {
1126                 DEBUG(5,("open_file_shared: create new requested for file %s and file already exists.\n",
1127                         fname ));
1128                 if (S_ISDIR(psbuf->st_mode)) {
1129                         errno = EISDIR;
1130                 } else {
1131                         errno = EEXIST;
1132                 }
1133                 return NULL;
1134         }
1135       
1136         if (CAN_WRITE(conn) && (GET_FILE_CREATE_DISPOSITION(ofun) == FILE_CREATE_IF_NOT_EXIST))
1137                 flags2 |= O_CREAT;
1138
1139         if (CAN_WRITE(conn) && (GET_FILE_OPEN_DISPOSITION(ofun) == FILE_EXISTS_TRUNCATE))
1140                 flags2 |= O_TRUNC;
1141
1142         /* We only care about matching attributes on file exists and truncate. */
1143         if (file_existed && (GET_FILE_OPEN_DISPOSITION(ofun) == FILE_EXISTS_TRUNCATE)) {
1144                 if (!open_match_attributes(conn, fname, existing_dos_mode, new_dos_mode,
1145                                         psbuf->st_mode, mode, &new_mode)) {
1146                         DEBUG(5,("open_file_shared: attributes missmatch for file %s (%x %x) (0%o, 0%o)\n",
1147                                                 fname, existing_dos_mode, new_dos_mode,
1148                                                 (int)psbuf->st_mode, (int)mode ));
1149                         errno = EACCES;
1150                         return NULL;
1151                 }
1152         }
1153
1154         if (GET_FILE_OPEN_DISPOSITION(ofun) == FILE_EXISTS_FAIL)
1155                 flags2 |= O_EXCL;
1156
1157         /* note that we ignore the append flag as 
1158                 append does not mean the same thing under dos and unix */
1159
1160         switch (GET_OPEN_MODE(share_mode)) {
1161                 case DOS_OPEN_EXEC:
1162                 case DOS_OPEN_RDONLY:
1163                         flags = O_RDONLY;
1164                         if (desired_access == 0)
1165                                 desired_access = FILE_READ_DATA;
1166                         break;
1167                 case DOS_OPEN_WRONLY: 
1168                         flags = O_WRONLY; 
1169                         if (desired_access == 0)
1170                                 desired_access = FILE_WRITE_DATA;
1171                         break;
1172                 case DOS_OPEN_FCB: 
1173                         fcbopen = True;
1174                         flags = O_RDWR; 
1175                         if (desired_access == 0)
1176                                 desired_access = FILE_READ_DATA|FILE_WRITE_DATA;
1177                         break;
1178                 case DOS_OPEN_RDWR: 
1179                         flags = O_RDWR; 
1180                         if (desired_access == 0)
1181                                 desired_access = FILE_READ_DATA|FILE_WRITE_DATA;
1182                         break;
1183                 default:
1184                         /* Force DOS error. */
1185                         set_saved_error_triple(ERRDOS, ERRinvalidparam, NT_STATUS_INVALID);
1186                         return NULL;
1187         }
1188
1189 #if defined(O_SYNC)
1190         if (GET_FILE_SYNC_OPENMODE(share_mode)) {
1191                 flags2 |= O_SYNC;
1192         }
1193 #endif /* O_SYNC */
1194   
1195         if (flags != O_RDONLY && file_existed && 
1196                         (!CAN_WRITE(conn) || IS_DOS_READONLY(existing_dos_mode))) {
1197                 if (!fcbopen) {
1198                         DEBUG(5,("open_file_shared: read/write access requested for file %s on read only %s\n",
1199                                 fname, !CAN_WRITE(conn) ? "share" : "file" ));
1200                         errno = EACCES;
1201                         return NULL;
1202                 }
1203                 flags = O_RDONLY;
1204         }
1205
1206         if (deny_mode > DENY_NONE && deny_mode!=DENY_FCB) {
1207                 DEBUG(2,("Invalid deny mode %d on file %s\n",deny_mode,fname));
1208                 errno = EINVAL;
1209                 return NULL;
1210         }
1211
1212         if (desired_access && ((desired_access & ~(SYNCHRONIZE_ACCESS|FILE_READ_ATTRIBUTES|FILE_WRITE_ATTRIBUTES))==0) &&
1213                 ((desired_access & (SYNCHRONIZE_ACCESS|FILE_READ_ATTRIBUTES|FILE_WRITE_ATTRIBUTES)) != 0)) {
1214                 /* Stat open that doesn't trigger oplock breaks or share mode checks... ! JRA. */
1215                 deny_mode = DENY_NONE;
1216                 if (file_existed) {
1217                         oplock_request = 0;
1218                         add_share_mode = False;
1219                         flags2 &= ~O_CREAT;
1220                 }
1221         }
1222
1223         fsp = file_new(conn);
1224         if(!fsp)
1225                 return NULL;
1226
1227         if (file_existed) {
1228
1229                 dev = psbuf->st_dev;
1230                 inode = psbuf->st_ino;
1231
1232                 lock_share_entry(conn, dev, inode);
1233
1234                 num_share_modes = open_mode_check(conn, fname, dev, inode, 
1235                                                   desired_access,
1236                                                   share_mode,
1237                                                   &flags, &oplock_request, &all_current_opens_are_level_II);
1238                 if(num_share_modes == -1) {
1239
1240                         /*
1241                          * This next line is a subtlety we need for MS-Access. If a file open will
1242                          * fail due to share permissions and also for security (access)
1243                          * reasons, we need to return the access failed error, not the
1244                          * share error. This means we must attempt to open the file anyway
1245                          * in order to get the UNIX access error - even if we're going to
1246                          * fail the open for share reasons. This is bad, as we're burning
1247                          * another fd if there are existing locks but there's nothing else
1248                          * we can do. We also ensure we're not going to create or tuncate
1249                          * the file as we only want an access decision at this stage. JRA.
1250                          */
1251                         errno = 0;
1252                         fsp_open = open_file(fsp,conn,fname,psbuf,
1253                                                 flags|(flags2&~(O_TRUNC|O_CREAT)),mode,desired_access);
1254
1255                         DEBUG(4,("open_file_shared : share_mode deny - calling open_file with \
1256 flags=0x%X flags2=0x%X mode=0%o returned %d\n",
1257                                 flags,(flags2&~(O_TRUNC|O_CREAT)),(int)mode,(int)fsp_open ));
1258
1259                         if (!fsp_open && errno) {
1260                                 /* Default error. */
1261                                 set_saved_error_triple(ERRDOS, ERRnoaccess, NT_STATUS_ACCESS_DENIED);
1262                         }
1263
1264                         /* 
1265                          * If we're returning a share violation, ensure we cope with
1266                          * the braindead 1 second delay.
1267                          */
1268
1269                         if (!internal_only_open) {
1270                                 NTSTATUS status;
1271                                 get_saved_error_triple(NULL, NULL, &status);
1272                                 if (NT_STATUS_EQUAL(status,NT_STATUS_SHARING_VIOLATION)) {
1273                                         /* The fsp->open_time here represents the current time of day. */
1274                                         defer_open_sharing_error(conn, &fsp->open_time, fname, dev, inode);
1275                                 }
1276                         }
1277
1278                         unlock_share_entry(conn, dev, inode);
1279                         if (fsp_open) {
1280                                 fd_close(conn, fsp);
1281                                 /*
1282                                  * We have detected a sharing violation here
1283                                  * so return the correct error code
1284                                  */
1285                                 set_saved_error_triple(ERRDOS, ERRbadshare, NT_STATUS_SHARING_VIOLATION);
1286                         }
1287                         file_free(fsp);
1288                         return NULL;
1289                 }
1290
1291                 /*
1292                  * We exit this block with the share entry *locked*.....
1293                  */
1294         }
1295
1296         /*
1297          * Ensure we pay attention to default ACLs on directories if required.
1298          */
1299
1300         if ((flags2 & O_CREAT) && lp_inherit_acls(SNUM(conn)) &&
1301                         (def_acl = directory_has_default_acl(conn, parent_dirname(fname))))
1302                 mode = 0777;
1303
1304         DEBUG(4,("calling open_file with flags=0x%X flags2=0x%X mode=0%o\n",
1305                         flags,flags2,(int)mode));
1306
1307         /*
1308          * open_file strips any O_TRUNC flags itself.
1309          */
1310
1311         fsp_open = open_file(fsp,conn,fname,psbuf,flags|flags2,mode,desired_access);
1312
1313         if (!fsp_open && (flags == O_RDWR) && (errno != ENOENT) && fcbopen) {
1314                 if((fsp_open = open_file(fsp,conn,fname,psbuf,O_RDONLY,mode,desired_access)) == True)
1315                         flags = O_RDONLY;
1316         }
1317
1318         if (!fsp_open) {
1319                 if(file_existed)
1320                         unlock_share_entry(conn, dev, inode);
1321                 file_free(fsp);
1322                 return NULL;
1323         }
1324
1325         /*
1326          * Deal with the race condition where two smbd's detect the file doesn't
1327          * exist and do the create at the same time. One of them will win and
1328          * set a share mode, the other (ie. this one) should check if the
1329          * requested share mode for this create is allowed.
1330          */
1331
1332         if (!file_existed) { 
1333
1334                 /*
1335                  * Now the file exists and fsp is successfully opened,
1336                  * fsp->dev and fsp->inode are valid and should replace the
1337                  * dev=0,inode=0 from a non existent file. Spotted by
1338                  * Nadav Danieli <nadavd@exanet.com>. JRA.
1339                  */
1340
1341                 dev = fsp->dev;
1342                 inode = fsp->inode;
1343
1344                 lock_share_entry_fsp(fsp);
1345
1346                 num_share_modes = open_mode_check(conn, fname, dev, inode, 
1347                                                   desired_access,
1348                                                   share_mode,
1349                                                   &flags, &oplock_request, &all_current_opens_are_level_II);
1350
1351                 if(num_share_modes == -1) {
1352                         /* 
1353                          * If we're returning a share violation, ensure we cope with
1354                          * the braindead 1 second delay.
1355                          */
1356
1357                         NTSTATUS status;
1358                         get_saved_error_triple(NULL, NULL, &status);
1359                         if (NT_STATUS_EQUAL(status,NT_STATUS_SHARING_VIOLATION)) {
1360                                 /* The fsp->open_time here represents the current time of day. */
1361                                 defer_open_sharing_error(conn, &fsp->open_time, fname, dev, inode);
1362                         }
1363
1364                         unlock_share_entry_fsp(fsp);
1365                         fd_close(conn,fsp);
1366                         file_free(fsp);
1367                         /*
1368                          * We have detected a sharing violation here, so
1369                          * return the correct code.
1370                          */
1371                         set_saved_error_triple(ERRDOS, ERRbadshare, NT_STATUS_SHARING_VIOLATION);
1372                         return NULL;
1373                 }
1374
1375                 /*
1376                  * If there are any share modes set then the file *did*
1377                  * exist. Ensure we return the correct value for action.
1378                  */
1379
1380                 if (num_share_modes > 0)
1381                         file_existed = True;
1382
1383                 /*
1384                  * We exit this block with the share entry *locked*.....
1385                  */
1386         }
1387
1388         /* note that we ignore failure for the following. It is
1389            basically a hack for NFS, and NFS will never set one of
1390            these only read them. Nobody but Samba can ever set a deny
1391            mode and we have already checked our more authoritative
1392            locking database for permission to set this deny mode. If
1393            the kernel refuses the operations then the kernel is wrong */
1394         kernel_flock(fsp, deny_mode);
1395
1396         /*
1397          * At this point onwards, we can guarentee that the share entry
1398          * is locked, whether we created the file or not, and that the
1399          * deny mode is compatible with all current opens.
1400          */
1401
1402         /*
1403          * If requested, truncate the file.
1404          */
1405
1406         if (flags2&O_TRUNC) {
1407                 /*
1408                  * We are modifing the file after open - update the stat struct..
1409                  */
1410                 if ((SMB_VFS_FTRUNCATE(fsp,fsp->fd,0) == -1) || (SMB_VFS_FSTAT(fsp,fsp->fd,psbuf)==-1)) {
1411                         unlock_share_entry_fsp(fsp);
1412                         fd_close(conn,fsp);
1413                         file_free(fsp);
1414                         return NULL;
1415                 }
1416         }
1417
1418         switch (flags) {
1419                 case O_RDONLY:
1420                         open_mode = DOS_OPEN_RDONLY;
1421                         break;
1422                 case O_RDWR:
1423                         open_mode = DOS_OPEN_RDWR;
1424                         break;
1425                 case O_WRONLY:
1426                         open_mode = DOS_OPEN_WRONLY;
1427                         break;
1428         }
1429
1430         fsp->share_mode = SET_DENY_MODE(deny_mode) | 
1431                                                 SET_OPEN_MODE(open_mode) | 
1432                                                 SET_ALLOW_SHARE_DELETE(allow_share_delete);
1433
1434         DEBUG(10,("open_file_shared : share_mode = %x\n", fsp->share_mode ));
1435
1436         if (Access) {
1437                 (*Access) = (SET_DENY_MODE(deny_mode) | SET_OPEN_MODE(open_mode));
1438         }
1439
1440         action = 0;
1441
1442         if (file_existed && !(flags2 & O_TRUNC))
1443                 action = FILE_WAS_OPENED;
1444         if (file_existed && (flags2 & O_TRUNC))
1445                 action = FILE_WAS_OVERWRITTEN;
1446         if (!file_existed) {
1447                 action = FILE_WAS_CREATED;
1448                 /* Change the owner if required. */
1449                 if (lp_inherit_owner(SNUM(conn))) {
1450                         change_owner_to_parent(conn, fsp, fsp->fsp_name, psbuf);
1451                 }
1452         }
1453
1454         if (paction) {
1455                 *paction = action;
1456         }
1457
1458         /* 
1459          * Setup the oplock info in both the shared memory and
1460          * file structs.
1461          */
1462
1463         if(oplock_request && (num_share_modes == 0) && 
1464                         !IS_VETO_OPLOCK_PATH(conn,fname) && set_file_oplock(fsp, oplock_request) ) {
1465                 port = global_oplock_port;
1466         } else if (oplock_request && all_current_opens_are_level_II) {
1467                 port = global_oplock_port;
1468                 oplock_request = LEVEL_II_OPLOCK;
1469                 set_file_oplock(fsp, oplock_request);
1470         } else {
1471                 port = 0;
1472                 oplock_request = 0;
1473         }
1474
1475         if (add_share_mode) {
1476                 set_share_mode(fsp, port, oplock_request);
1477         }
1478
1479         if (delete_on_close) {
1480                 uint32 dosmode = existing_dos_mode;
1481                 NTSTATUS result;
1482
1483                 if (action == FILE_WAS_OVERWRITTEN || action == FILE_WAS_CREATED) {
1484                         dosmode = new_dos_mode;
1485                 }
1486                 result = set_delete_on_close_internal(fsp, delete_on_close, dosmode);
1487
1488                 if (NT_STATUS_V(result) !=  NT_STATUS_V(NT_STATUS_OK)) {
1489                         uint8 u_e_c;
1490                         uint32 u_e_code;
1491                         /* Remember to delete the mode we just added. */
1492                         if (add_share_mode) {
1493                                 del_share_mode(fsp, NULL);
1494                         }
1495                         unlock_share_entry_fsp(fsp);
1496                         fd_close(conn,fsp);
1497                         file_free(fsp);
1498                         ntstatus_to_dos(result, &u_e_c, &u_e_code);
1499                         set_saved_error_triple(u_e_c, u_e_code, result);
1500                         return NULL;
1501                 }
1502         }
1503         
1504         if (action == FILE_WAS_OVERWRITTEN || action == FILE_WAS_CREATED) {
1505                 /* Files should be initially set as archive */
1506                 if (lp_map_archive(SNUM(conn)) || lp_store_dos_attributes(SNUM(conn))) {
1507                         file_set_dosmode(conn, fname, new_dos_mode | aARCH, NULL, True);
1508                 }
1509         }
1510
1511         /*
1512          * Take care of inherited ACLs on created files - if default ACL not
1513          * selected.
1514          */
1515
1516         if (!file_existed && !def_acl) {
1517
1518                 int saved_errno = errno; /* We might get ENOSYS in the next call.. */
1519
1520                 if (SMB_VFS_FCHMOD_ACL(fsp, fsp->fd, mode) == -1 && errno == ENOSYS)
1521                         errno = saved_errno; /* Ignore ENOSYS */
1522
1523         } else if (new_mode) {
1524
1525                 int ret = -1;
1526
1527                 /* Attributes need changing. File already existed. */
1528
1529                 {
1530                         int saved_errno = errno; /* We might get ENOSYS in the next call.. */
1531                         ret = SMB_VFS_FCHMOD_ACL(fsp, fsp->fd, new_mode);
1532
1533                         if (ret == -1 && errno == ENOSYS) {
1534                                 errno = saved_errno; /* Ignore ENOSYS */
1535                         } else {
1536                                 DEBUG(5, ("open_file_shared: failed to reset attributes of file %s to 0%o\n",
1537                                         fname, (int)new_mode));
1538                                 ret = 0; /* Don't do the fchmod below. */
1539                         }
1540                 }
1541
1542                 if ((ret == -1) && (SMB_VFS_FCHMOD(fsp, fsp->fd, new_mode) == -1))
1543                         DEBUG(5, ("open_file_shared: failed to reset attributes of file %s to 0%o\n",
1544                                 fname, (int)new_mode));
1545         }
1546
1547         /* If this is a successful open, we must remove any deferred open records. */
1548         delete_defered_open_entry_record(conn, fsp->dev, fsp->inode);
1549         unlock_share_entry_fsp(fsp);
1550
1551         conn->num_files_open++;
1552
1553         return fsp;
1554 }
1555
1556 /****************************************************************************
1557  Open a file for for write to ensure that we can fchmod it.
1558 ****************************************************************************/
1559
1560 files_struct *open_file_fchmod(connection_struct *conn, const char *fname, SMB_STRUCT_STAT *psbuf)
1561 {
1562         files_struct *fsp = NULL;
1563         BOOL fsp_open;
1564
1565         if (!VALID_STAT(*psbuf))
1566                 return NULL;
1567
1568         fsp = file_new(conn);
1569         if(!fsp)
1570                 return NULL;
1571
1572         /* note! we must use a non-zero desired access or we don't get
1573            a real file descriptor. Oh what a twisted web we weave. */
1574         fsp_open = open_file(fsp,conn,fname,psbuf,O_WRONLY,0,FILE_WRITE_DATA);
1575
1576         /* 
1577          * This is not a user visible file open.
1578          * Don't set a share mode and don't increment
1579          * the conn->num_files_open.
1580          */
1581
1582         if (!fsp_open) {
1583                 file_free(fsp);
1584                 return NULL;
1585         }
1586
1587         return fsp;
1588 }
1589
1590 /****************************************************************************
1591  Close the fchmod file fd - ensure no locks are lost.
1592 ****************************************************************************/
1593
1594 int close_file_fchmod(files_struct *fsp)
1595 {
1596         int ret = fd_close(fsp->conn, fsp);
1597         file_free(fsp);
1598         return ret;
1599 }
1600
1601 /****************************************************************************
1602  Open a directory from an NT SMB call.
1603 ****************************************************************************/
1604
1605 files_struct *open_directory(connection_struct *conn, const char *fname, SMB_STRUCT_STAT *psbuf,
1606                         uint32 desired_access, int share_mode, int smb_ofun, int *action)
1607 {
1608         BOOL got_stat = False;
1609         files_struct *fsp = file_new(conn);
1610         BOOL delete_on_close = GET_DELETE_ON_CLOSE_FLAG(share_mode);
1611
1612         if(!fsp)
1613                 return NULL;
1614
1615         if (VALID_STAT(*psbuf))
1616                 got_stat = True;
1617
1618         if (got_stat && (GET_FILE_OPEN_DISPOSITION(smb_ofun) == FILE_EXISTS_FAIL)) {
1619                 file_free(fsp);
1620                 errno = EEXIST; /* Setup so correct error is returned to client. */
1621                 return NULL;
1622         }
1623
1624         if (GET_FILE_CREATE_DISPOSITION(smb_ofun) == FILE_CREATE_IF_NOT_EXIST) {
1625
1626                 if (got_stat) {
1627
1628                         if(!S_ISDIR(psbuf->st_mode)) {
1629                                 DEBUG(0,("open_directory: %s is not a directory !\n", fname ));
1630                                 file_free(fsp);
1631                                 errno = EACCES;
1632                                 return NULL;
1633                         }
1634                         *action = FILE_WAS_OPENED;
1635
1636                 } else {
1637
1638                         /*
1639                          * Try and create the directory.
1640                          */
1641
1642                         /* We know bad_path is false as it's caught earlier. */
1643
1644                         NTSTATUS status = mkdir_internal(conn, fname, False);
1645
1646                         if (!NT_STATUS_IS_OK(status)) {
1647                                 DEBUG(2,("open_directory: unable to create %s. Error was %s\n",
1648                                          fname, strerror(errno) ));
1649                                 file_free(fsp);
1650                                 /* Ensure we return the correct NT status to the client. */
1651                                 set_saved_error_triple(0, 0, status);
1652                                 return NULL;
1653                         }
1654
1655                         /* Ensure we're checking for a symlink here.... */
1656                         /* We don't want to get caught by a symlink racer. */
1657
1658                         if(SMB_VFS_LSTAT(conn,fname, psbuf) != 0) {
1659                                 file_free(fsp);
1660                                 return NULL;
1661                         }
1662
1663                         if(!S_ISDIR(psbuf->st_mode)) {
1664                                 DEBUG(0,("open_directory: %s is not a directory !\n", fname ));
1665                                 file_free(fsp);
1666                                 return NULL;
1667                         }
1668
1669                         *action = FILE_WAS_CREATED;
1670
1671                 }
1672         } else {
1673
1674                 /*
1675                  * Don't create - just check that it *was* a directory.
1676                  */
1677
1678                 if(!got_stat) {
1679                         DEBUG(3,("open_directory: unable to stat name = %s. Error was %s\n",
1680                                  fname, strerror(errno) ));
1681                         file_free(fsp);
1682                         return NULL;
1683                 }
1684
1685                 if(!S_ISDIR(psbuf->st_mode)) {
1686                         DEBUG(0,("open_directory: %s is not a directory !\n", fname ));
1687                         file_free(fsp);
1688                         return NULL;
1689                 }
1690
1691                 *action = FILE_WAS_OPENED;
1692         }
1693         
1694         DEBUG(5,("open_directory: opening directory %s\n", fname));
1695
1696         /*
1697          * Setup the files_struct for it.
1698          */
1699         
1700         fsp->mode = psbuf->st_mode;
1701         fsp->inode = psbuf->st_ino;
1702         fsp->dev = psbuf->st_dev;
1703         fsp->vuid = current_user.vuid;
1704         fsp->file_pid = global_smbpid;
1705         fsp->can_lock = True;
1706         fsp->can_read = False;
1707         fsp->can_write = False;
1708         fsp->share_mode = share_mode;
1709         fsp->desired_access = desired_access;
1710         fsp->print_file = False;
1711         fsp->modified = False;
1712         fsp->oplock_type = NO_OPLOCK;
1713         fsp->sent_oplock_break = NO_BREAK_SENT;
1714         fsp->is_directory = True;
1715         fsp->is_stat = False;
1716         fsp->directory_delete_on_close = False;
1717         string_set(&fsp->fsp_name,fname);
1718
1719         if (delete_on_close) {
1720                 NTSTATUS status = set_delete_on_close_internal(fsp, delete_on_close, 0);
1721
1722                 if (!NT_STATUS_IS_OK(status)) {
1723                         file_free(fsp);
1724                         return NULL;
1725                 }
1726         }
1727
1728         /* Change the owner if required. */
1729         if ((*action == FILE_WAS_CREATED) && lp_inherit_owner(SNUM(conn))) {
1730                 change_owner_to_parent(conn, fsp, fsp->fsp_name, psbuf);
1731         }
1732
1733         conn->num_files_open++;
1734
1735         return fsp;
1736 }
1737
1738 /****************************************************************************
1739  Open a pseudo-file (no locking checks - a 'stat' open).
1740 ****************************************************************************/
1741
1742 files_struct *open_file_stat(connection_struct *conn, char *fname, SMB_STRUCT_STAT *psbuf)
1743 {
1744         files_struct *fsp = NULL;
1745
1746         if (!VALID_STAT(*psbuf))
1747                 return NULL;
1748
1749         /* Can't 'stat' open directories. */
1750         if(S_ISDIR(psbuf->st_mode))
1751                 return NULL;
1752
1753         fsp = file_new(conn);
1754         if(!fsp)
1755                 return NULL;
1756
1757         DEBUG(5,("open_file_stat: 'opening' file %s\n", fname));
1758
1759         /*
1760          * Setup the files_struct for it.
1761          */
1762         
1763         fsp->mode = psbuf->st_mode;
1764         fsp->inode = psbuf->st_ino;
1765         fsp->dev = psbuf->st_dev;
1766         fsp->vuid = current_user.vuid;
1767         fsp->file_pid = global_smbpid;
1768         fsp->can_lock = False;
1769         fsp->can_read = False;
1770         fsp->can_write = False;
1771         fsp->share_mode = 0;
1772         fsp->desired_access = 0;
1773         fsp->print_file = False;
1774         fsp->modified = False;
1775         fsp->oplock_type = NO_OPLOCK;
1776         fsp->sent_oplock_break = NO_BREAK_SENT;
1777         fsp->is_directory = False;
1778         fsp->is_stat = True;
1779         fsp->directory_delete_on_close = False;
1780         string_set(&fsp->fsp_name,fname);
1781
1782         conn->num_files_open++;
1783
1784         return fsp;
1785 }