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