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