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