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