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