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