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