Fixed the first locking error (test #8 found by locktest code from
[ira/wip.git] / source3 / smbd / open.c
1 /* 
2    Unix SMB/Netbios implementation.
3    Version 1.9.
4    file opening and share modes
5    Copyright (C) Andrew Tridgell 1992-1998
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 int DEBUGLEVEL;
25
26 extern userdom_struct current_user_info;
27 extern uint16 global_oplock_port;
28 extern BOOL global_client_failed_oplock_break;
29
30 /****************************************************************************
31  fd support routines - attempt to do a dos_open.
32 ****************************************************************************/
33
34 static int fd_open(struct connection_struct *conn, char *fname, 
35                    int flags, mode_t mode)
36 {
37         int fd;
38 #ifdef O_NONBLOCK
39         flags |= O_NONBLOCK;
40 #endif
41
42         fd = conn->vfs_ops.open(conn,dos_to_unix(fname,False),flags,mode);
43
44         /* Fix for files ending in '.' */
45         if((fd == -1) && (errno == ENOENT) &&
46            (strchr(fname,'.')==NULL)) {
47                 pstrcat(fname,".");
48                 fd = conn->vfs_ops.open(conn,dos_to_unix(fname,False),flags,mode);
49         }
50
51         DEBUG(10,("fd_open: name %s, flags = 0%o mode = 0%o, fd = %d. %s\n", fname,
52                 flags, (int)mode, fd, (fd == -1) ? strerror(errno) : "" ));
53
54         return fd;
55 }
56
57 /****************************************************************************
58  Close the file associated with a fsp.
59 ****************************************************************************/
60
61 int fd_close(struct connection_struct *conn, files_struct *fsp)
62 {
63         if (fsp->fd == -1)
64                 return -1;
65         return fd_close_posix(conn, fsp);
66 }
67
68
69 /****************************************************************************
70  Check a filename for the pipe string.
71 ****************************************************************************/
72
73 static void check_for_pipe(char *fname)
74 {
75         /* special case of pipe opens */
76         char s[10];
77         StrnCpy(s,fname,sizeof(s)-1);
78         strlower(s);
79         if (strstr(s,"pipe/")) {
80                 DEBUG(3,("Rejecting named pipe open for %s\n",fname));
81                 unix_ERR_class = ERRSRV;
82                 unix_ERR_code = ERRaccess;
83         }
84 }
85
86 /****************************************************************************
87  Open a file.
88 ****************************************************************************/
89
90 static BOOL open_file(files_struct *fsp,connection_struct *conn,
91                       char *fname1,SMB_STRUCT_STAT *psbuf,int flags,mode_t mode)
92 {
93         extern struct current_user current_user;
94         pstring fname;
95         int accmode = (flags & O_ACCMODE);
96         int local_flags = flags;
97
98         fsp->fd = -1;
99         fsp->oplock_type = NO_OPLOCK;
100         errno = EPERM;
101
102         pstrcpy(fname,fname1);
103
104         /* Check permissions */
105
106         /*
107          * This code was changed after seeing a client open request 
108          * containing the open mode of (DENY_WRITE/read-only) with
109          * the 'create if not exist' bit set. The previous code
110          * would fail to open the file read only on a read-only share
111          * as it was checking the flags parameter  directly against O_RDONLY,
112          * this was failing as the flags parameter was set to O_RDONLY|O_CREAT.
113          * JRA.
114          */
115
116         if (!CAN_WRITE(conn)) {
117                 /* It's a read-only share - fail if we wanted to write. */
118                 if(accmode != O_RDONLY) {
119                         DEBUG(3,("Permission denied opening %s\n",fname));
120                         check_for_pipe(fname);
121                         return False;
122                 } else if(flags & O_CREAT) {
123                         /* We don't want to write - but we must make sure that O_CREAT
124                            doesn't create the file if we have write access into the
125                            directory.
126                         */
127                         flags &= ~O_CREAT;
128                 }
129         }
130
131         /*
132          * This little piece of insanity is inspired by the
133          * fact that an NT client can open a file for O_RDONLY,
134          * but set the create disposition to FILE_EXISTS_TRUNCATE.
135          * If the client *can* write to the file, then it expects to
136          * truncate the file, even though it is opening for readonly.
137          * Quicken uses this stupid trick in backup file creation...
138          * Thanks *greatly* to "David W. Chapman Jr." <dwcjr@inethouston.net>
139          * for helping track this one down. It didn't bite us in 2.0.x
140          * as we always opened files read-write in that release. JRA.
141          */
142
143         if ((accmode == O_RDONLY) && ((flags & O_TRUNC) == O_TRUNC))
144                 local_flags = (flags & ~O_ACCMODE)|O_RDWR;
145
146         /*
147          * We can't actually truncate here as the file may be locked.
148          * open_file_shared will take care of the truncate later. JRA.
149          */
150
151         local_flags &= ~O_TRUNC;
152
153         /* actually do the open */
154         fsp->fd = fd_open(conn, fname, local_flags, mode);
155
156         if (fsp->fd == -1)  {
157                 DEBUG(3,("Error opening file %s (%s) (local_flags=%d) (flags=%d)\n",
158                          fname,strerror(errno),local_flags,flags));
159                 check_for_pipe(fname);
160                 return False;
161         }
162
163         if (!VALID_STAT(*psbuf)) {
164                 if (vfs_fstat(fsp,fsp->fd,psbuf) == -1) {
165                         DEBUG(0,("Error doing fstat on open file %s (%s)\n", fname,strerror(errno) ));
166                         fd_close(conn, fsp);
167                         return False;
168                 }
169         }
170
171         /*
172          * POSIX allows read-only opens of directories. We don't
173          * want to do this (we use a different code path for this)
174          * so catch a directory open and return an EISDIR. JRA.
175          */
176
177         if(S_ISDIR(psbuf->st_mode)) {
178                 fd_close(conn, fsp);
179                 errno = EISDIR;
180                 return False;
181         }
182
183         fsp->mode = psbuf->st_mode;
184         fsp->inode = psbuf->st_ino;
185         fsp->dev = psbuf->st_dev;
186         GetTimeOfDay(&fsp->open_time);
187         fsp->vuid = current_user.vuid;
188         fsp->size = psbuf->st_size;
189         fsp->pos = -1;
190         fsp->can_lock = True;
191         fsp->can_read = ((flags & O_WRONLY)==0);
192         fsp->can_write = ((flags & (O_WRONLY|O_RDWR))!=0);
193         fsp->share_mode = 0;
194         fsp->print_file = False;
195         fsp->modified = False;
196         fsp->oplock_type = NO_OPLOCK;
197         fsp->sent_oplock_break = NO_BREAK_SENT;
198         fsp->is_directory = False;
199         fsp->stat_open = False;
200         fsp->directory_delete_on_close = False;
201         fsp->conn = conn;
202         /*
203          * Note that the file name here is the *untranslated* name
204          * ie. it is still in the DOS codepage sent from the client.
205          * All use of this filename will pass though the sys_xxxx
206          * functions which will do the dos_to_unix translation before
207          * mapping into a UNIX filename. JRA.
208          */
209         string_set(&fsp->fsp_name,fname);
210         fsp->wbmpx_ptr = NULL;      
211         fsp->wcp = NULL; /* Write cache pointer. */
212
213         DEBUG(2,("%s opened file %s read=%s write=%s (numopen=%d)\n",
214                  *current_user_info.smb_name ? current_user_info.smb_name : conn->user,fsp->fsp_name,
215                  BOOLSTR(fsp->can_read), BOOLSTR(fsp->can_write),
216                  conn->num_files_open + 1));
217
218         /*
219          * Take care of inherited ACLs on created files. JRA.
220          */
221
222         if ((flags & O_CREAT) && (conn->vfs_ops.fchmod_acl != NULL)) {
223                 int saved_errno = errno; /* We might get ENOSYS in the next call.. */
224                 if (conn->vfs_ops.fchmod_acl(fsp, fsp->fd, mode) == -1 && errno == ENOSYS)
225                         errno = saved_errno; /* Ignore ENOSYS */
226         }
227                 
228         return True;
229 }
230
231 /****************************************************************************
232   C. Hoch 11/22/95
233   Helper for open_file_shared. 
234   Truncate a file after checking locking; close file if locked.
235   **************************************************************************/
236
237 static int truncate_unless_locked(struct connection_struct *conn, files_struct *fsp)
238 {
239         SMB_BIG_UINT mask = (SMB_BIG_UINT)-1;
240
241         if (is_locked(fsp,fsp->conn,mask,0,WRITE_LOCK,True)){
242                 errno = EACCES;
243                 unix_ERR_class = ERRDOS;
244                 unix_ERR_code = ERRlock;
245                 return -1;
246         } else {
247                 return conn->vfs_ops.ftruncate(fsp,fsp->fd,0); 
248         }
249 }
250
251 /*******************************************************************
252 return True if the filename is one of the special executable types
253 ********************************************************************/
254 static BOOL is_executable(const char *fname)
255 {
256         if ((fname = strrchr(fname,'.'))) {
257                 if (strequal(fname,".com") ||
258                     strequal(fname,".dll") ||
259                     strequal(fname,".exe") ||
260                     strequal(fname,".sym")) {
261                         return True;
262                 }
263         }
264         return False;
265 }
266
267 enum {AFAIL,AREAD,AWRITE,AALL};
268
269 /*******************************************************************
270 reproduce the share mode access table
271 this is horrendoously complex, and really can't be justified on any
272 rational grounds except that this is _exactly_ what NT does. See
273 the DENY1 and DENY2 tests in smbtorture for a comprehensive set of
274 test routines.
275 ********************************************************************/
276 static int access_table(int new_deny,int old_deny,int old_mode,
277                         BOOL same_pid, BOOL isexe)
278 {
279           if (new_deny == DENY_ALL || old_deny == DENY_ALL) return(AFAIL);
280
281           if (same_pid) {
282                   if (isexe && old_mode == DOS_OPEN_RDONLY && 
283                       old_deny == DENY_DOS && new_deny == DENY_READ) {
284                           return AFAIL;
285                   }
286                   if (!isexe && old_mode == DOS_OPEN_RDONLY && 
287                       old_deny == DENY_DOS && new_deny == DENY_DOS) {
288                           return AREAD;
289                   }
290                   if (new_deny == DENY_FCB && old_deny == DENY_DOS) {
291                           if (isexe) return AFAIL;
292                           if (old_mode == DOS_OPEN_RDONLY) return AFAIL;
293                           return AALL;
294                   }
295                   if (old_mode == DOS_OPEN_RDONLY && old_deny == DENY_DOS) {
296                           if (new_deny == DENY_FCB || new_deny == DENY_READ) {
297                                   if (isexe) return AREAD;
298                                   return AFAIL;
299                           }
300                   }
301                   if (old_deny == DENY_FCB) {
302                           if (new_deny == DENY_DOS || new_deny == DENY_FCB) return AALL;
303                           return AFAIL;
304                   }
305           }
306
307           if (old_deny == DENY_DOS || new_deny == DENY_DOS || 
308               old_deny == DENY_FCB || new_deny == DENY_FCB) {
309                   if (isexe) {
310                           if (old_deny == DENY_FCB || new_deny == DENY_FCB) {
311                                   return AFAIL;
312                           }
313                           if (old_deny == DENY_DOS) {
314                                   if (new_deny == DENY_READ && 
315                                       (old_mode == DOS_OPEN_RDONLY || 
316                                        old_mode == DOS_OPEN_RDWR)) {
317                                           return AFAIL;
318                                   }
319                                   if (new_deny == DENY_WRITE && 
320                                       (old_mode == DOS_OPEN_WRONLY || 
321                                        old_mode == DOS_OPEN_RDWR)) {
322                                           return AFAIL;
323                                   }
324                                   return AALL;
325                           }
326                           if (old_deny == DENY_NONE) return AALL;
327                           if (old_deny == DENY_READ) return AWRITE;
328                           if (old_deny == DENY_WRITE) return AREAD;
329                   }
330                   /* it isn't a exe, dll, sym or com file */
331                   if (old_deny == new_deny && same_pid)
332                           return(AALL);    
333
334                   if (old_deny == DENY_READ || new_deny == DENY_READ) return AFAIL;
335                   if (old_mode == DOS_OPEN_RDONLY) return(AREAD);
336                   
337                   return(AFAIL);
338           }
339           
340           switch (new_deny) 
341                   {
342                   case DENY_WRITE:
343                           if (old_deny==DENY_WRITE && old_mode==DOS_OPEN_RDONLY) return(AREAD);
344                           if (old_deny==DENY_READ && old_mode==DOS_OPEN_RDONLY) return(AWRITE);
345                           if (old_deny==DENY_NONE && old_mode==DOS_OPEN_RDONLY) return(AALL);
346                           return(AFAIL);
347                   case DENY_READ:
348                           if (old_deny==DENY_WRITE && old_mode==DOS_OPEN_WRONLY) return(AREAD);
349                           if (old_deny==DENY_READ && old_mode==DOS_OPEN_WRONLY) return(AWRITE);
350                           if (old_deny==DENY_NONE && old_mode==DOS_OPEN_WRONLY) return(AALL);
351                           return(AFAIL);
352                   case DENY_NONE:
353                           if (old_deny==DENY_WRITE) return(AREAD);
354                           if (old_deny==DENY_READ) return(AWRITE);
355                           if (old_deny==DENY_NONE) return(AALL);
356                           return(AFAIL);      
357                   }
358           return(AFAIL);      
359 }
360
361
362 /****************************************************************************
363 check if we can open a file with a share mode
364 ****************************************************************************/
365
366 static int check_share_mode( share_mode_entry *share, int share_mode, 
367                              const char *fname, BOOL fcbopen, int *flags)
368 {
369         int deny_mode = GET_DENY_MODE(share_mode);
370         int old_open_mode = GET_OPEN_MODE(share->share_mode);
371         int old_deny_mode = GET_DENY_MODE(share->share_mode);
372
373         /*
374          * Don't allow any opens once the delete on close flag has been
375          * set.
376          */
377
378         if (GET_DELETE_ON_CLOSE_FLAG(share->share_mode)) {
379                 DEBUG(5,("check_share_mode: Failing open on file %s as delete on close flag is set.\n",
380                         fname ));
381                 unix_ERR_class = ERRDOS;
382                 unix_ERR_code = ERRnoaccess;
383                 return False;
384         }
385
386         /*
387          * If delete access was requested and the existing share mode doesn't have
388          * ALLOW_SHARE_DELETE then deny.
389          */
390
391         if (GET_DELETE_ACCESS_REQUESTED(share_mode) && !GET_ALLOW_SHARE_DELETE(share->share_mode)) {
392                 DEBUG(5,("check_share_mode: Failing open on file %s as delete access requested and allow share delete not set.\n",
393                         fname ));
394                 unix_ERR_class = ERRDOS;
395                 unix_ERR_code = ERRbadshare;
396
397                 return False;
398         }
399
400         /*
401          * The inverse of the above.
402          * If delete access was granted and the new share mode doesn't have
403          * ALLOW_SHARE_DELETE then deny.
404          */
405
406         if (GET_DELETE_ACCESS_REQUESTED(share->share_mode) && !GET_ALLOW_SHARE_DELETE(share_mode)) {
407                 DEBUG(5,("check_share_mode: Failing open on file %s as delete access granted and allow share delete not requested.\n",
408                         fname ));
409                 unix_ERR_class = ERRDOS;
410                 unix_ERR_code = ERRbadshare;
411
412                 return False;
413         }
414
415         {
416                 int access_allowed = access_table(deny_mode,old_deny_mode,old_open_mode,
417                                                                                 (share->pid == sys_getpid()),is_executable(fname));
418
419                 if ((access_allowed == AFAIL) ||
420                         (!fcbopen && (access_allowed == AREAD && *flags == O_RDWR)) ||
421                         (access_allowed == AREAD && *flags != O_RDONLY) ||
422                         (access_allowed == AWRITE && *flags != O_WRONLY)) {
423
424                         DEBUG(2,("Share violation on file (%d,%d,%d,%d,%s,fcbopen = %d, flags = %d) = %d\n",
425                                 deny_mode,old_deny_mode,old_open_mode,
426                                 (int)share->pid,fname, fcbopen, *flags, access_allowed));
427
428                         unix_ERR_class = ERRDOS;
429                         unix_ERR_code = ERRbadshare;
430
431                         return False;
432                 }
433
434                 if (access_allowed == AREAD)
435                         *flags = O_RDONLY;
436
437                 if (access_allowed == AWRITE)
438                         *flags = O_WRONLY;
439
440         }
441
442         return True;
443 }
444
445 /****************************************************************************
446  Deal with open deny mode and oplock break processing.
447  Invarient: Share mode must be locked on entry and exit.
448  Returns -1 on error, or number of share modes on success (may be zero).
449 ****************************************************************************/
450
451 static int open_mode_check(connection_struct *conn, const char *fname, SMB_DEV_T dev,
452                                                         SMB_INO_T inode, int share_mode, int *p_flags, int *p_oplock_request,
453                                                         BOOL *p_all_current_opens_are_level_II)
454 {
455   int i;
456   int num_share_modes;
457   int oplock_contention_count = 0;
458   share_mode_entry *old_shares = 0;
459   BOOL fcbopen = False;
460   BOOL broke_oplock;    
461
462   if(GET_OPEN_MODE(share_mode) == DOS_OPEN_FCB)
463     fcbopen = True;
464
465   num_share_modes = get_share_modes(conn, dev, inode, &old_shares);
466
467   if(num_share_modes == 0)
468     return 0;
469
470   /*
471    * Check if the share modes will give us access.
472    */
473
474   do {
475
476     broke_oplock = False;
477     *p_all_current_opens_are_level_II = True;
478
479     for(i = 0; i < num_share_modes; i++) {
480       share_mode_entry *share_entry = &old_shares[i];
481
482       /* 
483        * By observation of NetBench, oplocks are broken *before* share
484        * modes are checked. This allows a file to be closed by the client
485        * if the share mode would deny access and the client has an oplock. 
486        * Check if someone has an oplock on this file. If so we must break 
487        * it before continuing. 
488        */
489
490       if((*p_oplock_request && EXCLUSIVE_OPLOCK_TYPE(share_entry->op_type)) ||
491          (!*p_oplock_request && (share_entry->op_type != NO_OPLOCK))) {
492
493         BOOL opb_ret;
494
495         DEBUG(5,("open_mode_check: oplock_request = %d, breaking oplock (%x) on file %s, \
496 dev = %x, inode = %.0f\n", *p_oplock_request, share_entry->op_type, fname, (unsigned int)dev, (double)inode));
497
498         /* Oplock break - unlock to request it. */
499         unlock_share_entry(conn, dev, inode);
500
501         opb_ret = request_oplock_break(share_entry, dev, inode);
502
503         /* Now relock. */
504         lock_share_entry(conn, dev, inode);
505
506         if(opb_ret == False) {
507           free((char *)old_shares);
508           DEBUG(0,("open_mode_check: FAILED when breaking oplock (%x) on file %s, \
509 dev = %x, inode = %.0f\n", old_shares[i].op_type, fname, (unsigned int)dev, (double)inode));
510           errno = EACCES;
511           unix_ERR_class = ERRDOS;
512           unix_ERR_code = ERRbadshare;
513           return -1;
514         }
515
516         broke_oplock = True;
517         *p_all_current_opens_are_level_II = False;
518         break;
519
520       } else if (!LEVEL_II_OPLOCK_TYPE(share_entry->op_type)) {
521         *p_all_current_opens_are_level_II = False;
522       }
523
524       /* someone else has a share lock on it, check to see 
525          if we can too */
526
527       if(check_share_mode(share_entry, share_mode, fname, fcbopen, p_flags) == False) {
528         free((char *)old_shares);
529         errno = EACCES;
530         return -1;
531       }
532
533     } /* end for */
534
535     if(broke_oplock) {
536       free((char *)old_shares);
537       num_share_modes = get_share_modes(conn, dev, inode, &old_shares);
538       oplock_contention_count++;
539     }
540   } while(broke_oplock);
541
542   if(old_shares != 0)
543     free((char *)old_shares);
544
545   /*
546    * Refuse to grant an oplock in case the contention limit is
547    * reached when going through the lock list multiple times.
548    */
549
550   if(oplock_contention_count >= lp_oplock_contention_limit(SNUM(conn))) {
551     *p_oplock_request = 0;
552     DEBUG(4,("open_mode_check: oplock contention = %d. Not granting oplock.\n",
553           oplock_contention_count ));
554   }
555
556   return num_share_modes;
557 }
558
559 /****************************************************************************
560 set a kernel flock on a file for NFS interoperability
561 this requires a patch to Linux
562 ****************************************************************************/
563 static void kernel_flock(files_struct *fsp, int deny_mode)
564 {
565 #if HAVE_KERNEL_SHARE_MODES
566         int kernel_mode = 0;
567         if (deny_mode == DENY_READ) kernel_mode = LOCK_MAND|LOCK_WRITE;
568         else if (deny_mode == DENY_WRITE) kernel_mode = LOCK_MAND|LOCK_READ;
569         else if (deny_mode == DENY_ALL) kernel_mode = LOCK_MAND;
570         if (kernel_mode) flock(fsp->fd, kernel_mode);
571 #endif
572 }
573
574
575 /****************************************************************************
576  Open a file with a share mode. On output from this open we are guarenteeing
577  that 
578 ****************************************************************************/
579 files_struct *open_file_shared(connection_struct *conn,char *fname, SMB_STRUCT_STAT *psbuf, 
580                                 int share_mode,int ofun, mode_t mode,int oplock_request, int *Access,int *action)
581 {
582         int flags=0;
583         int flags2=0;
584         int deny_mode = GET_DENY_MODE(share_mode);
585         BOOL allow_share_delete = GET_ALLOW_SHARE_DELETE(share_mode);
586         BOOL delete_access_requested = GET_DELETE_ACCESS_REQUESTED(share_mode);
587         BOOL file_existed = VALID_STAT(*psbuf);
588         BOOL fcbopen = False;
589         SMB_DEV_T dev = 0;
590         SMB_INO_T inode = 0;
591         int num_share_modes = 0;
592         BOOL all_current_opens_are_level_II = False;
593         BOOL fsp_open = False;
594         files_struct *fsp = NULL;
595         int open_mode=0;
596         uint16 port = 0;
597
598         if (conn->printer) {
599                 /* printers are handled completely differently. Most of the passed parameters are
600                         ignored */
601                 *Access = DOS_OPEN_WRONLY;
602                 *action = FILE_WAS_CREATED;
603                 return print_fsp_open(conn);
604         }
605
606         fsp = file_new(conn);
607         if(!fsp)
608                 return NULL;
609
610         DEBUG(10,("open_file_shared: fname = %s, share_mode = %x, ofun = %x, mode = %o, oplock request = %d\n",
611                 fname, share_mode, ofun, (int)mode,  oplock_request ));
612
613         if (!check_name(fname,conn)) {
614                 file_free(fsp);
615                 return NULL;
616         } 
617
618         /* ignore any oplock requests if oplocks are disabled */
619         if (!lp_oplocks(SNUM(conn)) || global_client_failed_oplock_break) {
620                 oplock_request = 0;
621         }
622
623         /* this is for OS/2 EAs - try and say we don't support them */
624         if (strstr(fname,".+,;=[].")) {
625                 unix_ERR_class = ERRDOS;
626                 /* OS/2 Workplace shell fix may be main code stream in a later release. */ 
627 #if 1 /* OS2_WPS_FIX - Recent versions of OS/2 need this. */
628                 unix_ERR_code = ERRcannotopen;
629 #else /* OS2_WPS_FIX */
630                 unix_ERR_code = ERROR_EAS_NOT_SUPPORTED;
631 #endif /* OS2_WPS_FIX */
632
633                 DEBUG(5,("open_file_shared: OS/2 EA's are not supported.\n"));
634                 file_free(fsp);
635                 return NULL;
636         }
637
638         if ((GET_FILE_OPEN_DISPOSITION(ofun) == FILE_EXISTS_FAIL) && file_existed)  {
639                 DEBUG(5,("open_file_shared: create new requested for file %s and file already exists.\n",
640                         fname ));
641                 file_free(fsp);
642                 errno = EEXIST;
643                 return NULL;
644         }
645       
646         if (GET_FILE_CREATE_DISPOSITION(ofun) == FILE_CREATE_IF_NOT_EXIST)
647                 flags2 |= O_CREAT;
648
649         if (GET_FILE_OPEN_DISPOSITION(ofun) == FILE_EXISTS_TRUNCATE)
650                 flags2 |= O_TRUNC;
651
652         if (GET_FILE_OPEN_DISPOSITION(ofun) == FILE_EXISTS_FAIL)
653                 flags2 |= O_EXCL;
654
655         /* note that we ignore the append flag as 
656                 append does not mean the same thing under dos and unix */
657
658         switch (GET_OPEN_MODE(share_mode)) {
659                 case DOS_OPEN_WRONLY: 
660                         flags = O_WRONLY; 
661                         break;
662                 case DOS_OPEN_FCB: 
663                         fcbopen = True;
664                         flags = O_RDWR; 
665                         break;
666                 case DOS_OPEN_RDWR: 
667                         flags = O_RDWR; 
668                         break;
669                 default:
670                         flags = O_RDONLY;
671                         break;
672         }
673
674 #if defined(O_SYNC)
675         if (GET_FILE_SYNC_OPENMODE(share_mode)) {
676                 flags2 |= O_SYNC;
677         }
678 #endif /* O_SYNC */
679   
680         if (flags != O_RDONLY && file_existed && 
681                         (!CAN_WRITE(conn) || IS_DOS_READONLY(dos_mode(conn,fname,psbuf)))) {
682                 if (!fcbopen) {
683                         DEBUG(5,("open_file_shared: read/write access requested for file %s on read only %s\n",
684                                 fname, !CAN_WRITE(conn) ? "share" : "file" ));
685                         file_free(fsp);
686                         errno = EACCES;
687                         return NULL;
688                 }
689                 flags = O_RDONLY;
690         }
691
692         if (deny_mode > DENY_NONE && deny_mode!=DENY_FCB) {
693                 DEBUG(2,("Invalid deny mode %d on file %s\n",deny_mode,fname));
694                 file_free(fsp);
695                 errno = EINVAL;
696                 return NULL;
697         }
698
699         if (file_existed) {
700
701                 dev = psbuf->st_dev;
702                 inode = psbuf->st_ino;
703
704                 lock_share_entry(conn, dev, inode);
705
706                 num_share_modes = open_mode_check(conn, fname, dev, inode, share_mode,
707                                                                 &flags, &oplock_request, &all_current_opens_are_level_II);
708                 if(num_share_modes == -1) {
709
710                         /*
711                          * This next line is a subtlety we need for MS-Access. If a file open will
712                          * fail due to share permissions and also for security (access)
713                          * reasons, we need to return the access failed error, not the
714                          * share error. This means we must attempt to open the file anyway
715                          * in order to get the UNIX access error - even if we're going to
716                          * fail the open for share reasons. This is bad, as we're burning
717                          * another fd if there are existing locks but there's nothing else
718                          * we can do. We also ensure we're not going to create or tuncate
719                          * the file as we only want an access decision at this stage. JRA.
720                          */
721                         fsp_open = open_file(fsp,conn,fname,psbuf,flags|(flags2&~(O_TRUNC|O_CREAT)),mode);
722
723                         DEBUG(4,("open_file_shared : share_mode deny - calling open_file with \
724 flags=0x%X flags2=0x%X mode=0%o returned %d\n",
725                                 flags,(flags2&~(O_TRUNC|O_CREAT)),(int)mode,(int)fsp_open ));
726
727                         unlock_share_entry(conn, dev, inode);
728                         if (fsp_open)
729                                 fd_close(conn, fsp);
730                         file_free(fsp);
731                         return NULL;
732                 }
733
734                 /*
735                  * We exit this block with the share entry *locked*.....
736                  */
737         }
738
739         DEBUG(4,("calling open_file with flags=0x%X flags2=0x%X mode=0%o\n",
740                         flags,flags2,(int)mode));
741
742         /*
743          * open_file strips any O_TRUNC flags itself.
744          */
745
746         fsp_open = open_file(fsp,conn,fname,psbuf,flags|flags2,mode);
747
748         if (!fsp_open && (flags == O_RDWR) && (errno != ENOENT) && fcbopen) {
749                 if((fsp_open = open_file(fsp,conn,fname,psbuf,O_RDONLY,mode)) == True)
750                         flags = O_RDONLY;
751         }
752
753         if (!fsp_open) {
754                 if(file_existed)
755                         unlock_share_entry(conn, dev, inode);
756                 file_free(fsp);
757                 return NULL;
758         }
759
760         /*
761          * Deal with the race condition where two smbd's detect the file doesn't
762          * exist and do the create at the same time. One of them will win and
763          * set a share mode, the other (ie. this one) should check if the
764          * requested share mode for this create is allowed.
765          */
766
767         if (!file_existed) { 
768
769                 lock_share_entry_fsp(fsp);
770
771                 num_share_modes = open_mode_check(conn, fname, dev, inode, share_mode,
772                                                                 &flags, &oplock_request, &all_current_opens_are_level_II);
773
774                 if(num_share_modes == -1) {
775                         unlock_share_entry_fsp(fsp);
776                         fd_close(conn,fsp);
777                         file_free(fsp);
778                         return NULL;
779                 }
780
781                 /*
782                  * We exit this block with the share entry *locked*.....
783                  */
784         }
785
786         /* note that we ignore failure for the following. It is
787            basically a hack for NFS, and NFS will never set one of
788            these only read them. Nobody but Samba can ever set a deny
789            mode and we have already checked our more authoritative
790            locking database for permission to set this deny mode. If
791            the kernel refuses the operations then the kernel is wrong */
792         kernel_flock(fsp, deny_mode);
793
794         /*
795          * At this point onwards, we can guarentee that the share entry
796          * is locked, whether we created the file or not, and that the
797          * deny mode is compatible with all current opens.
798          */
799
800         /*
801          * If requested, truncate the file.
802          */
803
804         if (flags2&O_TRUNC) {
805                 /*
806                  * We are modifing the file after open - update the stat struct..
807                  */
808                 if ((truncate_unless_locked(conn,fsp) == -1) || (vfs_fstat(fsp,fsp->fd,psbuf)==-1)) {
809                         unlock_share_entry_fsp(fsp);
810                         fd_close(conn,fsp);
811                         file_free(fsp);
812                         return NULL;
813                 }
814         }
815
816         switch (flags) {
817                 case O_RDONLY:
818                         open_mode = DOS_OPEN_RDONLY;
819                         break;
820                 case O_RDWR:
821                         open_mode = DOS_OPEN_RDWR;
822                         break;
823                 case O_WRONLY:
824                         open_mode = DOS_OPEN_WRONLY;
825                         break;
826         }
827
828         fsp->share_mode = SET_DENY_MODE(deny_mode) | 
829                                                 SET_OPEN_MODE(open_mode) | 
830                                                 SET_ALLOW_SHARE_DELETE(allow_share_delete) |
831                                                 SET_DELETE_ACCESS_REQUESTED(delete_access_requested);
832
833         DEBUG(10,("open_file_shared : share_mode = %x\n", fsp->share_mode ));
834
835         if (Access)
836                 (*Access) = open_mode;
837
838         if (action) {
839                 if (file_existed && !(flags2 & O_TRUNC))
840                         *action = FILE_WAS_OPENED;
841                 if (!file_existed)
842                         *action = FILE_WAS_CREATED;
843                 if (file_existed && (flags2 & O_TRUNC))
844                         *action = FILE_WAS_OVERWRITTEN;
845         }
846
847         /* 
848          * Setup the oplock info in both the shared memory and
849          * file structs.
850          */
851
852         if(oplock_request && (num_share_modes == 0) && 
853                         !IS_VETO_OPLOCK_PATH(conn,fname) && set_file_oplock(fsp, oplock_request) ) {
854                 port = global_oplock_port;
855         } else if (oplock_request && all_current_opens_are_level_II) {
856                 port = global_oplock_port;
857                 oplock_request = LEVEL_II_OPLOCK;
858                 set_file_oplock(fsp, oplock_request);
859         } else {
860                 port = 0;
861                 oplock_request = 0;
862         }
863
864         set_share_mode(fsp, port, oplock_request);
865
866         unlock_share_entry_fsp(fsp);
867
868         conn->num_files_open++;
869
870         return fsp;
871 }
872
873 /****************************************************************************
874  Open a file for permissions read only. Return a pseudo file entry
875  with the 'stat_open' flag set 
876 ****************************************************************************/
877
878 files_struct *open_file_stat(connection_struct *conn, char *fname,
879                                                         SMB_STRUCT_STAT *psbuf, int smb_ofun, int *action)
880 {
881         extern struct current_user current_user;
882         files_struct *fsp = NULL;
883
884         if (!VALID_STAT(*psbuf)) {
885                 DEBUG(0,("open_file_stat: unable to stat name = %s. Error was %s\n", fname, strerror(errno) ));
886                 return NULL;
887         }
888
889         if(S_ISDIR(psbuf->st_mode)) {
890                 DEBUG(0,("open_file_stat: %s is a directory !\n", fname ));
891                 return NULL;
892         }
893
894         fsp = file_new(conn);
895         if(!fsp)
896                 return NULL;
897
898         *action = FILE_WAS_OPENED;
899         
900         DEBUG(5,("open_file_stat: opening file %s as a stat entry\n", fname));
901
902         /*
903          * Setup the files_struct for it.
904          */
905         
906         fsp->fd = -1;
907         fsp->mode = psbuf->st_mode;
908         fsp->inode = psbuf->st_ino;
909         fsp->dev = psbuf->st_dev;
910         GetTimeOfDay(&fsp->open_time);
911         fsp->size = psbuf->st_size;
912         fsp->vuid = current_user.vuid;
913         fsp->pos = -1;
914         fsp->can_lock = False;
915         fsp->can_read = False;
916         fsp->can_write = False;
917         fsp->share_mode = 0;
918         fsp->print_file = False;
919         fsp->modified = False;
920         fsp->oplock_type = NO_OPLOCK;
921         fsp->sent_oplock_break = NO_BREAK_SENT;
922         fsp->is_directory = False;
923         fsp->stat_open = True;
924         fsp->directory_delete_on_close = False;
925         fsp->conn = conn;
926         /*
927          * Note that the file name here is the *untranslated* name
928          * ie. it is still in the DOS codepage sent from the client.
929          * All use of this filename will pass though the sys_xxxx
930          * functions which will do the dos_to_unix translation before
931          * mapping into a UNIX filename. JRA.
932          */
933         string_set(&fsp->fsp_name,fname);
934         fsp->wbmpx_ptr = NULL;
935     fsp->wcp = NULL; /* Write cache pointer. */
936
937         conn->num_files_open++;
938
939         return fsp;
940 }
941
942 /****************************************************************************
943  Open a file for for write to ensure that we can fchmod it.
944 ****************************************************************************/
945
946 files_struct *open_file_fchmod(connection_struct *conn, char *fname, SMB_STRUCT_STAT *psbuf)
947 {
948         files_struct *fsp = NULL;
949         BOOL fsp_open;
950
951         if (!VALID_STAT(*psbuf))
952                 return NULL;
953
954         fsp = file_new(conn);
955         if(!fsp)
956                 return NULL;
957
958         fsp_open = open_file(fsp,conn,fname,psbuf,O_WRONLY,0);
959
960         /* 
961          * This is not a user visible file open.
962          * Don't set a share mode and don't increment
963          * the conn->num_files_open.
964          */
965
966         if (!fsp_open) {
967                 file_free(fsp);
968                 return NULL;
969         }
970
971         return fsp;
972 }
973
974 /****************************************************************************
975  Close the fchmod file fd - ensure no locks are lost.
976 ****************************************************************************/
977
978 int close_file_fchmod(files_struct *fsp)
979 {
980         int ret = fd_close(fsp->conn, fsp);
981         file_free(fsp);
982         return ret;
983 }
984
985 /****************************************************************************
986  Open a directory from an NT SMB call.
987 ****************************************************************************/
988
989 files_struct *open_directory(connection_struct *conn, char *fname,
990                                                         SMB_STRUCT_STAT *psbuf, int smb_ofun, mode_t unixmode, int *action)
991 {
992         extern struct current_user current_user;
993         BOOL got_stat = False;
994         files_struct *fsp = file_new(conn);
995
996         if(!fsp)
997                 return NULL;
998
999         fsp->conn = conn; /* The vfs_fXXX() macros need this. */
1000
1001         if (VALID_STAT(*psbuf))
1002                 got_stat = True;
1003
1004         if (got_stat && (GET_FILE_OPEN_DISPOSITION(smb_ofun) == FILE_EXISTS_FAIL)) {
1005                 file_free(fsp);
1006                 errno = EEXIST; /* Setup so correct error is returned to client. */
1007                 return NULL;
1008         }
1009
1010         if (GET_FILE_CREATE_DISPOSITION(smb_ofun) == FILE_CREATE_IF_NOT_EXIST) {
1011
1012                 if (got_stat) {
1013
1014                         if(!S_ISDIR(psbuf->st_mode)) {
1015                                 DEBUG(0,("open_directory: %s is not a directory !\n", fname ));
1016                                 file_free(fsp);
1017                                 errno = EACCES;
1018                                 return NULL;
1019                         }
1020                         *action = FILE_WAS_OPENED;
1021
1022                 } else {
1023
1024                         /*
1025                          * Try and create the directory.
1026                          */
1027
1028                         if(!CAN_WRITE(conn)) {
1029                                 DEBUG(2,("open_directory: failing create on read-only share\n"));
1030                                 file_free(fsp);
1031                                 errno = EACCES;
1032                                 return NULL;
1033                         }
1034
1035                         if(vfs_mkdir(conn,fname, unix_mode(conn,aDIR, fname)) < 0) {
1036                                 DEBUG(0,("open_directory: unable to create %s. Error was %s\n",
1037                                          fname, strerror(errno) ));
1038                                 file_free(fsp);
1039                                 return NULL;
1040                         }
1041
1042                         if(vfs_stat(conn,fname, psbuf) != 0) {
1043                                 file_free(fsp);
1044                                 return NULL;
1045                         }
1046
1047                         *action = FILE_WAS_CREATED;
1048
1049                 }
1050         } else {
1051
1052                 /*
1053                  * Don't create - just check that it *was* a directory.
1054                  */
1055
1056                 if(!got_stat) {
1057                         DEBUG(0,("open_directory: unable to stat name = %s. Error was %s\n",
1058                                  fname, strerror(errno) ));
1059                         file_free(fsp);
1060                         return NULL;
1061                 }
1062
1063                 if(!S_ISDIR(psbuf->st_mode)) {
1064                         DEBUG(0,("open_directory: %s is not a directory !\n", fname ));
1065                         file_free(fsp);
1066                         return NULL;
1067                 }
1068
1069                 *action = FILE_WAS_OPENED;
1070         }
1071         
1072         DEBUG(5,("open_directory: opening directory %s\n", fname));
1073
1074         /*
1075          * Setup the files_struct for it.
1076          */
1077         
1078         fsp->fd = -1;
1079         fsp->mode = psbuf->st_mode;
1080         fsp->inode = psbuf->st_ino;
1081         fsp->dev = psbuf->st_dev;
1082         GetTimeOfDay(&fsp->open_time);
1083         fsp->size = psbuf->st_size;
1084         fsp->vuid = current_user.vuid;
1085         fsp->pos = -1;
1086         fsp->can_lock = True;
1087         fsp->can_read = False;
1088         fsp->can_write = False;
1089         fsp->share_mode = 0;
1090         fsp->print_file = False;
1091         fsp->modified = False;
1092         fsp->oplock_type = NO_OPLOCK;
1093         fsp->sent_oplock_break = NO_BREAK_SENT;
1094         fsp->is_directory = True;
1095         fsp->directory_delete_on_close = False;
1096         fsp->conn = conn;
1097         /*
1098          * Note that the file name here is the *untranslated* name
1099          * ie. it is still in the DOS codepage sent from the client.
1100          * All use of this filename will pass though the sys_xxxx
1101          * functions which will do the dos_to_unix translation before
1102          * mapping into a UNIX filename. JRA.
1103          */
1104         string_set(&fsp->fsp_name,fname);
1105         fsp->wbmpx_ptr = NULL;
1106
1107         conn->num_files_open++;
1108
1109         return fsp;
1110 }
1111
1112 /*******************************************************************
1113  Check if the share mode on a file allows it to be deleted or unlinked.
1114  Return True if sharing doesn't prevent the operation.
1115 ********************************************************************/
1116
1117 BOOL check_file_sharing(connection_struct *conn,char *fname, BOOL rename_op)
1118 {
1119   int i;
1120   int ret = False;
1121   share_mode_entry *old_shares = 0;
1122   int num_share_modes;
1123   SMB_STRUCT_STAT sbuf;
1124   pid_t pid = sys_getpid();
1125   SMB_DEV_T dev;
1126   SMB_INO_T inode;
1127
1128   if (vfs_stat(conn,fname,&sbuf) == -1)
1129     return(True);
1130
1131   dev = sbuf.st_dev;
1132   inode = sbuf.st_ino;
1133
1134   lock_share_entry(conn, dev, inode);
1135   num_share_modes = get_share_modes(conn, dev, inode, &old_shares);
1136
1137   /*
1138    * Check if the share modes will give us access.
1139    */
1140
1141   if(num_share_modes != 0)
1142   {
1143     BOOL broke_oplock;
1144
1145     do
1146     {
1147
1148       broke_oplock = False;
1149       for(i = 0; i < num_share_modes; i++)
1150       {
1151         share_mode_entry *share_entry = &old_shares[i];
1152
1153         /* 
1154          * Break oplocks before checking share modes. See comment in
1155          * open_file_shared for details. 
1156          * Check if someone has an oplock on this file. If so we must 
1157          * break it before continuing. 
1158          */
1159         if(BATCH_OPLOCK_TYPE(share_entry->op_type))
1160         {
1161
1162 #if 0
1163
1164 /* JRA. Try removing this code to see if the new oplock changes
1165    fix the problem. I'm dubious, but Andrew is recommending we
1166    try this....
1167 */
1168
1169           /*
1170            * It appears that the NT redirector may have a bug, in that
1171            * it tries to do an SMBmv on a file that it has open with a
1172            * batch oplock, and then fails to respond to the oplock break
1173            * request. This only seems to occur when the client is doing an
1174            * SMBmv to the smbd it is using - thus we try and detect this
1175            * condition by checking if the file being moved is open and oplocked by
1176            * this smbd process, and then not sending the oplock break in this
1177            * special case. If the file was open with a deny mode that 
1178            * prevents the move the SMBmv will fail anyway with a share
1179            * violation error. JRA.
1180            */
1181           if(rename_op && (share_entry->pid == pid))
1182           {
1183
1184             DEBUG(0,("check_file_sharing: NT redirector workaround - rename attempted on \
1185 batch oplocked file %s, dev = %x, inode = %.0f\n", fname, (unsigned int)dev, (double)inode));
1186
1187             /* 
1188              * This next line is a test that allows the deny-mode
1189              * processing to be skipped. This seems to be needed as
1190              * NT insists on the rename succeeding (in Office 9x no less !).
1191              * This should be removed as soon as (a) MS fix the redirector
1192              * bug or (b) NT SMB support in Samba makes NT not issue the
1193              * call (as is my fervent hope). JRA.
1194              */ 
1195             continue;
1196           }
1197           else
1198 #endif /* 0 */
1199           {
1200
1201             DEBUG(5,("check_file_sharing: breaking oplock (%x) on file %s, \
1202 dev = %x, inode = %.0f\n", share_entry->op_type, fname, (unsigned int)dev, (double)inode));
1203
1204             /* Oplock break.... */
1205             unlock_share_entry(conn, dev, inode);
1206             if(request_oplock_break(share_entry, dev, inode) == False)
1207             {
1208               free((char *)old_shares);
1209
1210               DEBUG(0,("check_file_sharing: FAILED when breaking oplock (%x) on file %s, \
1211 dev = %x, inode = %.0f\n", old_shares[i].op_type, fname, (unsigned int)dev, (double)inode));
1212
1213               return False;
1214             }
1215             lock_share_entry(conn, dev, inode);
1216             broke_oplock = True;
1217             break;
1218           }
1219         }
1220
1221         /* 
1222          * If this is a delete request and ALLOW_SHARE_DELETE is set then allow 
1223          * this to proceed. This takes precedence over share modes.
1224          */
1225
1226         if(!rename_op && GET_ALLOW_SHARE_DELETE(share_entry->share_mode))
1227           continue;
1228
1229         /* 
1230          * Someone else has a share lock on it, check to see 
1231          * if we can too.
1232          */
1233
1234         if ((GET_DENY_MODE(share_entry->share_mode) != DENY_DOS) || 
1235             (share_entry->pid != pid))
1236           goto free_and_exit;
1237
1238       } /* end for */
1239
1240       if(broke_oplock)
1241       {
1242         free((char *)old_shares);
1243         num_share_modes = get_share_modes(conn, dev, inode, &old_shares);
1244       }
1245     } while(broke_oplock);
1246   }
1247
1248   /* XXXX exactly what share mode combinations should be allowed for
1249      deleting/renaming? */
1250   /* 
1251    * If we got here then either there were no share modes or
1252    * all share modes were DENY_DOS and the pid == getpid() or
1253    * delete access was requested and all share modes had the
1254    * ALLOW_SHARE_DELETE bit set (takes precedence over other
1255    * share modes).
1256    */
1257
1258   ret = True;
1259
1260 free_and_exit:
1261
1262   unlock_share_entry(conn, dev, inode);
1263   if(old_shares != NULL)
1264     free((char *)old_shares);
1265   return(ret);
1266 }