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