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