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