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