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