s3: Lift smbd_server_conn from file_find_di_first
[samba.git] / source3 / smbd / open.c
1 /* 
2    Unix SMB/CIFS implementation.
3    file opening and share modes
4    Copyright (C) Andrew Tridgell 1992-1998
5    Copyright (C) Jeremy Allison 2001-2004
6    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 #include "printing.h"
24 #include "smbd/globals.h"
25 #include "fake_file.h"
26 #include "librpc/gen_ndr/messaging.h"
27 #include "../librpc/gen_ndr/ndr_security.h"
28
29 extern const struct generic_mapping file_generic_mapping;
30
31 struct deferred_open_record {
32         bool delayed_for_oplocks;
33         struct file_id id;
34 };
35
36 static NTSTATUS create_file_unixpath(connection_struct *conn,
37                                      struct smb_request *req,
38                                      struct smb_filename *smb_fname,
39                                      uint32_t access_mask,
40                                      uint32_t share_access,
41                                      uint32_t create_disposition,
42                                      uint32_t create_options,
43                                      uint32_t file_attributes,
44                                      uint32_t oplock_request,
45                                      uint64_t allocation_size,
46                                      uint32_t private_flags,
47                                      struct security_descriptor *sd,
48                                      struct ea_list *ea_list,
49
50                                      files_struct **result,
51                                      int *pinfo);
52
53 /****************************************************************************
54  SMB1 file varient of se_access_check. Never test FILE_READ_ATTRIBUTES.
55 ****************************************************************************/
56
57 NTSTATUS smb1_file_se_access_check(struct connection_struct *conn,
58                                 const struct security_descriptor *sd,
59                                 const struct security_token *token,
60                                 uint32_t access_desired,
61                                 uint32_t *access_granted)
62 {
63         *access_granted = 0;
64
65         if (get_current_uid(conn) == (uid_t)0) {
66                 /* I'm sorry sir, I didn't know you were root... */
67                 *access_granted = access_desired;
68                 if (access_desired & SEC_FLAG_MAXIMUM_ALLOWED) {
69                         *access_granted |= FILE_GENERIC_ALL;
70                 }
71                 return NT_STATUS_OK;
72         }
73
74         return se_access_check(sd,
75                                 token,
76                                 (access_desired & ~FILE_READ_ATTRIBUTES),
77                                 access_granted);
78 }
79
80 /****************************************************************************
81  Check if we have open rights.
82 ****************************************************************************/
83
84 NTSTATUS smbd_check_open_rights(struct connection_struct *conn,
85                                 const struct smb_filename *smb_fname,
86                                 uint32_t access_mask,
87                                 uint32_t *access_granted)
88 {
89         /* Check if we have rights to open. */
90         NTSTATUS status;
91         struct security_descriptor *sd = NULL;
92
93         status = SMB_VFS_GET_NT_ACL(conn, smb_fname->base_name,
94                         (SECINFO_OWNER |
95                         SECINFO_GROUP |
96                         SECINFO_DACL),&sd);
97
98         if (!NT_STATUS_IS_OK(status)) {
99                 DEBUG(10, ("smbd_check_open_rights: Could not get acl "
100                         "on %s: %s\n",
101                         smb_fname_str_dbg(smb_fname),
102                         nt_errstr(status)));
103                 return status;
104         }
105
106         status = smb1_file_se_access_check(conn,
107                                 sd,
108                                 get_current_nttok(conn),
109                                 access_mask,
110                                 access_granted);
111
112         DEBUG(10,("smbd_check_open_rights: file %s requesting "
113                 "0x%x returning 0x%x (%s)\n",
114                 smb_fname_str_dbg(smb_fname),
115                 (unsigned int)access_mask,
116                 (unsigned int)*access_granted,
117                 nt_errstr(status) ));
118
119         if (!NT_STATUS_IS_OK(status)) {
120                 if (DEBUGLEVEL >= 10) {
121                         DEBUG(10,("smbd_check_open_rights: acl for %s is:\n",
122                                 smb_fname_str_dbg(smb_fname) ));
123                         NDR_PRINT_DEBUG(security_descriptor, sd);
124                 }
125         }
126
127         TALLOC_FREE(sd);
128
129         return status;
130 }
131
132 /****************************************************************************
133  fd support routines - attempt to do a dos_open.
134 ****************************************************************************/
135
136 static NTSTATUS fd_open(struct connection_struct *conn,
137                     files_struct *fsp,
138                     int flags,
139                     mode_t mode)
140 {
141         struct smb_filename *smb_fname = fsp->fsp_name;
142         NTSTATUS status = NT_STATUS_OK;
143
144 #ifdef O_NOFOLLOW
145         /* 
146          * Never follow symlinks on a POSIX client. The
147          * client should be doing this.
148          */
149
150         if (fsp->posix_open || !lp_symlinks(SNUM(conn))) {
151                 flags |= O_NOFOLLOW;
152         }
153 #endif
154
155         fsp->fh->fd = SMB_VFS_OPEN(conn, smb_fname, fsp, flags, mode);
156         if (fsp->fh->fd == -1) {
157                 status = map_nt_error_from_unix(errno);
158                 if (errno == EMFILE) {
159                         static time_t last_warned = 0L;
160
161                         if (time((time_t *) NULL) > last_warned) {
162                                 DEBUG(0,("Too many open files, unable "
163                                         "to open more!  smbd's max "
164                                         "open files = %d\n",
165                                         lp_max_open_files()));
166                                 last_warned = time((time_t *) NULL);
167                         }
168                 }
169
170         }
171
172         DEBUG(10,("fd_open: name %s, flags = 0%o mode = 0%o, fd = %d. %s\n",
173                   smb_fname_str_dbg(smb_fname), flags, (int)mode, fsp->fh->fd,
174                 (fsp->fh->fd == -1) ? strerror(errno) : "" ));
175
176         return status;
177 }
178
179 /****************************************************************************
180  Close the file associated with a fsp.
181 ****************************************************************************/
182
183 NTSTATUS fd_close(files_struct *fsp)
184 {
185         int ret;
186
187         if (fsp->fh->fd == -1) {
188                 return NT_STATUS_OK; /* What we used to call a stat open. */
189         }
190         if (fsp->fh->ref_count > 1) {
191                 return NT_STATUS_OK; /* Shared handle. Only close last reference. */
192         }
193
194         ret = SMB_VFS_CLOSE(fsp);
195         fsp->fh->fd = -1;
196         if (ret == -1) {
197                 return map_nt_error_from_unix(errno);
198         }
199         return NT_STATUS_OK;
200 }
201
202 /****************************************************************************
203  Change the ownership of a file to that of the parent directory.
204  Do this by fd if possible.
205 ****************************************************************************/
206
207 void change_file_owner_to_parent(connection_struct *conn,
208                                         const char *inherit_from_dir,
209                                         files_struct *fsp)
210 {
211         struct smb_filename *smb_fname_parent = NULL;
212         NTSTATUS status;
213         int ret;
214
215         status = create_synthetic_smb_fname(talloc_tos(), inherit_from_dir,
216                                             NULL, NULL, &smb_fname_parent);
217         if (!NT_STATUS_IS_OK(status)) {
218                 return;
219         }
220
221         ret = SMB_VFS_STAT(conn, smb_fname_parent);
222         if (ret == -1) {
223                 DEBUG(0,("change_file_owner_to_parent: failed to stat parent "
224                          "directory %s. Error was %s\n",
225                          smb_fname_str_dbg(smb_fname_parent),
226                          strerror(errno)));
227                 return;
228         }
229
230         become_root();
231         ret = SMB_VFS_FCHOWN(fsp, smb_fname_parent->st.st_ex_uid, (gid_t)-1);
232         unbecome_root();
233         if (ret == -1) {
234                 DEBUG(0,("change_file_owner_to_parent: failed to fchown "
235                          "file %s to parent directory uid %u. Error "
236                          "was %s\n", fsp_str_dbg(fsp),
237                          (unsigned int)smb_fname_parent->st.st_ex_uid,
238                          strerror(errno) ));
239         }
240
241         DEBUG(10,("change_file_owner_to_parent: changed new file %s to "
242                   "parent directory uid %u.\n", fsp_str_dbg(fsp),
243                   (unsigned int)smb_fname_parent->st.st_ex_uid));
244
245         TALLOC_FREE(smb_fname_parent);
246 }
247
248 NTSTATUS change_dir_owner_to_parent(connection_struct *conn,
249                                        const char *inherit_from_dir,
250                                        const char *fname,
251                                        SMB_STRUCT_STAT *psbuf)
252 {
253         struct smb_filename *smb_fname_parent = NULL;
254         struct smb_filename *smb_fname_cwd = NULL;
255         char *saved_dir = NULL;
256         TALLOC_CTX *ctx = talloc_tos();
257         NTSTATUS status = NT_STATUS_OK;
258         int ret;
259
260         status = create_synthetic_smb_fname(ctx, inherit_from_dir, NULL, NULL,
261                                             &smb_fname_parent);
262         if (!NT_STATUS_IS_OK(status)) {
263                 return status;
264         }
265
266         ret = SMB_VFS_STAT(conn, smb_fname_parent);
267         if (ret == -1) {
268                 status = map_nt_error_from_unix(errno);
269                 DEBUG(0,("change_dir_owner_to_parent: failed to stat parent "
270                          "directory %s. Error was %s\n",
271                          smb_fname_str_dbg(smb_fname_parent),
272                          strerror(errno)));
273                 goto out;
274         }
275
276         /* We've already done an lstat into psbuf, and we know it's a
277            directory. If we can cd into the directory and the dev/ino
278            are the same then we can safely chown without races as
279            we're locking the directory in place by being in it.  This
280            should work on any UNIX (thanks tridge :-). JRA.
281         */
282
283         saved_dir = vfs_GetWd(ctx,conn);
284         if (!saved_dir) {
285                 status = map_nt_error_from_unix(errno);
286                 DEBUG(0,("change_dir_owner_to_parent: failed to get "
287                          "current working directory. Error was %s\n",
288                          strerror(errno)));
289                 goto out;
290         }
291
292         /* Chdir into the new path. */
293         if (vfs_ChDir(conn, fname) == -1) {
294                 status = map_nt_error_from_unix(errno);
295                 DEBUG(0,("change_dir_owner_to_parent: failed to change "
296                          "current working directory to %s. Error "
297                          "was %s\n", fname, strerror(errno) ));
298                 goto chdir;
299         }
300
301         status = create_synthetic_smb_fname(ctx, ".", NULL, NULL,
302                                             &smb_fname_cwd);
303         if (!NT_STATUS_IS_OK(status)) {
304                 return status;
305         }
306
307         ret = SMB_VFS_STAT(conn, smb_fname_cwd);
308         if (ret == -1) {
309                 status = map_nt_error_from_unix(errno);
310                 DEBUG(0,("change_dir_owner_to_parent: failed to stat "
311                          "directory '.' (%s) Error was %s\n",
312                          fname, strerror(errno)));
313                 goto chdir;
314         }
315
316         /* Ensure we're pointing at the same place. */
317         if (smb_fname_cwd->st.st_ex_dev != psbuf->st_ex_dev ||
318             smb_fname_cwd->st.st_ex_ino != psbuf->st_ex_ino ||
319             smb_fname_cwd->st.st_ex_mode != psbuf->st_ex_mode ) {
320                 DEBUG(0,("change_dir_owner_to_parent: "
321                          "device/inode/mode on directory %s changed. "
322                          "Refusing to chown !\n", fname ));
323                 status = NT_STATUS_ACCESS_DENIED;
324                 goto chdir;
325         }
326
327         become_root();
328         ret = SMB_VFS_CHOWN(conn, ".", smb_fname_parent->st.st_ex_uid,
329                             (gid_t)-1);
330         unbecome_root();
331         if (ret == -1) {
332                 status = map_nt_error_from_unix(errno);
333                 DEBUG(10,("change_dir_owner_to_parent: failed to chown "
334                           "directory %s to parent directory uid %u. "
335                           "Error was %s\n", fname,
336                           (unsigned int)smb_fname_parent->st.st_ex_uid,
337                           strerror(errno) ));
338                 goto chdir;
339         }
340
341         DEBUG(10,("change_dir_owner_to_parent: changed ownership of new "
342                   "directory %s to parent directory uid %u.\n",
343                   fname, (unsigned int)smb_fname_parent->st.st_ex_uid ));
344
345  chdir:
346         vfs_ChDir(conn,saved_dir);
347  out:
348         TALLOC_FREE(smb_fname_parent);
349         TALLOC_FREE(smb_fname_cwd);
350         return status;
351 }
352
353 /****************************************************************************
354  Open a file.
355 ****************************************************************************/
356
357 static NTSTATUS open_file(files_struct *fsp,
358                           connection_struct *conn,
359                           struct smb_request *req,
360                           const char *parent_dir,
361                           int flags,
362                           mode_t unx_mode,
363                           uint32 access_mask, /* client requested access mask. */
364                           uint32 open_access_mask) /* what we're actually using in the open. */
365 {
366         struct smb_filename *smb_fname = fsp->fsp_name;
367         NTSTATUS status = NT_STATUS_OK;
368         int accmode = (flags & O_ACCMODE);
369         int local_flags = flags;
370         bool file_existed = VALID_STAT(fsp->fsp_name->st);
371
372         fsp->fh->fd = -1;
373         errno = EPERM;
374
375         /* Check permissions */
376
377         /*
378          * This code was changed after seeing a client open request 
379          * containing the open mode of (DENY_WRITE/read-only) with
380          * the 'create if not exist' bit set. The previous code
381          * would fail to open the file read only on a read-only share
382          * as it was checking the flags parameter  directly against O_RDONLY,
383          * this was failing as the flags parameter was set to O_RDONLY|O_CREAT.
384          * JRA.
385          */
386
387         if (!CAN_WRITE(conn)) {
388                 /* It's a read-only share - fail if we wanted to write. */
389                 if(accmode != O_RDONLY || (flags & O_TRUNC) || (flags & O_APPEND)) {
390                         DEBUG(3,("Permission denied opening %s\n",
391                                  smb_fname_str_dbg(smb_fname)));
392                         return NT_STATUS_ACCESS_DENIED;
393                 } else if(flags & O_CREAT) {
394                         /* We don't want to write - but we must make sure that
395                            O_CREAT doesn't create the file if we have write
396                            access into the directory.
397                         */
398                         flags &= ~(O_CREAT|O_EXCL);
399                         local_flags &= ~(O_CREAT|O_EXCL);
400                 }
401         }
402
403         /*
404          * This little piece of insanity is inspired by the
405          * fact that an NT client can open a file for O_RDONLY,
406          * but set the create disposition to FILE_EXISTS_TRUNCATE.
407          * If the client *can* write to the file, then it expects to
408          * truncate the file, even though it is opening for readonly.
409          * Quicken uses this stupid trick in backup file creation...
410          * Thanks *greatly* to "David W. Chapman Jr." <dwcjr@inethouston.net>
411          * for helping track this one down. It didn't bite us in 2.0.x
412          * as we always opened files read-write in that release. JRA.
413          */
414
415         if ((accmode == O_RDONLY) && ((flags & O_TRUNC) == O_TRUNC)) {
416                 DEBUG(10,("open_file: truncate requested on read-only open "
417                           "for file %s\n", smb_fname_str_dbg(smb_fname)));
418                 local_flags = (flags & ~O_ACCMODE)|O_RDWR;
419         }
420
421         if ((open_access_mask & (FILE_READ_DATA|FILE_WRITE_DATA|FILE_APPEND_DATA|FILE_EXECUTE)) ||
422             (!file_existed && (local_flags & O_CREAT)) ||
423             ((local_flags & O_TRUNC) == O_TRUNC) ) {
424                 const char *wild;
425
426                 /*
427                  * We can't actually truncate here as the file may be locked.
428                  * open_file_ntcreate will take care of the truncate later. JRA.
429                  */
430
431                 local_flags &= ~O_TRUNC;
432
433 #if defined(O_NONBLOCK) && defined(S_ISFIFO)
434                 /*
435                  * We would block on opening a FIFO with no one else on the
436                  * other end. Do what we used to do and add O_NONBLOCK to the
437                  * open flags. JRA.
438                  */
439
440                 if (file_existed && S_ISFIFO(smb_fname->st.st_ex_mode)) {
441                         local_flags |= O_NONBLOCK;
442                 }
443 #endif
444
445                 /* Don't create files with Microsoft wildcard characters. */
446                 if (fsp->base_fsp) {
447                         /*
448                          * wildcard characters are allowed in stream names
449                          * only test the basefilename
450                          */
451                         wild = fsp->base_fsp->fsp_name->base_name;
452                 } else {
453                         wild = smb_fname->base_name;
454                 }
455                 if ((local_flags & O_CREAT) && !file_existed &&
456                     ms_has_wild(wild))  {
457                         return NT_STATUS_OBJECT_NAME_INVALID;
458                 }
459
460                 /* Actually do the open */
461                 status = fd_open(conn, fsp, local_flags, unx_mode);
462                 if (!NT_STATUS_IS_OK(status)) {
463                         DEBUG(3,("Error opening file %s (%s) (local_flags=%d) "
464                                  "(flags=%d)\n", smb_fname_str_dbg(smb_fname),
465                                  nt_errstr(status),local_flags,flags));
466                         return status;
467                 }
468
469                 if ((local_flags & O_CREAT) && !file_existed) {
470
471                         /* Inherit the ACL if required */
472                         if (lp_inherit_perms(SNUM(conn))) {
473                                 inherit_access_posix_acl(conn, parent_dir,
474                                                          smb_fname->base_name,
475                                                          unx_mode);
476                         }
477
478                         /* Change the owner if required. */
479                         if (lp_inherit_owner(SNUM(conn))) {
480                                 change_file_owner_to_parent(conn, parent_dir,
481                                                             fsp);
482                         }
483
484                         notify_fname(conn, NOTIFY_ACTION_ADDED,
485                                      FILE_NOTIFY_CHANGE_FILE_NAME,
486                                      smb_fname->base_name);
487                 }
488
489         } else {
490                 fsp->fh->fd = -1; /* What we used to call a stat open. */
491                 if (file_existed) {
492                         uint32_t access_granted = 0;
493
494                         status = smbd_check_open_rights(conn,
495                                         smb_fname,
496                                         access_mask,
497                                         &access_granted);
498                         if (!NT_STATUS_IS_OK(status)) {
499                                 if (NT_STATUS_EQUAL(status, NT_STATUS_ACCESS_DENIED)) {
500                                         /*
501                                          * On NT_STATUS_ACCESS_DENIED, access_granted
502                                          * contains the denied bits.
503                                          */
504
505                                         if ((access_mask & FILE_WRITE_ATTRIBUTES) &&
506                                                         (access_granted & FILE_WRITE_ATTRIBUTES) &&
507                                                         (lp_map_readonly(SNUM(conn)) ||
508                                                          lp_map_archive(SNUM(conn)) ||
509                                                          lp_map_hidden(SNUM(conn)) ||
510                                                          lp_map_system(SNUM(conn)))) {
511                                                 access_granted &= ~FILE_WRITE_ATTRIBUTES;
512
513                                                 DEBUG(10,("open_file: "
514                                                           "overrode "
515                                                           "FILE_WRITE_"
516                                                           "ATTRIBUTES "
517                                                           "on file %s\n",
518                                                           smb_fname_str_dbg(
519                                                                   smb_fname)));
520                                         }
521
522                                         if ((access_mask & DELETE_ACCESS) &&
523                                             (access_granted & DELETE_ACCESS) &&
524                                             can_delete_file_in_directory(conn,
525                                                 smb_fname)) {
526                                                 /* Were we trying to do a stat open
527                                                  * for delete and didn't get DELETE
528                                                  * access (only) ? Check if the
529                                                  * directory allows DELETE_CHILD.
530                                                  * See here:
531                                                  * http://blogs.msdn.com/oldnewthing/archive/2004/06/04/148426.aspx
532                                                  * for details. */
533
534                                                 access_granted &= ~DELETE_ACCESS;
535
536                                                 DEBUG(10,("open_file: "
537                                                           "overrode "
538                                                           "DELETE_ACCESS on "
539                                                           "file %s\n",
540                                                           smb_fname_str_dbg(
541                                                                   smb_fname)));
542                                         }
543
544                                         if (access_granted != 0) {
545                                                 DEBUG(10,("open_file: Access "
546                                                           "denied on file "
547                                                           "%s\n",
548                                                           smb_fname_str_dbg(
549                                                                   smb_fname)));
550                                                 return status;
551                                         }
552                                 } else if (NT_STATUS_EQUAL(status, NT_STATUS_OBJECT_NAME_NOT_FOUND) &&
553                                     fsp->posix_open &&
554                                     S_ISLNK(smb_fname->st.st_ex_mode)) {
555                                         /* This is a POSIX stat open for delete
556                                          * or rename on a symlink that points
557                                          * nowhere. Allow. */
558                                         DEBUG(10,("open_file: allowing POSIX "
559                                                   "open on bad symlink %s\n",
560                                                   smb_fname_str_dbg(
561                                                           smb_fname)));
562                                 } else {
563                                         DEBUG(10,("open_file: "
564                                                   "smbd_check_open_rights on file "
565                                                   "%s returned %s\n",
566                                                   smb_fname_str_dbg(smb_fname),
567                                                   nt_errstr(status) ));
568                                         return status;
569                                 }
570                         }
571                 }
572         }
573
574         if (!file_existed) {
575                 int ret;
576
577                 if (fsp->fh->fd == -1) {
578                         ret = SMB_VFS_STAT(conn, smb_fname);
579                 } else {
580                         ret = SMB_VFS_FSTAT(fsp, &smb_fname->st);
581                         /* If we have an fd, this stat should succeed. */
582                         if (ret == -1) {
583                                 DEBUG(0,("Error doing fstat on open file %s "
584                                          "(%s)\n",
585                                          smb_fname_str_dbg(smb_fname),
586                                          strerror(errno) ));
587                         }
588                 }
589
590                 /* For a non-io open, this stat failing means file not found. JRA */
591                 if (ret == -1) {
592                         status = map_nt_error_from_unix(errno);
593                         fd_close(fsp);
594                         return status;
595                 }
596         }
597
598         /*
599          * POSIX allows read-only opens of directories. We don't
600          * want to do this (we use a different code path for this)
601          * so catch a directory open and return an EISDIR. JRA.
602          */
603
604         if(S_ISDIR(smb_fname->st.st_ex_mode)) {
605                 fd_close(fsp);
606                 errno = EISDIR;
607                 return NT_STATUS_FILE_IS_A_DIRECTORY;
608         }
609
610         fsp->mode = smb_fname->st.st_ex_mode;
611         fsp->file_id = vfs_file_id_from_sbuf(conn, &smb_fname->st);
612         fsp->vuid = req ? req->vuid : UID_FIELD_INVALID;
613         fsp->file_pid = req ? req->smbpid : 0;
614         fsp->can_lock = True;
615         fsp->can_read = (access_mask & (FILE_READ_DATA)) ? True : False;
616         if (!CAN_WRITE(conn)) {
617                 fsp->can_write = False;
618         } else {
619                 fsp->can_write = (access_mask & (FILE_WRITE_DATA | FILE_APPEND_DATA)) ?
620                         True : False;
621         }
622         fsp->print_file = NULL;
623         fsp->modified = False;
624         fsp->sent_oplock_break = NO_BREAK_SENT;
625         fsp->is_directory = False;
626         if (conn->aio_write_behind_list &&
627             is_in_path(smb_fname->base_name, conn->aio_write_behind_list,
628                        conn->case_sensitive)) {
629                 fsp->aio_write_behind = True;
630         }
631
632         fsp->wcp = NULL; /* Write cache pointer. */
633
634         DEBUG(2,("%s opened file %s read=%s write=%s (numopen=%d)\n",
635                  conn->server_info->unix_name,
636                  smb_fname_str_dbg(smb_fname),
637                  BOOLSTR(fsp->can_read), BOOLSTR(fsp->can_write),
638                  conn->num_files_open));
639
640         errno = 0;
641         return NT_STATUS_OK;
642 }
643
644 /*******************************************************************
645  Return True if the filename is one of the special executable types.
646 ********************************************************************/
647
648 bool is_executable(const char *fname)
649 {
650         if ((fname = strrchr_m(fname,'.'))) {
651                 if (strequal(fname,".com") ||
652                     strequal(fname,".dll") ||
653                     strequal(fname,".exe") ||
654                     strequal(fname,".sym")) {
655                         return True;
656                 }
657         }
658         return False;
659 }
660
661 /****************************************************************************
662  Check if we can open a file with a share mode.
663  Returns True if conflict, False if not.
664 ****************************************************************************/
665
666 static bool share_conflict(struct share_mode_entry *entry,
667                            uint32 access_mask,
668                            uint32 share_access)
669 {
670         DEBUG(10,("share_conflict: entry->access_mask = 0x%x, "
671                   "entry->share_access = 0x%x, "
672                   "entry->private_options = 0x%x\n",
673                   (unsigned int)entry->access_mask,
674                   (unsigned int)entry->share_access,
675                   (unsigned int)entry->private_options));
676
677         DEBUG(10,("share_conflict: access_mask = 0x%x, share_access = 0x%x\n",
678                   (unsigned int)access_mask, (unsigned int)share_access));
679
680         if ((entry->access_mask & (FILE_WRITE_DATA|
681                                    FILE_APPEND_DATA|
682                                    FILE_READ_DATA|
683                                    FILE_EXECUTE|
684                                    DELETE_ACCESS)) == 0) {
685                 DEBUG(10,("share_conflict: No conflict due to "
686                           "entry->access_mask = 0x%x\n",
687                           (unsigned int)entry->access_mask ));
688                 return False;
689         }
690
691         if ((access_mask & (FILE_WRITE_DATA|
692                             FILE_APPEND_DATA|
693                             FILE_READ_DATA|
694                             FILE_EXECUTE|
695                             DELETE_ACCESS)) == 0) {
696                 DEBUG(10,("share_conflict: No conflict due to "
697                           "access_mask = 0x%x\n",
698                           (unsigned int)access_mask ));
699                 return False;
700         }
701
702 #if 1 /* JRA TEST - Superdebug. */
703 #define CHECK_MASK(num, am, right, sa, share) \
704         DEBUG(10,("share_conflict: [%d] am (0x%x) & right (0x%x) = 0x%x\n", \
705                 (unsigned int)(num), (unsigned int)(am), \
706                 (unsigned int)(right), (unsigned int)(am)&(right) )); \
707         DEBUG(10,("share_conflict: [%d] sa (0x%x) & share (0x%x) = 0x%x\n", \
708                 (unsigned int)(num), (unsigned int)(sa), \
709                 (unsigned int)(share), (unsigned int)(sa)&(share) )); \
710         if (((am) & (right)) && !((sa) & (share))) { \
711                 DEBUG(10,("share_conflict: check %d conflict am = 0x%x, right = 0x%x, \
712 sa = 0x%x, share = 0x%x\n", (num), (unsigned int)(am), (unsigned int)(right), (unsigned int)(sa), \
713                         (unsigned int)(share) )); \
714                 return True; \
715         }
716 #else
717 #define CHECK_MASK(num, am, right, sa, share) \
718         if (((am) & (right)) && !((sa) & (share))) { \
719                 DEBUG(10,("share_conflict: check %d conflict am = 0x%x, right = 0x%x, \
720 sa = 0x%x, share = 0x%x\n", (num), (unsigned int)(am), (unsigned int)(right), (unsigned int)(sa), \
721                         (unsigned int)(share) )); \
722                 return True; \
723         }
724 #endif
725
726         CHECK_MASK(1, entry->access_mask, FILE_WRITE_DATA | FILE_APPEND_DATA,
727                    share_access, FILE_SHARE_WRITE);
728         CHECK_MASK(2, access_mask, FILE_WRITE_DATA | FILE_APPEND_DATA,
729                    entry->share_access, FILE_SHARE_WRITE);
730         
731         CHECK_MASK(3, entry->access_mask, FILE_READ_DATA | FILE_EXECUTE,
732                    share_access, FILE_SHARE_READ);
733         CHECK_MASK(4, access_mask, FILE_READ_DATA | FILE_EXECUTE,
734                    entry->share_access, FILE_SHARE_READ);
735
736         CHECK_MASK(5, entry->access_mask, DELETE_ACCESS,
737                    share_access, FILE_SHARE_DELETE);
738         CHECK_MASK(6, access_mask, DELETE_ACCESS,
739                    entry->share_access, FILE_SHARE_DELETE);
740
741         DEBUG(10,("share_conflict: No conflict.\n"));
742         return False;
743 }
744
745 #if defined(DEVELOPER)
746 static void validate_my_share_entries(int num,
747                                       struct share_mode_entry *share_entry)
748 {
749         files_struct *fsp;
750
751         if (!procid_is_me(&share_entry->pid)) {
752                 return;
753         }
754
755         if (is_deferred_open_entry(share_entry) &&
756             !open_was_deferred(share_entry->op_mid)) {
757                 char *str = talloc_asprintf(talloc_tos(),
758                         "Got a deferred entry without a request: "
759                         "PANIC: %s\n",
760                         share_mode_str(talloc_tos(), num, share_entry));
761                 smb_panic(str);
762         }
763
764         if (!is_valid_share_mode_entry(share_entry)) {
765                 return;
766         }
767
768         fsp = file_find_dif(smbd_server_conn, share_entry->id,
769                             share_entry->share_file_id);
770         if (!fsp) {
771                 DEBUG(0,("validate_my_share_entries: PANIC : %s\n",
772                          share_mode_str(talloc_tos(), num, share_entry) ));
773                 smb_panic("validate_my_share_entries: Cannot match a "
774                           "share entry with an open file\n");
775         }
776
777         if (is_deferred_open_entry(share_entry) ||
778             is_unused_share_mode_entry(share_entry)) {
779                 goto panic;
780         }
781
782         if ((share_entry->op_type == NO_OPLOCK) &&
783             (fsp->oplock_type == FAKE_LEVEL_II_OPLOCK)) {
784                 /* Someone has already written to it, but I haven't yet
785                  * noticed */
786                 return;
787         }
788
789         if (((uint16)fsp->oplock_type) != share_entry->op_type) {
790                 goto panic;
791         }
792
793         return;
794
795  panic:
796         {
797                 char *str;
798                 DEBUG(0,("validate_my_share_entries: PANIC : %s\n",
799                          share_mode_str(talloc_tos(), num, share_entry) ));
800                 str = talloc_asprintf(talloc_tos(),
801                         "validate_my_share_entries: "
802                         "file %s, oplock_type = 0x%x, op_type = 0x%x\n",
803                          fsp->fsp_name->base_name,
804                          (unsigned int)fsp->oplock_type,
805                          (unsigned int)share_entry->op_type );
806                 smb_panic(str);
807         }
808 }
809 #endif
810
811 bool is_stat_open(uint32 access_mask)
812 {
813         return (access_mask &&
814                 ((access_mask & ~(SYNCHRONIZE_ACCESS| FILE_READ_ATTRIBUTES|
815                                   FILE_WRITE_ATTRIBUTES))==0) &&
816                 ((access_mask & (SYNCHRONIZE_ACCESS|FILE_READ_ATTRIBUTES|
817                                  FILE_WRITE_ATTRIBUTES)) != 0));
818 }
819
820 /****************************************************************************
821  Deal with share modes
822  Invarient: Share mode must be locked on entry and exit.
823  Returns -1 on error, or number of share modes on success (may be zero).
824 ****************************************************************************/
825
826 static NTSTATUS open_mode_check(connection_struct *conn,
827                                 struct share_mode_lock *lck,
828                                 uint32 access_mask,
829                                 uint32 share_access,
830                                 uint32 create_options,
831                                 bool *file_existed)
832 {
833         int i;
834
835         if(lck->num_share_modes == 0) {
836                 return NT_STATUS_OK;
837         }
838
839         *file_existed = True;
840
841         /* A delete on close prohibits everything */
842
843         if (lck->delete_on_close) {
844                 return NT_STATUS_DELETE_PENDING;
845         }
846
847         if (is_stat_open(access_mask)) {
848                 /* Stat open that doesn't trigger oplock breaks or share mode
849                  * checks... ! JRA. */
850                 return NT_STATUS_OK;
851         }
852
853         /*
854          * Check if the share modes will give us access.
855          */
856         
857 #if defined(DEVELOPER)
858         for(i = 0; i < lck->num_share_modes; i++) {
859                 validate_my_share_entries(i, &lck->share_modes[i]);
860         }
861 #endif
862
863         if (!lp_share_modes(SNUM(conn))) {
864                 return NT_STATUS_OK;
865         }
866
867         /* Now we check the share modes, after any oplock breaks. */
868         for(i = 0; i < lck->num_share_modes; i++) {
869
870                 if (!is_valid_share_mode_entry(&lck->share_modes[i])) {
871                         continue;
872                 }
873
874                 /* someone else has a share lock on it, check to see if we can
875                  * too */
876                 if (share_conflict(&lck->share_modes[i],
877                                    access_mask, share_access)) {
878                         return NT_STATUS_SHARING_VIOLATION;
879                 }
880         }
881         
882         return NT_STATUS_OK;
883 }
884
885 static bool is_delete_request(files_struct *fsp) {
886         return ((fsp->access_mask == DELETE_ACCESS) &&
887                 (fsp->oplock_type == NO_OPLOCK));
888 }
889
890 /*
891  * Send a break message to the oplock holder and delay the open for
892  * our client.
893  */
894
895 static NTSTATUS send_break_message(files_struct *fsp,
896                                         struct share_mode_entry *exclusive,
897                                         uint64_t mid,
898                                         int oplock_request)
899 {
900         NTSTATUS status;
901         char msg[MSG_SMB_SHARE_MODE_ENTRY_SIZE];
902
903         DEBUG(10, ("Sending break request to PID %s\n",
904                    procid_str_static(&exclusive->pid)));
905         exclusive->op_mid = mid;
906
907         /* Create the message. */
908         share_mode_entry_to_message(msg, exclusive);
909
910         /* Add in the FORCE_OPLOCK_BREAK_TO_NONE bit in the message if set. We
911            don't want this set in the share mode struct pointed to by lck. */
912
913         if (oplock_request & FORCE_OPLOCK_BREAK_TO_NONE) {
914                 SSVAL(msg,OP_BREAK_MSG_OP_TYPE_OFFSET,
915                         exclusive->op_type | FORCE_OPLOCK_BREAK_TO_NONE);
916         }
917
918         status = messaging_send_buf(fsp->conn->sconn->msg_ctx, exclusive->pid,
919                                     MSG_SMB_BREAK_REQUEST,
920                                     (uint8 *)msg,
921                                     MSG_SMB_SHARE_MODE_ENTRY_SIZE);
922         if (!NT_STATUS_IS_OK(status)) {
923                 DEBUG(3, ("Could not send oplock break message: %s\n",
924                           nt_errstr(status)));
925         }
926
927         return status;
928 }
929
930 /*
931  * 1) No files open at all or internal open: Grant whatever the client wants.
932  *
933  * 2) Exclusive (or batch) oplock around: If the requested access is a delete
934  *    request, break if the oplock around is a batch oplock. If it's another
935  *    requested access type, break.
936  *
937  * 3) Only level2 around: Grant level2 and do nothing else.
938  */
939
940 static bool delay_for_oplocks(struct share_mode_lock *lck,
941                               files_struct *fsp,
942                               uint64_t mid,
943                               int pass_number,
944                               int oplock_request)
945 {
946         int i;
947         struct share_mode_entry *exclusive = NULL;
948         bool valid_entry = false;
949         bool have_level2 = false;
950         bool have_a_none_oplock = false;
951         bool allow_level2 = (global_client_caps & CAP_LEVEL_II_OPLOCKS) &&
952                             lp_level2_oplocks(SNUM(fsp->conn));
953
954         if (oplock_request & INTERNAL_OPEN_ONLY) {
955                 fsp->oplock_type = NO_OPLOCK;
956         }
957
958         if ((oplock_request & INTERNAL_OPEN_ONLY) || is_stat_open(fsp->access_mask)) {
959                 return false;
960         }
961
962         for (i=0; i<lck->num_share_modes; i++) {
963
964                 if (!is_valid_share_mode_entry(&lck->share_modes[i])) {
965                         continue;
966                 }
967
968                 /* At least one entry is not an invalid or deferred entry. */
969                 valid_entry = true;
970
971                 if (pass_number == 1) {
972                         if (BATCH_OPLOCK_TYPE(lck->share_modes[i].op_type)) {
973                                 SMB_ASSERT(exclusive == NULL);
974                                 exclusive = &lck->share_modes[i];
975                         }
976                 } else {
977                         if (EXCLUSIVE_OPLOCK_TYPE(lck->share_modes[i].op_type)) {
978                                 SMB_ASSERT(exclusive == NULL);
979                                 exclusive = &lck->share_modes[i];
980                         }
981                 }
982
983                 if (LEVEL_II_OPLOCK_TYPE(lck->share_modes[i].op_type)) {
984                         SMB_ASSERT(exclusive == NULL);
985                         have_level2 = true;
986                 }
987
988                 if (lck->share_modes[i].op_type == NO_OPLOCK) {
989                         have_a_none_oplock = true;
990                 }
991         }
992
993         if (exclusive != NULL) { /* Found an exclusive oplock */
994                 bool delay_it = is_delete_request(fsp) ?
995                                 BATCH_OPLOCK_TYPE(exclusive->op_type) : true;
996                 SMB_ASSERT(!have_level2);
997                 if (delay_it) {
998                         send_break_message(fsp, exclusive, mid, oplock_request);
999                         return true;
1000                 }
1001         }
1002
1003         /*
1004          * Match what was requested (fsp->oplock_type) with
1005          * what was found in the existing share modes.
1006          */
1007
1008         if (!valid_entry) {
1009                 /* All entries are placeholders or deferred.
1010                  * Directly grant whatever the client wants. */
1011                 if (fsp->oplock_type == NO_OPLOCK) {
1012                         /* Store a level2 oplock, but don't tell the client */
1013                         fsp->oplock_type = FAKE_LEVEL_II_OPLOCK;
1014                 }
1015         } else if (have_a_none_oplock) {
1016                 fsp->oplock_type = NO_OPLOCK;
1017         } else if (have_level2) {
1018                 if (fsp->oplock_type == NO_OPLOCK ||
1019                                 fsp->oplock_type == FAKE_LEVEL_II_OPLOCK) {
1020                         /* Store a level2 oplock, but don't tell the client */
1021                         fsp->oplock_type = FAKE_LEVEL_II_OPLOCK;
1022                 } else {
1023                         fsp->oplock_type = LEVEL_II_OPLOCK;
1024                 }
1025         } else {
1026                 /* This case can never happen. */
1027                 SMB_ASSERT(1);
1028         }
1029
1030         /*
1031          * Don't grant level2 to clients that don't want them
1032          * or if we've turned them off.
1033          */
1034         if (fsp->oplock_type == LEVEL_II_OPLOCK && !allow_level2) {
1035                 fsp->oplock_type = FAKE_LEVEL_II_OPLOCK;
1036         }
1037
1038         DEBUG(10,("delay_for_oplocks: oplock type 0x%x on file %s\n",
1039                   fsp->oplock_type, fsp_str_dbg(fsp)));
1040
1041         /* No delay. */
1042         return false;
1043 }
1044
1045 bool request_timed_out(struct timeval request_time,
1046                        struct timeval timeout)
1047 {
1048         struct timeval now, end_time;
1049         GetTimeOfDay(&now);
1050         end_time = timeval_sum(&request_time, &timeout);
1051         return (timeval_compare(&end_time, &now) < 0);
1052 }
1053
1054 /****************************************************************************
1055  Handle the 1 second delay in returning a SHARING_VIOLATION error.
1056 ****************************************************************************/
1057
1058 static void defer_open(struct share_mode_lock *lck,
1059                        struct timeval request_time,
1060                        struct timeval timeout,
1061                        struct smb_request *req,
1062                        struct deferred_open_record *state)
1063 {
1064         int i;
1065
1066         /* Paranoia check */
1067
1068         for (i=0; i<lck->num_share_modes; i++) {
1069                 struct share_mode_entry *e = &lck->share_modes[i];
1070
1071                 if (!is_deferred_open_entry(e)) {
1072                         continue;
1073                 }
1074
1075                 if (procid_is_me(&e->pid) && (e->op_mid == req->mid)) {
1076                         DEBUG(0, ("Trying to defer an already deferred "
1077                                 "request: mid=%llu, exiting\n",
1078                                 (unsigned long long)req->mid));
1079                         exit_server("attempt to defer a deferred request");
1080                 }
1081         }
1082
1083         /* End paranoia check */
1084
1085         DEBUG(10,("defer_open_sharing_error: time [%u.%06u] adding deferred "
1086                   "open entry for mid %llu\n",
1087                   (unsigned int)request_time.tv_sec,
1088                   (unsigned int)request_time.tv_usec,
1089                   (unsigned long long)req->mid));
1090
1091         if (!push_deferred_open_message_smb(req, request_time, timeout,
1092                                        state->id, (char *)state, sizeof(*state))) {
1093                 exit_server("push_deferred_open_message_smb failed");
1094         }
1095         add_deferred_open(lck, req->mid, request_time,
1096                           sconn_server_id(req->sconn), state->id);
1097 }
1098
1099
1100 /****************************************************************************
1101  On overwrite open ensure that the attributes match.
1102 ****************************************************************************/
1103
1104 bool open_match_attributes(connection_struct *conn,
1105                            uint32 old_dos_attr,
1106                            uint32 new_dos_attr,
1107                            mode_t existing_unx_mode,
1108                            mode_t new_unx_mode,
1109                            mode_t *returned_unx_mode)
1110 {
1111         uint32 noarch_old_dos_attr, noarch_new_dos_attr;
1112
1113         noarch_old_dos_attr = (old_dos_attr & ~FILE_ATTRIBUTE_ARCHIVE);
1114         noarch_new_dos_attr = (new_dos_attr & ~FILE_ATTRIBUTE_ARCHIVE);
1115
1116         if((noarch_old_dos_attr == 0 && noarch_new_dos_attr != 0) || 
1117            (noarch_old_dos_attr != 0 && ((noarch_old_dos_attr & noarch_new_dos_attr) == noarch_old_dos_attr))) {
1118                 *returned_unx_mode = new_unx_mode;
1119         } else {
1120                 *returned_unx_mode = (mode_t)0;
1121         }
1122
1123         DEBUG(10,("open_match_attributes: old_dos_attr = 0x%x, "
1124                   "existing_unx_mode = 0%o, new_dos_attr = 0x%x "
1125                   "returned_unx_mode = 0%o\n",
1126                   (unsigned int)old_dos_attr,
1127                   (unsigned int)existing_unx_mode,
1128                   (unsigned int)new_dos_attr,
1129                   (unsigned int)*returned_unx_mode ));
1130
1131         /* If we're mapping SYSTEM and HIDDEN ensure they match. */
1132         if (lp_map_system(SNUM(conn)) || lp_store_dos_attributes(SNUM(conn))) {
1133                 if ((old_dos_attr & FILE_ATTRIBUTE_SYSTEM) &&
1134                     !(new_dos_attr & FILE_ATTRIBUTE_SYSTEM)) {
1135                         return False;
1136                 }
1137         }
1138         if (lp_map_hidden(SNUM(conn)) || lp_store_dos_attributes(SNUM(conn))) {
1139                 if ((old_dos_attr & FILE_ATTRIBUTE_HIDDEN) &&
1140                     !(new_dos_attr & FILE_ATTRIBUTE_HIDDEN)) {
1141                         return False;
1142                 }
1143         }
1144         return True;
1145 }
1146
1147 /****************************************************************************
1148  Special FCB or DOS processing in the case of a sharing violation.
1149  Try and find a duplicated file handle.
1150 ****************************************************************************/
1151
1152 NTSTATUS fcb_or_dos_open(struct smb_request *req,
1153                                      connection_struct *conn,
1154                                      files_struct *fsp_to_dup_into,
1155                                      const struct smb_filename *smb_fname,
1156                                      struct file_id id,
1157                                      uint16 file_pid,
1158                                      uint16 vuid,
1159                                      uint32 access_mask,
1160                                      uint32 share_access,
1161                                      uint32 create_options)
1162 {
1163         files_struct *fsp;
1164
1165         DEBUG(5,("fcb_or_dos_open: attempting old open semantics for "
1166                  "file %s.\n", smb_fname_str_dbg(smb_fname)));
1167
1168         for(fsp = file_find_di_first(conn->sconn, id); fsp;
1169             fsp = file_find_di_next(fsp)) {
1170
1171                 DEBUG(10,("fcb_or_dos_open: checking file %s, fd = %d, "
1172                           "vuid = %u, file_pid = %u, private_options = 0x%x "
1173                           "access_mask = 0x%x\n", fsp_str_dbg(fsp),
1174                           fsp->fh->fd, (unsigned int)fsp->vuid,
1175                           (unsigned int)fsp->file_pid,
1176                           (unsigned int)fsp->fh->private_options,
1177                           (unsigned int)fsp->access_mask ));
1178
1179                 if (fsp->fh->fd != -1 &&
1180                     fsp->vuid == vuid &&
1181                     fsp->file_pid == file_pid &&
1182                     (fsp->fh->private_options & (NTCREATEX_OPTIONS_PRIVATE_DENY_DOS |
1183                                                  NTCREATEX_OPTIONS_PRIVATE_DENY_FCB)) &&
1184                     (fsp->access_mask & FILE_WRITE_DATA) &&
1185                     strequal(fsp->fsp_name->base_name, smb_fname->base_name) &&
1186                     strequal(fsp->fsp_name->stream_name,
1187                              smb_fname->stream_name)) {
1188                         DEBUG(10,("fcb_or_dos_open: file match\n"));
1189                         break;
1190                 }
1191         }
1192
1193         if (!fsp) {
1194                 return NT_STATUS_NOT_FOUND;
1195         }
1196
1197         /* quite an insane set of semantics ... */
1198         if (is_executable(smb_fname->base_name) &&
1199             (fsp->fh->private_options & NTCREATEX_OPTIONS_PRIVATE_DENY_DOS)) {
1200                 DEBUG(10,("fcb_or_dos_open: file fail due to is_executable.\n"));
1201                 return NT_STATUS_INVALID_PARAMETER;
1202         }
1203
1204         /* We need to duplicate this fsp. */
1205         return dup_file_fsp(req, fsp, access_mask, share_access,
1206                             create_options, fsp_to_dup_into);
1207 }
1208
1209 /****************************************************************************
1210  Open a file with a share mode - old openX method - map into NTCreate.
1211 ****************************************************************************/
1212
1213 bool map_open_params_to_ntcreate(const struct smb_filename *smb_fname,
1214                                  int deny_mode, int open_func,
1215                                  uint32 *paccess_mask,
1216                                  uint32 *pshare_mode,
1217                                  uint32 *pcreate_disposition,
1218                                  uint32 *pcreate_options,
1219                                  uint32_t *pprivate_flags)
1220 {
1221         uint32 access_mask;
1222         uint32 share_mode;
1223         uint32 create_disposition;
1224         uint32 create_options = FILE_NON_DIRECTORY_FILE;
1225         uint32_t private_flags = 0;
1226
1227         DEBUG(10,("map_open_params_to_ntcreate: fname = %s, deny_mode = 0x%x, "
1228                   "open_func = 0x%x\n",
1229                   smb_fname_str_dbg(smb_fname), (unsigned int)deny_mode,
1230                   (unsigned int)open_func ));
1231
1232         /* Create the NT compatible access_mask. */
1233         switch (GET_OPENX_MODE(deny_mode)) {
1234                 case DOS_OPEN_EXEC: /* Implies read-only - used to be FILE_READ_DATA */
1235                 case DOS_OPEN_RDONLY:
1236                         access_mask = FILE_GENERIC_READ;
1237                         break;
1238                 case DOS_OPEN_WRONLY:
1239                         access_mask = FILE_GENERIC_WRITE;
1240                         break;
1241                 case DOS_OPEN_RDWR:
1242                 case DOS_OPEN_FCB:
1243                         access_mask = FILE_GENERIC_READ|FILE_GENERIC_WRITE;
1244                         break;
1245                 default:
1246                         DEBUG(10,("map_open_params_to_ntcreate: bad open mode = 0x%x\n",
1247                                   (unsigned int)GET_OPENX_MODE(deny_mode)));
1248                         return False;
1249         }
1250
1251         /* Create the NT compatible create_disposition. */
1252         switch (open_func) {
1253                 case OPENX_FILE_EXISTS_FAIL|OPENX_FILE_CREATE_IF_NOT_EXIST:
1254                         create_disposition = FILE_CREATE;
1255                         break;
1256
1257                 case OPENX_FILE_EXISTS_OPEN:
1258                         create_disposition = FILE_OPEN;
1259                         break;
1260
1261                 case OPENX_FILE_EXISTS_OPEN|OPENX_FILE_CREATE_IF_NOT_EXIST:
1262                         create_disposition = FILE_OPEN_IF;
1263                         break;
1264        
1265                 case OPENX_FILE_EXISTS_TRUNCATE:
1266                         create_disposition = FILE_OVERWRITE;
1267                         break;
1268
1269                 case OPENX_FILE_EXISTS_TRUNCATE|OPENX_FILE_CREATE_IF_NOT_EXIST:
1270                         create_disposition = FILE_OVERWRITE_IF;
1271                         break;
1272
1273                 default:
1274                         /* From samba4 - to be confirmed. */
1275                         if (GET_OPENX_MODE(deny_mode) == DOS_OPEN_EXEC) {
1276                                 create_disposition = FILE_CREATE;
1277                                 break;
1278                         }
1279                         DEBUG(10,("map_open_params_to_ntcreate: bad "
1280                                   "open_func 0x%x\n", (unsigned int)open_func));
1281                         return False;
1282         }
1283  
1284         /* Create the NT compatible share modes. */
1285         switch (GET_DENY_MODE(deny_mode)) {
1286                 case DENY_ALL:
1287                         share_mode = FILE_SHARE_NONE;
1288                         break;
1289
1290                 case DENY_WRITE:
1291                         share_mode = FILE_SHARE_READ;
1292                         break;
1293
1294                 case DENY_READ:
1295                         share_mode = FILE_SHARE_WRITE;
1296                         break;
1297
1298                 case DENY_NONE:
1299                         share_mode = FILE_SHARE_READ|FILE_SHARE_WRITE;
1300                         break;
1301
1302                 case DENY_DOS:
1303                         private_flags |= NTCREATEX_OPTIONS_PRIVATE_DENY_DOS;
1304                         if (is_executable(smb_fname->base_name)) {
1305                                 share_mode = FILE_SHARE_READ|FILE_SHARE_WRITE;
1306                         } else {
1307                                 if (GET_OPENX_MODE(deny_mode) == DOS_OPEN_RDONLY) {
1308                                         share_mode = FILE_SHARE_READ;
1309                                 } else {
1310                                         share_mode = FILE_SHARE_NONE;
1311                                 }
1312                         }
1313                         break;
1314
1315                 case DENY_FCB:
1316                         private_flags |= NTCREATEX_OPTIONS_PRIVATE_DENY_FCB;
1317                         share_mode = FILE_SHARE_NONE;
1318                         break;
1319
1320                 default:
1321                         DEBUG(10,("map_open_params_to_ntcreate: bad deny_mode 0x%x\n",
1322                                 (unsigned int)GET_DENY_MODE(deny_mode) ));
1323                         return False;
1324         }
1325
1326         DEBUG(10,("map_open_params_to_ntcreate: file %s, access_mask = 0x%x, "
1327                   "share_mode = 0x%x, create_disposition = 0x%x, "
1328                   "create_options = 0x%x private_flags = 0x%x\n",
1329                   smb_fname_str_dbg(smb_fname),
1330                   (unsigned int)access_mask,
1331                   (unsigned int)share_mode,
1332                   (unsigned int)create_disposition,
1333                   (unsigned int)create_options,
1334                   (unsigned int)private_flags));
1335
1336         if (paccess_mask) {
1337                 *paccess_mask = access_mask;
1338         }
1339         if (pshare_mode) {
1340                 *pshare_mode = share_mode;
1341         }
1342         if (pcreate_disposition) {
1343                 *pcreate_disposition = create_disposition;
1344         }
1345         if (pcreate_options) {
1346                 *pcreate_options = create_options;
1347         }
1348         if (pprivate_flags) {
1349                 *pprivate_flags = private_flags;
1350         }
1351
1352         return True;
1353
1354 }
1355
1356 static void schedule_defer_open(struct share_mode_lock *lck,
1357                                 struct timeval request_time,
1358                                 struct smb_request *req)
1359 {
1360         struct deferred_open_record state;
1361
1362         /* This is a relative time, added to the absolute
1363            request_time value to get the absolute timeout time.
1364            Note that if this is the second or greater time we enter
1365            this codepath for this particular request mid then
1366            request_time is left as the absolute time of the *first*
1367            time this request mid was processed. This is what allows
1368            the request to eventually time out. */
1369
1370         struct timeval timeout;
1371
1372         /* Normally the smbd we asked should respond within
1373          * OPLOCK_BREAK_TIMEOUT seconds regardless of whether
1374          * the client did, give twice the timeout as a safety
1375          * measure here in case the other smbd is stuck
1376          * somewhere else. */
1377
1378         timeout = timeval_set(OPLOCK_BREAK_TIMEOUT*2, 0);
1379
1380         /* Nothing actually uses state.delayed_for_oplocks
1381            but it's handy to differentiate in debug messages
1382            between a 30 second delay due to oplock break, and
1383            a 1 second delay for share mode conflicts. */
1384
1385         state.delayed_for_oplocks = True;
1386         state.id = lck->id;
1387
1388         if (!request_timed_out(request_time, timeout)) {
1389                 defer_open(lck, request_time, timeout, req, &state);
1390         }
1391 }
1392
1393 /****************************************************************************
1394  Work out what access_mask to use from what the client sent us.
1395 ****************************************************************************/
1396
1397 static NTSTATUS calculate_access_mask(connection_struct *conn,
1398                                         const struct smb_filename *smb_fname,
1399                                         bool file_existed,
1400                                         uint32_t access_mask,
1401                                         uint32_t *access_mask_out)
1402 {
1403         NTSTATUS status;
1404
1405         /*
1406          * Convert GENERIC bits to specific bits.
1407          */
1408
1409         se_map_generic(&access_mask, &file_generic_mapping);
1410
1411         /* Calculate MAXIMUM_ALLOWED_ACCESS if requested. */
1412         if (access_mask & MAXIMUM_ALLOWED_ACCESS) {
1413                 if (file_existed) {
1414
1415                         struct security_descriptor *sd;
1416                         uint32_t access_granted = 0;
1417
1418                         status = SMB_VFS_GET_NT_ACL(conn, smb_fname->base_name,
1419                                         (SECINFO_OWNER |
1420                                         SECINFO_GROUP |
1421                                         SECINFO_DACL),&sd);
1422
1423                         if (!NT_STATUS_IS_OK(status)) {
1424                                 DEBUG(10, ("calculate_access_mask: Could not get acl "
1425                                         "on file %s: %s\n",
1426                                         smb_fname_str_dbg(smb_fname),
1427                                         nt_errstr(status)));
1428                                 return NT_STATUS_ACCESS_DENIED;
1429                         }
1430
1431                         status = smb1_file_se_access_check(conn,
1432                                         sd,
1433                                         get_current_nttok(conn),
1434                                         access_mask,
1435                                         &access_granted);
1436
1437                         TALLOC_FREE(sd);
1438
1439                         if (!NT_STATUS_IS_OK(status)) {
1440                                 DEBUG(10, ("calculate_access_mask: Access denied on "
1441                                         "file %s: when calculating maximum access\n",
1442                                         smb_fname_str_dbg(smb_fname)));
1443                                 return NT_STATUS_ACCESS_DENIED;
1444                         }
1445
1446                         access_mask = access_granted;
1447                 } else {
1448                         access_mask = FILE_GENERIC_ALL;
1449                 }
1450         }
1451
1452         *access_mask_out = access_mask;
1453         return NT_STATUS_OK;
1454 }
1455
1456 /****************************************************************************
1457  Remove the deferred open entry under lock.
1458 ****************************************************************************/
1459
1460 void remove_deferred_open_entry(struct file_id id, uint64_t mid,
1461                                 struct server_id pid)
1462 {
1463         struct share_mode_lock *lck = get_share_mode_lock(talloc_tos(), id,
1464                         NULL, NULL, NULL);
1465         if (lck == NULL) {
1466                 DEBUG(0, ("could not get share mode lock\n"));
1467         } else {
1468                 del_deferred_open_entry(lck, mid, pid);
1469                 TALLOC_FREE(lck);
1470         }
1471 }
1472
1473 /****************************************************************************
1474  Open a file with a share mode. Passed in an already created files_struct *.
1475 ****************************************************************************/
1476
1477 static NTSTATUS open_file_ntcreate(connection_struct *conn,
1478                             struct smb_request *req,
1479                             uint32 access_mask,         /* access bits (FILE_READ_DATA etc.) */
1480                             uint32 share_access,        /* share constants (FILE_SHARE_READ etc) */
1481                             uint32 create_disposition,  /* FILE_OPEN_IF etc. */
1482                             uint32 create_options,      /* options such as delete on close. */
1483                             uint32 new_dos_attributes,  /* attributes used for new file. */
1484                             int oplock_request,         /* internal Samba oplock codes. */
1485                                                         /* Information (FILE_EXISTS etc.) */
1486                             uint32_t private_flags,     /* Samba specific flags. */
1487                             int *pinfo,
1488                             files_struct *fsp)
1489 {
1490         struct smb_filename *smb_fname = fsp->fsp_name;
1491         int flags=0;
1492         int flags2=0;
1493         bool file_existed = VALID_STAT(smb_fname->st);
1494         bool def_acl = False;
1495         bool posix_open = False;
1496         bool new_file_created = False;
1497         bool clear_ads = false;
1498         struct file_id id;
1499         NTSTATUS fsp_open = NT_STATUS_ACCESS_DENIED;
1500         mode_t new_unx_mode = (mode_t)0;
1501         mode_t unx_mode = (mode_t)0;
1502         int info;
1503         uint32 existing_dos_attributes = 0;
1504         struct timeval request_time = timeval_zero();
1505         struct share_mode_lock *lck = NULL;
1506         uint32 open_access_mask = access_mask;
1507         NTSTATUS status;
1508         char *parent_dir;
1509
1510         ZERO_STRUCT(id);
1511
1512         if (conn->printer) {
1513                 /*
1514                  * Printers are handled completely differently.
1515                  * Most of the passed parameters are ignored.
1516                  */
1517
1518                 if (pinfo) {
1519                         *pinfo = FILE_WAS_CREATED;
1520                 }
1521
1522                 DEBUG(10, ("open_file_ntcreate: printer open fname=%s\n",
1523                            smb_fname_str_dbg(smb_fname)));
1524
1525                 if (!req) {
1526                         DEBUG(0,("open_file_ntcreate: printer open without "
1527                                 "an SMB request!\n"));
1528                         return NT_STATUS_INTERNAL_ERROR;
1529                 }
1530
1531                 return print_spool_open(fsp, smb_fname->base_name,
1532                                         req->vuid);
1533         }
1534
1535         if (!parent_dirname(talloc_tos(), smb_fname->base_name, &parent_dir,
1536                             NULL)) {
1537                 return NT_STATUS_NO_MEMORY;
1538         }
1539
1540         if (new_dos_attributes & FILE_FLAG_POSIX_SEMANTICS) {
1541                 posix_open = True;
1542                 unx_mode = (mode_t)(new_dos_attributes & ~FILE_FLAG_POSIX_SEMANTICS);
1543                 new_dos_attributes = 0;
1544         } else {
1545                 /* We add aARCH to this as this mode is only used if the file is
1546                  * created new. */
1547                 unx_mode = unix_mode(conn, new_dos_attributes | aARCH,
1548                                      smb_fname, parent_dir);
1549         }
1550
1551         DEBUG(10, ("open_file_ntcreate: fname=%s, dos_attrs=0x%x "
1552                    "access_mask=0x%x share_access=0x%x "
1553                    "create_disposition = 0x%x create_options=0x%x "
1554                    "unix mode=0%o oplock_request=%d private_flags = 0x%x\n",
1555                    smb_fname_str_dbg(smb_fname), new_dos_attributes,
1556                    access_mask, share_access, create_disposition,
1557                    create_options, (unsigned int)unx_mode, oplock_request,
1558                    (unsigned int)private_flags));
1559
1560         if ((req == NULL) && ((oplock_request & INTERNAL_OPEN_ONLY) == 0)) {
1561                 DEBUG(0, ("No smb request but not an internal only open!\n"));
1562                 return NT_STATUS_INTERNAL_ERROR;
1563         }
1564
1565         /*
1566          * Only non-internal opens can be deferred at all
1567          */
1568
1569         if (req) {
1570                 void *ptr;
1571                 if (get_deferred_open_message_state(req,
1572                                 &request_time,
1573                                 &ptr)) {
1574
1575                         struct deferred_open_record *state = (struct deferred_open_record *)ptr;
1576                         /* Remember the absolute time of the original
1577                            request with this mid. We'll use it later to
1578                            see if this has timed out. */
1579
1580                         /* Remove the deferred open entry under lock. */
1581                         remove_deferred_open_entry(
1582                                 state->id, req->mid,
1583                                 sconn_server_id(req->sconn));
1584
1585                         /* Ensure we don't reprocess this message. */
1586                         remove_deferred_open_message_smb(req->mid);
1587                 }
1588         }
1589
1590         status = check_name(conn, smb_fname->base_name);
1591         if (!NT_STATUS_IS_OK(status)) {
1592                 return status;
1593         }
1594
1595         if (!posix_open) {
1596                 new_dos_attributes &= SAMBA_ATTRIBUTES_MASK;
1597                 if (file_existed) {
1598                         existing_dos_attributes = dos_mode(conn, smb_fname);
1599                 }
1600         }
1601
1602         /* ignore any oplock requests if oplocks are disabled */
1603         if (!lp_oplocks(SNUM(conn)) ||
1604             IS_VETO_OPLOCK_PATH(conn, smb_fname->base_name)) {
1605                 /* Mask off everything except the private Samba bits. */
1606                 oplock_request &= SAMBA_PRIVATE_OPLOCK_MASK;
1607         }
1608
1609         /* this is for OS/2 long file names - say we don't support them */
1610         if (!lp_posix_pathnames() && strstr(smb_fname->base_name,".+,;=[].")) {
1611                 /* OS/2 Workplace shell fix may be main code stream in a later
1612                  * release. */
1613                 DEBUG(5,("open_file_ntcreate: OS/2 long filenames are not "
1614                          "supported.\n"));
1615                 if (use_nt_status()) {
1616                         return NT_STATUS_OBJECT_NAME_NOT_FOUND;
1617                 }
1618                 return NT_STATUS_DOS(ERRDOS, ERRcannotopen);
1619         }
1620
1621         switch( create_disposition ) {
1622                 /*
1623                  * Currently we're using FILE_SUPERSEDE as the same as
1624                  * FILE_OVERWRITE_IF but they really are
1625                  * different. FILE_SUPERSEDE deletes an existing file
1626                  * (requiring delete access) then recreates it.
1627                  */
1628                 case FILE_SUPERSEDE:
1629                         /* If file exists replace/overwrite. If file doesn't
1630                          * exist create. */
1631                         flags2 |= (O_CREAT | O_TRUNC);
1632                         clear_ads = true;
1633                         break;
1634
1635                 case FILE_OVERWRITE_IF:
1636                         /* If file exists replace/overwrite. If file doesn't
1637                          * exist create. */
1638                         flags2 |= (O_CREAT | O_TRUNC);
1639                         clear_ads = true;
1640                         break;
1641
1642                 case FILE_OPEN:
1643                         /* If file exists open. If file doesn't exist error. */
1644                         if (!file_existed) {
1645                                 DEBUG(5,("open_file_ntcreate: FILE_OPEN "
1646                                          "requested for file %s and file "
1647                                          "doesn't exist.\n",
1648                                          smb_fname_str_dbg(smb_fname)));
1649                                 errno = ENOENT;
1650                                 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
1651                         }
1652                         break;
1653
1654                 case FILE_OVERWRITE:
1655                         /* If file exists overwrite. If file doesn't exist
1656                          * error. */
1657                         if (!file_existed) {
1658                                 DEBUG(5,("open_file_ntcreate: FILE_OVERWRITE "
1659                                          "requested for file %s and file "
1660                                          "doesn't exist.\n",
1661                                          smb_fname_str_dbg(smb_fname) ));
1662                                 errno = ENOENT;
1663                                 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
1664                         }
1665                         flags2 |= O_TRUNC;
1666                         clear_ads = true;
1667                         break;
1668
1669                 case FILE_CREATE:
1670                         /* If file exists error. If file doesn't exist
1671                          * create. */
1672                         if (file_existed) {
1673                                 DEBUG(5,("open_file_ntcreate: FILE_CREATE "
1674                                          "requested for file %s and file "
1675                                          "already exists.\n",
1676                                          smb_fname_str_dbg(smb_fname)));
1677                                 if (S_ISDIR(smb_fname->st.st_ex_mode)) {
1678                                         errno = EISDIR;
1679                                 } else {
1680                                         errno = EEXIST;
1681                                 }
1682                                 return map_nt_error_from_unix(errno);
1683                         }
1684                         flags2 |= (O_CREAT|O_EXCL);
1685                         break;
1686
1687                 case FILE_OPEN_IF:
1688                         /* If file exists open. If file doesn't exist
1689                          * create. */
1690                         flags2 |= O_CREAT;
1691                         break;
1692
1693                 default:
1694                         return NT_STATUS_INVALID_PARAMETER;
1695         }
1696
1697         /* We only care about matching attributes on file exists and
1698          * overwrite. */
1699
1700         if (!posix_open && file_existed && ((create_disposition == FILE_OVERWRITE) ||
1701                              (create_disposition == FILE_OVERWRITE_IF))) {
1702                 if (!open_match_attributes(conn, existing_dos_attributes,
1703                                            new_dos_attributes,
1704                                            smb_fname->st.st_ex_mode,
1705                                            unx_mode, &new_unx_mode)) {
1706                         DEBUG(5,("open_file_ntcreate: attributes missmatch "
1707                                  "for file %s (%x %x) (0%o, 0%o)\n",
1708                                  smb_fname_str_dbg(smb_fname),
1709                                  existing_dos_attributes,
1710                                  new_dos_attributes,
1711                                  (unsigned int)smb_fname->st.st_ex_mode,
1712                                  (unsigned int)unx_mode ));
1713                         errno = EACCES;
1714                         return NT_STATUS_ACCESS_DENIED;
1715                 }
1716         }
1717
1718         status = calculate_access_mask(conn, smb_fname, file_existed,
1719                                         access_mask,
1720                                         &access_mask); 
1721         if (!NT_STATUS_IS_OK(status)) {
1722                 DEBUG(10, ("open_file_ntcreate: calculate_access_mask "
1723                         "on file %s returned %s\n",
1724                         smb_fname_str_dbg(smb_fname), nt_errstr(status)));
1725                 return status;
1726         }
1727
1728         open_access_mask = access_mask;
1729
1730         if ((flags2 & O_TRUNC) || (oplock_request & FORCE_OPLOCK_BREAK_TO_NONE)) {
1731                 open_access_mask |= FILE_WRITE_DATA; /* This will cause oplock breaks. */
1732         }
1733
1734         DEBUG(10, ("open_file_ntcreate: fname=%s, after mapping "
1735                    "access_mask=0x%x\n", smb_fname_str_dbg(smb_fname),
1736                     access_mask));
1737
1738         /*
1739          * Note that we ignore the append flag as append does not
1740          * mean the same thing under DOS and Unix.
1741          */
1742
1743         if ((access_mask & (FILE_WRITE_DATA | FILE_APPEND_DATA)) ||
1744                         (oplock_request & FORCE_OPLOCK_BREAK_TO_NONE)) {
1745                 /* DENY_DOS opens are always underlying read-write on the
1746                    file handle, no matter what the requested access mask
1747                     says. */
1748                 if ((private_flags & NTCREATEX_OPTIONS_PRIVATE_DENY_DOS) ||
1749                         access_mask & (FILE_READ_ATTRIBUTES|FILE_READ_DATA|FILE_READ_EA|FILE_EXECUTE)) {
1750                         flags = O_RDWR;
1751                 } else {
1752                         flags = O_WRONLY;
1753                 }
1754         } else {
1755                 flags = O_RDONLY;
1756         }
1757
1758         /*
1759          * Currently we only look at FILE_WRITE_THROUGH for create options.
1760          */
1761
1762 #if defined(O_SYNC)
1763         if ((create_options & FILE_WRITE_THROUGH) && lp_strict_sync(SNUM(conn))) {
1764                 flags2 |= O_SYNC;
1765         }
1766 #endif /* O_SYNC */
1767
1768         if (posix_open && (access_mask & FILE_APPEND_DATA)) {
1769                 flags2 |= O_APPEND;
1770         }
1771
1772         if (!posix_open && !CAN_WRITE(conn)) {
1773                 /*
1774                  * We should really return a permission denied error if either
1775                  * O_CREAT or O_TRUNC are set, but for compatibility with
1776                  * older versions of Samba we just AND them out.
1777                  */
1778                 flags2 &= ~(O_CREAT|O_TRUNC);
1779         }
1780
1781         /*
1782          * Ensure we can't write on a read-only share or file.
1783          */
1784
1785         if (flags != O_RDONLY && file_existed &&
1786             (!CAN_WRITE(conn) || IS_DOS_READONLY(existing_dos_attributes))) {
1787                 DEBUG(5,("open_file_ntcreate: write access requested for "
1788                          "file %s on read only %s\n",
1789                          smb_fname_str_dbg(smb_fname),
1790                          !CAN_WRITE(conn) ? "share" : "file" ));
1791                 errno = EACCES;
1792                 return NT_STATUS_ACCESS_DENIED;
1793         }
1794
1795         fsp->file_id = vfs_file_id_from_sbuf(conn, &smb_fname->st);
1796         fsp->share_access = share_access;
1797         fsp->fh->private_options = private_flags;
1798         fsp->access_mask = open_access_mask; /* We change this to the
1799                                               * requested access_mask after
1800                                               * the open is done. */
1801         fsp->posix_open = posix_open;
1802
1803         /* Ensure no SAMBA_PRIVATE bits can be set. */
1804         fsp->oplock_type = (oplock_request & ~SAMBA_PRIVATE_OPLOCK_MASK);
1805
1806         if (timeval_is_zero(&request_time)) {
1807                 request_time = fsp->open_time;
1808         }
1809
1810         if (file_existed) {
1811                 struct timespec old_write_time = smb_fname->st.st_ex_mtime;
1812                 id = vfs_file_id_from_sbuf(conn, &smb_fname->st);
1813
1814                 lck = get_share_mode_lock(talloc_tos(), id,
1815                                           conn->connectpath,
1816                                           smb_fname, &old_write_time);
1817
1818                 if (lck == NULL) {
1819                         DEBUG(0, ("Could not get share mode lock\n"));
1820                         return NT_STATUS_SHARING_VIOLATION;
1821                 }
1822
1823                 /* First pass - send break only on batch oplocks. */
1824                 if ((req != NULL)
1825                     && delay_for_oplocks(lck, fsp, req->mid, 1,
1826                                          oplock_request)) {
1827                         schedule_defer_open(lck, request_time, req);
1828                         TALLOC_FREE(lck);
1829                         return NT_STATUS_SHARING_VIOLATION;
1830                 }
1831
1832                 /* Use the client requested access mask here, not the one we
1833                  * open with. */
1834                 status = open_mode_check(conn, lck, access_mask, share_access,
1835                                          create_options, &file_existed);
1836
1837                 if (NT_STATUS_IS_OK(status)) {
1838                         /* We might be going to allow this open. Check oplock
1839                          * status again. */
1840                         /* Second pass - send break for both batch or
1841                          * exclusive oplocks. */
1842                         if ((req != NULL)
1843                              && delay_for_oplocks(lck, fsp, req->mid, 2,
1844                                                   oplock_request)) {
1845                                 schedule_defer_open(lck, request_time, req);
1846                                 TALLOC_FREE(lck);
1847                                 return NT_STATUS_SHARING_VIOLATION;
1848                         }
1849                 }
1850
1851                 if (NT_STATUS_EQUAL(status, NT_STATUS_DELETE_PENDING)) {
1852                         /* DELETE_PENDING is not deferred for a second */
1853                         TALLOC_FREE(lck);
1854                         return status;
1855                 }
1856
1857                 if (!NT_STATUS_IS_OK(status)) {
1858                         uint32 can_access_mask;
1859                         bool can_access = True;
1860
1861                         SMB_ASSERT(NT_STATUS_EQUAL(status, NT_STATUS_SHARING_VIOLATION));
1862
1863                         /* Check if this can be done with the deny_dos and fcb
1864                          * calls. */
1865                         if (private_flags &
1866                             (NTCREATEX_OPTIONS_PRIVATE_DENY_DOS|
1867                              NTCREATEX_OPTIONS_PRIVATE_DENY_FCB)) {
1868                                 if (req == NULL) {
1869                                         DEBUG(0, ("DOS open without an SMB "
1870                                                   "request!\n"));
1871                                         TALLOC_FREE(lck);
1872                                         return NT_STATUS_INTERNAL_ERROR;
1873                                 }
1874
1875                                 /* Use the client requested access mask here,
1876                                  * not the one we open with. */
1877                                 status = fcb_or_dos_open(req,
1878                                                         conn,
1879                                                         fsp,
1880                                                         smb_fname,
1881                                                         id,
1882                                                         req->smbpid,
1883                                                         req->vuid,
1884                                                         access_mask,
1885                                                         share_access,
1886                                                         create_options);
1887
1888                                 if (NT_STATUS_IS_OK(status)) {
1889                                         TALLOC_FREE(lck);
1890                                         if (pinfo) {
1891                                                 *pinfo = FILE_WAS_OPENED;
1892                                         }
1893                                         return NT_STATUS_OK;
1894                                 }
1895                         }
1896
1897                         /*
1898                          * This next line is a subtlety we need for
1899                          * MS-Access. If a file open will fail due to share
1900                          * permissions and also for security (access) reasons,
1901                          * we need to return the access failed error, not the
1902                          * share error. We can't open the file due to kernel
1903                          * oplock deadlock (it's possible we failed above on
1904                          * the open_mode_check()) so use a userspace check.
1905                          */
1906
1907                         if (flags & O_RDWR) {
1908                                 can_access_mask = FILE_READ_DATA|FILE_WRITE_DATA;
1909                         } else if (flags & O_WRONLY) {
1910                                 can_access_mask = FILE_WRITE_DATA;
1911                         } else {
1912                                 can_access_mask = FILE_READ_DATA;
1913                         }
1914
1915                         if (((can_access_mask & FILE_WRITE_DATA) &&
1916                                 !CAN_WRITE(conn)) ||
1917                             !can_access_file_data(conn, smb_fname,
1918                                                   can_access_mask)) {
1919                                 can_access = False;
1920                         }
1921
1922                         /*
1923                          * If we're returning a share violation, ensure we
1924                          * cope with the braindead 1 second delay.
1925                          */
1926
1927                         if (!(oplock_request & INTERNAL_OPEN_ONLY) &&
1928                             lp_defer_sharing_violations()) {
1929                                 struct timeval timeout;
1930                                 struct deferred_open_record state;
1931                                 int timeout_usecs;
1932
1933                                 /* this is a hack to speed up torture tests
1934                                    in 'make test' */
1935                                 timeout_usecs = lp_parm_int(SNUM(conn),
1936                                                             "smbd","sharedelay",
1937                                                             SHARING_VIOLATION_USEC_WAIT);
1938
1939                                 /* This is a relative time, added to the absolute
1940                                    request_time value to get the absolute timeout time.
1941                                    Note that if this is the second or greater time we enter
1942                                    this codepath for this particular request mid then
1943                                    request_time is left as the absolute time of the *first*
1944                                    time this request mid was processed. This is what allows
1945                                    the request to eventually time out. */
1946
1947                                 timeout = timeval_set(0, timeout_usecs);
1948
1949                                 /* Nothing actually uses state.delayed_for_oplocks
1950                                    but it's handy to differentiate in debug messages
1951                                    between a 30 second delay due to oplock break, and
1952                                    a 1 second delay for share mode conflicts. */
1953
1954                                 state.delayed_for_oplocks = False;
1955                                 state.id = id;
1956
1957                                 if ((req != NULL)
1958                                     && !request_timed_out(request_time,
1959                                                           timeout)) {
1960                                         defer_open(lck, request_time, timeout,
1961                                                    req, &state);
1962                                 }
1963                         }
1964
1965                         TALLOC_FREE(lck);
1966                         if (can_access) {
1967                                 /*
1968                                  * We have detected a sharing violation here
1969                                  * so return the correct error code
1970                                  */
1971                                 status = NT_STATUS_SHARING_VIOLATION;
1972                         } else {
1973                                 status = NT_STATUS_ACCESS_DENIED;
1974                         }
1975                         return status;
1976                 }
1977
1978                 /*
1979                  * We exit this block with the share entry *locked*.....
1980                  */
1981         }
1982
1983         SMB_ASSERT(!file_existed || (lck != NULL));
1984
1985         /*
1986          * Ensure we pay attention to default ACLs on directories if required.
1987          */
1988
1989         if ((flags2 & O_CREAT) && lp_inherit_acls(SNUM(conn)) &&
1990             (def_acl = directory_has_default_acl(conn, parent_dir))) {
1991                 unx_mode = 0777;
1992         }
1993
1994         DEBUG(4,("calling open_file with flags=0x%X flags2=0x%X mode=0%o, "
1995                 "access_mask = 0x%x, open_access_mask = 0x%x\n",
1996                  (unsigned int)flags, (unsigned int)flags2,
1997                  (unsigned int)unx_mode, (unsigned int)access_mask,
1998                  (unsigned int)open_access_mask));
1999
2000         /*
2001          * open_file strips any O_TRUNC flags itself.
2002          */
2003
2004         fsp_open = open_file(fsp, conn, req, parent_dir,
2005                              flags|flags2, unx_mode, access_mask,
2006                              open_access_mask);
2007
2008         if (!NT_STATUS_IS_OK(fsp_open)) {
2009                 if (lck != NULL) {
2010                         TALLOC_FREE(lck);
2011                 }
2012                 return fsp_open;
2013         }
2014
2015         if (!file_existed) {
2016                 struct timespec old_write_time = smb_fname->st.st_ex_mtime;
2017                 /*
2018                  * Deal with the race condition where two smbd's detect the
2019                  * file doesn't exist and do the create at the same time. One
2020                  * of them will win and set a share mode, the other (ie. this
2021                  * one) should check if the requested share mode for this
2022                  * create is allowed.
2023                  */
2024
2025                 /*
2026                  * Now the file exists and fsp is successfully opened,
2027                  * fsp->dev and fsp->inode are valid and should replace the
2028                  * dev=0,inode=0 from a non existent file. Spotted by
2029                  * Nadav Danieli <nadavd@exanet.com>. JRA.
2030                  */
2031
2032                 id = fsp->file_id;
2033
2034                 lck = get_share_mode_lock(talloc_tos(), id,
2035                                           conn->connectpath,
2036                                           smb_fname, &old_write_time);
2037
2038                 if (lck == NULL) {
2039                         DEBUG(0, ("open_file_ntcreate: Could not get share "
2040                                   "mode lock for %s\n",
2041                                   smb_fname_str_dbg(smb_fname)));
2042                         fd_close(fsp);
2043                         return NT_STATUS_SHARING_VIOLATION;
2044                 }
2045
2046                 /* First pass - send break only on batch oplocks. */
2047                 if ((req != NULL)
2048                     && delay_for_oplocks(lck, fsp, req->mid, 1,
2049                                          oplock_request)) {
2050                         schedule_defer_open(lck, request_time, req);
2051                         TALLOC_FREE(lck);
2052                         fd_close(fsp);
2053                         return NT_STATUS_SHARING_VIOLATION;
2054                 }
2055
2056                 status = open_mode_check(conn, lck, access_mask, share_access,
2057                                          create_options, &file_existed);
2058
2059                 if (NT_STATUS_IS_OK(status)) {
2060                         /* We might be going to allow this open. Check oplock
2061                          * status again. */
2062                         /* Second pass - send break for both batch or
2063                          * exclusive oplocks. */
2064                         if ((req != NULL)
2065                             && delay_for_oplocks(lck, fsp, req->mid, 2,
2066                                                  oplock_request)) {
2067                                 schedule_defer_open(lck, request_time, req);
2068                                 TALLOC_FREE(lck);
2069                                 fd_close(fsp);
2070                                 return NT_STATUS_SHARING_VIOLATION;
2071                         }
2072                 }
2073
2074                 if (!NT_STATUS_IS_OK(status)) {
2075                         struct deferred_open_record state;
2076
2077                         fd_close(fsp);
2078
2079                         state.delayed_for_oplocks = False;
2080                         state.id = id;
2081
2082                         /* Do it all over again immediately. In the second
2083                          * round we will find that the file existed and handle
2084                          * the DELETE_PENDING and FCB cases correctly. No need
2085                          * to duplicate the code here. Essentially this is a
2086                          * "goto top of this function", but don't tell
2087                          * anybody... */
2088
2089                         if (req != NULL) {
2090                                 defer_open(lck, request_time, timeval_zero(),
2091                                            req, &state);
2092                         }
2093                         TALLOC_FREE(lck);
2094                         return status;
2095                 }
2096
2097                 /*
2098                  * We exit this block with the share entry *locked*.....
2099                  */
2100
2101         }
2102
2103         SMB_ASSERT(lck != NULL);
2104
2105         /* Delete streams if create_disposition requires it */
2106         if (file_existed && clear_ads &&
2107             !is_ntfs_stream_smb_fname(smb_fname)) {
2108                 status = delete_all_streams(conn, smb_fname->base_name);
2109                 if (!NT_STATUS_IS_OK(status)) {
2110                         TALLOC_FREE(lck);
2111                         fd_close(fsp);
2112                         return status;
2113                 }
2114         }
2115
2116         /* note that we ignore failure for the following. It is
2117            basically a hack for NFS, and NFS will never set one of
2118            these only read them. Nobody but Samba can ever set a deny
2119            mode and we have already checked our more authoritative
2120            locking database for permission to set this deny mode. If
2121            the kernel refuses the operations then the kernel is wrong.
2122            note that GPFS supports it as well - jmcd */
2123
2124         if (fsp->fh->fd != -1) {
2125                 int ret_flock;
2126                 ret_flock = SMB_VFS_KERNEL_FLOCK(fsp, share_access, access_mask);
2127                 if(ret_flock == -1 ){
2128
2129                         TALLOC_FREE(lck);
2130                         fd_close(fsp);
2131
2132                         return NT_STATUS_SHARING_VIOLATION;
2133                 }
2134         }
2135
2136         /*
2137          * At this point onwards, we can guarentee that the share entry
2138          * is locked, whether we created the file or not, and that the
2139          * deny mode is compatible with all current opens.
2140          */
2141
2142         /*
2143          * If requested, truncate the file.
2144          */
2145
2146         if (file_existed && (flags2&O_TRUNC)) {
2147                 /*
2148                  * We are modifing the file after open - update the stat
2149                  * struct..
2150                  */
2151                 if ((SMB_VFS_FTRUNCATE(fsp, 0) == -1) ||
2152                     (SMB_VFS_FSTAT(fsp, &smb_fname->st)==-1)) {
2153                         status = map_nt_error_from_unix(errno);
2154                         TALLOC_FREE(lck);
2155                         fd_close(fsp);
2156                         return status;
2157                 }
2158         }
2159
2160         /*
2161          * According to Samba4, SEC_FILE_READ_ATTRIBUTE is always granted,
2162          */
2163         fsp->access_mask = access_mask | FILE_READ_ATTRIBUTES;
2164
2165         if (file_existed) {
2166                 /* stat opens on existing files don't get oplocks. */
2167                 if (is_stat_open(open_access_mask)) {
2168                         fsp->oplock_type = NO_OPLOCK;
2169                 }
2170
2171                 if (!(flags2 & O_TRUNC)) {
2172                         info = FILE_WAS_OPENED;
2173                 } else {
2174                         info = FILE_WAS_OVERWRITTEN;
2175                 }
2176         } else {
2177                 info = FILE_WAS_CREATED;
2178         }
2179
2180         if (pinfo) {
2181                 *pinfo = info;
2182         }
2183
2184         /*
2185          * Setup the oplock info in both the shared memory and
2186          * file structs.
2187          */
2188
2189         if (!set_file_oplock(fsp, fsp->oplock_type)) {
2190                 /* Could not get the kernel oplock */
2191                 fsp->oplock_type = NO_OPLOCK;
2192         }
2193
2194         if (info == FILE_WAS_OVERWRITTEN || info == FILE_WAS_CREATED || info == FILE_WAS_SUPERSEDED) {
2195                 new_file_created = True;
2196         }
2197
2198         set_share_mode(lck, fsp, get_current_uid(conn), 0,
2199                        fsp->oplock_type);
2200
2201         /* Handle strange delete on close create semantics. */
2202         if (create_options & FILE_DELETE_ON_CLOSE) {
2203
2204                 status = can_set_delete_on_close(fsp, new_dos_attributes);
2205
2206                 if (!NT_STATUS_IS_OK(status)) {
2207                         /* Remember to delete the mode we just added. */
2208                         del_share_mode(lck, fsp);
2209                         TALLOC_FREE(lck);
2210                         fd_close(fsp);
2211                         return status;
2212                 }
2213                 /* Note that here we set the *inital* delete on close flag,
2214                    not the regular one. The magic gets handled in close. */
2215                 fsp->initial_delete_on_close = True;
2216         }
2217
2218         if (new_file_created) {
2219                 /* Files should be initially set as archive */
2220                 if (lp_map_archive(SNUM(conn)) ||
2221                     lp_store_dos_attributes(SNUM(conn))) {
2222                         if (!posix_open) {
2223                                 if (file_set_dosmode(conn, smb_fname,
2224                                             new_dos_attributes | aARCH,
2225                                             parent_dir, true) == 0) {
2226                                         unx_mode = smb_fname->st.st_ex_mode;
2227                                 }
2228                         }
2229                 }
2230         }
2231
2232         /*
2233          * Take care of inherited ACLs on created files - if default ACL not
2234          * selected.
2235          */
2236
2237         if (!posix_open && !file_existed && !def_acl) {
2238
2239                 int saved_errno = errno; /* We might get ENOSYS in the next
2240                                           * call.. */
2241
2242                 if (SMB_VFS_FCHMOD_ACL(fsp, unx_mode) == -1 &&
2243                     errno == ENOSYS) {
2244                         errno = saved_errno; /* Ignore ENOSYS */
2245                 }
2246
2247         } else if (new_unx_mode) {
2248
2249                 int ret = -1;
2250
2251                 /* Attributes need changing. File already existed. */
2252
2253                 {
2254                         int saved_errno = errno; /* We might get ENOSYS in the
2255                                                   * next call.. */
2256                         ret = SMB_VFS_FCHMOD_ACL(fsp, new_unx_mode);
2257
2258                         if (ret == -1 && errno == ENOSYS) {
2259                                 errno = saved_errno; /* Ignore ENOSYS */
2260                         } else {
2261                                 DEBUG(5, ("open_file_ntcreate: reset "
2262                                           "attributes of file %s to 0%o\n",
2263                                           smb_fname_str_dbg(smb_fname),
2264                                           (unsigned int)new_unx_mode));
2265                                 ret = 0; /* Don't do the fchmod below. */
2266                         }
2267                 }
2268
2269                 if ((ret == -1) &&
2270                     (SMB_VFS_FCHMOD(fsp, new_unx_mode) == -1))
2271                         DEBUG(5, ("open_file_ntcreate: failed to reset "
2272                                   "attributes of file %s to 0%o\n",
2273                                   smb_fname_str_dbg(smb_fname),
2274                                   (unsigned int)new_unx_mode));
2275         }
2276
2277         /* If this is a successful open, we must remove any deferred open
2278          * records. */
2279         if (req != NULL) {
2280                 del_deferred_open_entry(lck, req->mid,
2281                                         sconn_server_id(req->sconn));
2282         }
2283         TALLOC_FREE(lck);
2284
2285         return NT_STATUS_OK;
2286 }
2287
2288
2289 /****************************************************************************
2290  Open a file for for write to ensure that we can fchmod it.
2291 ****************************************************************************/
2292
2293 NTSTATUS open_file_fchmod(struct smb_request *req, connection_struct *conn,
2294                           struct smb_filename *smb_fname,
2295                           files_struct **result)
2296 {
2297         files_struct *fsp = NULL;
2298         NTSTATUS status;
2299
2300         if (!VALID_STAT(smb_fname->st)) {
2301                 return NT_STATUS_INVALID_PARAMETER;
2302         }
2303
2304         status = file_new(req, conn, &fsp);
2305         if(!NT_STATUS_IS_OK(status)) {
2306                 return status;
2307         }
2308
2309         status = SMB_VFS_CREATE_FILE(
2310                 conn,                                   /* conn */
2311                 NULL,                                   /* req */
2312                 0,                                      /* root_dir_fid */
2313                 smb_fname,                              /* fname */
2314                 FILE_WRITE_DATA,                        /* access_mask */
2315                 (FILE_SHARE_READ | FILE_SHARE_WRITE |   /* share_access */
2316                     FILE_SHARE_DELETE),
2317                 FILE_OPEN,                              /* create_disposition*/
2318                 0,                                      /* create_options */
2319                 0,                                      /* file_attributes */
2320                 0,                                      /* oplock_request */
2321                 0,                                      /* allocation_size */
2322                 0,                                      /* private_flags */
2323                 NULL,                                   /* sd */
2324                 NULL,                                   /* ea_list */
2325                 &fsp,                                   /* result */
2326                 NULL);                                  /* pinfo */
2327
2328         /*
2329          * This is not a user visible file open.
2330          * Don't set a share mode.
2331          */
2332
2333         if (!NT_STATUS_IS_OK(status)) {
2334                 file_free(req, fsp);
2335                 return status;
2336         }
2337
2338         *result = fsp;
2339         return NT_STATUS_OK;
2340 }
2341
2342 /****************************************************************************
2343  Close the fchmod file fd - ensure no locks are lost.
2344 ****************************************************************************/
2345
2346 NTSTATUS close_file_fchmod(struct smb_request *req, files_struct *fsp)
2347 {
2348         NTSTATUS status = fd_close(fsp);
2349         file_free(req, fsp);
2350         return status;
2351 }
2352
2353 static NTSTATUS mkdir_internal(connection_struct *conn,
2354                                struct smb_filename *smb_dname,
2355                                uint32 file_attributes)
2356 {
2357         mode_t mode;
2358         char *parent_dir;
2359         NTSTATUS status;
2360         bool posix_open = false;
2361
2362         if(!CAN_WRITE(conn)) {
2363                 DEBUG(5,("mkdir_internal: failing create on read-only share "
2364                          "%s\n", lp_servicename(SNUM(conn))));
2365                 return NT_STATUS_ACCESS_DENIED;
2366         }
2367
2368         status = check_name(conn, smb_dname->base_name);
2369         if (!NT_STATUS_IS_OK(status)) {
2370                 return status;
2371         }
2372
2373         if (!parent_dirname(talloc_tos(), smb_dname->base_name, &parent_dir,
2374                             NULL)) {
2375                 return NT_STATUS_NO_MEMORY;
2376         }
2377
2378         if (file_attributes & FILE_FLAG_POSIX_SEMANTICS) {
2379                 posix_open = true;
2380                 mode = (mode_t)(file_attributes & ~FILE_FLAG_POSIX_SEMANTICS);
2381         } else {
2382                 mode = unix_mode(conn, aDIR, smb_dname, parent_dir);
2383         }
2384
2385         if (SMB_VFS_MKDIR(conn, smb_dname->base_name, mode) != 0) {
2386                 return map_nt_error_from_unix(errno);
2387         }
2388
2389         /* Ensure we're checking for a symlink here.... */
2390         /* We don't want to get caught by a symlink racer. */
2391
2392         if (SMB_VFS_LSTAT(conn, smb_dname) == -1) {
2393                 DEBUG(2, ("Could not stat directory '%s' just created: %s\n",
2394                           smb_fname_str_dbg(smb_dname), strerror(errno)));
2395                 return map_nt_error_from_unix(errno);
2396         }
2397
2398         if (!S_ISDIR(smb_dname->st.st_ex_mode)) {
2399                 DEBUG(0, ("Directory just '%s' created is not a directory\n",
2400                           smb_fname_str_dbg(smb_dname)));
2401                 return NT_STATUS_ACCESS_DENIED;
2402         }
2403
2404         if (lp_store_dos_attributes(SNUM(conn))) {
2405                 if (!posix_open) {
2406                         file_set_dosmode(conn, smb_dname,
2407                                          file_attributes | aDIR,
2408                                          parent_dir, true);
2409                 }
2410         }
2411
2412         if (lp_inherit_perms(SNUM(conn))) {
2413                 inherit_access_posix_acl(conn, parent_dir,
2414                                          smb_dname->base_name, mode);
2415         }
2416
2417         if (!posix_open) {
2418                 /*
2419                  * Check if high bits should have been set,
2420                  * then (if bits are missing): add them.
2421                  * Consider bits automagically set by UNIX, i.e. SGID bit from parent
2422                  * dir.
2423                  */
2424                 if ((mode & ~(S_IRWXU|S_IRWXG|S_IRWXO)) &&
2425                     (mode & ~smb_dname->st.st_ex_mode)) {
2426                         SMB_VFS_CHMOD(conn, smb_dname->base_name,
2427                                       (smb_dname->st.st_ex_mode |
2428                                           (mode & ~smb_dname->st.st_ex_mode)));
2429                 }
2430         }
2431
2432         /* Change the owner if required. */
2433         if (lp_inherit_owner(SNUM(conn))) {
2434                 change_dir_owner_to_parent(conn, parent_dir,
2435                                            smb_dname->base_name,
2436                                            &smb_dname->st);
2437         }
2438
2439         notify_fname(conn, NOTIFY_ACTION_ADDED, FILE_NOTIFY_CHANGE_DIR_NAME,
2440                      smb_dname->base_name);
2441
2442         return NT_STATUS_OK;
2443 }
2444
2445 /****************************************************************************
2446  Open a directory from an NT SMB call.
2447 ****************************************************************************/
2448
2449 static NTSTATUS open_directory(connection_struct *conn,
2450                                struct smb_request *req,
2451                                struct smb_filename *smb_dname,
2452                                uint32 access_mask,
2453                                uint32 share_access,
2454                                uint32 create_disposition,
2455                                uint32 create_options,
2456                                uint32 file_attributes,
2457                                int *pinfo,
2458                                files_struct **result)
2459 {
2460         files_struct *fsp = NULL;
2461         bool dir_existed = VALID_STAT(smb_dname->st) ? True : False;
2462         struct share_mode_lock *lck = NULL;
2463         NTSTATUS status;
2464         struct timespec mtimespec;
2465         int info = 0;
2466
2467         SMB_ASSERT(!is_ntfs_stream_smb_fname(smb_dname));
2468
2469         DEBUG(5,("open_directory: opening directory %s, access_mask = 0x%x, "
2470                  "share_access = 0x%x create_options = 0x%x, "
2471                  "create_disposition = 0x%x, file_attributes = 0x%x\n",
2472                  smb_fname_str_dbg(smb_dname),
2473                  (unsigned int)access_mask,
2474                  (unsigned int)share_access,
2475                  (unsigned int)create_options,
2476                  (unsigned int)create_disposition,
2477                  (unsigned int)file_attributes));
2478
2479         if (!(file_attributes & FILE_FLAG_POSIX_SEMANTICS) &&
2480                         (conn->fs_capabilities & FILE_NAMED_STREAMS) &&
2481                         is_ntfs_stream_smb_fname(smb_dname)) {
2482                 DEBUG(2, ("open_directory: %s is a stream name!\n",
2483                           smb_fname_str_dbg(smb_dname)));
2484                 return NT_STATUS_NOT_A_DIRECTORY;
2485         }
2486
2487         status = calculate_access_mask(conn, smb_dname, dir_existed,
2488                                        access_mask, &access_mask);
2489         if (!NT_STATUS_IS_OK(status)) {
2490                 DEBUG(10, ("open_directory: calculate_access_mask "
2491                         "on file %s returned %s\n",
2492                         smb_fname_str_dbg(smb_dname),
2493                         nt_errstr(status)));
2494                 return status;
2495         }
2496
2497         /* We need to support SeSecurityPrivilege for this. */
2498         if (access_mask & SEC_FLAG_SYSTEM_SECURITY) {
2499                 DEBUG(10, ("open_directory: open on %s "
2500                         "failed - SEC_FLAG_SYSTEM_SECURITY denied.\n",
2501                         smb_fname_str_dbg(smb_dname)));
2502                 return NT_STATUS_PRIVILEGE_NOT_HELD;
2503         }
2504
2505         switch( create_disposition ) {
2506                 case FILE_OPEN:
2507
2508                         info = FILE_WAS_OPENED;
2509
2510                         /*
2511                          * We want to follow symlinks here.
2512                          */
2513
2514                         if (SMB_VFS_STAT(conn, smb_dname) != 0) {
2515                                 return map_nt_error_from_unix(errno);
2516                         }
2517                                 
2518                         break;
2519
2520                 case FILE_CREATE:
2521
2522                         /* If directory exists error. If directory doesn't
2523                          * exist create. */
2524
2525                         status = mkdir_internal(conn, smb_dname,
2526                                                 file_attributes);
2527
2528                         if (!NT_STATUS_IS_OK(status)) {
2529                                 DEBUG(2, ("open_directory: unable to create "
2530                                           "%s. Error was %s\n",
2531                                           smb_fname_str_dbg(smb_dname),
2532                                           nt_errstr(status)));
2533                                 return status;
2534                         }
2535
2536                         info = FILE_WAS_CREATED;
2537                         break;
2538
2539                 case FILE_OPEN_IF:
2540                         /*
2541                          * If directory exists open. If directory doesn't
2542                          * exist create.
2543                          */
2544
2545                         status = mkdir_internal(conn, smb_dname,
2546                                                 file_attributes);
2547
2548                         if (NT_STATUS_IS_OK(status)) {
2549                                 info = FILE_WAS_CREATED;
2550                         }
2551
2552                         if (NT_STATUS_EQUAL(status,
2553                                             NT_STATUS_OBJECT_NAME_COLLISION)) {
2554                                 info = FILE_WAS_OPENED;
2555                                 status = NT_STATUS_OK;
2556                         }
2557                                 
2558                         break;
2559
2560                 case FILE_SUPERSEDE:
2561                 case FILE_OVERWRITE:
2562                 case FILE_OVERWRITE_IF:
2563                 default:
2564                         DEBUG(5,("open_directory: invalid create_disposition "
2565                                  "0x%x for directory %s\n",
2566                                  (unsigned int)create_disposition,
2567                                  smb_fname_str_dbg(smb_dname)));
2568                         return NT_STATUS_INVALID_PARAMETER;
2569         }
2570
2571         if(!S_ISDIR(smb_dname->st.st_ex_mode)) {
2572                 DEBUG(5,("open_directory: %s is not a directory !\n",
2573                          smb_fname_str_dbg(smb_dname)));
2574                 return NT_STATUS_NOT_A_DIRECTORY;
2575         }
2576
2577         if (info == FILE_WAS_OPENED) {
2578                 uint32_t access_granted = 0;
2579                 status = smbd_check_open_rights(conn, smb_dname, access_mask,
2580                                                 &access_granted);
2581
2582                 /* Were we trying to do a directory open
2583                  * for delete and didn't get DELETE
2584                  * access (only) ? Check if the
2585                  * directory allows DELETE_CHILD.
2586                  * See here:
2587                  * http://blogs.msdn.com/oldnewthing/archive/2004/06/04/148426.aspx
2588                  * for details. */
2589
2590                 if ((NT_STATUS_EQUAL(status, NT_STATUS_ACCESS_DENIED) &&
2591                         (access_mask & DELETE_ACCESS) &&
2592                         (access_granted == DELETE_ACCESS) &&
2593                         can_delete_file_in_directory(conn, smb_dname))) {
2594                         DEBUG(10,("open_directory: overrode ACCESS_DENIED "
2595                                 "on directory %s\n",
2596                                 smb_fname_str_dbg(smb_dname)));
2597                         status = NT_STATUS_OK;
2598                 }
2599
2600                 if (!NT_STATUS_IS_OK(status)) {
2601                         DEBUG(10, ("open_directory: smbd_check_open_rights on "
2602                                 "file %s failed with %s\n",
2603                                 smb_fname_str_dbg(smb_dname),
2604                                 nt_errstr(status)));
2605                         return status;
2606                 }
2607         }
2608
2609         status = file_new(req, conn, &fsp);
2610         if(!NT_STATUS_IS_OK(status)) {
2611                 return status;
2612         }
2613
2614         /*
2615          * Setup the files_struct for it.
2616          */
2617         
2618         fsp->mode = smb_dname->st.st_ex_mode;
2619         fsp->file_id = vfs_file_id_from_sbuf(conn, &smb_dname->st);
2620         fsp->vuid = req ? req->vuid : UID_FIELD_INVALID;
2621         fsp->file_pid = req ? req->smbpid : 0;
2622         fsp->can_lock = False;
2623         fsp->can_read = False;
2624         fsp->can_write = False;
2625
2626         fsp->share_access = share_access;
2627         fsp->fh->private_options = 0;
2628         /*
2629          * According to Samba4, SEC_FILE_READ_ATTRIBUTE is always granted,
2630          */
2631         fsp->access_mask = access_mask | FILE_READ_ATTRIBUTES;
2632         fsp->print_file = NULL;
2633         fsp->modified = False;
2634         fsp->oplock_type = NO_OPLOCK;
2635         fsp->sent_oplock_break = NO_BREAK_SENT;
2636         fsp->is_directory = True;
2637         fsp->posix_open = (file_attributes & FILE_FLAG_POSIX_SEMANTICS) ? True : False;
2638         status = fsp_set_smb_fname(fsp, smb_dname);
2639         if (!NT_STATUS_IS_OK(status)) {
2640                 return status;
2641         }
2642
2643         mtimespec = smb_dname->st.st_ex_mtime;
2644
2645         lck = get_share_mode_lock(talloc_tos(), fsp->file_id,
2646                                   conn->connectpath, smb_dname, &mtimespec);
2647
2648         if (lck == NULL) {
2649                 DEBUG(0, ("open_directory: Could not get share mode lock for "
2650                           "%s\n", smb_fname_str_dbg(smb_dname)));
2651                 file_free(req, fsp);
2652                 return NT_STATUS_SHARING_VIOLATION;
2653         }
2654
2655         status = open_mode_check(conn, lck, access_mask, share_access,
2656                                  create_options, &dir_existed);
2657
2658         if (!NT_STATUS_IS_OK(status)) {
2659                 TALLOC_FREE(lck);
2660                 file_free(req, fsp);
2661                 return status;
2662         }
2663
2664         set_share_mode(lck, fsp, get_current_uid(conn), 0, NO_OPLOCK);
2665
2666         /* For directories the delete on close bit at open time seems
2667            always to be honored on close... See test 19 in Samba4 BASE-DELETE. */
2668         if (create_options & FILE_DELETE_ON_CLOSE) {
2669                 status = can_set_delete_on_close(fsp, 0);
2670                 if (!NT_STATUS_IS_OK(status) && !NT_STATUS_EQUAL(status, NT_STATUS_DIRECTORY_NOT_EMPTY)) {
2671                         TALLOC_FREE(lck);
2672                         file_free(req, fsp);
2673                         return status;
2674                 }
2675
2676                 if (NT_STATUS_IS_OK(status)) {
2677                         /* Note that here we set the *inital* delete on close flag,
2678                            not the regular one. The magic gets handled in close. */
2679                         fsp->initial_delete_on_close = True;
2680                 }
2681         }
2682
2683         TALLOC_FREE(lck);
2684
2685         if (pinfo) {
2686                 *pinfo = info;
2687         }
2688
2689         *result = fsp;
2690         return NT_STATUS_OK;
2691 }
2692
2693 NTSTATUS create_directory(connection_struct *conn, struct smb_request *req,
2694                           struct smb_filename *smb_dname)
2695 {
2696         NTSTATUS status;
2697         files_struct *fsp;
2698
2699         status = SMB_VFS_CREATE_FILE(
2700                 conn,                                   /* conn */
2701                 req,                                    /* req */
2702                 0,                                      /* root_dir_fid */
2703                 smb_dname,                              /* fname */
2704                 FILE_READ_ATTRIBUTES,                   /* access_mask */
2705                 FILE_SHARE_NONE,                        /* share_access */
2706                 FILE_CREATE,                            /* create_disposition*/
2707                 FILE_DIRECTORY_FILE,                    /* create_options */
2708                 FILE_ATTRIBUTE_DIRECTORY,               /* file_attributes */
2709                 0,                                      /* oplock_request */
2710                 0,                                      /* allocation_size */
2711                 0,                                      /* private_flags */
2712                 NULL,                                   /* sd */
2713                 NULL,                                   /* ea_list */
2714                 &fsp,                                   /* result */
2715                 NULL);                                  /* pinfo */
2716
2717         if (NT_STATUS_IS_OK(status)) {
2718                 close_file(req, fsp, NORMAL_CLOSE);
2719         }
2720
2721         return status;
2722 }
2723
2724 /****************************************************************************
2725  Receive notification that one of our open files has been renamed by another
2726  smbd process.
2727 ****************************************************************************/
2728
2729 void msg_file_was_renamed(struct messaging_context *msg,
2730                           void *private_data,
2731                           uint32_t msg_type,
2732                           struct server_id server_id,
2733                           DATA_BLOB *data)
2734 {
2735         files_struct *fsp;
2736         char *frm = (char *)data->data;
2737         struct file_id id;
2738         const char *sharepath;
2739         const char *base_name;
2740         const char *stream_name;
2741         struct smb_filename *smb_fname = NULL;
2742         size_t sp_len, bn_len;
2743         NTSTATUS status;
2744
2745         if (data->data == NULL
2746             || data->length < MSG_FILE_RENAMED_MIN_SIZE + 2) {
2747                 DEBUG(0, ("msg_file_was_renamed: Got invalid msg len %d\n",
2748                           (int)data->length));
2749                 return;
2750         }
2751
2752         /* Unpack the message. */
2753         pull_file_id_24(frm, &id);
2754         sharepath = &frm[24];
2755         sp_len = strlen(sharepath);
2756         base_name = sharepath + sp_len + 1;
2757         bn_len = strlen(base_name);
2758         stream_name = sharepath + sp_len + 1 + bn_len + 1;
2759
2760         /* stream_name must always be NULL if there is no stream. */
2761         if (stream_name[0] == '\0') {
2762                 stream_name = NULL;
2763         }
2764
2765         status = create_synthetic_smb_fname(talloc_tos(), base_name,
2766                                             stream_name, NULL, &smb_fname);
2767         if (!NT_STATUS_IS_OK(status)) {
2768                 return;
2769         }
2770
2771         DEBUG(10,("msg_file_was_renamed: Got rename message for sharepath %s, new name %s, "
2772                 "file_id %s\n",
2773                 sharepath, smb_fname_str_dbg(smb_fname),
2774                 file_id_string_tos(&id)));
2775
2776         for(fsp = file_find_di_first(smbd_server_conn, id); fsp;
2777             fsp = file_find_di_next(fsp)) {
2778                 if (memcmp(fsp->conn->connectpath, sharepath, sp_len) == 0) {
2779
2780                         DEBUG(10,("msg_file_was_renamed: renaming file fnum %d from %s -> %s\n",
2781                                 fsp->fnum, fsp_str_dbg(fsp),
2782                                 smb_fname_str_dbg(smb_fname)));
2783                         status = fsp_set_smb_fname(fsp, smb_fname);
2784                         if (!NT_STATUS_IS_OK(status)) {
2785                                 goto out;
2786                         }
2787                 } else {
2788                         /* TODO. JRA. */
2789                         /* Now we have the complete path we can work out if this is
2790                            actually within this share and adjust newname accordingly. */
2791                         DEBUG(10,("msg_file_was_renamed: share mismatch (sharepath %s "
2792                                 "not sharepath %s) "
2793                                 "fnum %d from %s -> %s\n",
2794                                 fsp->conn->connectpath,
2795                                 sharepath,
2796                                 fsp->fnum,
2797                                 fsp_str_dbg(fsp),
2798                                 smb_fname_str_dbg(smb_fname)));
2799                 }
2800         }
2801  out:
2802         TALLOC_FREE(smb_fname);
2803         return;
2804 }
2805
2806 /*
2807  * If a main file is opened for delete, all streams need to be checked for
2808  * !FILE_SHARE_DELETE. Do this by opening with DELETE_ACCESS.
2809  * If that works, delete them all by setting the delete on close and close.
2810  */
2811
2812 NTSTATUS open_streams_for_delete(connection_struct *conn,
2813                                         const char *fname)
2814 {
2815         struct stream_struct *stream_info;
2816         files_struct **streams;
2817         int i;
2818         unsigned int num_streams;
2819         TALLOC_CTX *frame = talloc_stackframe();
2820         NTSTATUS status;
2821
2822         status = SMB_VFS_STREAMINFO(conn, NULL, fname, talloc_tos(),
2823                                     &num_streams, &stream_info);
2824
2825         if (NT_STATUS_EQUAL(status, NT_STATUS_NOT_IMPLEMENTED)
2826             || NT_STATUS_EQUAL(status, NT_STATUS_OBJECT_NAME_NOT_FOUND)) {
2827                 DEBUG(10, ("no streams around\n"));
2828                 TALLOC_FREE(frame);
2829                 return NT_STATUS_OK;
2830         }
2831
2832         if (!NT_STATUS_IS_OK(status)) {
2833                 DEBUG(10, ("SMB_VFS_STREAMINFO failed: %s\n",
2834                            nt_errstr(status)));
2835                 goto fail;
2836         }
2837
2838         DEBUG(10, ("open_streams_for_delete found %d streams\n",
2839                    num_streams));
2840
2841         if (num_streams == 0) {
2842                 TALLOC_FREE(frame);
2843                 return NT_STATUS_OK;
2844         }
2845
2846         streams = TALLOC_ARRAY(talloc_tos(), files_struct *, num_streams);
2847         if (streams == NULL) {
2848                 DEBUG(0, ("talloc failed\n"));
2849                 status = NT_STATUS_NO_MEMORY;
2850                 goto fail;
2851         }
2852
2853         for (i=0; i<num_streams; i++) {
2854                 struct smb_filename *smb_fname = NULL;
2855
2856                 if (strequal(stream_info[i].name, "::$DATA")) {
2857                         streams[i] = NULL;
2858                         continue;
2859                 }
2860
2861                 status = create_synthetic_smb_fname(talloc_tos(), fname,
2862                                                     stream_info[i].name,
2863                                                     NULL, &smb_fname);
2864                 if (!NT_STATUS_IS_OK(status)) {
2865                         goto fail;
2866                 }
2867
2868                 if (SMB_VFS_STAT(conn, smb_fname) == -1) {
2869                         DEBUG(10, ("Unable to stat stream: %s\n",
2870                                    smb_fname_str_dbg(smb_fname)));
2871                 }
2872
2873                 status = SMB_VFS_CREATE_FILE(
2874                          conn,                  /* conn */
2875                          NULL,                  /* req */
2876                          0,                     /* root_dir_fid */
2877                          smb_fname,             /* fname */
2878                          DELETE_ACCESS,         /* access_mask */
2879                          (FILE_SHARE_READ |     /* share_access */
2880                              FILE_SHARE_WRITE | FILE_SHARE_DELETE),
2881                          FILE_OPEN,             /* create_disposition*/
2882                          0,                     /* create_options */
2883                          FILE_ATTRIBUTE_NORMAL, /* file_attributes */
2884                          0,                     /* oplock_request */
2885                          0,                     /* allocation_size */
2886                          NTCREATEX_OPTIONS_PRIVATE_STREAM_DELETE, /* private_flags */
2887                          NULL,                  /* sd */
2888                          NULL,                  /* ea_list */
2889                          &streams[i],           /* result */
2890                          NULL);                 /* pinfo */
2891
2892                 if (!NT_STATUS_IS_OK(status)) {
2893                         DEBUG(10, ("Could not open stream %s: %s\n",
2894                                    smb_fname_str_dbg(smb_fname),
2895                                    nt_errstr(status)));
2896
2897                         TALLOC_FREE(smb_fname);
2898                         break;
2899                 }
2900                 TALLOC_FREE(smb_fname);
2901         }
2902
2903         /*
2904          * don't touch the variable "status" beyond this point :-)
2905          */
2906
2907         for (i -= 1 ; i >= 0; i--) {
2908                 if (streams[i] == NULL) {
2909                         continue;
2910                 }
2911
2912                 DEBUG(10, ("Closing stream # %d, %s\n", i,
2913                            fsp_str_dbg(streams[i])));
2914                 close_file(NULL, streams[i], NORMAL_CLOSE);
2915         }
2916
2917  fail:
2918         TALLOC_FREE(frame);
2919         return status;
2920 }
2921
2922 /*
2923  * Wrapper around open_file_ntcreate and open_directory
2924  */
2925
2926 static NTSTATUS create_file_unixpath(connection_struct *conn,
2927                                      struct smb_request *req,
2928                                      struct smb_filename *smb_fname,
2929                                      uint32_t access_mask,
2930                                      uint32_t share_access,
2931                                      uint32_t create_disposition,
2932                                      uint32_t create_options,
2933                                      uint32_t file_attributes,
2934                                      uint32_t oplock_request,
2935                                      uint64_t allocation_size,
2936                                      uint32_t private_flags,
2937                                      struct security_descriptor *sd,
2938                                      struct ea_list *ea_list,
2939
2940                                      files_struct **result,
2941                                      int *pinfo)
2942 {
2943         int info = FILE_WAS_OPENED;
2944         files_struct *base_fsp = NULL;
2945         files_struct *fsp = NULL;
2946         NTSTATUS status;
2947
2948         DEBUG(10,("create_file_unixpath: access_mask = 0x%x "
2949                   "file_attributes = 0x%x, share_access = 0x%x, "
2950                   "create_disposition = 0x%x create_options = 0x%x "
2951                   "oplock_request = 0x%x private_flags = 0x%x "
2952                   "ea_list = 0x%p, sd = 0x%p, "
2953                   "fname = %s\n",
2954                   (unsigned int)access_mask,
2955                   (unsigned int)file_attributes,
2956                   (unsigned int)share_access,
2957                   (unsigned int)create_disposition,
2958                   (unsigned int)create_options,
2959                   (unsigned int)oplock_request,
2960                   (unsigned int)private_flags,
2961                   ea_list, sd, smb_fname_str_dbg(smb_fname)));
2962
2963         if (create_options & FILE_OPEN_BY_FILE_ID) {
2964                 status = NT_STATUS_NOT_SUPPORTED;
2965                 goto fail;
2966         }
2967
2968         if (create_options & NTCREATEX_OPTIONS_INVALID_PARAM_MASK) {
2969                 status = NT_STATUS_INVALID_PARAMETER;
2970                 goto fail;
2971         }
2972
2973         if (req == NULL) {
2974                 oplock_request |= INTERNAL_OPEN_ONLY;
2975         }
2976
2977         if ((conn->fs_capabilities & FILE_NAMED_STREAMS)
2978             && (access_mask & DELETE_ACCESS)
2979             && !is_ntfs_stream_smb_fname(smb_fname)) {
2980                 /*
2981                  * We can't open a file with DELETE access if any of the
2982                  * streams is open without FILE_SHARE_DELETE
2983                  */
2984                 status = open_streams_for_delete(conn, smb_fname->base_name);
2985
2986                 if (!NT_STATUS_IS_OK(status)) {
2987                         goto fail;
2988                 }
2989         }
2990
2991         /* This is the correct thing to do (check every time) but can_delete
2992          * is expensive (it may have to read the parent directory
2993          * permissions). So for now we're not doing it unless we have a strong
2994          * hint the client is really going to delete this file. If the client
2995          * is forcing FILE_CREATE let the filesystem take care of the
2996          * permissions. */
2997
2998         /* Setting FILE_SHARE_DELETE is the hint. */
2999
3000         if (lp_acl_check_permissions(SNUM(conn))
3001             && (create_disposition != FILE_CREATE)
3002             && (share_access & FILE_SHARE_DELETE)
3003             && (access_mask & DELETE_ACCESS)
3004             && (!(can_delete_file_in_directory(conn, smb_fname) ||
3005                  can_access_file_acl(conn, smb_fname, DELETE_ACCESS)))) {
3006                 status = NT_STATUS_ACCESS_DENIED;
3007                 DEBUG(10,("create_file_unixpath: open file %s "
3008                           "for delete ACCESS_DENIED\n",
3009                           smb_fname_str_dbg(smb_fname)));
3010                 goto fail;
3011         }
3012
3013 #if 0
3014         /* We need to support SeSecurityPrivilege for this. */
3015         if ((access_mask & SEC_FLAG_SYSTEM_SECURITY) &&
3016             !user_has_privileges(current_user.nt_user_token,
3017                                  &se_security)) {
3018                 status = NT_STATUS_PRIVILEGE_NOT_HELD;
3019                 goto fail;
3020         }
3021 #else
3022         /* We need to support SeSecurityPrivilege for this. */
3023         if (access_mask & SEC_FLAG_SYSTEM_SECURITY) {
3024                 status = NT_STATUS_PRIVILEGE_NOT_HELD;
3025                 goto fail;
3026         }
3027         /* Don't allow a SACL set from an NTtrans create until we
3028          * support SeSecurityPrivilege. */
3029         if (!VALID_STAT(smb_fname->st) &&
3030                         lp_nt_acl_support(SNUM(conn)) &&
3031                         sd && (sd->sacl != NULL)) {
3032                 status = NT_STATUS_PRIVILEGE_NOT_HELD;
3033                 goto fail;
3034         }
3035 #endif
3036
3037         if ((conn->fs_capabilities & FILE_NAMED_STREAMS)
3038             && is_ntfs_stream_smb_fname(smb_fname)
3039             && (!(private_flags & NTCREATEX_OPTIONS_PRIVATE_STREAM_DELETE))) {
3040                 uint32 base_create_disposition;
3041                 struct smb_filename *smb_fname_base = NULL;
3042
3043                 if (create_options & FILE_DIRECTORY_FILE) {
3044                         status = NT_STATUS_NOT_A_DIRECTORY;
3045                         goto fail;
3046                 }
3047
3048                 switch (create_disposition) {
3049                 case FILE_OPEN:
3050                         base_create_disposition = FILE_OPEN;
3051                         break;
3052                 default:
3053                         base_create_disposition = FILE_OPEN_IF;
3054                         break;
3055                 }
3056
3057                 /* Create an smb_filename with stream_name == NULL. */
3058                 status = create_synthetic_smb_fname(talloc_tos(),
3059                                                     smb_fname->base_name,
3060                                                     NULL, NULL,
3061                                                     &smb_fname_base);
3062                 if (!NT_STATUS_IS_OK(status)) {
3063                         goto fail;
3064                 }
3065
3066                 if (SMB_VFS_STAT(conn, smb_fname_base) == -1) {
3067                         DEBUG(10, ("Unable to stat stream: %s\n",
3068                                    smb_fname_str_dbg(smb_fname_base)));
3069                 }
3070
3071                 /* Open the base file. */
3072                 status = create_file_unixpath(conn, NULL, smb_fname_base, 0,
3073                                               FILE_SHARE_READ
3074                                               | FILE_SHARE_WRITE
3075                                               | FILE_SHARE_DELETE,
3076                                               base_create_disposition,
3077                                               0, 0, 0, 0, 0, NULL, NULL,
3078                                               &base_fsp, NULL);
3079                 TALLOC_FREE(smb_fname_base);
3080
3081                 if (!NT_STATUS_IS_OK(status)) {
3082                         DEBUG(10, ("create_file_unixpath for base %s failed: "
3083                                    "%s\n", smb_fname->base_name,
3084                                    nt_errstr(status)));
3085                         goto fail;
3086                 }
3087                 /* we don't need to low level fd */
3088                 fd_close(base_fsp);
3089         }
3090
3091         /*
3092          * If it's a request for a directory open, deal with it separately.
3093          */
3094
3095         if (create_options & FILE_DIRECTORY_FILE) {
3096
3097                 if (create_options & FILE_NON_DIRECTORY_FILE) {
3098                         status = NT_STATUS_INVALID_PARAMETER;
3099                         goto fail;
3100                 }
3101
3102                 /* Can't open a temp directory. IFS kit test. */
3103                 if (!(file_attributes & FILE_FLAG_POSIX_SEMANTICS) &&
3104                      (file_attributes & FILE_ATTRIBUTE_TEMPORARY)) {
3105                         status = NT_STATUS_INVALID_PARAMETER;
3106                         goto fail;
3107                 }
3108
3109                 /*
3110                  * We will get a create directory here if the Win32
3111                  * app specified a security descriptor in the
3112                  * CreateDirectory() call.
3113                  */
3114
3115                 oplock_request = 0;
3116                 status = open_directory(
3117                         conn, req, smb_fname, access_mask, share_access,
3118                         create_disposition, create_options, file_attributes,
3119                         &info, &fsp);
3120         } else {
3121
3122                 /*
3123                  * Ordinary file case.
3124                  */
3125
3126                 status = file_new(req, conn, &fsp);
3127                 if(!NT_STATUS_IS_OK(status)) {
3128                         goto fail;
3129                 }
3130
3131                 status = fsp_set_smb_fname(fsp, smb_fname);
3132                 if (!NT_STATUS_IS_OK(status)) {
3133                         goto fail;
3134                 }
3135
3136                 /*
3137                  * We're opening the stream element of a base_fsp
3138                  * we already opened. Set up the base_fsp pointer.
3139                  */
3140                 if (base_fsp) {
3141                         fsp->base_fsp = base_fsp;
3142                 }
3143
3144                 status = open_file_ntcreate(conn,
3145                                             req,
3146                                             access_mask,
3147                                             share_access,
3148                                             create_disposition,
3149                                             create_options,
3150                                             file_attributes,
3151                                             oplock_request,
3152                                             private_flags,
3153                                             &info,
3154                                             fsp);
3155
3156                 if(!NT_STATUS_IS_OK(status)) {
3157                         file_free(req, fsp);
3158                         fsp = NULL;
3159                 }
3160
3161                 if (NT_STATUS_EQUAL(status, NT_STATUS_FILE_IS_A_DIRECTORY)) {
3162
3163                         /* A stream open never opens a directory */
3164
3165                         if (base_fsp) {
3166                                 status = NT_STATUS_FILE_IS_A_DIRECTORY;
3167                                 goto fail;
3168                         }
3169
3170                         /*
3171                          * Fail the open if it was explicitly a non-directory
3172                          * file.
3173                          */
3174
3175                         if (create_options & FILE_NON_DIRECTORY_FILE) {
3176                                 status = NT_STATUS_FILE_IS_A_DIRECTORY;
3177                                 goto fail;
3178                         }
3179
3180                         oplock_request = 0;
3181                         status = open_directory(
3182                                 conn, req, smb_fname, access_mask,
3183                                 share_access, create_disposition,
3184                                 create_options, file_attributes,
3185                                 &info, &fsp);
3186                 }
3187         }
3188
3189         if (!NT_STATUS_IS_OK(status)) {
3190                 goto fail;
3191         }
3192
3193         fsp->base_fsp = base_fsp;
3194
3195         /*
3196          * According to the MS documentation, the only time the security
3197          * descriptor is applied to the opened file is iff we *created* the
3198          * file; an existing file stays the same.
3199          *
3200          * Also, it seems (from observation) that you can open the file with
3201          * any access mask but you can still write the sd. We need to override
3202          * the granted access before we call set_sd
3203          * Patch for bug #2242 from Tom Lackemann <cessnatomny@yahoo.com>.
3204          */
3205
3206         if ((sd != NULL) && (info == FILE_WAS_CREATED)
3207             && lp_nt_acl_support(SNUM(conn))) {
3208
3209                 uint32_t sec_info_sent;
3210                 uint32_t saved_access_mask = fsp->access_mask;
3211
3212                 sec_info_sent = get_sec_info(sd);
3213
3214                 fsp->access_mask = FILE_GENERIC_ALL;
3215
3216                 /* Convert all the generic bits. */
3217                 security_acl_map_generic(sd->dacl, &file_generic_mapping);
3218                 security_acl_map_generic(sd->sacl, &file_generic_mapping);
3219
3220                 if (sec_info_sent & (SECINFO_OWNER|
3221                                         SECINFO_GROUP|
3222                                         SECINFO_DACL|
3223                                         SECINFO_SACL)) {
3224                         status = SMB_VFS_FSET_NT_ACL(fsp, sec_info_sent, sd);
3225                 }
3226
3227                 fsp->access_mask = saved_access_mask;
3228
3229                 if (!NT_STATUS_IS_OK(status)) {
3230                         goto fail;
3231                 }
3232         }
3233
3234         if ((ea_list != NULL) &&
3235             ((info == FILE_WAS_CREATED) || (info == FILE_WAS_OVERWRITTEN))) {
3236                 status = set_ea(conn, fsp, fsp->fsp_name, ea_list);
3237                 if (!NT_STATUS_IS_OK(status)) {
3238                         goto fail;
3239                 }
3240         }
3241
3242         if (!fsp->is_directory && S_ISDIR(fsp->fsp_name->st.st_ex_mode)) {
3243                 status = NT_STATUS_ACCESS_DENIED;
3244                 goto fail;
3245         }
3246
3247         /* Save the requested allocation size. */
3248         if ((info == FILE_WAS_CREATED) || (info == FILE_WAS_OVERWRITTEN)) {
3249                 if (allocation_size
3250                     && (allocation_size > fsp->fsp_name->st.st_ex_size)) {
3251                         fsp->initial_allocation_size = smb_roundup(
3252                                 fsp->conn, allocation_size);
3253                         if (fsp->is_directory) {
3254                                 /* Can't set allocation size on a directory. */
3255                                 status = NT_STATUS_ACCESS_DENIED;
3256                                 goto fail;
3257                         }
3258                         if (vfs_allocate_file_space(
3259                                     fsp, fsp->initial_allocation_size) == -1) {
3260                                 status = NT_STATUS_DISK_FULL;
3261                                 goto fail;
3262                         }
3263                 } else {
3264                         fsp->initial_allocation_size = smb_roundup(
3265                                 fsp->conn, (uint64_t)fsp->fsp_name->st.st_ex_size);
3266                 }
3267         }
3268
3269         DEBUG(10, ("create_file_unixpath: info=%d\n", info));
3270
3271         *result = fsp;
3272         if (pinfo != NULL) {
3273                 *pinfo = info;
3274         }
3275
3276         smb_fname->st = fsp->fsp_name->st;
3277
3278         return NT_STATUS_OK;
3279
3280  fail:
3281         DEBUG(10, ("create_file_unixpath: %s\n", nt_errstr(status)));
3282
3283         if (fsp != NULL) {
3284                 if (base_fsp && fsp->base_fsp == base_fsp) {
3285                         /*
3286                          * The close_file below will close
3287                          * fsp->base_fsp.
3288                          */
3289                         base_fsp = NULL;
3290                 }
3291                 close_file(req, fsp, ERROR_CLOSE);
3292                 fsp = NULL;
3293         }
3294         if (base_fsp != NULL) {
3295                 close_file(req, base_fsp, ERROR_CLOSE);
3296                 base_fsp = NULL;
3297         }
3298         return status;
3299 }
3300
3301 /*
3302  * Calculate the full path name given a relative fid.
3303  */
3304 NTSTATUS get_relative_fid_filename(connection_struct *conn,
3305                                    struct smb_request *req,
3306                                    uint16_t root_dir_fid,
3307                                    struct smb_filename *smb_fname)
3308 {
3309         files_struct *dir_fsp;
3310         char *parent_fname = NULL;
3311         char *new_base_name = NULL;
3312         NTSTATUS status;
3313
3314         if (root_dir_fid == 0 || !smb_fname) {
3315                 status = NT_STATUS_INTERNAL_ERROR;
3316                 goto out;
3317         }
3318
3319         dir_fsp = file_fsp(req, root_dir_fid);
3320
3321         if (dir_fsp == NULL) {
3322                 status = NT_STATUS_INVALID_HANDLE;
3323                 goto out;
3324         }
3325
3326         if (is_ntfs_stream_smb_fname(dir_fsp->fsp_name)) {
3327                 status = NT_STATUS_INVALID_HANDLE;
3328                 goto out;
3329         }
3330
3331         if (!dir_fsp->is_directory) {
3332
3333                 /*
3334                  * Check to see if this is a mac fork of some kind.
3335                  */
3336
3337                 if ((conn->fs_capabilities & FILE_NAMED_STREAMS) &&
3338                     is_ntfs_stream_smb_fname(smb_fname)) {
3339                         status = NT_STATUS_OBJECT_PATH_NOT_FOUND;
3340                         goto out;
3341                 }
3342
3343                 /*
3344                   we need to handle the case when we get a
3345                   relative open relative to a file and the
3346                   pathname is blank - this is a reopen!
3347                   (hint from demyn plantenberg)
3348                 */
3349
3350                 status = NT_STATUS_INVALID_HANDLE;
3351                 goto out;
3352         }
3353
3354         if (ISDOT(dir_fsp->fsp_name->base_name)) {
3355                 /*
3356                  * We're at the toplevel dir, the final file name
3357                  * must not contain ./, as this is filtered out
3358                  * normally by srvstr_get_path and unix_convert
3359                  * explicitly rejects paths containing ./.
3360                  */
3361                 parent_fname = talloc_strdup(talloc_tos(), "");
3362                 if (parent_fname == NULL) {
3363                         status = NT_STATUS_NO_MEMORY;
3364                         goto out;
3365                 }
3366         } else {
3367                 size_t dir_name_len = strlen(dir_fsp->fsp_name->base_name);
3368
3369                 /*
3370                  * Copy in the base directory name.
3371                  */
3372
3373                 parent_fname = TALLOC_ARRAY(talloc_tos(), char,
3374                     dir_name_len+2);
3375                 if (parent_fname == NULL) {
3376                         status = NT_STATUS_NO_MEMORY;
3377                         goto out;
3378                 }
3379                 memcpy(parent_fname, dir_fsp->fsp_name->base_name,
3380                     dir_name_len+1);
3381
3382                 /*
3383                  * Ensure it ends in a '/'.
3384                  * We used TALLOC_SIZE +2 to add space for the '/'.
3385                  */
3386
3387                 if(dir_name_len
3388                     && (parent_fname[dir_name_len-1] != '\\')
3389                     && (parent_fname[dir_name_len-1] != '/')) {
3390                         parent_fname[dir_name_len] = '/';
3391                         parent_fname[dir_name_len+1] = '\0';
3392                 }
3393         }
3394
3395         new_base_name = talloc_asprintf(smb_fname, "%s%s", parent_fname,
3396                                         smb_fname->base_name);
3397         if (new_base_name == NULL) {
3398                 status = NT_STATUS_NO_MEMORY;
3399                 goto out;
3400         }
3401
3402         TALLOC_FREE(smb_fname->base_name);
3403         smb_fname->base_name = new_base_name;
3404         status = NT_STATUS_OK;
3405
3406  out:
3407         TALLOC_FREE(parent_fname);
3408         return status;
3409 }
3410
3411 NTSTATUS create_file_default(connection_struct *conn,
3412                              struct smb_request *req,
3413                              uint16_t root_dir_fid,
3414                              struct smb_filename *smb_fname,
3415                              uint32_t access_mask,
3416                              uint32_t share_access,
3417                              uint32_t create_disposition,
3418                              uint32_t create_options,
3419                              uint32_t file_attributes,
3420                              uint32_t oplock_request,
3421                              uint64_t allocation_size,
3422                              uint32_t private_flags,
3423                              struct security_descriptor *sd,
3424                              struct ea_list *ea_list,
3425                              files_struct **result,
3426                              int *pinfo)
3427 {
3428         int info = FILE_WAS_OPENED;
3429         files_struct *fsp = NULL;
3430         NTSTATUS status;
3431         bool stream_name = false;
3432
3433         DEBUG(10,("create_file: access_mask = 0x%x "
3434                   "file_attributes = 0x%x, share_access = 0x%x, "
3435                   "create_disposition = 0x%x create_options = 0x%x "
3436                   "oplock_request = 0x%x "
3437                   "private_flags = 0x%x "
3438                   "root_dir_fid = 0x%x, ea_list = 0x%p, sd = 0x%p, "
3439                   "fname = %s\n",
3440                   (unsigned int)access_mask,
3441                   (unsigned int)file_attributes,
3442                   (unsigned int)share_access,
3443                   (unsigned int)create_disposition,
3444                   (unsigned int)create_options,
3445                   (unsigned int)oplock_request,
3446                   (unsigned int)private_flags,
3447                   (unsigned int)root_dir_fid,
3448                   ea_list, sd, smb_fname_str_dbg(smb_fname)));
3449
3450         /*
3451          * Calculate the filename from the root_dir_if if necessary.
3452          */
3453
3454         if (root_dir_fid != 0) {
3455                 status = get_relative_fid_filename(conn, req, root_dir_fid,
3456                                                    smb_fname);
3457                 if (!NT_STATUS_IS_OK(status)) {
3458                         goto fail;
3459                 }
3460         }
3461
3462         /*
3463          * Check to see if this is a mac fork of some kind.
3464          */
3465
3466         stream_name = is_ntfs_stream_smb_fname(smb_fname);
3467         if (stream_name) {
3468                 enum FAKE_FILE_TYPE fake_file_type;
3469
3470                 fake_file_type = is_fake_file(smb_fname);
3471
3472                 if (fake_file_type != FAKE_FILE_TYPE_NONE) {
3473
3474                         /*
3475                          * Here we go! support for changing the disk quotas
3476                          * --metze
3477                          *
3478                          * We need to fake up to open this MAGIC QUOTA file
3479                          * and return a valid FID.
3480                          *
3481                          * w2k close this file directly after openening xp
3482                          * also tries a QUERY_FILE_INFO on the file and then
3483                          * close it
3484                          */
3485                         status = open_fake_file(req, conn, req->vuid,
3486                                                 fake_file_type, smb_fname,
3487                                                 access_mask, &fsp);
3488                         if (!NT_STATUS_IS_OK(status)) {
3489                                 goto fail;
3490                         }
3491
3492                         ZERO_STRUCT(smb_fname->st);
3493                         goto done;
3494                 }
3495
3496                 if (!(conn->fs_capabilities & FILE_NAMED_STREAMS)) {
3497                         status = NT_STATUS_OBJECT_NAME_NOT_FOUND;
3498                         goto fail;
3499                 }
3500         }
3501
3502         /* All file access must go through check_name() */
3503
3504         status = check_name(conn, smb_fname->base_name);
3505         if (!NT_STATUS_IS_OK(status)) {
3506                 goto fail;
3507         }
3508
3509         if (stream_name && is_ntfs_default_stream_smb_fname(smb_fname)) {
3510                 int ret;
3511                 smb_fname->stream_name = NULL;
3512                 /* We have to handle this error here. */
3513                 if (create_options & FILE_DIRECTORY_FILE) {
3514                         status = NT_STATUS_NOT_A_DIRECTORY;
3515                         goto fail;
3516                 }
3517                 if (lp_posix_pathnames()) {
3518                         ret = SMB_VFS_LSTAT(conn, smb_fname);
3519                 } else {
3520                         ret = SMB_VFS_STAT(conn, smb_fname);
3521                 }
3522
3523                 if (ret == 0 && VALID_STAT_OF_DIR(smb_fname->st)) {
3524                         status = NT_STATUS_FILE_IS_A_DIRECTORY;
3525                         goto fail;
3526                 }
3527         }
3528
3529         status = create_file_unixpath(
3530                 conn, req, smb_fname, access_mask, share_access,
3531                 create_disposition, create_options, file_attributes,
3532                 oplock_request, allocation_size, private_flags,
3533                 sd, ea_list,
3534                 &fsp, &info);
3535
3536         if (!NT_STATUS_IS_OK(status)) {
3537                 goto fail;
3538         }
3539
3540  done:
3541         DEBUG(10, ("create_file: info=%d\n", info));
3542
3543         *result = fsp;
3544         if (pinfo != NULL) {
3545                 *pinfo = info;
3546         }
3547         return NT_STATUS_OK;
3548
3549  fail:
3550         DEBUG(10, ("create_file: %s\n", nt_errstr(status)));
3551
3552         if (fsp != NULL) {
3553                 close_file(req, fsp, ERROR_CLOSE);
3554                 fsp = NULL;
3555         }
3556         return status;
3557 }