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