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