r25391: Fix bug #4978 : Store DOS Attributes fails when copying folders.
[sfrench/samba-autobuild/.git] / source3 / smbd / open.c
1 /* 
2    Unix SMB/CIFS implementation.
3    file opening and share modes
4    Copyright (C) Andrew Tridgell 1992-1998
5    Copyright (C) Jeremy Allison 2001-2004
6    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 3 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, see <http://www.gnu.org/licenses/>.
20 */
21
22 #include "includes.h"
23
24 extern struct generic_mapping file_generic_mapping;
25 extern struct current_user current_user;
26 extern userdom_struct current_user_info;
27 extern BOOL global_client_failed_oplock_break;
28
29 struct deferred_open_record {
30         BOOL delayed_for_oplocks;
31         struct file_id id;
32 };
33
34 /****************************************************************************
35  fd support routines - attempt to do a dos_open.
36 ****************************************************************************/
37
38 static NTSTATUS fd_open(struct connection_struct *conn,
39                     const char *fname, 
40                     files_struct *fsp,
41                     int flags,
42                     mode_t mode)
43 {
44         NTSTATUS status = NT_STATUS_OK;
45
46 #ifdef O_NOFOLLOW
47         /* 
48          * Never follow symlinks on a POSIX client. The
49          * client should be doing this.
50          */
51
52         if (fsp->posix_open || !lp_symlinks(SNUM(conn))) {
53                 flags |= O_NOFOLLOW;
54         }
55 #endif
56
57         fsp->fh->fd = SMB_VFS_OPEN(conn,fname,fsp,flags,mode);
58         if (fsp->fh->fd == -1) {
59                 status = map_nt_error_from_unix(errno);
60         }
61
62         DEBUG(10,("fd_open: name %s, flags = 0%o mode = 0%o, fd = %d. %s\n",
63                     fname, flags, (int)mode, fsp->fh->fd,
64                 (fsp->fh->fd == -1) ? strerror(errno) : "" ));
65
66         return status;
67 }
68
69 /****************************************************************************
70  Close the file associated with a fsp.
71 ****************************************************************************/
72
73 NTSTATUS fd_close(struct connection_struct *conn, files_struct *fsp)
74 {
75         if (fsp->fh->fd == -1) {
76                 return NT_STATUS_OK; /* What we used to call a stat open. */
77         }
78         if (fsp->fh->ref_count > 1) {
79                 return NT_STATUS_OK; /* Shared handle. Only close last reference. */
80         }
81         return fd_close_posix(conn, fsp);
82 }
83
84 /****************************************************************************
85  Change the ownership of a file to that of the parent directory.
86  Do this by fd if possible.
87 ****************************************************************************/
88
89 static void change_file_owner_to_parent(connection_struct *conn,
90                                         const char *inherit_from_dir,
91                                         files_struct *fsp)
92 {
93         SMB_STRUCT_STAT parent_st;
94         int ret;
95
96         ret = SMB_VFS_STAT(conn, inherit_from_dir, &parent_st);
97         if (ret == -1) {
98                 DEBUG(0,("change_file_owner_to_parent: failed to stat parent "
99                          "directory %s. Error was %s\n",
100                          inherit_from_dir, strerror(errno) ));
101                 return;
102         }
103
104         become_root();
105         ret = SMB_VFS_FCHOWN(fsp, fsp->fh->fd, parent_st.st_uid, (gid_t)-1);
106         unbecome_root();
107         if (ret == -1) {
108                 DEBUG(0,("change_file_owner_to_parent: failed to fchown "
109                          "file %s to parent directory uid %u. Error "
110                          "was %s\n", fsp->fsp_name,
111                          (unsigned int)parent_st.st_uid,
112                          strerror(errno) ));
113         }
114
115         DEBUG(10,("change_file_owner_to_parent: changed new file %s to "
116                   "parent directory uid %u.\n", fsp->fsp_name,
117                   (unsigned int)parent_st.st_uid ));
118 }
119
120 static NTSTATUS change_dir_owner_to_parent(connection_struct *conn,
121                                        const char *inherit_from_dir,
122                                        const char *fname,
123                                        SMB_STRUCT_STAT *psbuf)
124 {
125         char *saved_dir = NULL;
126         SMB_STRUCT_STAT sbuf;
127         SMB_STRUCT_STAT parent_st;
128         TALLOC_CTX *ctx = talloc_stackframe();
129         NTSTATUS status = NT_STATUS_OK;
130         int ret;
131
132         ret = SMB_VFS_STAT(conn, inherit_from_dir, &parent_st);
133         if (ret == -1) {
134                 status = map_nt_error_from_unix(errno);
135                 DEBUG(0,("change_dir_owner_to_parent: failed to stat parent "
136                          "directory %s. Error was %s\n",
137                          inherit_from_dir, strerror(errno) ));
138                 TALLOC_FREE(ctx);
139                 return status;
140         }
141
142         /* We've already done an lstat into psbuf, and we know it's a
143            directory. If we can cd into the directory and the dev/ino
144            are the same then we can safely chown without races as
145            we're locking the directory in place by being in it.  This
146            should work on any UNIX (thanks tridge :-). JRA.
147         */
148
149         saved_dir = vfs_GetWd(ctx,conn);
150         if (!saved_dir) {
151                 status = map_nt_error_from_unix(errno);
152                 DEBUG(0,("change_dir_owner_to_parent: failed to get "
153                          "current working directory. Error was %s\n",
154                          strerror(errno)));
155                 TALLOC_FREE(ctx);
156                 return status;
157         }
158
159         /* Chdir into the new path. */
160         if (vfs_ChDir(conn, fname) == -1) {
161                 status = map_nt_error_from_unix(errno);
162                 DEBUG(0,("change_dir_owner_to_parent: failed to change "
163                          "current working directory to %s. Error "
164                          "was %s\n", fname, strerror(errno) ));
165                 goto out;
166         }
167
168         if (SMB_VFS_STAT(conn,".",&sbuf) == -1) {
169                 status = map_nt_error_from_unix(errno);
170                 DEBUG(0,("change_dir_owner_to_parent: failed to stat "
171                          "directory '.' (%s) Error was %s\n",
172                          fname, strerror(errno)));
173                 goto out;
174         }
175
176         /* Ensure we're pointing at the same place. */
177         if (sbuf.st_dev != psbuf->st_dev ||
178             sbuf.st_ino != psbuf->st_ino ||
179             sbuf.st_mode != psbuf->st_mode ) {
180                 DEBUG(0,("change_dir_owner_to_parent: "
181                          "device/inode/mode on directory %s changed. "
182                          "Refusing to chown !\n", fname ));
183                 status = NT_STATUS_ACCESS_DENIED;
184                 goto out;
185         }
186
187         become_root();
188         ret = SMB_VFS_CHOWN(conn, ".", parent_st.st_uid, (gid_t)-1);
189         unbecome_root();
190         if (ret == -1) {
191                 status = map_nt_error_from_unix(errno);
192                 DEBUG(10,("change_dir_owner_to_parent: failed to chown "
193                           "directory %s to parent directory uid %u. "
194                           "Error was %s\n", fname,
195                           (unsigned int)parent_st.st_uid, strerror(errno) ));
196                 goto out;
197         }
198
199         DEBUG(10,("change_dir_owner_to_parent: changed ownership of new "
200                   "directory %s to parent directory uid %u.\n",
201                   fname, (unsigned int)parent_st.st_uid ));
202
203  out:
204
205         TALLOC_FREE(ctx);
206         vfs_ChDir(conn,saved_dir);
207         return status;
208 }
209
210 /****************************************************************************
211  Open a file.
212 ****************************************************************************/
213
214 static NTSTATUS open_file(files_struct *fsp,
215                           connection_struct *conn,
216                           struct smb_request *req,
217                           const char *parent_dir,
218                           const char *name,
219                           const char *path,
220                           SMB_STRUCT_STAT *psbuf,
221                           int flags,
222                           mode_t unx_mode,
223                           uint32 access_mask, /* client requested access mask. */
224                           uint32 open_access_mask) /* what we're actually using in the open. */
225 {
226         NTSTATUS status = NT_STATUS_OK;
227         int accmode = (flags & O_ACCMODE);
228         int local_flags = flags;
229         BOOL file_existed = VALID_STAT(*psbuf);
230
231         fsp->fh->fd = -1;
232         errno = EPERM;
233
234         /* Check permissions */
235
236         /*
237          * This code was changed after seeing a client open request 
238          * containing the open mode of (DENY_WRITE/read-only) with
239          * the 'create if not exist' bit set. The previous code
240          * would fail to open the file read only on a read-only share
241          * as it was checking the flags parameter  directly against O_RDONLY,
242          * this was failing as the flags parameter was set to O_RDONLY|O_CREAT.
243          * JRA.
244          */
245
246         if (!CAN_WRITE(conn)) {
247                 /* It's a read-only share - fail if we wanted to write. */
248                 if(accmode != O_RDONLY) {
249                         DEBUG(3,("Permission denied opening %s\n", path));
250                         return NT_STATUS_ACCESS_DENIED;
251                 } else if(flags & O_CREAT) {
252                         /* We don't want to write - but we must make sure that
253                            O_CREAT doesn't create the file if we have write
254                            access into the directory.
255                         */
256                         flags &= ~O_CREAT;
257                         local_flags &= ~O_CREAT;
258                 }
259         }
260
261         /*
262          * This little piece of insanity is inspired by the
263          * fact that an NT client can open a file for O_RDONLY,
264          * but set the create disposition to FILE_EXISTS_TRUNCATE.
265          * If the client *can* write to the file, then it expects to
266          * truncate the file, even though it is opening for readonly.
267          * Quicken uses this stupid trick in backup file creation...
268          * Thanks *greatly* to "David W. Chapman Jr." <dwcjr@inethouston.net>
269          * for helping track this one down. It didn't bite us in 2.0.x
270          * as we always opened files read-write in that release. JRA.
271          */
272
273         if ((accmode == O_RDONLY) && ((flags & O_TRUNC) == O_TRUNC)) {
274                 DEBUG(10,("open_file: truncate requested on read-only open "
275                           "for file %s\n", path));
276                 local_flags = (flags & ~O_ACCMODE)|O_RDWR;
277         }
278
279         if ((open_access_mask & (FILE_READ_DATA|FILE_WRITE_DATA|FILE_APPEND_DATA|FILE_EXECUTE)) ||
280             (!file_existed && (local_flags & O_CREAT)) ||
281             ((local_flags & O_TRUNC) == O_TRUNC) ) {
282
283                 /*
284                  * We can't actually truncate here as the file may be locked.
285                  * open_file_ntcreate will take care of the truncate later. JRA.
286                  */
287
288                 local_flags &= ~O_TRUNC;
289
290 #if defined(O_NONBLOCK) && defined(S_ISFIFO)
291                 /*
292                  * We would block on opening a FIFO with no one else on the
293                  * other end. Do what we used to do and add O_NONBLOCK to the
294                  * open flags. JRA.
295                  */
296
297                 if (file_existed && S_ISFIFO(psbuf->st_mode)) {
298                         local_flags |= O_NONBLOCK;
299                 }
300 #endif
301
302                 /* Don't create files with Microsoft wildcard characters. */
303                 if ((local_flags & O_CREAT) && !file_existed &&
304                     ms_has_wild(path))  {
305                         return NT_STATUS_OBJECT_NAME_INVALID;
306                 }
307
308                 /* Actually do the open */
309                 status = fd_open(conn, path, fsp, local_flags, unx_mode);
310                 if (!NT_STATUS_IS_OK(status)) {
311                         DEBUG(3,("Error opening file %s (%s) (local_flags=%d) "
312                                  "(flags=%d)\n",
313                                  path,nt_errstr(status),local_flags,flags));
314                         return status;
315                 }
316
317                 if ((local_flags & O_CREAT) && !file_existed) {
318
319                         /* Inherit the ACL if required */
320                         if (lp_inherit_perms(SNUM(conn))) {
321                                 inherit_access_acl(conn, parent_dir, path,
322                                                    unx_mode);
323                         }
324
325                         /* Change the owner if required. */
326                         if (lp_inherit_owner(SNUM(conn))) {
327                                 change_file_owner_to_parent(conn, parent_dir,
328                                                             fsp);
329                         }
330
331                         notify_fname(conn, NOTIFY_ACTION_ADDED,
332                                      FILE_NOTIFY_CHANGE_FILE_NAME, path);
333                 }
334
335         } else {
336                 fsp->fh->fd = -1; /* What we used to call a stat open. */
337         }
338
339         if (!file_existed) {
340                 int ret;
341
342                 if (fsp->fh->fd == -1) {
343                         ret = SMB_VFS_STAT(conn, path, psbuf);
344                 } else {
345                         ret = SMB_VFS_FSTAT(fsp,fsp->fh->fd,psbuf);
346                         /* If we have an fd, this stat should succeed. */
347                         if (ret == -1) {
348                                 DEBUG(0,("Error doing fstat on open file %s "
349                                          "(%s)\n", path,strerror(errno) ));
350                         }
351                 }
352
353                 /* For a non-io open, this stat failing means file not found. JRA */
354                 if (ret == -1) {
355                         status = map_nt_error_from_unix(errno);
356                         fd_close(conn, fsp);
357                         return status;
358                 }
359         }
360
361         /*
362          * POSIX allows read-only opens of directories. We don't
363          * want to do this (we use a different code path for this)
364          * so catch a directory open and return an EISDIR. JRA.
365          */
366
367         if(S_ISDIR(psbuf->st_mode)) {
368                 fd_close(conn, fsp);
369                 errno = EISDIR;
370                 return NT_STATUS_FILE_IS_A_DIRECTORY;
371         }
372
373         fsp->mode = psbuf->st_mode;
374         fsp->file_id = vfs_file_id_from_sbuf(conn, psbuf);
375         fsp->vuid = req ? req->vuid : UID_FIELD_INVALID;
376         fsp->file_pid = req ? req->smbpid : 0;
377         fsp->can_lock = True;
378         fsp->can_read = (access_mask & (FILE_READ_DATA)) ? True : False;
379         if (!CAN_WRITE(conn)) {
380                 fsp->can_write = False;
381         } else {
382                 fsp->can_write = (access_mask & (FILE_WRITE_DATA | FILE_APPEND_DATA)) ?
383                         True : False;
384         }
385         fsp->print_file = False;
386         fsp->modified = False;
387         fsp->sent_oplock_break = NO_BREAK_SENT;
388         fsp->is_directory = False;
389         fsp->is_stat = False;
390
391         string_set(&fsp->fsp_name, path);
392         fsp->wcp = NULL; /* Write cache pointer. */
393
394         DEBUG(2,("%s opened file %s read=%s write=%s (numopen=%d)\n",
395                  *current_user_info.smb_name ?
396                  current_user_info.smb_name : conn->user,fsp->fsp_name,
397                  BOOLSTR(fsp->can_read), BOOLSTR(fsp->can_write),
398                  conn->num_files_open + 1));
399
400         errno = 0;
401         return NT_STATUS_OK;
402 }
403
404 /*******************************************************************
405  Return True if the filename is one of the special executable types.
406 ********************************************************************/
407
408 static BOOL is_executable(const char *fname)
409 {
410         if ((fname = strrchr_m(fname,'.'))) {
411                 if (strequal(fname,".com") ||
412                     strequal(fname,".dll") ||
413                     strequal(fname,".exe") ||
414                     strequal(fname,".sym")) {
415                         return True;
416                 }
417         }
418         return False;
419 }
420
421 /****************************************************************************
422  Check if we can open a file with a share mode.
423  Returns True if conflict, False if not.
424 ****************************************************************************/
425
426 static BOOL share_conflict(struct share_mode_entry *entry,
427                            uint32 access_mask,
428                            uint32 share_access)
429 {
430         DEBUG(10,("share_conflict: entry->access_mask = 0x%x, "
431                   "entry->share_access = 0x%x, "
432                   "entry->private_options = 0x%x\n",
433                   (unsigned int)entry->access_mask,
434                   (unsigned int)entry->share_access,
435                   (unsigned int)entry->private_options));
436
437         DEBUG(10,("share_conflict: access_mask = 0x%x, share_access = 0x%x\n",
438                   (unsigned int)access_mask, (unsigned int)share_access));
439
440         if ((entry->access_mask & (FILE_WRITE_DATA|
441                                    FILE_APPEND_DATA|
442                                    FILE_READ_DATA|
443                                    FILE_EXECUTE|
444                                    DELETE_ACCESS)) == 0) {
445                 DEBUG(10,("share_conflict: No conflict due to "
446                           "entry->access_mask = 0x%x\n",
447                           (unsigned int)entry->access_mask ));
448                 return False;
449         }
450
451         if ((access_mask & (FILE_WRITE_DATA|
452                             FILE_APPEND_DATA|
453                             FILE_READ_DATA|
454                             FILE_EXECUTE|
455                             DELETE_ACCESS)) == 0) {
456                 DEBUG(10,("share_conflict: No conflict due to "
457                           "access_mask = 0x%x\n",
458                           (unsigned int)access_mask ));
459                 return False;
460         }
461
462 #if 1 /* JRA TEST - Superdebug. */
463 #define CHECK_MASK(num, am, right, sa, share) \
464         DEBUG(10,("share_conflict: [%d] am (0x%x) & right (0x%x) = 0x%x\n", \
465                 (unsigned int)(num), (unsigned int)(am), \
466                 (unsigned int)(right), (unsigned int)(am)&(right) )); \
467         DEBUG(10,("share_conflict: [%d] sa (0x%x) & share (0x%x) = 0x%x\n", \
468                 (unsigned int)(num), (unsigned int)(sa), \
469                 (unsigned int)(share), (unsigned int)(sa)&(share) )); \
470         if (((am) & (right)) && !((sa) & (share))) { \
471                 DEBUG(10,("share_conflict: check %d conflict am = 0x%x, right = 0x%x, \
472 sa = 0x%x, share = 0x%x\n", (num), (unsigned int)(am), (unsigned int)(right), (unsigned int)(sa), \
473                         (unsigned int)(share) )); \
474                 return True; \
475         }
476 #else
477 #define CHECK_MASK(num, am, right, sa, share) \
478         if (((am) & (right)) && !((sa) & (share))) { \
479                 DEBUG(10,("share_conflict: check %d conflict am = 0x%x, right = 0x%x, \
480 sa = 0x%x, share = 0x%x\n", (num), (unsigned int)(am), (unsigned int)(right), (unsigned int)(sa), \
481                         (unsigned int)(share) )); \
482                 return True; \
483         }
484 #endif
485
486         CHECK_MASK(1, entry->access_mask, FILE_WRITE_DATA | FILE_APPEND_DATA,
487                    share_access, FILE_SHARE_WRITE);
488         CHECK_MASK(2, access_mask, FILE_WRITE_DATA | FILE_APPEND_DATA,
489                    entry->share_access, FILE_SHARE_WRITE);
490         
491         CHECK_MASK(3, entry->access_mask, FILE_READ_DATA | FILE_EXECUTE,
492                    share_access, FILE_SHARE_READ);
493         CHECK_MASK(4, access_mask, FILE_READ_DATA | FILE_EXECUTE,
494                    entry->share_access, FILE_SHARE_READ);
495
496         CHECK_MASK(5, entry->access_mask, DELETE_ACCESS,
497                    share_access, FILE_SHARE_DELETE);
498         CHECK_MASK(6, access_mask, DELETE_ACCESS,
499                    entry->share_access, FILE_SHARE_DELETE);
500
501         DEBUG(10,("share_conflict: No conflict.\n"));
502         return False;
503 }
504
505 #if defined(DEVELOPER)
506 static void validate_my_share_entries(int num,
507                                       struct share_mode_entry *share_entry)
508 {
509         files_struct *fsp;
510
511         if (!procid_is_me(&share_entry->pid)) {
512                 return;
513         }
514
515         if (is_deferred_open_entry(share_entry) &&
516             !open_was_deferred(share_entry->op_mid)) {
517                 char *str = talloc_asprintf(talloc_tos(),
518                         "Got a deferred entry without a request: "
519                         "PANIC: %s\n",
520                         share_mode_str(num, share_entry));
521                 smb_panic(str);
522         }
523
524         if (!is_valid_share_mode_entry(share_entry)) {
525                 return;
526         }
527
528         fsp = file_find_dif(share_entry->id,
529                             share_entry->share_file_id);
530         if (!fsp) {
531                 DEBUG(0,("validate_my_share_entries: PANIC : %s\n",
532                          share_mode_str(num, share_entry) ));
533                 smb_panic("validate_my_share_entries: Cannot match a "
534                           "share entry with an open file\n");
535         }
536
537         if (is_deferred_open_entry(share_entry) ||
538             is_unused_share_mode_entry(share_entry)) {
539                 goto panic;
540         }
541
542         if ((share_entry->op_type == NO_OPLOCK) &&
543             (fsp->oplock_type == FAKE_LEVEL_II_OPLOCK)) {
544                 /* Someone has already written to it, but I haven't yet
545                  * noticed */
546                 return;
547         }
548
549         if (((uint16)fsp->oplock_type) != share_entry->op_type) {
550                 goto panic;
551         }
552
553         return;
554
555  panic:
556         {
557                 char *str;
558                 DEBUG(0,("validate_my_share_entries: PANIC : %s\n",
559                          share_mode_str(num, share_entry) ));
560                 str = talloc_asprintf(talloc_tos(),
561                         "validate_my_share_entries: "
562                         "file %s, oplock_type = 0x%x, op_type = 0x%x\n",
563                          fsp->fsp_name, (unsigned int)fsp->oplock_type,
564                          (unsigned int)share_entry->op_type );
565                 smb_panic(str);
566         }
567 }
568 #endif
569
570 static BOOL is_stat_open(uint32 access_mask)
571 {
572         return (access_mask &&
573                 ((access_mask & ~(SYNCHRONIZE_ACCESS| FILE_READ_ATTRIBUTES|
574                                   FILE_WRITE_ATTRIBUTES))==0) &&
575                 ((access_mask & (SYNCHRONIZE_ACCESS|FILE_READ_ATTRIBUTES|
576                                  FILE_WRITE_ATTRIBUTES)) != 0));
577 }
578
579 /****************************************************************************
580  Deal with share modes
581  Invarient: Share mode must be locked on entry and exit.
582  Returns -1 on error, or number of share modes on success (may be zero).
583 ****************************************************************************/
584
585 static NTSTATUS open_mode_check(connection_struct *conn,
586                                 const char *fname,
587                                 struct share_mode_lock *lck,
588                                 uint32 access_mask,
589                                 uint32 share_access,
590                                 uint32 create_options,
591                                 BOOL *file_existed)
592 {
593         int i;
594
595         if(lck->num_share_modes == 0) {
596                 return NT_STATUS_OK;
597         }
598
599         *file_existed = True;
600         
601         if (is_stat_open(access_mask)) {
602                 /* Stat open that doesn't trigger oplock breaks or share mode
603                  * checks... ! JRA. */
604                 return NT_STATUS_OK;
605         }
606
607         /* A delete on close prohibits everything */
608
609         if (lck->delete_on_close) {
610                 return NT_STATUS_DELETE_PENDING;
611         }
612
613         /*
614          * Check if the share modes will give us access.
615          */
616         
617 #if defined(DEVELOPER)
618         for(i = 0; i < lck->num_share_modes; i++) {
619                 validate_my_share_entries(i, &lck->share_modes[i]);
620         }
621 #endif
622
623         if (!lp_share_modes(SNUM(conn))) {
624                 return NT_STATUS_OK;
625         }
626
627         /* Now we check the share modes, after any oplock breaks. */
628         for(i = 0; i < lck->num_share_modes; i++) {
629
630                 if (!is_valid_share_mode_entry(&lck->share_modes[i])) {
631                         continue;
632                 }
633
634                 /* someone else has a share lock on it, check to see if we can
635                  * too */
636                 if (share_conflict(&lck->share_modes[i],
637                                    access_mask, share_access)) {
638                         return NT_STATUS_SHARING_VIOLATION;
639                 }
640         }
641         
642         return NT_STATUS_OK;
643 }
644
645 static BOOL is_delete_request(files_struct *fsp) {
646         return ((fsp->access_mask == DELETE_ACCESS) &&
647                 (fsp->oplock_type == NO_OPLOCK));
648 }
649
650 /*
651  * 1) No files open at all or internal open: Grant whatever the client wants.
652  *
653  * 2) Exclusive (or batch) oplock around: If the requested access is a delete
654  *    request, break if the oplock around is a batch oplock. If it's another
655  *    requested access type, break.
656  * 
657  * 3) Only level2 around: Grant level2 and do nothing else.
658  */
659
660 static BOOL delay_for_oplocks(struct share_mode_lock *lck,
661                               files_struct *fsp,
662                               uint16 mid,
663                               int pass_number,
664                               int oplock_request)
665 {
666         int i;
667         struct share_mode_entry *exclusive = NULL;
668         BOOL valid_entry = False;
669         BOOL delay_it = False;
670         BOOL have_level2 = False;
671         NTSTATUS status;
672         char msg[MSG_SMB_SHARE_MODE_ENTRY_SIZE];
673
674         if (oplock_request & INTERNAL_OPEN_ONLY) {
675                 fsp->oplock_type = NO_OPLOCK;
676         }
677
678         if ((oplock_request & INTERNAL_OPEN_ONLY) || is_stat_open(fsp->access_mask)) {
679                 return False;
680         }
681
682         for (i=0; i<lck->num_share_modes; i++) {
683
684                 if (!is_valid_share_mode_entry(&lck->share_modes[i])) {
685                         continue;
686                 }
687
688                 /* At least one entry is not an invalid or deferred entry. */
689                 valid_entry = True;
690
691                 if (pass_number == 1) {
692                         if (BATCH_OPLOCK_TYPE(lck->share_modes[i].op_type)) {
693                                 SMB_ASSERT(exclusive == NULL);                  
694                                 exclusive = &lck->share_modes[i];
695                         }
696                 } else {
697                         if (EXCLUSIVE_OPLOCK_TYPE(lck->share_modes[i].op_type)) {
698                                 SMB_ASSERT(exclusive == NULL);                  
699                                 exclusive = &lck->share_modes[i];
700                         }
701                 }
702
703                 if (lck->share_modes[i].op_type == LEVEL_II_OPLOCK) {
704                         SMB_ASSERT(exclusive == NULL);                  
705                         have_level2 = True;
706                 }
707         }
708
709         if (!valid_entry) {
710                 /* All entries are placeholders or deferred.
711                  * Directly grant whatever the client wants. */
712                 if (fsp->oplock_type == NO_OPLOCK) {
713                         /* Store a level2 oplock, but don't tell the client */
714                         fsp->oplock_type = FAKE_LEVEL_II_OPLOCK;
715                 }
716                 return False;
717         }
718
719         if (exclusive != NULL) { /* Found an exclusive oplock */
720                 SMB_ASSERT(!have_level2);
721                 delay_it = is_delete_request(fsp) ?
722                         BATCH_OPLOCK_TYPE(exclusive->op_type) : True;
723         }
724
725         if (EXCLUSIVE_OPLOCK_TYPE(fsp->oplock_type)) {
726                 /* We can at most grant level2 as there are other
727                  * level2 or NO_OPLOCK entries. */
728                 fsp->oplock_type = LEVEL_II_OPLOCK;
729         }
730
731         if ((fsp->oplock_type == NO_OPLOCK) && have_level2) {
732                 /* Store a level2 oplock, but don't tell the client */
733                 fsp->oplock_type = FAKE_LEVEL_II_OPLOCK;
734         }
735
736         if (!delay_it) {
737                 return False;
738         }
739
740         /*
741          * Send a break message to the oplock holder and delay the open for
742          * our client.
743          */
744
745         DEBUG(10, ("Sending break request to PID %s\n",
746                    procid_str_static(&exclusive->pid)));
747         exclusive->op_mid = mid;
748
749         /* Create the message. */
750         share_mode_entry_to_message(msg, exclusive);
751
752         /* Add in the FORCE_OPLOCK_BREAK_TO_NONE bit in the message if set. We
753            don't want this set in the share mode struct pointed to by lck. */
754
755         if (oplock_request & FORCE_OPLOCK_BREAK_TO_NONE) {
756                 SSVAL(msg,6,exclusive->op_type | FORCE_OPLOCK_BREAK_TO_NONE);
757         }
758
759         status = messaging_send_buf(smbd_messaging_context(), exclusive->pid,
760                                     MSG_SMB_BREAK_REQUEST,
761                                     (uint8 *)msg,
762                                     MSG_SMB_SHARE_MODE_ENTRY_SIZE);
763         if (!NT_STATUS_IS_OK(status)) {
764                 DEBUG(3, ("Could not send oplock break message: %s\n",
765                           nt_errstr(status)));
766         }
767
768         return True;
769 }
770
771 static BOOL request_timed_out(struct timeval request_time,
772                               struct timeval timeout)
773 {
774         struct timeval now, end_time;
775         GetTimeOfDay(&now);
776         end_time = timeval_sum(&request_time, &timeout);
777         return (timeval_compare(&end_time, &now) < 0);
778 }
779
780 /****************************************************************************
781  Handle the 1 second delay in returning a SHARING_VIOLATION error.
782 ****************************************************************************/
783
784 static void defer_open(struct share_mode_lock *lck,
785                        struct timeval request_time,
786                        struct timeval timeout,
787                        struct smb_request *req,
788                        struct deferred_open_record *state)
789 {
790         int i;
791
792         /* Paranoia check */
793
794         for (i=0; i<lck->num_share_modes; i++) {
795                 struct share_mode_entry *e = &lck->share_modes[i];
796
797                 if (!is_deferred_open_entry(e)) {
798                         continue;
799                 }
800
801                 if (procid_is_me(&e->pid) && (e->op_mid == req->mid)) {
802                         DEBUG(0, ("Trying to defer an already deferred "
803                                   "request: mid=%d, exiting\n", req->mid));
804                         exit_server("attempt to defer a deferred request");
805                 }
806         }
807
808         /* End paranoia check */
809
810         DEBUG(10,("defer_open_sharing_error: time [%u.%06u] adding deferred "
811                   "open entry for mid %u\n",
812                   (unsigned int)request_time.tv_sec,
813                   (unsigned int)request_time.tv_usec,
814                   (unsigned int)req->mid));
815
816         if (!push_deferred_smb_message(req, request_time, timeout,
817                                        (char *)state, sizeof(*state))) {
818                 exit_server("push_deferred_smb_message failed");
819         }
820         add_deferred_open(lck, req->mid, request_time, state->id);
821
822         /*
823          * Push the MID of this packet on the signing queue.
824          * We only do this once, the first time we push the packet
825          * onto the deferred open queue, as this has a side effect
826          * of incrementing the response sequence number.
827          */
828
829         srv_defer_sign_response(req->mid);
830 }
831
832
833 /****************************************************************************
834  On overwrite open ensure that the attributes match.
835 ****************************************************************************/
836
837 static BOOL open_match_attributes(connection_struct *conn,
838                                   const char *path,
839                                   uint32 old_dos_attr,
840                                   uint32 new_dos_attr,
841                                   mode_t existing_unx_mode,
842                                   mode_t new_unx_mode,
843                                   mode_t *returned_unx_mode)
844 {
845         uint32 noarch_old_dos_attr, noarch_new_dos_attr;
846
847         noarch_old_dos_attr = (old_dos_attr & ~FILE_ATTRIBUTE_ARCHIVE);
848         noarch_new_dos_attr = (new_dos_attr & ~FILE_ATTRIBUTE_ARCHIVE);
849
850         if((noarch_old_dos_attr == 0 && noarch_new_dos_attr != 0) || 
851            (noarch_old_dos_attr != 0 && ((noarch_old_dos_attr & noarch_new_dos_attr) == noarch_old_dos_attr))) {
852                 *returned_unx_mode = new_unx_mode;
853         } else {
854                 *returned_unx_mode = (mode_t)0;
855         }
856
857         DEBUG(10,("open_match_attributes: file %s old_dos_attr = 0x%x, "
858                   "existing_unx_mode = 0%o, new_dos_attr = 0x%x "
859                   "returned_unx_mode = 0%o\n",
860                   path,
861                   (unsigned int)old_dos_attr,
862                   (unsigned int)existing_unx_mode,
863                   (unsigned int)new_dos_attr,
864                   (unsigned int)*returned_unx_mode ));
865
866         /* If we're mapping SYSTEM and HIDDEN ensure they match. */
867         if (lp_map_system(SNUM(conn)) || lp_store_dos_attributes(SNUM(conn))) {
868                 if ((old_dos_attr & FILE_ATTRIBUTE_SYSTEM) &&
869                     !(new_dos_attr & FILE_ATTRIBUTE_SYSTEM)) {
870                         return False;
871                 }
872         }
873         if (lp_map_hidden(SNUM(conn)) || lp_store_dos_attributes(SNUM(conn))) {
874                 if ((old_dos_attr & FILE_ATTRIBUTE_HIDDEN) &&
875                     !(new_dos_attr & FILE_ATTRIBUTE_HIDDEN)) {
876                         return False;
877                 }
878         }
879         return True;
880 }
881
882 /****************************************************************************
883  Special FCB or DOS processing in the case of a sharing violation.
884  Try and find a duplicated file handle.
885 ****************************************************************************/
886
887 static files_struct *fcb_or_dos_open(connection_struct *conn,
888                                      const char *fname, 
889                                      struct file_id id,
890                                      uint16 file_pid,
891                                      uint16 vuid,
892                                      uint32 access_mask,
893                                      uint32 share_access,
894                                      uint32 create_options)
895 {
896         files_struct *fsp;
897         files_struct *dup_fsp;
898
899         DEBUG(5,("fcb_or_dos_open: attempting old open semantics for "
900                  "file %s.\n", fname ));
901
902         for(fsp = file_find_di_first(id); fsp;
903             fsp = file_find_di_next(fsp)) {
904
905                 DEBUG(10,("fcb_or_dos_open: checking file %s, fd = %d, "
906                           "vuid = %u, file_pid = %u, private_options = 0x%x "
907                           "access_mask = 0x%x\n", fsp->fsp_name,
908                           fsp->fh->fd, (unsigned int)fsp->vuid,
909                           (unsigned int)fsp->file_pid,
910                           (unsigned int)fsp->fh->private_options,
911                           (unsigned int)fsp->access_mask ));
912
913                 if (fsp->fh->fd != -1 &&
914                     fsp->vuid == vuid &&
915                     fsp->file_pid == file_pid &&
916                     (fsp->fh->private_options & (NTCREATEX_OPTIONS_PRIVATE_DENY_DOS |
917                                                  NTCREATEX_OPTIONS_PRIVATE_DENY_FCB)) &&
918                     (fsp->access_mask & FILE_WRITE_DATA) &&
919                     strequal(fsp->fsp_name, fname)) {
920                         DEBUG(10,("fcb_or_dos_open: file match\n"));
921                         break;
922                 }
923         }
924
925         if (!fsp) {
926                 return NULL;
927         }
928
929         /* quite an insane set of semantics ... */
930         if (is_executable(fname) &&
931             (fsp->fh->private_options & NTCREATEX_OPTIONS_PRIVATE_DENY_DOS)) {
932                 DEBUG(10,("fcb_or_dos_open: file fail due to is_executable.\n"));
933                 return NULL;
934         }
935
936         /* We need to duplicate this fsp. */
937         if (!NT_STATUS_IS_OK(dup_file_fsp(fsp, access_mask, share_access,
938                                           create_options, &dup_fsp))) {
939                 return NULL;
940         }
941
942         return dup_fsp;
943 }
944
945 /****************************************************************************
946  Open a file with a share mode - old openX method - map into NTCreate.
947 ****************************************************************************/
948
949 BOOL map_open_params_to_ntcreate(const char *fname, int deny_mode, int open_func,
950                                  uint32 *paccess_mask,
951                                  uint32 *pshare_mode,
952                                  uint32 *pcreate_disposition,
953                                  uint32 *pcreate_options)
954 {
955         uint32 access_mask;
956         uint32 share_mode;
957         uint32 create_disposition;
958         uint32 create_options = 0;
959
960         DEBUG(10,("map_open_params_to_ntcreate: fname = %s, deny_mode = 0x%x, "
961                   "open_func = 0x%x\n",
962                   fname, (unsigned int)deny_mode, (unsigned int)open_func ));
963
964         /* Create the NT compatible access_mask. */
965         switch (GET_OPENX_MODE(deny_mode)) {
966                 case DOS_OPEN_EXEC: /* Implies read-only - used to be FILE_READ_DATA */
967                 case DOS_OPEN_RDONLY:
968                         access_mask = FILE_GENERIC_READ;
969                         break;
970                 case DOS_OPEN_WRONLY:
971                         access_mask = FILE_GENERIC_WRITE;
972                         break;
973                 case DOS_OPEN_RDWR:
974                 case DOS_OPEN_FCB:
975                         access_mask = FILE_GENERIC_READ|FILE_GENERIC_WRITE;
976                         break;
977                 default:
978                         DEBUG(10,("map_open_params_to_ntcreate: bad open mode = 0x%x\n",
979                                   (unsigned int)GET_OPENX_MODE(deny_mode)));
980                         return False;
981         }
982
983         /* Create the NT compatible create_disposition. */
984         switch (open_func) {
985                 case OPENX_FILE_EXISTS_FAIL|OPENX_FILE_CREATE_IF_NOT_EXIST:
986                         create_disposition = FILE_CREATE;
987                         break;
988
989                 case OPENX_FILE_EXISTS_OPEN:
990                         create_disposition = FILE_OPEN;
991                         break;
992
993                 case OPENX_FILE_EXISTS_OPEN|OPENX_FILE_CREATE_IF_NOT_EXIST:
994                         create_disposition = FILE_OPEN_IF;
995                         break;
996        
997                 case OPENX_FILE_EXISTS_TRUNCATE:
998                         create_disposition = FILE_OVERWRITE;
999                         break;
1000
1001                 case OPENX_FILE_EXISTS_TRUNCATE|OPENX_FILE_CREATE_IF_NOT_EXIST:
1002                         create_disposition = FILE_OVERWRITE_IF;
1003                         break;
1004
1005                 default:
1006                         /* From samba4 - to be confirmed. */
1007                         if (GET_OPENX_MODE(deny_mode) == DOS_OPEN_EXEC) {
1008                                 create_disposition = FILE_CREATE;
1009                                 break;
1010                         }
1011                         DEBUG(10,("map_open_params_to_ntcreate: bad "
1012                                   "open_func 0x%x\n", (unsigned int)open_func));
1013                         return False;
1014         }
1015  
1016         /* Create the NT compatible share modes. */
1017         switch (GET_DENY_MODE(deny_mode)) {
1018                 case DENY_ALL:
1019                         share_mode = FILE_SHARE_NONE;
1020                         break;
1021
1022                 case DENY_WRITE:
1023                         share_mode = FILE_SHARE_READ;
1024                         break;
1025
1026                 case DENY_READ:
1027                         share_mode = FILE_SHARE_WRITE;
1028                         break;
1029
1030                 case DENY_NONE:
1031                         share_mode = FILE_SHARE_READ|FILE_SHARE_WRITE;
1032                         break;
1033
1034                 case DENY_DOS:
1035                         create_options |= NTCREATEX_OPTIONS_PRIVATE_DENY_DOS;
1036                         if (is_executable(fname)) {
1037                                 share_mode = FILE_SHARE_READ|FILE_SHARE_WRITE;
1038                         } else {
1039                                 if (GET_OPENX_MODE(deny_mode) == DOS_OPEN_RDONLY) {
1040                                         share_mode = FILE_SHARE_READ;
1041                                 } else {
1042                                         share_mode = FILE_SHARE_NONE;
1043                                 }
1044                         }
1045                         break;
1046
1047                 case DENY_FCB:
1048                         create_options |= NTCREATEX_OPTIONS_PRIVATE_DENY_FCB;
1049                         share_mode = FILE_SHARE_NONE;
1050                         break;
1051
1052                 default:
1053                         DEBUG(10,("map_open_params_to_ntcreate: bad deny_mode 0x%x\n",
1054                                 (unsigned int)GET_DENY_MODE(deny_mode) ));
1055                         return False;
1056         }
1057
1058         DEBUG(10,("map_open_params_to_ntcreate: file %s, access_mask = 0x%x, "
1059                   "share_mode = 0x%x, create_disposition = 0x%x, "
1060                   "create_options = 0x%x\n",
1061                   fname,
1062                   (unsigned int)access_mask,
1063                   (unsigned int)share_mode,
1064                   (unsigned int)create_disposition,
1065                   (unsigned int)create_options ));
1066
1067         if (paccess_mask) {
1068                 *paccess_mask = access_mask;
1069         }
1070         if (pshare_mode) {
1071                 *pshare_mode = share_mode;
1072         }
1073         if (pcreate_disposition) {
1074                 *pcreate_disposition = create_disposition;
1075         }
1076         if (pcreate_options) {
1077                 *pcreate_options = create_options;
1078         }
1079
1080         return True;
1081
1082 }
1083
1084 static void schedule_defer_open(struct share_mode_lock *lck,
1085                                 struct timeval request_time,
1086                                 struct smb_request *req)
1087 {
1088         struct deferred_open_record state;
1089
1090         /* This is a relative time, added to the absolute
1091            request_time value to get the absolute timeout time.
1092            Note that if this is the second or greater time we enter
1093            this codepath for this particular request mid then
1094            request_time is left as the absolute time of the *first*
1095            time this request mid was processed. This is what allows
1096            the request to eventually time out. */
1097
1098         struct timeval timeout;
1099
1100         /* Normally the smbd we asked should respond within
1101          * OPLOCK_BREAK_TIMEOUT seconds regardless of whether
1102          * the client did, give twice the timeout as a safety
1103          * measure here in case the other smbd is stuck
1104          * somewhere else. */
1105
1106         timeout = timeval_set(OPLOCK_BREAK_TIMEOUT*2, 0);
1107
1108         /* Nothing actually uses state.delayed_for_oplocks
1109            but it's handy to differentiate in debug messages
1110            between a 30 second delay due to oplock break, and
1111            a 1 second delay for share mode conflicts. */
1112
1113         state.delayed_for_oplocks = True;
1114         state.id = lck->id;
1115
1116         if (!request_timed_out(request_time, timeout)) {
1117                 defer_open(lck, request_time, timeout, req, &state);
1118         }
1119 }
1120
1121 /****************************************************************************
1122  Open a file with a share mode.
1123 ****************************************************************************/
1124
1125 NTSTATUS open_file_ntcreate(connection_struct *conn,
1126                             struct smb_request *req,
1127                             const char *fname,
1128                             SMB_STRUCT_STAT *psbuf,
1129                             uint32 access_mask,         /* access bits (FILE_READ_DATA etc.) */
1130                             uint32 share_access,        /* share constants (FILE_SHARE_READ etc) */
1131                             uint32 create_disposition,  /* FILE_OPEN_IF etc. */
1132                             uint32 create_options,      /* options such as delete on close. */
1133                             uint32 new_dos_attributes,  /* attributes used for new file. */
1134                             int oplock_request,         /* internal Samba oplock codes. */
1135                                                         /* Information (FILE_EXISTS etc.) */
1136                             int *pinfo,
1137                             files_struct **result)
1138 {
1139         int flags=0;
1140         int flags2=0;
1141         BOOL file_existed = VALID_STAT(*psbuf);
1142         BOOL def_acl = False;
1143         BOOL posix_open = False;
1144         BOOL new_file_created = False;
1145         struct file_id id;
1146         NTSTATUS fsp_open = NT_STATUS_ACCESS_DENIED;
1147         files_struct *fsp = NULL;
1148         mode_t new_unx_mode = (mode_t)0;
1149         mode_t unx_mode = (mode_t)0;
1150         int info;
1151         uint32 existing_dos_attributes = 0;
1152         struct pending_message_list *pml = NULL;
1153         struct timeval request_time = timeval_zero();
1154         struct share_mode_lock *lck = NULL;
1155         uint32 open_access_mask = access_mask;
1156         NTSTATUS status;
1157         int ret_flock;
1158         char *parent_dir;
1159         const char *newname;
1160
1161         ZERO_STRUCT(id);
1162
1163         if (conn->printer) {
1164                 /* 
1165                  * Printers are handled completely differently.
1166                  * Most of the passed parameters are ignored.
1167                  */
1168
1169                 if (pinfo) {
1170                         *pinfo = FILE_WAS_CREATED;
1171                 }
1172
1173                 DEBUG(10, ("open_file_ntcreate: printer open fname=%s\n", fname));
1174
1175                 return print_fsp_open(conn, fname, result);
1176         }
1177
1178         if (!parent_dirname_talloc(talloc_tos(), fname, &parent_dir,
1179                                    &newname)) {
1180                 return NT_STATUS_NO_MEMORY;
1181         }
1182
1183         if (new_dos_attributes & FILE_FLAG_POSIX_SEMANTICS) {
1184                 posix_open = True;
1185                 unx_mode = (mode_t)(new_dos_attributes & ~FILE_FLAG_POSIX_SEMANTICS);
1186                 new_dos_attributes = 0;
1187         } else {
1188                 /* We add aARCH to this as this mode is only used if the file is
1189                  * created new. */
1190                 unx_mode = unix_mode(conn, new_dos_attributes | aARCH, fname,
1191                                      parent_dir);
1192         }
1193
1194         DEBUG(10, ("open_file_ntcreate: fname=%s, dos_attrs=0x%x "
1195                    "access_mask=0x%x share_access=0x%x "
1196                    "create_disposition = 0x%x create_options=0x%x "
1197                    "unix mode=0%o oplock_request=%d\n",
1198                    fname, new_dos_attributes, access_mask, share_access,
1199                    create_disposition, create_options, unx_mode,
1200                    oplock_request));
1201
1202         if ((req == NULL) && ((oplock_request & INTERNAL_OPEN_ONLY) == 0)) {
1203                 DEBUG(0, ("No smb request but not an internal only open!\n"));
1204                 return NT_STATUS_INTERNAL_ERROR;
1205         }
1206
1207         /*
1208          * Only non-internal opens can be deferred at all
1209          */
1210
1211         if ((req != NULL)
1212             && ((pml = get_open_deferred_message(req->mid)) != NULL)) {
1213                 struct deferred_open_record *state =
1214                         (struct deferred_open_record *)pml->private_data.data;
1215
1216                 /* Remember the absolute time of the original
1217                    request with this mid. We'll use it later to
1218                    see if this has timed out. */
1219
1220                 request_time = pml->request_time;
1221
1222                 /* Remove the deferred open entry under lock. */
1223                 lck = get_share_mode_lock(NULL, state->id, NULL, NULL);
1224                 if (lck == NULL) {
1225                         DEBUG(0, ("could not get share mode lock\n"));
1226                 } else {
1227                         del_deferred_open_entry(lck, req->mid);
1228                         TALLOC_FREE(lck);
1229                 }
1230
1231                 /* Ensure we don't reprocess this message. */
1232                 remove_deferred_open_smb_message(req->mid);
1233         }
1234
1235         status = check_name(conn, fname);
1236         if (!NT_STATUS_IS_OK(status)) {
1237                 return status;
1238         } 
1239
1240         if (!posix_open) {
1241                 new_dos_attributes &= SAMBA_ATTRIBUTES_MASK;
1242                 if (file_existed) {
1243                         existing_dos_attributes = dos_mode(conn, fname, psbuf);
1244                 }
1245         }
1246
1247         /* ignore any oplock requests if oplocks are disabled */
1248         if (!lp_oplocks(SNUM(conn)) || global_client_failed_oplock_break ||
1249             IS_VETO_OPLOCK_PATH(conn, fname)) {
1250                 /* Mask off everything except the private Samba bits. */
1251                 oplock_request &= SAMBA_PRIVATE_OPLOCK_MASK;
1252         }
1253
1254         /* this is for OS/2 long file names - say we don't support them */
1255         if (!lp_posix_pathnames() && strstr(fname,".+,;=[].")) {
1256                 /* OS/2 Workplace shell fix may be main code stream in a later
1257                  * release. */
1258                 DEBUG(5,("open_file_ntcreate: OS/2 long filenames are not "
1259                          "supported.\n"));
1260                 if (use_nt_status()) {
1261                         return NT_STATUS_OBJECT_NAME_NOT_FOUND;
1262                 }
1263                 return NT_STATUS_DOS(ERRDOS, ERRcannotopen);
1264         }
1265
1266         switch( create_disposition ) {
1267                 /*
1268                  * Currently we're using FILE_SUPERSEDE as the same as
1269                  * FILE_OVERWRITE_IF but they really are
1270                  * different. FILE_SUPERSEDE deletes an existing file
1271                  * (requiring delete access) then recreates it.
1272                  */
1273                 case FILE_SUPERSEDE:
1274                         /* If file exists replace/overwrite. If file doesn't
1275                          * exist create. */
1276                         flags2 |= (O_CREAT | O_TRUNC);
1277                         break;
1278
1279                 case FILE_OVERWRITE_IF:
1280                         /* If file exists replace/overwrite. If file doesn't
1281                          * exist create. */
1282                         flags2 |= (O_CREAT | O_TRUNC);
1283                         break;
1284
1285                 case FILE_OPEN:
1286                         /* If file exists open. If file doesn't exist error. */
1287                         if (!file_existed) {
1288                                 DEBUG(5,("open_file_ntcreate: FILE_OPEN "
1289                                          "requested for file %s and file "
1290                                          "doesn't exist.\n", fname ));
1291                                 errno = ENOENT;
1292                                 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
1293                         }
1294                         break;
1295
1296                 case FILE_OVERWRITE:
1297                         /* If file exists overwrite. If file doesn't exist
1298                          * error. */
1299                         if (!file_existed) {
1300                                 DEBUG(5,("open_file_ntcreate: FILE_OVERWRITE "
1301                                          "requested for file %s and file "
1302                                          "doesn't exist.\n", fname ));
1303                                 errno = ENOENT;
1304                                 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
1305                         }
1306                         flags2 |= O_TRUNC;
1307                         break;
1308
1309                 case FILE_CREATE:
1310                         /* If file exists error. If file doesn't exist
1311                          * create. */
1312                         if (file_existed) {
1313                                 DEBUG(5,("open_file_ntcreate: FILE_CREATE "
1314                                          "requested for file %s and file "
1315                                          "already exists.\n", fname ));
1316                                 if (S_ISDIR(psbuf->st_mode)) {
1317                                         errno = EISDIR;
1318                                 } else {
1319                                         errno = EEXIST;
1320                                 }
1321                                 return map_nt_error_from_unix(errno);
1322                         }
1323                         flags2 |= (O_CREAT|O_EXCL);
1324                         break;
1325
1326                 case FILE_OPEN_IF:
1327                         /* If file exists open. If file doesn't exist
1328                          * create. */
1329                         flags2 |= O_CREAT;
1330                         break;
1331
1332                 default:
1333                         return NT_STATUS_INVALID_PARAMETER;
1334         }
1335
1336         /* We only care about matching attributes on file exists and
1337          * overwrite. */
1338
1339         if (!posix_open && file_existed && ((create_disposition == FILE_OVERWRITE) ||
1340                              (create_disposition == FILE_OVERWRITE_IF))) {
1341                 if (!open_match_attributes(conn, fname,
1342                                            existing_dos_attributes,
1343                                            new_dos_attributes, psbuf->st_mode,
1344                                            unx_mode, &new_unx_mode)) {
1345                         DEBUG(5,("open_file_ntcreate: attributes missmatch "
1346                                  "for file %s (%x %x) (0%o, 0%o)\n",
1347                                  fname, existing_dos_attributes,
1348                                  new_dos_attributes,
1349                                  (unsigned int)psbuf->st_mode,
1350                                  (unsigned int)unx_mode ));
1351                         errno = EACCES;
1352                         return NT_STATUS_ACCESS_DENIED;
1353                 }
1354         }
1355
1356         /* This is a nasty hack - must fix... JRA. */
1357         if (access_mask == MAXIMUM_ALLOWED_ACCESS) {
1358                 open_access_mask = access_mask = FILE_GENERIC_ALL;
1359         }
1360
1361         /*
1362          * Convert GENERIC bits to specific bits.
1363          */
1364
1365         se_map_generic(&access_mask, &file_generic_mapping);
1366         open_access_mask = access_mask;
1367
1368         if (flags2 & O_TRUNC) {
1369                 open_access_mask |= FILE_WRITE_DATA; /* This will cause oplock breaks. */
1370         }
1371
1372         DEBUG(10, ("open_file_ntcreate: fname=%s, after mapping "
1373                    "access_mask=0x%x\n", fname, access_mask ));
1374
1375         /*
1376          * Note that we ignore the append flag as append does not
1377          * mean the same thing under DOS and Unix.
1378          */
1379
1380         if (access_mask & (FILE_WRITE_DATA | FILE_APPEND_DATA)) {
1381                 /* DENY_DOS opens are always underlying read-write on the
1382                    file handle, no matter what the requested access mask
1383                     says. */
1384                 if ((create_options & NTCREATEX_OPTIONS_PRIVATE_DENY_DOS) ||
1385                         access_mask & (FILE_READ_ATTRIBUTES|FILE_READ_DATA|FILE_READ_EA|FILE_EXECUTE)) {
1386                         flags = O_RDWR;
1387                 } else {
1388                         flags = O_WRONLY;
1389                 }
1390         } else {
1391                 flags = O_RDONLY;
1392         }
1393
1394         /*
1395          * Currently we only look at FILE_WRITE_THROUGH for create options.
1396          */
1397
1398 #if defined(O_SYNC)
1399         if ((create_options & FILE_WRITE_THROUGH) && lp_strict_sync(SNUM(conn))) {
1400                 flags2 |= O_SYNC;
1401         }
1402 #endif /* O_SYNC */
1403   
1404         if (posix_open & (access_mask & FILE_APPEND_DATA)) {
1405                 flags2 |= O_APPEND;
1406         }
1407
1408         if (!posix_open && !CAN_WRITE(conn)) {
1409                 /*
1410                  * We should really return a permission denied error if either
1411                  * O_CREAT or O_TRUNC are set, but for compatibility with
1412                  * older versions of Samba we just AND them out.
1413                  */
1414                 flags2 &= ~(O_CREAT|O_TRUNC);
1415         }
1416
1417         /*
1418          * Ensure we can't write on a read-only share or file.
1419          */
1420
1421         if (flags != O_RDONLY && file_existed &&
1422             (!CAN_WRITE(conn) || IS_DOS_READONLY(existing_dos_attributes))) {
1423                 DEBUG(5,("open_file_ntcreate: write access requested for "
1424                          "file %s on read only %s\n",
1425                          fname, !CAN_WRITE(conn) ? "share" : "file" ));
1426                 errno = EACCES;
1427                 return NT_STATUS_ACCESS_DENIED;
1428         }
1429
1430         status = file_new(conn, &fsp);
1431         if(!NT_STATUS_IS_OK(status)) {
1432                 return status;
1433         }
1434
1435         fsp->file_id = vfs_file_id_from_sbuf(conn, psbuf);
1436         fsp->share_access = share_access;
1437         fsp->fh->private_options = create_options;
1438         fsp->access_mask = open_access_mask; /* We change this to the
1439                                               * requested access_mask after
1440                                               * the open is done. */
1441         fsp->posix_open = posix_open;
1442
1443         /* Ensure no SAMBA_PRIVATE bits can be set. */
1444         fsp->oplock_type = (oplock_request & ~SAMBA_PRIVATE_OPLOCK_MASK);
1445
1446         if (timeval_is_zero(&request_time)) {
1447                 request_time = fsp->open_time;
1448         }
1449
1450         if (file_existed) {
1451                 id = vfs_file_id_from_sbuf(conn, psbuf);
1452
1453                 lck = get_share_mode_lock(NULL, id,
1454                                           conn->connectpath,
1455                                           fname);
1456
1457                 if (lck == NULL) {
1458                         file_free(fsp);
1459                         DEBUG(0, ("Could not get share mode lock\n"));
1460                         return NT_STATUS_SHARING_VIOLATION;
1461                 }
1462
1463                 /* First pass - send break only on batch oplocks. */
1464                 if ((req != NULL)
1465                     && delay_for_oplocks(lck, fsp, req->mid, 1,
1466                                          oplock_request)) {
1467                         schedule_defer_open(lck, request_time, req);
1468                         TALLOC_FREE(lck);
1469                         file_free(fsp);
1470                         return NT_STATUS_SHARING_VIOLATION;
1471                 }
1472
1473                 /* Use the client requested access mask here, not the one we
1474                  * open with. */
1475                 status = open_mode_check(conn, fname, lck,
1476                                          access_mask, share_access,
1477                                          create_options, &file_existed);
1478
1479                 if (NT_STATUS_IS_OK(status)) {
1480                         /* We might be going to allow this open. Check oplock
1481                          * status again. */
1482                         /* Second pass - send break for both batch or
1483                          * exclusive oplocks. */
1484                         if ((req != NULL)
1485                              && delay_for_oplocks(lck, fsp, req->mid, 2,
1486                                                   oplock_request)) {
1487                                 schedule_defer_open(lck, request_time, req);
1488                                 TALLOC_FREE(lck);
1489                                 file_free(fsp);
1490                                 return NT_STATUS_SHARING_VIOLATION;
1491                         }
1492                 }
1493
1494                 if (NT_STATUS_EQUAL(status, NT_STATUS_DELETE_PENDING)) {
1495                         /* DELETE_PENDING is not deferred for a second */
1496                         TALLOC_FREE(lck);
1497                         file_free(fsp);
1498                         return status;
1499                 }
1500
1501                 if (!NT_STATUS_IS_OK(status)) {
1502                         uint32 can_access_mask;
1503                         BOOL can_access = True;
1504
1505                         SMB_ASSERT(NT_STATUS_EQUAL(status, NT_STATUS_SHARING_VIOLATION));
1506
1507                         /* Check if this can be done with the deny_dos and fcb
1508                          * calls. */
1509                         if (create_options &
1510                             (NTCREATEX_OPTIONS_PRIVATE_DENY_DOS|
1511                              NTCREATEX_OPTIONS_PRIVATE_DENY_FCB)) {
1512                                 files_struct *fsp_dup;
1513
1514                                 if (req == NULL) {
1515                                         DEBUG(0, ("DOS open without an SMB "
1516                                                   "request!\n"));
1517                                         TALLOC_FREE(lck);
1518                                         file_free(fsp);
1519                                         return NT_STATUS_INTERNAL_ERROR;
1520                                 }
1521
1522                                 /* Use the client requested access mask here,
1523                                  * not the one we open with. */
1524                                 fsp_dup = fcb_or_dos_open(conn, fname, id,
1525                                                           req->smbpid,
1526                                                           req->vuid,
1527                                                           access_mask,
1528                                                           share_access,
1529                                                           create_options);
1530
1531                                 if (fsp_dup) {
1532                                         TALLOC_FREE(lck);
1533                                         file_free(fsp);
1534                                         if (pinfo) {
1535                                                 *pinfo = FILE_WAS_OPENED;
1536                                         }
1537                                         conn->num_files_open++;
1538                                         *result = fsp_dup;
1539                                         return NT_STATUS_OK;
1540                                 }
1541                         }
1542
1543                         /*
1544                          * This next line is a subtlety we need for
1545                          * MS-Access. If a file open will fail due to share
1546                          * permissions and also for security (access) reasons,
1547                          * we need to return the access failed error, not the
1548                          * share error. We can't open the file due to kernel
1549                          * oplock deadlock (it's possible we failed above on
1550                          * the open_mode_check()) so use a userspace check.
1551                          */
1552
1553                         if (flags & O_RDWR) {
1554                                 can_access_mask = FILE_READ_DATA|FILE_WRITE_DATA;
1555                         } else if (flags & O_WRONLY) {
1556                                 can_access_mask = FILE_WRITE_DATA;
1557                         } else {
1558                                 can_access_mask = FILE_READ_DATA;
1559                         }
1560
1561                         if (((can_access_mask & FILE_WRITE_DATA) && !CAN_WRITE(conn)) ||
1562                             !can_access_file(conn,fname,psbuf,can_access_mask)) {
1563                                 can_access = False;
1564                         }
1565
1566                         /* 
1567                          * If we're returning a share violation, ensure we
1568                          * cope with the braindead 1 second delay.
1569                          */
1570
1571                         if (!(oplock_request & INTERNAL_OPEN_ONLY) &&
1572                             lp_defer_sharing_violations()) {
1573                                 struct timeval timeout;
1574                                 struct deferred_open_record state;
1575                                 int timeout_usecs;
1576
1577                                 /* this is a hack to speed up torture tests
1578                                    in 'make test' */
1579                                 timeout_usecs = lp_parm_int(SNUM(conn),
1580                                                             "smbd","sharedelay",
1581                                                             SHARING_VIOLATION_USEC_WAIT);
1582
1583                                 /* This is a relative time, added to the absolute
1584                                    request_time value to get the absolute timeout time.
1585                                    Note that if this is the second or greater time we enter
1586                                    this codepath for this particular request mid then
1587                                    request_time is left as the absolute time of the *first*
1588                                    time this request mid was processed. This is what allows
1589                                    the request to eventually time out. */
1590
1591                                 timeout = timeval_set(0, timeout_usecs);
1592
1593                                 /* Nothing actually uses state.delayed_for_oplocks
1594                                    but it's handy to differentiate in debug messages
1595                                    between a 30 second delay due to oplock break, and
1596                                    a 1 second delay for share mode conflicts. */
1597
1598                                 state.delayed_for_oplocks = False;
1599                                 state.id = id;
1600
1601                                 if ((req != NULL)
1602                                     && !request_timed_out(request_time,
1603                                                           timeout)) {
1604                                         defer_open(lck, request_time, timeout,
1605                                                    req, &state);
1606                                 }
1607                         }
1608
1609                         TALLOC_FREE(lck);
1610                         if (can_access) {
1611                                 /*
1612                                  * We have detected a sharing violation here
1613                                  * so return the correct error code
1614                                  */
1615                                 status = NT_STATUS_SHARING_VIOLATION;
1616                         } else {
1617                                 status = NT_STATUS_ACCESS_DENIED;
1618                         }
1619                         file_free(fsp);
1620                         return status;
1621                 }
1622
1623                 /*
1624                  * We exit this block with the share entry *locked*.....
1625                  */
1626         }
1627
1628         SMB_ASSERT(!file_existed || (lck != NULL));
1629
1630         /*
1631          * Ensure we pay attention to default ACLs on directories if required.
1632          */
1633
1634         if ((flags2 & O_CREAT) && lp_inherit_acls(SNUM(conn)) &&
1635             (def_acl = directory_has_default_acl(conn, parent_dir))) {
1636                 unx_mode = 0777;
1637         }
1638
1639         DEBUG(4,("calling open_file with flags=0x%X flags2=0x%X mode=0%o, "
1640                 "access_mask = 0x%x, open_access_mask = 0x%x\n",
1641                  (unsigned int)flags, (unsigned int)flags2,
1642                  (unsigned int)unx_mode, (unsigned int)access_mask,
1643                  (unsigned int)open_access_mask));
1644
1645         /*
1646          * open_file strips any O_TRUNC flags itself.
1647          */
1648
1649         fsp_open = open_file(fsp, conn, req, parent_dir, newname, fname, psbuf,
1650                              flags|flags2, unx_mode, access_mask,
1651                              open_access_mask);
1652
1653         if (!NT_STATUS_IS_OK(fsp_open)) {
1654                 if (lck != NULL) {
1655                         TALLOC_FREE(lck);
1656                 }
1657                 file_free(fsp);
1658                 return fsp_open;
1659         }
1660
1661         if (!file_existed) {
1662
1663                 /*
1664                  * Deal with the race condition where two smbd's detect the
1665                  * file doesn't exist and do the create at the same time. One
1666                  * of them will win and set a share mode, the other (ie. this
1667                  * one) should check if the requested share mode for this
1668                  * create is allowed.
1669                  */
1670
1671                 /*
1672                  * Now the file exists and fsp is successfully opened,
1673                  * fsp->dev and fsp->inode are valid and should replace the
1674                  * dev=0,inode=0 from a non existent file. Spotted by
1675                  * Nadav Danieli <nadavd@exanet.com>. JRA.
1676                  */
1677
1678                 id = fsp->file_id;
1679
1680                 lck = get_share_mode_lock(NULL, id,
1681                                           conn->connectpath,
1682                                           fname);
1683
1684                 if (lck == NULL) {
1685                         DEBUG(0, ("open_file_ntcreate: Could not get share "
1686                                   "mode lock for %s\n", fname));
1687                         fd_close(conn, fsp);
1688                         file_free(fsp);
1689                         return NT_STATUS_SHARING_VIOLATION;
1690                 }
1691
1692                 /* First pass - send break only on batch oplocks. */
1693                 if ((req != NULL)
1694                     && delay_for_oplocks(lck, fsp, req->mid, 1,
1695                                          oplock_request)) {
1696                         schedule_defer_open(lck, request_time, req);
1697                         TALLOC_FREE(lck);
1698                         fd_close(conn, fsp);
1699                         file_free(fsp);
1700                         return NT_STATUS_SHARING_VIOLATION;
1701                 }
1702
1703                 status = open_mode_check(conn, fname, lck,
1704                                          access_mask, share_access,
1705                                          create_options, &file_existed);
1706
1707                 if (NT_STATUS_IS_OK(status)) {
1708                         /* We might be going to allow this open. Check oplock
1709                          * status again. */
1710                         /* Second pass - send break for both batch or
1711                          * exclusive oplocks. */
1712                         if ((req != NULL)
1713                             && delay_for_oplocks(lck, fsp, req->mid, 2,
1714                                                  oplock_request)) {
1715                                 schedule_defer_open(lck, request_time, req);
1716                                 TALLOC_FREE(lck);
1717                                 fd_close(conn, fsp);
1718                                 file_free(fsp);
1719                                 return NT_STATUS_SHARING_VIOLATION;
1720                         }
1721                 }
1722
1723                 if (!NT_STATUS_IS_OK(status)) {
1724                         struct deferred_open_record state;
1725
1726                         fd_close(conn, fsp);
1727                         file_free(fsp);
1728
1729                         state.delayed_for_oplocks = False;
1730                         state.id = id;
1731
1732                         /* Do it all over again immediately. In the second
1733                          * round we will find that the file existed and handle
1734                          * the DELETE_PENDING and FCB cases correctly. No need
1735                          * to duplicate the code here. Essentially this is a
1736                          * "goto top of this function", but don't tell
1737                          * anybody... */
1738
1739                         if (req != NULL) {
1740                                 defer_open(lck, request_time, timeval_zero(),
1741                                            req, &state);
1742                         }
1743                         TALLOC_FREE(lck);
1744                         return status;
1745                 }
1746
1747                 /*
1748                  * We exit this block with the share entry *locked*.....
1749                  */
1750
1751         }
1752
1753         SMB_ASSERT(lck != NULL);
1754
1755         /* note that we ignore failure for the following. It is
1756            basically a hack for NFS, and NFS will never set one of
1757            these only read them. Nobody but Samba can ever set a deny
1758            mode and we have already checked our more authoritative
1759            locking database for permission to set this deny mode. If
1760            the kernel refuses the operations then the kernel is wrong.
1761            note that GPFS supports it as well - jmcd */
1762
1763         ret_flock = SMB_VFS_KERNEL_FLOCK(fsp, fsp->fh->fd, share_access);
1764         if(ret_flock == -1 ){
1765
1766                 TALLOC_FREE(lck);
1767                 fd_close(conn, fsp);
1768                 file_free(fsp);
1769                 
1770                 return NT_STATUS_SHARING_VIOLATION;
1771         }
1772
1773         /*
1774          * At this point onwards, we can guarentee that the share entry
1775          * is locked, whether we created the file or not, and that the
1776          * deny mode is compatible with all current opens.
1777          */
1778
1779         /*
1780          * If requested, truncate the file.
1781          */
1782
1783         if (flags2&O_TRUNC) {
1784                 /*
1785                  * We are modifing the file after open - update the stat
1786                  * struct..
1787                  */
1788                 if ((SMB_VFS_FTRUNCATE(fsp,fsp->fh->fd,0) == -1) ||
1789                     (SMB_VFS_FSTAT(fsp,fsp->fh->fd,psbuf)==-1)) {
1790                         status = map_nt_error_from_unix(errno);
1791                         TALLOC_FREE(lck);
1792                         fd_close(conn,fsp);
1793                         file_free(fsp);
1794                         return status;
1795                 }
1796         }
1797
1798         /* Record the options we were opened with. */
1799         fsp->share_access = share_access;
1800         fsp->fh->private_options = create_options;
1801         fsp->access_mask = access_mask;
1802
1803         if (file_existed) {
1804                 /* stat opens on existing files don't get oplocks. */
1805                 if (is_stat_open(open_access_mask)) {
1806                         fsp->oplock_type = NO_OPLOCK;
1807                 }
1808
1809                 if (!(flags2 & O_TRUNC)) {
1810                         info = FILE_WAS_OPENED;
1811                 } else {
1812                         info = FILE_WAS_OVERWRITTEN;
1813                 }
1814         } else {
1815                 info = FILE_WAS_CREATED;
1816         }
1817
1818         if (pinfo) {
1819                 *pinfo = info;
1820         }
1821
1822         /* 
1823          * Setup the oplock info in both the shared memory and
1824          * file structs.
1825          */
1826
1827         if ((fsp->oplock_type != NO_OPLOCK) &&
1828             (fsp->oplock_type != FAKE_LEVEL_II_OPLOCK)) {
1829                 if (!set_file_oplock(fsp, fsp->oplock_type)) {
1830                         /* Could not get the kernel oplock */
1831                         fsp->oplock_type = NO_OPLOCK;
1832                 }
1833         }
1834
1835         if (info == FILE_WAS_OVERWRITTEN || info == FILE_WAS_CREATED || info == FILE_WAS_SUPERSEDED) {
1836                 new_file_created = True;
1837         }
1838
1839         set_share_mode(lck, fsp, current_user.ut.uid, 0, fsp->oplock_type, new_file_created);
1840
1841         /* Handle strange delete on close create semantics. */
1842         if ((create_options & FILE_DELETE_ON_CLOSE) && can_set_initial_delete_on_close(lck)) {
1843                 status = can_set_delete_on_close(fsp, True, new_dos_attributes);
1844
1845                 if (!NT_STATUS_IS_OK(status)) {
1846                         /* Remember to delete the mode we just added. */
1847                         del_share_mode(lck, fsp);
1848                         TALLOC_FREE(lck);
1849                         fd_close(conn,fsp);
1850                         file_free(fsp);
1851                         return status;
1852                 }
1853                 /* Note that here we set the *inital* delete on close flag,
1854                    not the regular one. The magic gets handled in close. */
1855                 fsp->initial_delete_on_close = True;
1856         }
1857         
1858         if (new_file_created) {
1859                 /* Files should be initially set as archive */
1860                 if (lp_map_archive(SNUM(conn)) ||
1861                     lp_store_dos_attributes(SNUM(conn))) {
1862                         if (!posix_open) {
1863                                 file_set_dosmode(conn, fname,
1864                                          new_dos_attributes | aARCH, NULL,
1865                                          parent_dir);
1866                         }
1867                 }
1868         }
1869
1870         /*
1871          * Take care of inherited ACLs on created files - if default ACL not
1872          * selected.
1873          */
1874
1875         if (!posix_open && !file_existed && !def_acl) {
1876
1877                 int saved_errno = errno; /* We might get ENOSYS in the next
1878                                           * call.. */
1879
1880                 if (SMB_VFS_FCHMOD_ACL(fsp, fsp->fh->fd, unx_mode) == -1 &&
1881                     errno == ENOSYS) {
1882                         errno = saved_errno; /* Ignore ENOSYS */
1883                 }
1884
1885         } else if (new_unx_mode) {
1886
1887                 int ret = -1;
1888
1889                 /* Attributes need changing. File already existed. */
1890
1891                 {
1892                         int saved_errno = errno; /* We might get ENOSYS in the
1893                                                   * next call.. */
1894                         ret = SMB_VFS_FCHMOD_ACL(fsp, fsp->fh->fd,
1895                                                  new_unx_mode);
1896
1897                         if (ret == -1 && errno == ENOSYS) {
1898                                 errno = saved_errno; /* Ignore ENOSYS */
1899                         } else {
1900                                 DEBUG(5, ("open_file_ntcreate: reset "
1901                                           "attributes of file %s to 0%o\n",
1902                                           fname, (unsigned int)new_unx_mode));
1903                                 ret = 0; /* Don't do the fchmod below. */
1904                         }
1905                 }
1906
1907                 if ((ret == -1) &&
1908                     (SMB_VFS_FCHMOD(fsp, fsp->fh->fd, new_unx_mode) == -1))
1909                         DEBUG(5, ("open_file_ntcreate: failed to reset "
1910                                   "attributes of file %s to 0%o\n",
1911                                   fname, (unsigned int)new_unx_mode));
1912         }
1913
1914         /* If this is a successful open, we must remove any deferred open
1915          * records. */
1916         if (req != NULL) {
1917                 del_deferred_open_entry(lck, req->mid);
1918         }
1919         TALLOC_FREE(lck);
1920
1921         conn->num_files_open++;
1922
1923         *result = fsp;
1924         return NT_STATUS_OK;
1925 }
1926
1927 /****************************************************************************
1928  Open a file for for write to ensure that we can fchmod it.
1929 ****************************************************************************/
1930
1931 NTSTATUS open_file_fchmod(connection_struct *conn, const char *fname,
1932                           SMB_STRUCT_STAT *psbuf, files_struct **result)
1933 {
1934         files_struct *fsp = NULL;
1935         NTSTATUS status;
1936
1937         if (!VALID_STAT(*psbuf)) {
1938                 return NT_STATUS_INVALID_PARAMETER;
1939         }
1940
1941         status = file_new(conn, &fsp);
1942         if(!NT_STATUS_IS_OK(status)) {
1943                 return status;
1944         }
1945
1946         /* note! we must use a non-zero desired access or we don't get
1947            a real file descriptor. Oh what a twisted web we weave. */
1948         status = open_file(fsp, conn, NULL, NULL, NULL, fname, psbuf, O_WRONLY,
1949                            0, FILE_WRITE_DATA, FILE_WRITE_DATA);
1950
1951         /* 
1952          * This is not a user visible file open.
1953          * Don't set a share mode and don't increment
1954          * the conn->num_files_open.
1955          */
1956
1957         if (!NT_STATUS_IS_OK(status)) {
1958                 file_free(fsp);
1959                 return status;
1960         }
1961
1962         *result = fsp;
1963         return NT_STATUS_OK;
1964 }
1965
1966 /****************************************************************************
1967  Close the fchmod file fd - ensure no locks are lost.
1968 ****************************************************************************/
1969
1970 NTSTATUS close_file_fchmod(files_struct *fsp)
1971 {
1972         NTSTATUS status = fd_close(fsp->conn, fsp);
1973         file_free(fsp);
1974         return status;
1975 }
1976
1977 static NTSTATUS mkdir_internal(connection_struct *conn,
1978                                 const char *name,
1979                                 uint32 file_attributes,
1980                                 SMB_STRUCT_STAT *psbuf)
1981 {
1982         mode_t mode;
1983         char *parent_dir;
1984         const char *dirname;
1985         NTSTATUS status;
1986         bool posix_open = false;
1987
1988         if(!CAN_WRITE(conn)) {
1989                 DEBUG(5,("mkdir_internal: failing create on read-only share "
1990                          "%s\n", lp_servicename(SNUM(conn))));
1991                 return NT_STATUS_ACCESS_DENIED;
1992         }
1993
1994         status = check_name(conn, name);
1995         if (!NT_STATUS_IS_OK(status)) {
1996                 return status;
1997         }
1998
1999         if (!parent_dirname_talloc(talloc_tos(), name, &parent_dir,
2000                                    &dirname)) {
2001                 return NT_STATUS_NO_MEMORY;
2002         }
2003
2004         if (file_attributes & FILE_FLAG_POSIX_SEMANTICS) {
2005                 posix_open = true;
2006                 mode = (mode_t)(file_attributes & ~FILE_FLAG_POSIX_SEMANTICS);
2007         } else {
2008                 mode = unix_mode(conn, aDIR, name, parent_dir);
2009         }
2010
2011         if (SMB_VFS_MKDIR(conn, name, mode) != 0) {
2012                 return map_nt_error_from_unix(errno);
2013         }
2014
2015         /* Ensure we're checking for a symlink here.... */
2016         /* We don't want to get caught by a symlink racer. */
2017
2018         if (SMB_VFS_LSTAT(conn, name, psbuf) == -1) {
2019                 DEBUG(2, ("Could not stat directory '%s' just created: %s\n",
2020                           name, strerror(errno)));
2021                 return map_nt_error_from_unix(errno);
2022         }
2023
2024         if (!S_ISDIR(psbuf->st_mode)) {
2025                 DEBUG(0, ("Directory just '%s' created is not a directory\n",
2026                           name));
2027                 return NT_STATUS_ACCESS_DENIED;
2028         }
2029
2030         if (lp_store_dos_attributes(SNUM(conn))) {
2031                 if (!posix_open) {
2032                         file_set_dosmode(conn, name,
2033                                  file_attributes | aDIR, NULL,
2034                                  parent_dir);
2035                 }
2036         }
2037
2038         if (lp_inherit_perms(SNUM(conn))) {
2039                 inherit_access_acl(conn, parent_dir, name, mode);
2040         }
2041
2042         if (!(file_attributes & FILE_FLAG_POSIX_SEMANTICS)) {
2043                 /*
2044                  * Check if high bits should have been set,
2045                  * then (if bits are missing): add them.
2046                  * Consider bits automagically set by UNIX, i.e. SGID bit from parent
2047                  * dir.
2048                  */
2049                 if (mode & ~(S_IRWXU|S_IRWXG|S_IRWXO) && (mode & ~psbuf->st_mode)) {
2050                         SMB_VFS_CHMOD(conn, name,
2051                                       psbuf->st_mode | (mode & ~psbuf->st_mode));
2052                 }
2053         }
2054
2055         /* Change the owner if required. */
2056         if (lp_inherit_owner(SNUM(conn))) {
2057                 change_dir_owner_to_parent(conn, parent_dir, name, psbuf);
2058         }
2059
2060         notify_fname(conn, NOTIFY_ACTION_ADDED, FILE_NOTIFY_CHANGE_DIR_NAME,
2061                      name);
2062
2063         return NT_STATUS_OK;
2064 }
2065
2066 /****************************************************************************
2067  Open a directory from an NT SMB call.
2068 ****************************************************************************/
2069
2070 NTSTATUS open_directory(connection_struct *conn,
2071                         struct smb_request *req,
2072                         const char *fname,
2073                         SMB_STRUCT_STAT *psbuf,
2074                         uint32 access_mask,
2075                         uint32 share_access,
2076                         uint32 create_disposition,
2077                         uint32 create_options,
2078                         uint32 file_attributes,
2079                         int *pinfo,
2080                         files_struct **result)
2081 {
2082         files_struct *fsp = NULL;
2083         BOOL dir_existed = VALID_STAT(*psbuf) ? True : False;
2084         struct share_mode_lock *lck = NULL;
2085         NTSTATUS status;
2086         int info = 0;
2087
2088         DEBUG(5,("open_directory: opening directory %s, access_mask = 0x%x, "
2089                  "share_access = 0x%x create_options = 0x%x, "
2090                  "create_disposition = 0x%x, file_attributes = 0x%x\n",
2091                  fname,
2092                  (unsigned int)access_mask,
2093                  (unsigned int)share_access,
2094                  (unsigned int)create_options,
2095                  (unsigned int)create_disposition,
2096                  (unsigned int)file_attributes));
2097
2098         if (is_ntfs_stream_name(fname)) {
2099                 DEBUG(0,("open_directory: %s is a stream name!\n", fname ));
2100                 return NT_STATUS_NOT_A_DIRECTORY;
2101         }
2102
2103         switch( create_disposition ) {
2104                 case FILE_OPEN:
2105
2106                         info = FILE_WAS_OPENED;
2107
2108                         /*
2109                          * We want to follow symlinks here.
2110                          */
2111
2112                         if (SMB_VFS_STAT(conn, fname, psbuf) != 0) {
2113                                 return map_nt_error_from_unix(errno);
2114                         }
2115                                 
2116                         break;
2117
2118                 case FILE_CREATE:
2119
2120                         /* If directory exists error. If directory doesn't
2121                          * exist create. */
2122
2123                         status = mkdir_internal(conn,
2124                                                 fname,
2125                                                 file_attributes,
2126                                                 psbuf);
2127
2128                         if (!NT_STATUS_IS_OK(status)) {
2129                                 DEBUG(2, ("open_directory: unable to create "
2130                                           "%s. Error was %s\n", fname,
2131                                           nt_errstr(status)));
2132                                 return status;
2133                         }
2134
2135                         info = FILE_WAS_CREATED;
2136                         break;
2137
2138                 case FILE_OPEN_IF:
2139                         /*
2140                          * If directory exists open. If directory doesn't
2141                          * exist create.
2142                          */
2143
2144                         status = mkdir_internal(conn,
2145                                                 fname,
2146                                                 file_attributes,
2147                                                 psbuf);
2148
2149                         if (NT_STATUS_IS_OK(status)) {
2150                                 info = FILE_WAS_CREATED;
2151                         }
2152
2153                         if (NT_STATUS_EQUAL(status,
2154                                             NT_STATUS_OBJECT_NAME_COLLISION)) {
2155                                 info = FILE_WAS_OPENED;
2156                                 status = NT_STATUS_OK;
2157                         }
2158                                 
2159                         break;
2160
2161                 case FILE_SUPERSEDE:
2162                 case FILE_OVERWRITE:
2163                 case FILE_OVERWRITE_IF:
2164                 default:
2165                         DEBUG(5,("open_directory: invalid create_disposition "
2166                                  "0x%x for directory %s\n",
2167                                  (unsigned int)create_disposition, fname));
2168                         return NT_STATUS_INVALID_PARAMETER;
2169         }
2170
2171         if(!S_ISDIR(psbuf->st_mode)) {
2172                 DEBUG(5,("open_directory: %s is not a directory !\n",
2173                          fname ));
2174                 return NT_STATUS_NOT_A_DIRECTORY;
2175         }
2176
2177         status = file_new(conn, &fsp);
2178         if(!NT_STATUS_IS_OK(status)) {
2179                 return status;
2180         }
2181
2182         /*
2183          * Setup the files_struct for it.
2184          */
2185         
2186         fsp->mode = psbuf->st_mode;
2187         fsp->file_id = vfs_file_id_from_sbuf(conn, psbuf);
2188         fsp->vuid = req ? req->vuid : UID_FIELD_INVALID;
2189         fsp->file_pid = req ? req->smbpid : 0;
2190         fsp->can_lock = False;
2191         fsp->can_read = False;
2192         fsp->can_write = False;
2193
2194         fsp->share_access = share_access;
2195         fsp->fh->private_options = create_options;
2196         fsp->access_mask = access_mask;
2197
2198         fsp->print_file = False;
2199         fsp->modified = False;
2200         fsp->oplock_type = NO_OPLOCK;
2201         fsp->sent_oplock_break = NO_BREAK_SENT;
2202         fsp->is_directory = True;
2203         fsp->is_stat = False;
2204         fsp->posix_open = (file_attributes & FILE_FLAG_POSIX_SEMANTICS) ? True : False;
2205
2206         string_set(&fsp->fsp_name,fname);
2207
2208         lck = get_share_mode_lock(NULL, fsp->file_id,
2209                                   conn->connectpath,
2210                                   fname);
2211
2212         if (lck == NULL) {
2213                 DEBUG(0, ("open_directory: Could not get share mode lock for %s\n", fname));
2214                 file_free(fsp);
2215                 return NT_STATUS_SHARING_VIOLATION;
2216         }
2217
2218         status = open_mode_check(conn, fname, lck,
2219                                 access_mask, share_access,
2220                                 create_options, &dir_existed);
2221
2222         if (!NT_STATUS_IS_OK(status)) {
2223                 TALLOC_FREE(lck);
2224                 file_free(fsp);
2225                 return status;
2226         }
2227
2228         set_share_mode(lck, fsp, current_user.ut.uid, 0, NO_OPLOCK, True);
2229
2230         /* For directories the delete on close bit at open time seems
2231            always to be honored on close... See test 19 in Samba4 BASE-DELETE. */
2232         if (create_options & FILE_DELETE_ON_CLOSE) {
2233                 status = can_set_delete_on_close(fsp, True, 0);
2234                 if (!NT_STATUS_IS_OK(status) && !NT_STATUS_EQUAL(status, NT_STATUS_DIRECTORY_NOT_EMPTY)) {
2235                         TALLOC_FREE(lck);
2236                         file_free(fsp);
2237                         return status;
2238                 }
2239
2240                 if (NT_STATUS_IS_OK(status)) {
2241                         /* Note that here we set the *inital* delete on close flag,
2242                            not the regular one. The magic gets handled in close. */
2243                         fsp->initial_delete_on_close = True;
2244                 }
2245         }
2246
2247         TALLOC_FREE(lck);
2248
2249         if (pinfo) {
2250                 *pinfo = info;
2251         }
2252
2253         conn->num_files_open++;
2254
2255         *result = fsp;
2256         return NT_STATUS_OK;
2257 }
2258
2259 NTSTATUS create_directory(connection_struct *conn, const char *directory)
2260 {
2261         NTSTATUS status;
2262         SMB_STRUCT_STAT sbuf;
2263         files_struct *fsp;
2264
2265         SET_STAT_INVALID(sbuf);
2266         
2267         status = open_directory(conn, NULL, directory, &sbuf,
2268                                 FILE_READ_ATTRIBUTES, /* Just a stat open */
2269                                 FILE_SHARE_NONE, /* Ignored for stat opens */
2270                                 FILE_CREATE,
2271                                 0,
2272                                 FILE_ATTRIBUTE_DIRECTORY,
2273                                 NULL,
2274                                 &fsp);
2275
2276         if (NT_STATUS_IS_OK(status)) {
2277                 close_file(fsp, NORMAL_CLOSE);
2278         }
2279
2280         return status;
2281 }
2282
2283 /****************************************************************************
2284  Open a pseudo-file (no locking checks - a 'stat' open).
2285 ****************************************************************************/
2286
2287 NTSTATUS open_file_stat(connection_struct *conn, struct smb_request *req,
2288                         const char *fname, SMB_STRUCT_STAT *psbuf,
2289                         files_struct **result)
2290 {
2291         files_struct *fsp = NULL;
2292         NTSTATUS status;
2293
2294         if (!VALID_STAT(*psbuf)) {
2295                 return NT_STATUS_INVALID_PARAMETER;
2296         }
2297
2298         /* Can't 'stat' open directories. */
2299         if(S_ISDIR(psbuf->st_mode)) {
2300                 return NT_STATUS_FILE_IS_A_DIRECTORY;
2301         }
2302
2303         status = file_new(conn, &fsp);
2304         if(!NT_STATUS_IS_OK(status)) {
2305                 return status;
2306         }
2307
2308         DEBUG(5,("open_file_stat: 'opening' file %s\n", fname));
2309
2310         /*
2311          * Setup the files_struct for it.
2312          */
2313         
2314         fsp->mode = psbuf->st_mode;
2315         fsp->file_id = vfs_file_id_from_sbuf(conn, psbuf);
2316         fsp->vuid = req ? req->vuid : UID_FIELD_INVALID;
2317         fsp->file_pid = req ? req->smbpid : 0;
2318         fsp->can_lock = False;
2319         fsp->can_read = False;
2320         fsp->can_write = False;
2321         fsp->print_file = False;
2322         fsp->modified = False;
2323         fsp->oplock_type = NO_OPLOCK;
2324         fsp->sent_oplock_break = NO_BREAK_SENT;
2325         fsp->is_directory = False;
2326         fsp->is_stat = True;
2327         string_set(&fsp->fsp_name,fname);
2328
2329         conn->num_files_open++;
2330
2331         *result = fsp;
2332         return NT_STATUS_OK;
2333 }
2334
2335 /****************************************************************************
2336  Receive notification that one of our open files has been renamed by another
2337  smbd process.
2338 ****************************************************************************/
2339
2340 void msg_file_was_renamed(struct messaging_context *msg,
2341                           void *private_data,
2342                           uint32_t msg_type,
2343                           struct server_id server_id,
2344                           DATA_BLOB *data)
2345 {
2346         files_struct *fsp;
2347         char *frm = (char *)data->data;
2348         struct file_id id;
2349         const char *sharepath;
2350         const char *newname;
2351         size_t sp_len;
2352
2353         if (data->data == NULL
2354             || data->length < MSG_FILE_RENAMED_MIN_SIZE + 2) {
2355                 DEBUG(0, ("msg_file_was_renamed: Got invalid msg len %d\n",
2356                           (int)data->length));
2357                 return;
2358         }
2359
2360         /* Unpack the message. */
2361         pull_file_id_16(frm, &id);
2362         sharepath = &frm[16];
2363         newname = sharepath + strlen(sharepath) + 1;
2364         sp_len = strlen(sharepath);
2365
2366         DEBUG(10,("msg_file_was_renamed: Got rename message for sharepath %s, new name %s, "
2367                 "file_id %s\n",
2368                   sharepath, newname, file_id_string_tos(&id)));
2369
2370         for(fsp = file_find_di_first(id); fsp; fsp = file_find_di_next(fsp)) {
2371                 if (memcmp(fsp->conn->connectpath, sharepath, sp_len) == 0) {
2372                         DEBUG(10,("msg_file_was_renamed: renaming file fnum %d from %s -> %s\n",
2373                                 fsp->fnum, fsp->fsp_name, newname ));
2374                         string_set(&fsp->fsp_name, newname);
2375                 } else {
2376                         /* TODO. JRA. */
2377                         /* Now we have the complete path we can work out if this is
2378                            actually within this share and adjust newname accordingly. */
2379                         DEBUG(10,("msg_file_was_renamed: share mismatch (sharepath %s "
2380                                 "not sharepath %s) "
2381                                 "fnum %d from %s -> %s\n",
2382                                 fsp->conn->connectpath,
2383                                 sharepath,
2384                                 fsp->fnum,
2385                                 fsp->fsp_name,
2386                                 newname ));
2387                 }
2388         }
2389 }