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