s3 onefs: Fix a race condition exists in onefs_open.c between multiple opens to the...
[samba.git] / source3 / modules / onefs_open.c
1 /*
2  * Unix SMB/CIFS implementation.
3  *
4  * This file began with some code from source3/smbd/open.c and has been
5  * modified it work with ifs_createfile.
6  *
7  * ifs_createfile is a CIFS-specific syscall for opening/files and
8  * directories.  It adds support for:
9  *    - Full in-kernel access checks using a windows access_mask
10  *    - Cluster-coherent share mode locks
11  *    - Cluster-coherent oplocks
12  *    - Streams
13  *    - Setting security descriptors at create time
14  *    - Setting dos_attributes at create time
15  *
16  * Copyright (C) Andrew Tridgell 1992-1998
17  * Copyright (C) Jeremy Allison 2001-2004
18  * Copyright (C) Volker Lendecke 2005
19  * Copyright (C) Tim Prouty, 2008
20  *
21  * This program is free software; you can redistribute it and/or modify
22  * it under the terms of the GNU General Public License as published by
23  * the Free Software Foundation; either version 3 of the License, or
24  * (at your option) any later version.
25  *
26  * This program is distributed in the hope that it will be useful,
27  * but WITHOUT ANY WARRANTY; without even the implied warranty of
28  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
29  * GNU General Public License for more details.
30  *
31  * You should have received a copy of the GNU General Public License
32  * along with this program; if not, see <http://www.gnu.org/licenses/>.
33  */
34
35 #include "includes.h"
36 #include "onefs.h"
37 #include "onefs_config.h"
38 #include "oplock_onefs.h"
39 #include "smbd/globals.h"
40
41 extern const struct generic_mapping file_generic_mapping;
42
43 struct onefs_fsp_data {
44         uint64_t oplock_callback_id;
45 };
46
47 static NTSTATUS onefs_create_file_unixpath(connection_struct *conn,
48                               struct smb_request *req,
49                               struct smb_filename *smb_fname,
50                               uint32_t access_mask,
51                               uint32_t share_access,
52                               uint32_t create_disposition,
53                               uint32_t create_options,
54                               uint32_t file_attributes,
55                               uint32_t oplock_request,
56                               uint64_t allocation_size,
57                               struct security_descriptor *sd,
58                               struct ea_list *ea_list,
59                               files_struct **result,
60                               int *pinfo,
61                               struct onefs_fsp_data *fsp_data);
62
63 /****************************************************************************
64  Open a file.
65 ****************************************************************************/
66
67 static NTSTATUS onefs_open_file(files_struct *fsp,
68                                 connection_struct *conn,
69                                 struct smb_request *req,
70                                 const char *parent_dir,
71                                 struct smb_filename *smb_fname,
72                                 int flags,
73                                 mode_t unx_mode,
74                                 uint32 access_mask,
75                                 uint32 open_access_mask,
76                                 int oplock_request,
77                                 uint64 id,
78                                 uint32 share_access,
79                                 uint32 create_options,
80                                 uint32_t new_dos_attributes,
81                                 struct security_descriptor *sd,
82                                 int *granted_oplock)
83 {
84         struct smb_filename *smb_fname_onefs = NULL;
85         NTSTATUS status = NT_STATUS_OK;
86         int accmode = (flags & O_ACCMODE);
87         int local_flags = flags;
88         bool file_existed = VALID_STAT(smb_fname->st);
89         const char *wild;
90         int base_fd = -1;
91
92         fsp->fh->fd = -1;
93         errno = EPERM;
94
95         /* Check permissions */
96
97         /*
98          * This code was changed after seeing a client open request
99          * containing the open mode of (DENY_WRITE/read-only) with
100          * the 'create if not exist' bit set. The previous code
101          * would fail to open the file read only on a read-only share
102          * as it was checking the flags parameter  directly against O_RDONLY,
103          * this was failing as the flags parameter was set to O_RDONLY|O_CREAT.
104          * JRA.
105          */
106
107         if (!CAN_WRITE(conn)) {
108                 /* It's a read-only share - fail if we wanted to write. */
109                 if(accmode != O_RDONLY) {
110                         DEBUG(3, ("Permission denied opening %s\n",
111                                   smb_fname_str_dbg(smb_fname)));
112                         return NT_STATUS_ACCESS_DENIED;
113                 } else if(flags & O_CREAT) {
114                         /* We don't want to write - but we must make sure that
115                            O_CREAT doesn't create the file if we have write
116                            access into the directory.
117                         */
118                         flags &= ~O_CREAT;
119                         local_flags &= ~O_CREAT;
120                 }
121         }
122
123         /*
124          * This little piece of insanity is inspired by the
125          * fact that an NT client can open a file for O_RDONLY,
126          * but set the create disposition to FILE_EXISTS_TRUNCATE.
127          * If the client *can* write to the file, then it expects to
128          * truncate the file, even though it is opening for readonly.
129          * Quicken uses this stupid trick in backup file creation...
130          * Thanks *greatly* to "David W. Chapman Jr." <dwcjr@inethouston.net>
131          * for helping track this one down. It didn't bite us in 2.0.x
132          * as we always opened files read-write in that release. JRA.
133          */
134
135         if ((accmode == O_RDONLY) && ((flags & O_TRUNC) == O_TRUNC)) {
136                 DEBUG(10,("onefs_open_file: truncate requested on read-only "
137                           "open for file %s\n", smb_fname_str_dbg(smb_fname)));
138                 local_flags = (flags & ~O_ACCMODE)|O_RDWR;
139         }
140
141 #if defined(O_NONBLOCK) && defined(S_ISFIFO)
142         /*
143          * We would block on opening a FIFO with no one else on the
144          * other end. Do what we used to do and add O_NONBLOCK to the
145          * open flags. JRA.
146          */
147
148         if (file_existed && S_ISFIFO(smb_fname->st.st_ex_mode)) {
149                 local_flags |= O_NONBLOCK;
150         }
151 #endif
152
153         /* Don't create files with Microsoft wildcard characters. */
154         if (fsp->base_fsp) {
155                 /*
156                  * wildcard characters are allowed in stream names
157                  * only test the basefilename
158                  */
159                 wild = fsp->base_fsp->fsp_name->base_name;
160         } else {
161                 wild = smb_fname->base_name;
162         }
163         if ((local_flags & O_CREAT) && !file_existed &&
164             ms_has_wild(wild))  {
165                 /*
166                  * XXX: may need to remvoe this return...
167                  *
168                  * We dont think this check needs to exist. All it does is
169                  * block creating files with Microsoft wildcards, which is
170                  * fine if the creation originated from NFS or locally and
171                  * then was copied via Samba.
172                  */
173                 DEBUG(1, ("onefs_open_file: creating file with wildcard: %s\n",
174                           smb_fname_str_dbg(smb_fname)));
175                 return NT_STATUS_OBJECT_NAME_INVALID;
176         }
177
178         /* Actually do the open */
179
180 #ifdef O_NOFOLLOW
181         /*
182          * Never follow symlinks on a POSIX client. The
183          * client should be doing this.
184          */
185
186         if (fsp->posix_open || !lp_symlinks(SNUM(conn))) {
187                 flags |= O_NOFOLLOW;
188         }
189 #endif
190         /* Setup a onefs-style smb_fname struct. */
191         status = onefs_stream_prep_smb_fname(talloc_tos(), smb_fname,
192                                              &smb_fname_onefs);
193         if (!NT_STATUS_IS_OK(status)) {
194                 return status;
195         }
196
197         /* If it's a stream pass in the base_fd */
198         if ((conn->fs_capabilities & FILE_NAMED_STREAMS) &&
199             is_ntfs_stream_smb_fname(smb_fname_onefs)) {
200                 SMB_ASSERT(fsp->base_fsp);
201
202                 DEBUG(10, ("Opening a stream: base=%s(%d), stream=%s\n",
203                            smb_fname_onefs->base_name, fsp->base_fsp->fh->fd,
204                            smb_fname_onefs->stream_name));
205
206                 base_fd = fsp->base_fsp->fh->fd;
207         }
208
209         fsp->fh->fd = onefs_sys_create_file(conn,
210                                             base_fd,
211                                             smb_fname_onefs->stream_name != NULL ?
212                                             smb_fname_onefs->stream_name :
213                                             smb_fname_onefs->base_name,
214                                             access_mask,
215                                             open_access_mask,
216                                             share_access,
217                                             create_options,
218                                             flags,
219                                             unx_mode,
220                                             oplock_request,
221                                             id,
222                                             sd,
223                                             new_dos_attributes,
224                                             granted_oplock);
225         TALLOC_FREE(smb_fname_onefs);
226
227         if (fsp->fh->fd == -1) {
228                 if (errno == EMFILE) {
229                         static time_t last_warned = 0L;
230
231                         if (time((time_t *) NULL) > last_warned) {
232                                 DEBUG(0, ("Too many open files, unable "
233                                           "to open more!  smbd's max "
234                                           "open files = %d, also check "
235                                           "sysctl kern.maxfiles and "
236                                           "sysctl kern.maxfilesperproc\n",
237                                           lp_max_open_files()));
238                                 last_warned = time((time_t *) NULL);
239                         }
240                 }
241
242                 status = map_nt_error_from_unix(errno);
243                 DEBUG(3, ("Error opening file %s (%s) (local_flags=%d) "
244                           "(flags=%d)\n", smb_fname_str_dbg(smb_fname),
245                           strerror(errno), local_flags, flags));
246                 return status;
247         }
248
249         if ((local_flags & O_CREAT) && !file_existed) {
250
251                 /* Inherit the ACL if required */
252                 if (lp_inherit_perms(SNUM(conn))) {
253                         inherit_access_posix_acl(conn, parent_dir,
254                             smb_fname->base_name, unx_mode);
255                 }
256
257                 /* Change the owner if required. */
258                 if (lp_inherit_owner(SNUM(conn))) {
259                         change_file_owner_to_parent(conn, parent_dir,
260                             fsp);
261                 }
262
263                 notify_fname(conn, NOTIFY_ACTION_ADDED,
264                     FILE_NOTIFY_CHANGE_FILE_NAME, smb_fname->base_name);
265         }
266
267         if (!file_existed) {
268                 int ret;
269
270                 if (fsp->fh->fd == -1) {
271                         ret = SMB_VFS_STAT(conn, smb_fname);
272                 } else {
273                         ret = SMB_VFS_FSTAT(fsp, &smb_fname->st);
274                         /* If we have an fd, this stat should succeed. */
275                         if (ret == -1) {
276                                 DEBUG(0, ("Error doing fstat on open file %s "
277                                           "(%s)\n",
278                                           smb_fname_str_dbg(smb_fname),
279                                           strerror(errno) ));
280                         }
281                 }
282
283                 /* For a non-io open, this stat failing means file not found. JRA */
284                 if (ret == -1) {
285                         status = map_nt_error_from_unix(errno);
286                         fd_close(fsp);
287                         return status;
288                 }
289         }
290
291         /*
292          * POSIX allows read-only opens of directories. We don't
293          * want to do this (we use a different code path for this)
294          * so catch a directory open and return an EISDIR. JRA.
295          */
296
297         if(S_ISDIR(smb_fname->st.st_ex_mode)) {
298                 fd_close(fsp);
299                 errno = EISDIR;
300                 return NT_STATUS_FILE_IS_A_DIRECTORY;
301         }
302
303         fsp->mode = smb_fname->st.st_ex_mode;
304         fsp->file_id = vfs_file_id_from_sbuf(conn, &smb_fname->st);
305         fsp->vuid = req ? req->vuid : UID_FIELD_INVALID;
306         fsp->file_pid = req ? req->smbpid : 0;
307         fsp->can_lock = True;
308         fsp->can_read = (access_mask & (FILE_READ_DATA)) ? True : False;
309         if (!CAN_WRITE(conn)) {
310                 fsp->can_write = False;
311         } else {
312                 fsp->can_write = (access_mask & (FILE_WRITE_DATA | FILE_APPEND_DATA)) ?
313                         True : False;
314         }
315         fsp->print_file = False;
316         fsp->modified = False;
317         fsp->sent_oplock_break = NO_BREAK_SENT;
318         fsp->is_directory = False;
319         if (conn->aio_write_behind_list &&
320             is_in_path(smb_fname->base_name, conn->aio_write_behind_list,
321                        conn->case_sensitive)) {
322                 fsp->aio_write_behind = True;
323         }
324
325         status = fsp_set_smb_fname(fsp, smb_fname);
326         if (!NT_STATUS_IS_OK(status)) {
327                 fd_close(fsp);
328                 errno = map_errno_from_nt_status(status);
329                 return status;
330         }
331
332         fsp->wcp = NULL; /* Write cache pointer. */
333
334         DEBUG(2,("%s opened file %s read=%s write=%s (numopen=%d)\n",
335                  conn->server_info->unix_name,
336                  smb_fname_str_dbg(smb_fname),
337                  BOOLSTR(fsp->can_read), BOOLSTR(fsp->can_write),
338                  conn->num_files_open));
339
340         errno = 0;
341         return NT_STATUS_OK;
342 }
343
344 /****************************************************************************
345  Handle the 1 second delay in returning a SHARING_VIOLATION error.
346 ****************************************************************************/
347
348 static void defer_open(struct share_mode_lock *lck,
349                        struct timeval request_time,
350                        struct timeval timeout,
351                        struct smb_request *req,
352                        struct deferred_open_record *state)
353 {
354         int i;
355
356         /* Paranoia check */
357
358         for (i=0; i<lck->num_share_modes; i++) {
359                 struct share_mode_entry *e = &lck->share_modes[i];
360
361                 if (!is_deferred_open_entry(e)) {
362                         continue;
363                 }
364
365                 if (procid_is_me(&e->pid) && (e->op_mid == req->mid)) {
366                         DEBUG(0, ("Trying to defer an already deferred "
367                                   "request: mid=%d, exiting\n", req->mid));
368                         exit_server("attempt to defer a deferred request");
369                 }
370         }
371
372         /* End paranoia check */
373
374         DEBUG(10,("defer_open_sharing_error: time [%u.%06u] adding deferred "
375                   "open entry for mid %u\n",
376                   (unsigned int)request_time.tv_sec,
377                   (unsigned int)request_time.tv_usec,
378                   (unsigned int)req->mid));
379
380         if (!push_deferred_smb_message(req, request_time, timeout,
381                                        (char *)state, sizeof(*state))) {
382                 exit_server("push_deferred_smb_message failed");
383         }
384         add_deferred_open(lck, req->mid, request_time, state->id);
385 }
386
387 static void schedule_defer_open(struct share_mode_lock *lck,
388                                 struct timeval request_time,
389                                 struct smb_request *req)
390 {
391         struct deferred_open_record state;
392
393         /* This is a relative time, added to the absolute
394            request_time value to get the absolute timeout time.
395            Note that if this is the second or greater time we enter
396            this codepath for this particular request mid then
397            request_time is left as the absolute time of the *first*
398            time this request mid was processed. This is what allows
399            the request to eventually time out. */
400
401         struct timeval timeout;
402
403         /* Normally the smbd we asked should respond within
404          * OPLOCK_BREAK_TIMEOUT seconds regardless of whether
405          * the client did, give twice the timeout as a safety
406          * measure here in case the other smbd is stuck
407          * somewhere else. */
408
409         /*
410          * On OneFS, the kernel will always send an oplock_revoked message
411          * before this timeout is hit.
412          */
413         timeout = timeval_set(OPLOCK_BREAK_TIMEOUT*10, 0);
414
415         /* Nothing actually uses state.delayed_for_oplocks
416            but it's handy to differentiate in debug messages
417            between a 30 second delay due to oplock break, and
418            a 1 second delay for share mode conflicts. */
419
420         state.delayed_for_oplocks = True;
421         state.failed = false;
422         state.id = lck->id;
423
424         if (!request_timed_out(request_time, timeout)) {
425                 defer_open(lck, request_time, timeout, req, &state);
426         } else {
427                 /* A delayed-for-oplocks deferred open timing out should only
428                  * happen if there is a bug or extreme load, since we set the
429                  * timeout to 300 seconds. */
430                 DEBUG(0, ("Deferred open timeout! request_time=%d.%d, "
431                     "mid=%d\n", request_time.tv_sec, request_time.tv_usec,
432                     req->mid));
433         }
434 }
435
436 /****************************************************************************
437  Open a file with a share mode.  Passed in an already created files_struct.
438 ****************************************************************************/
439 NTSTATUS onefs_open_file_ntcreate(connection_struct *conn,
440                                   struct smb_request *req,
441                                   struct smb_filename *smb_fname,
442                                   uint32 access_mask,
443                                   uint32 share_access,
444                                   uint32 create_disposition,
445                                   uint32 create_options,
446                                   uint32 new_dos_attributes,
447                                   int oplock_request,
448                                   struct security_descriptor *sd,
449                                   files_struct *fsp,
450                                   int *pinfo,
451                                   struct onefs_fsp_data *fsp_data)
452 {
453         int flags=0;
454         int flags2=0;
455         bool file_existed = VALID_STAT(smb_fname->st);
456         bool def_acl = False;
457         bool posix_open = False;
458         bool new_file_created = False;
459         bool clear_ads = False;
460         struct file_id id;
461         mode_t new_unx_mode = (mode_t)0;
462         mode_t unx_mode = (mode_t)0;
463         int info;
464         uint32 existing_dos_attributes = 0;
465         struct pending_message_list *pml = NULL;
466         struct timeval request_time = timeval_zero();
467         struct share_mode_lock *lck = NULL;
468         uint32 open_access_mask = access_mask;
469         NTSTATUS status;
470         int ret_flock;
471         char *parent_dir;
472         int granted_oplock;
473         uint64_t oplock_callback_id = 0;
474         uint32 createfile_attributes = 0;
475
476         ZERO_STRUCT(id);
477
478         if (conn->printer) {
479                 /*
480                  * Printers are handled completely differently.
481                  * Most of the passed parameters are ignored.
482                  */
483
484                 if (pinfo) {
485                         *pinfo = FILE_WAS_CREATED;
486                 }
487
488                 DEBUG(10, ("onefs_open_file_ntcreate: printer open fname=%s\n",
489                            smb_fname_str_dbg(smb_fname)));
490
491                 return print_fsp_open(req, conn, smb_fname->base_name,
492                                       req->vuid, fsp, &smb_fname->st);
493         }
494
495         if (!parent_dirname(talloc_tos(), smb_fname->base_name, &parent_dir,
496                             NULL)) {
497                 return NT_STATUS_NO_MEMORY;
498         }
499
500         if (new_dos_attributes & FILE_FLAG_POSIX_SEMANTICS) {
501                 posix_open = True;
502                 unx_mode = (mode_t)(new_dos_attributes & ~FILE_FLAG_POSIX_SEMANTICS);
503                 new_dos_attributes = 0;
504         } else {
505                 /* We add aARCH to this as this mode is only used if the file is
506                  * created new. */
507                 unx_mode = unix_mode(conn, new_dos_attributes | aARCH,
508                                      smb_fname, parent_dir);
509         }
510
511         DEBUG(10,("onefs_open_file_ntcreate: fname=%s, dos_attrs=0x%x "
512                   "access_mask=0x%x share_access=0x%x "
513                   "create_disposition = 0x%x create_options=0x%x "
514                   "unix mode=0%o oplock_request=0x%x\n",
515                   smb_fname_str_dbg(smb_fname), new_dos_attributes,
516                   access_mask, share_access, create_disposition,
517                   create_options, unx_mode, oplock_request));
518
519         /*
520          * Any non-stat-only open has the potential to contend oplocks, which
521          * means to avoid blocking in the kernel (which is unacceptable), the
522          * open must be deferred.  In order to defer opens, req must not be
523          * NULL.  The known cases of calling with a NULL req:
524          *
525          *   1. Open the base file of a stream: Always done stat-only
526          *
527          *   2. open_file_fchmod(), which is called from 3 places:
528          *      A. try_chown: Posix acls only. Never called on onefs.
529          *      B. set_ea_dos_attributes: Can't be called from onefs, because
530          *         SMB_VFS_SETXATTR return ENOSYS.
531          *      C. file_set_dos_mode: This would only happen if the "dos
532          *         filemode" smb.conf parameter is set to yes.  We ship with
533          *         it off, but if a customer were to turn it on it would be
534          *         bad.
535          */
536         if (req == NULL && !is_stat_open(access_mask) &&
537             !is_ntfs_stream_smb_fname(smb_fname)) {
538                 smb_panic("NULL req on a non-stat-open!");
539         }
540
541         if ((req == NULL) && ((oplock_request & INTERNAL_OPEN_ONLY) == 0)) {
542                 DEBUG(0, ("No smb request but not an internal only open!\n"));
543                 return NT_STATUS_INTERNAL_ERROR;
544         }
545
546         /*
547          * Only non-internal opens can be deferred at all
548          */
549
550         if ((req != NULL)
551             && ((pml = get_open_deferred_message(req->mid)) != NULL)) {
552                 struct deferred_open_record *state =
553                         (struct deferred_open_record *)pml->private_data.data;
554
555                 /* Remember the absolute time of the original
556                    request with this mid. We'll use it later to
557                    see if this has timed out. */
558
559                 request_time = pml->request_time;
560
561                 /* Remove the deferred open entry under lock. */
562                 lck = get_share_mode_lock(talloc_tos(), state->id, NULL, NULL,
563                                           NULL);
564                 if (lck == NULL) {
565                         DEBUG(0, ("could not get share mode lock\n"));
566                 } else {
567                         del_deferred_open_entry(lck, req->mid);
568                         TALLOC_FREE(lck);
569                 }
570
571                 /* Ensure we don't reprocess this message. */
572                 remove_deferred_open_smb_message(req->mid);
573
574                 /*
575                  * When receiving a semlock_async_failure message, the
576                  * deferred open will be marked as "failed". Returning
577                  * INTERNAL_ERROR.
578                  */
579                 if (state->failed) {
580                         DEBUG(0, ("onefs_open_file_ntcreate: "
581                                   "semlock_async_failure detected!\n"));
582                         return NT_STATUS_INTERNAL_ERROR;
583                 }
584         }
585
586         status = check_name(conn, smb_fname->base_name);
587         if (!NT_STATUS_IS_OK(status)) {
588                 return status;
589         }
590
591         if (!posix_open) {
592                 new_dos_attributes &= SAMBA_ATTRIBUTES_MASK;
593                 if (file_existed) {
594                         existing_dos_attributes = dos_mode(conn, smb_fname);
595                 }
596         }
597
598         /* Setup dos_attributes to be set by ifs_createfile */
599         if (lp_store_dos_attributes(SNUM(conn))) {
600                 createfile_attributes = (new_dos_attributes | aARCH) &
601                     ~(FILE_ATTRIBUTE_NONINDEXED | FILE_ATTRIBUTE_COMPRESSED);
602         }
603
604         /* Ignore oplock requests if oplocks are disabled. */
605         if (!lp_oplocks(SNUM(conn)) || global_client_failed_oplock_break ||
606             IS_VETO_OPLOCK_PATH(conn, smb_fname->base_name)) {
607                 /* Mask off everything except the private Samba bits. */
608                 oplock_request &= SAMBA_PRIVATE_OPLOCK_MASK;
609         }
610
611         /* this is for OS/2 long file names - say we don't support them */
612         if (!lp_posix_pathnames() && strstr(smb_fname->base_name,".+,;=[].")) {
613                 /* OS/2 Workplace shell fix may be main code stream in a later
614                  * release. */
615                 DEBUG(5,("onefs_open_file_ntcreate: OS/2 long filenames are "
616                           "not supported.\n"));
617                 if (use_nt_status()) {
618                         return NT_STATUS_OBJECT_NAME_NOT_FOUND;
619                 }
620                 return NT_STATUS_DOS(ERRDOS, ERRcannotopen);
621         }
622
623         switch( create_disposition ) {
624                 /*
625                  * Currently we're using FILE_SUPERSEDE as the same as
626                  * FILE_OVERWRITE_IF but they really are
627                  * different. FILE_SUPERSEDE deletes an existing file
628                  * (requiring delete access) then recreates it.
629                  */
630                 case FILE_SUPERSEDE:
631                         /**
632                          * @todo: Clear all file attributes?
633                          * http://www.osronline.com/article.cfm?article=302
634                          * create if not exist, trunc if exist
635                          *
636                          * If file exists replace/overwrite. If file doesn't
637                          * exist create.
638                          */
639                         flags2 |= (O_CREAT | O_TRUNC);
640                         clear_ads = true;
641                         break;
642
643                 case FILE_OVERWRITE_IF:
644                         /* If file exists replace/overwrite. If file doesn't
645                          * exist create. */
646                         flags2 |= (O_CREAT | O_TRUNC);
647                         clear_ads = true;
648                         break;
649
650                 case FILE_OPEN:
651                         /* If file exists open. If file doesn't exist error. */
652                         if (!file_existed) {
653                                 DEBUG(5,("onefs_open_file_ntcreate: FILE_OPEN "
654                                          "requested for file %s and file "
655                                          "doesn't exist.\n",
656                                          smb_fname_str_dbg(smb_fname)));
657                                 errno = ENOENT;
658                                 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
659                         }
660                         break;
661
662                 case FILE_OVERWRITE:
663                         /* If file exists overwrite. If file doesn't exist
664                          * error. */
665                         if (!file_existed) {
666                                 DEBUG(5, ("onefs_open_file_ntcreate: "
667                                           "FILE_OVERWRITE requested for file "
668                                           "%s and file doesn't exist.\n",
669                                           smb_fname_str_dbg(smb_fname)));
670                                 errno = ENOENT;
671                                 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
672                         }
673                         flags2 |= O_TRUNC;
674                         clear_ads = true;
675                         break;
676
677                 case FILE_CREATE:
678                         /* If file exists error. If file doesn't exist
679                          * create. */
680                         if (file_existed) {
681                                 DEBUG(5, ("onefs_open_file_ntcreate: "
682                                           "FILE_CREATE requested for file %s "
683                                           "and file already exists.\n",
684                                           smb_fname_str_dbg(smb_fname)));
685                                 if (S_ISDIR(smb_fname->st.st_ex_mode)) {
686                                         errno = EISDIR;
687                                 } else {
688                                         errno = EEXIST;
689                                 }
690                                 return map_nt_error_from_unix(errno);
691                         }
692                         flags2 |= (O_CREAT|O_EXCL);
693                         break;
694
695                 case FILE_OPEN_IF:
696                         /* If file exists open. If file doesn't exist
697                          * create. */
698                         flags2 |= O_CREAT;
699                         break;
700
701                 default:
702                         return NT_STATUS_INVALID_PARAMETER;
703         }
704
705         /* Match attributes on file exists and overwrite. */
706         if (!posix_open && file_existed &&
707             ((create_disposition == FILE_OVERWRITE) ||
708                 (create_disposition == FILE_OVERWRITE_IF))) {
709                 if (!open_match_attributes(conn, existing_dos_attributes,
710                                            new_dos_attributes,
711                                            smb_fname->st.st_ex_mode,
712                                            unx_mode, &new_unx_mode)) {
713                         DEBUG(5, ("onefs_open_file_ntcreate: attributes "
714                                   "missmatch for file %s (%x %x) (0%o, 0%o)\n",
715                                   smb_fname_str_dbg(smb_fname),
716                                   existing_dos_attributes,
717                                   new_dos_attributes,
718                                   (unsigned int)smb_fname->st.st_ex_mode,
719                                   (unsigned int)unx_mode ));
720                         errno = EACCES;
721                         return NT_STATUS_ACCESS_DENIED;
722                 }
723         }
724
725         /*
726          * OneFS understands MAXIMUM_ALLOWED_ACCESS, so only hack the
727          * access_mask, but leave the MAA for the actual open in
728          * open_access_mask.
729          */
730         open_access_mask = access_mask;
731         if (open_access_mask & MAXIMUM_ALLOWED_ACCESS) {
732                 access_mask |= FILE_GENERIC_ALL;
733         }
734
735         /* Convert GENERIC bits to specific bits. */
736         se_map_generic(&access_mask, &file_generic_mapping);
737         se_map_generic(&open_access_mask, &file_generic_mapping);
738
739         if ((flags2 & O_TRUNC) || (oplock_request & FORCE_OPLOCK_BREAK_TO_NONE)) {
740                 /* This will cause oplock breaks. */
741                 open_access_mask |= FILE_WRITE_DATA;
742         }
743
744         DEBUG(10, ("onefs_open_file_ntcreate: fname=%s, after mapping "
745                    "open_access_mask=%#x, access_mask=0x%x\n",
746                    smb_fname_str_dbg(smb_fname), open_access_mask,
747                    access_mask));
748
749         /*
750          * Note that we ignore the append flag as append does not
751          * mean the same thing under DOS and Unix.
752          */
753
754         if ((access_mask & (FILE_WRITE_DATA | FILE_APPEND_DATA)) ||
755             (oplock_request & FORCE_OPLOCK_BREAK_TO_NONE)) {
756
757                 /*
758                  * DENY_DOS opens are always underlying read-write on the
759                  * file handle, no matter what the requested access mask
760                  * says. Stock samba just sets the flags, but since
761                  * ifs_createfile uses the access_mask, it must be updated as
762                  * well.  This allows BASE-DENY* to pass.
763                  */
764                 if (create_options & NTCREATEX_OPTIONS_PRIVATE_DENY_DOS) {
765
766                         DEBUG(10,("onefs_open_file_ntcreate: deny_dos: "
767                                   "Adding O_RDWR to flags "
768                                   "(0x%x) and some READ bits to "
769                                   "open_access_mask (0x%x)\n",
770                                   flags, open_access_mask));
771
772                         flags = O_RDWR;
773                         open_access_mask |= (FILE_READ_ATTRIBUTES |
774                             FILE_READ_DATA | FILE_READ_EA | FILE_EXECUTE);
775
776                 } else if (access_mask & (FILE_READ_ATTRIBUTES |
777                                FILE_READ_DATA |
778                                FILE_READ_EA |
779                                FILE_EXECUTE)) {
780                         flags = O_RDWR;
781                 } else {
782                         flags = O_WRONLY;
783                 }
784         } else {
785                 flags = O_RDONLY;
786         }
787
788         /* Currently we only look at FILE_WRITE_THROUGH for create options. */
789 #if defined(O_SYNC)
790         if ((create_options & FILE_WRITE_THROUGH) &&
791             lp_strict_sync(SNUM(conn))) {
792                 flags2 |= O_SYNC;
793         }
794 #endif /* O_SYNC */
795
796         if (posix_open && (access_mask & FILE_APPEND_DATA)) {
797                 flags2 |= O_APPEND;
798         }
799
800         if (!posix_open && !CAN_WRITE(conn)) {
801                 /*
802                  * We should really return a permission denied error if either
803                  * O_CREAT or O_TRUNC are set, but for compatibility with
804                  * older versions of Samba we just AND them out.
805                  */
806                 flags2 &= ~(O_CREAT|O_TRUNC);
807
808                 /* Deny DELETE_ACCESS explicitly if the share is read only. */
809                 if (access_mask & DELETE_ACCESS) {
810                         return map_nt_error_from_unix(EACCES);
811                 }
812         }
813
814         /* Ensure we can't write on a read-only share or file. */
815         if (flags != O_RDONLY && file_existed &&
816             (!CAN_WRITE(conn) || IS_DOS_READONLY(existing_dos_attributes))) {
817                 DEBUG(5, ("onefs_open_file_ntcreate: write access requested "
818                           "for file %s on read only %s\n",
819                           smb_fname_str_dbg(smb_fname),
820                           !CAN_WRITE(conn) ? "share" : "file" ));
821                 errno = EACCES;
822                 return NT_STATUS_ACCESS_DENIED;
823         }
824
825         DEBUG(10, ("fsp = %p\n", fsp));
826
827         fsp->share_access = share_access;
828         fsp->fh->private_options = create_options;
829         fsp->access_mask = open_access_mask; /* We change this to the
830                                               * requested access_mask after
831                                               * the open is done. */
832         fsp->posix_open = posix_open;
833
834         /* Ensure no SAMBA_PRIVATE bits can be set. */
835         fsp->oplock_type = (oplock_request & ~SAMBA_PRIVATE_OPLOCK_MASK);
836
837         if (timeval_is_zero(&request_time)) {
838                 request_time = fsp->open_time;
839         }
840
841         if (file_existed) {
842                 struct timespec old_write_time = smb_fname->st.st_ex_mtime;
843                 id = vfs_file_id_from_sbuf(conn, &smb_fname->st);
844
845                 lck = get_share_mode_lock(talloc_tos(), id,
846                                           conn->connectpath,
847                                           smb_fname, &old_write_time);
848
849                 if (lck == NULL) {
850                         DEBUG(0, ("Could not get share mode lock\n"));
851                         return NT_STATUS_SHARING_VIOLATION;
852                 }
853
854                 if (lck->delete_on_close) {
855                         /* DELETE_PENDING is not deferred for a second */
856                         TALLOC_FREE(lck);
857                         return NT_STATUS_DELETE_PENDING;
858                 }
859         }
860
861         SMB_ASSERT(!file_existed || (lck != NULL));
862
863         /*
864          * Ensure we pay attention to default ACLs on directories.  May be
865          * neccessary depending on ACL policies.
866          */
867         if ((flags2 & O_CREAT) && lp_inherit_acls(SNUM(conn)) &&
868             (def_acl = directory_has_default_acl(conn, parent_dir))) {
869                 unx_mode = 0777;
870         }
871
872         DEBUG(4,("calling onefs_open_file with flags=0x%X flags2=0x%X "
873                  "mode=0%o, access_mask = 0x%x, open_access_mask = 0x%x\n",
874                  (unsigned int)flags, (unsigned int)flags2,
875                  (unsigned int)unx_mode, (unsigned int)access_mask,
876                  (unsigned int)open_access_mask));
877
878         /*
879          * Since the open is guaranteed to be stat only if req == NULL, a
880          * callback record is only needed if req != NULL.
881          */
882         if (req) {
883                 SMB_ASSERT(fsp_data);
884                 oplock_callback_id = onefs_oplock_wait_record(req->mid);
885                 if (oplock_callback_id == 0) {
886                         return NT_STATUS_NO_MEMORY;
887                 }
888         } else {
889                 /*
890                  * It is also already asserted it's either a stream or a
891                  * stat-only open at this point.
892                  */
893                 SMB_ASSERT(fsp->oplock_type == NO_OPLOCK);
894
895                 /* The kernel and Samba's version of stat-only differs
896                  * slightly: The kernel doesn't think its stat-only if we're
897                  * truncating.  We'd better have a req in order to defer the
898                  * open. */
899                 SMB_ASSERT(!((flags|flags2) & O_TRUNC));
900         }
901
902         /* Do the open. */
903         status = onefs_open_file(fsp,
904                                  conn,
905                                  req,
906                                  parent_dir,
907                                  smb_fname,
908                                  flags|flags2,
909                                  unx_mode,
910                                  access_mask,
911                                  open_access_mask,
912                                  fsp->oplock_type,
913                                  oplock_callback_id,
914                                  share_access,
915                                  create_options,
916                                  createfile_attributes,
917                                  sd,
918                                  &granted_oplock);
919
920         if (!NT_STATUS_IS_OK(status)) {
921
922                 /* OneFS Oplock Handling */
923                 if (errno == EINPROGRESS) {
924
925                         /* If we get EINPROGRESS, the kernel will send us an
926                          * asynchronous semlock event back. Ensure we can defer
927                          * the open, by asserting req. */
928                         SMB_ASSERT(req);
929
930                         if (lck == NULL) {
931                                 /*
932                                  * We hit the race that when we did the stat
933                                  * on the file it did not exist, and someone
934                                  * has created it in between the stat and the
935                                  * open_file() call. Defer our open waiting,
936                                  * to break the oplock of the first opener.
937                                  */
938
939                                 struct timespec old_write_time;
940
941                                 DEBUG(3, ("Someone created file %s with an "
942                                           "oplock after we looked: Retrying\n",
943                                           smb_fname_str_dbg(smb_fname)));
944                                 /*
945                                  * We hit the race that when we did the stat
946                                  * on the file it did not exist, and someone
947                                  * has created it in between the stat and the
948                                  * open_file() call. Just retry immediately.
949                                  */
950                                 id = vfs_file_id_from_sbuf(conn,
951                                                            &smb_fname->st);
952                                 if (!(lck = get_share_mode_lock(talloc_tos(),
953                                           id, conn->connectpath, smb_fname,
954                                           &old_write_time))) {
955                                         /*
956                                          * Emergency exit
957                                          */
958                                         DEBUG(0, ("onefs_open_file_ntcreate: "
959                                                   "Could not get share mode "
960                                                   "lock for %s\n",
961                                                 smb_fname_str_dbg(smb_fname)));
962                                         status = NT_STATUS_SHARING_VIOLATION;
963
964                                         /* XXXZLK: This will cause us to get a
965                                          * semlock event when we aren't
966                                          * expecting one. */
967                                         goto cleanup_destroy;
968                                 }
969
970                                 schedule_defer_open(lck, request_time, req);
971                                 goto cleanup;
972                         }
973                         /* Waiting for an oplock */
974                         DEBUG(5,("Async createfile because a client has an "
975                                  "oplock on %s\n",
976                                  smb_fname_str_dbg(smb_fname)));
977
978                         SMB_ASSERT(req);
979                         schedule_defer_open(lck, request_time, req);
980                         goto cleanup;
981                 }
982
983                 /* Check for a sharing violation */
984                 if ((errno == EAGAIN) || (errno == EWOULDBLOCK)) {
985                         uint32 can_access_mask;
986                         bool can_access = True;
987
988                         /* If we raced on open we may not have a valid file_id
989                          * or stat buf.  Get them again. */
990                         if (SMB_VFS_STAT(conn, fname, psbuf) == -1) {
991                                 DEBUG(0,("Error doing stat on file %s "
992                                         "(%s)\n", fname, strerror(errno)));
993                                 status = NT_STATUS_SHARING_VIOLATION;
994                                 goto cleanup_destroy;
995                         }
996                         id = vfs_file_id_from_sbuf(conn, psbuf);
997
998                         /* Check if this can be done with the deny_dos and fcb
999                          * calls. */
1000
1001                         /* Try to find dup fsp if possible. */
1002                         if (create_options &
1003                             (NTCREATEX_OPTIONS_PRIVATE_DENY_DOS|
1004                              NTCREATEX_OPTIONS_PRIVATE_DENY_FCB)) {
1005
1006                                 if (req == NULL) {
1007                                         DEBUG(0, ("DOS open without an SMB "
1008                                                   "request!\n"));
1009                                         status = NT_STATUS_INTERNAL_ERROR;
1010                                         goto cleanup_destroy;
1011                                 }
1012
1013                                 /* Use the client requested access mask here,
1014                                  * not the one we open with. */
1015                                 status = fcb_or_dos_open(req,
1016                                                         conn,
1017                                                         fsp,
1018                                                         smb_fname,
1019                                                         id,
1020                                                         req->smbpid,
1021                                                         req->vuid,
1022                                                         access_mask,
1023                                                         share_access,
1024                                                         create_options);
1025
1026                                 if (NT_STATUS_IS_OK(status)) {
1027                                         if (pinfo) {
1028                                                 *pinfo = FILE_WAS_OPENED;
1029                                         }
1030                                         status =  NT_STATUS_OK;
1031                                         goto cleanup;
1032                                 }
1033                         }
1034
1035                         /*
1036                          * This next line is a subtlety we need for
1037                          * MS-Access. If a file open will fail due to share
1038                          * permissions and also for security (access) reasons,
1039                          * we need to return the access failed error, not the
1040                          * share error. We can't open the file due to kernel
1041                          * oplock deadlock (it's possible we failed above on
1042                          * the open_mode_check()) so use a userspace check.
1043                          */
1044
1045                         if (flags & O_RDWR) {
1046                                 can_access_mask = FILE_READ_DATA|FILE_WRITE_DATA;
1047                         } else if (flags & O_WRONLY) {
1048                                 can_access_mask = FILE_WRITE_DATA;
1049                         } else {
1050                                 can_access_mask = FILE_READ_DATA;
1051                         }
1052
1053                         if (((can_access_mask & FILE_WRITE_DATA) &&
1054                                 !CAN_WRITE(conn)) ||
1055                             !can_access_file_data(conn, smb_fname,
1056                                                   can_access_mask)) {
1057                                 can_access = False;
1058                         }
1059
1060                         /*
1061                          * If we're returning a share violation, ensure we
1062                          * cope with the braindead 1 second delay.
1063                          */
1064                         if (!(oplock_request & INTERNAL_OPEN_ONLY) &&
1065                             lp_defer_sharing_violations()) {
1066                                 struct timeval timeout;
1067                                 struct deferred_open_record state;
1068                                 int timeout_usecs;
1069
1070                                 /* this is a hack to speed up torture tests
1071                                    in 'make test' */
1072                                 timeout_usecs = lp_parm_int(SNUM(conn),
1073                                     "smbd","sharedelay",
1074                                     SHARING_VIOLATION_USEC_WAIT);
1075
1076                                 /* This is a relative time, added to the
1077                                    absolute request_time value to get the
1078                                    absolute timeout time.  Note that if this
1079                                    is the second or greater time we enter this
1080                                    codepath for this particular request mid
1081                                    then request_time is left as the absolute
1082                                    time of the *first* time this request mid
1083                                    was processed. This is what allows the
1084                                    request to eventually time out. */
1085
1086                                 timeout = timeval_set(0, timeout_usecs);
1087
1088                                 /* Nothing actually uses
1089                                    state.delayed_for_oplocks but it's handy to
1090                                    differentiate in debug messages between a
1091                                    30 second delay due to oplock break, and a
1092                                    1 second delay for share mode conflicts. */
1093
1094                                 state.delayed_for_oplocks = False;
1095                                 state.id = id;
1096                                 state.failed = false;
1097
1098                                 if ((req != NULL)
1099                                     && !request_timed_out(request_time,
1100                                                           timeout)) {
1101                                         defer_open(lck, request_time, timeout,
1102                                                    req, &state);
1103                                 }
1104                         }
1105
1106                         if (can_access) {
1107                                 /*
1108                                  * We have detected a sharing violation here
1109                                  * so return the correct error code
1110                                  */
1111                                 status = NT_STATUS_SHARING_VIOLATION;
1112                         } else {
1113                                 status = NT_STATUS_ACCESS_DENIED;
1114                         }
1115
1116                         goto cleanup_destroy;
1117                 }
1118
1119                 /*
1120                  * Normal error, for example EACCES
1121                  */
1122          cleanup_destroy:
1123                 if (oplock_callback_id != 0) {
1124                         destroy_onefs_callback_record(oplock_callback_id);
1125                 }
1126          cleanup:
1127                 TALLOC_FREE(lck);
1128                 return status;
1129         }
1130
1131         fsp->oplock_type = granted_oplock;
1132
1133         if (oplock_callback_id != 0) {
1134                 onefs_set_oplock_callback(oplock_callback_id, fsp);
1135                 fsp_data->oplock_callback_id = oplock_callback_id;
1136         } else {
1137                 SMB_ASSERT(fsp->oplock_type == NO_OPLOCK);
1138         }
1139
1140         if (!file_existed) {
1141                 struct timespec old_write_time = smb_fname->st.st_ex_mtime;
1142                 /*
1143                  * Deal with the race condition where two smbd's detect the
1144                  * file doesn't exist and do the create at the same time. One
1145                  * of them will win and set a share mode, the other (ie. this
1146                  * one) should check if the requested share mode for this
1147                  * create is allowed.
1148                  */
1149
1150                 /*
1151                  * Now the file exists and fsp is successfully opened,
1152                  * fsp->file_id is valid and should replace the
1153                  * dev=0, inode=0 from a non existent file. Spotted by
1154                  * Nadav Danieli <nadavd@exanet.com>. JRA.
1155                  */
1156
1157                 id = fsp->file_id;
1158
1159                 lck = get_share_mode_lock(talloc_tos(), id,
1160                                           conn->connectpath,
1161                                           smb_fname, &old_write_time);
1162
1163                 if (lck == NULL) {
1164                         DEBUG(0, ("onefs_open_file_ntcreate: Could not get "
1165                                   "share mode lock for %s\n",
1166                                   smb_fname_str_dbg(smb_fname)));
1167                         fd_close(fsp);
1168                         return NT_STATUS_SHARING_VIOLATION;
1169                 }
1170
1171                 if (lck->delete_on_close) {
1172                         status = NT_STATUS_DELETE_PENDING;
1173                 }
1174
1175                 if (!NT_STATUS_IS_OK(status)) {
1176                         struct deferred_open_record state;
1177
1178                         fd_close(fsp);
1179
1180                         state.delayed_for_oplocks = False;
1181                         state.id = id;
1182
1183                         /* Do it all over again immediately. In the second
1184                          * round we will find that the file existed and handle
1185                          * the DELETE_PENDING and FCB cases correctly. No need
1186                          * to duplicate the code here. Essentially this is a
1187                          * "goto top of this function", but don't tell
1188                          * anybody... */
1189
1190                         if (req != NULL) {
1191                                 defer_open(lck, request_time, timeval_zero(),
1192                                            req, &state);
1193                         }
1194                         TALLOC_FREE(lck);
1195                         return status;
1196                 }
1197
1198                 /*
1199                  * We exit this block with the share entry *locked*.....
1200                  */
1201
1202         }
1203
1204         SMB_ASSERT(lck != NULL);
1205
1206         /* Delete streams if create_disposition requires it */
1207         if (file_existed && clear_ads &&
1208             !is_ntfs_stream_smb_fname(smb_fname)) {
1209                 status = delete_all_streams(conn, smb_fname->base_name);
1210                 if (!NT_STATUS_IS_OK(status)) {
1211                         TALLOC_FREE(lck);
1212                         fd_close(fsp);
1213                         return status;
1214                 }
1215         }
1216
1217         /* note that we ignore failure for the following. It is
1218            basically a hack for NFS, and NFS will never set one of
1219            these only read them. Nobody but Samba can ever set a deny
1220            mode and we have already checked our more authoritative
1221            locking database for permission to set this deny mode. If
1222            the kernel refuses the operations then the kernel is wrong.
1223            note that GPFS supports it as well - jmcd */
1224
1225         if (fsp->fh->fd != -1) {
1226                 ret_flock = SMB_VFS_KERNEL_FLOCK(fsp, share_access);
1227                 if(ret_flock == -1 ){
1228
1229                         TALLOC_FREE(lck);
1230                         fd_close(fsp);
1231                         return NT_STATUS_SHARING_VIOLATION;
1232                 }
1233         }
1234
1235         /*
1236          * At this point onwards, we can guarentee that the share entry
1237          * is locked, whether we created the file or not, and that the
1238          * deny mode is compatible with all current opens.
1239          */
1240
1241         /* Record the options we were opened with. */
1242         fsp->share_access = share_access;
1243         fsp->fh->private_options = create_options;
1244         /*
1245          * According to Samba4, SEC_FILE_READ_ATTRIBUTE is always granted,
1246          */
1247         fsp->access_mask = access_mask | FILE_READ_ATTRIBUTES;
1248
1249         if (file_existed) {
1250                 /* stat opens on existing files don't get oplocks. */
1251                 if (is_stat_open(open_access_mask)) {
1252                         fsp->oplock_type = NO_OPLOCK;
1253                 }
1254
1255                 if (!(flags2 & O_TRUNC)) {
1256                         info = FILE_WAS_OPENED;
1257                 } else {
1258                         info = FILE_WAS_OVERWRITTEN;
1259                 }
1260         } else {
1261                 info = FILE_WAS_CREATED;
1262         }
1263
1264         if (pinfo) {
1265                 *pinfo = info;
1266         }
1267
1268         /*
1269          * Setup the oplock info in both the shared memory and
1270          * file structs.
1271          */
1272
1273         if ((fsp->oplock_type != NO_OPLOCK) &&
1274             (fsp->oplock_type != FAKE_LEVEL_II_OPLOCK)) {
1275                 if (!set_file_oplock(fsp, fsp->oplock_type)) {
1276                         /* Could not get the kernel oplock */
1277                         fsp->oplock_type = NO_OPLOCK;
1278                 }
1279         }
1280
1281         if (fsp->oplock_type == LEVEL_II_OPLOCK &&
1282             (!lp_level2_oplocks(SNUM(conn)) ||
1283                 !(global_client_caps & CAP_LEVEL_II_OPLOCKS))) {
1284
1285                 DEBUG(5, ("Downgrading level2 oplock on open "
1286                           "because level2 oplocks = off\n"));
1287
1288                 release_file_oplock(fsp);
1289         }
1290
1291         if (info == FILE_WAS_OVERWRITTEN || info == FILE_WAS_CREATED ||
1292             info == FILE_WAS_SUPERSEDED) {
1293                 new_file_created = True;
1294         }
1295
1296         set_share_mode(lck, fsp, conn->server_info->utok.uid, 0,
1297                        fsp->oplock_type);
1298
1299         /* Handle strange delete on close create semantics. */
1300         if (create_options & FILE_DELETE_ON_CLOSE) {
1301                 status = can_set_delete_on_close(fsp, True, new_dos_attributes);
1302
1303                 if (!NT_STATUS_IS_OK(status)) {
1304                         /* Remember to delete the mode we just added. */
1305                         del_share_mode(lck, fsp);
1306                         TALLOC_FREE(lck);
1307                         fd_close(fsp);
1308                         return status;
1309                 }
1310                 /* Note that here we set the *inital* delete on close flag,
1311                    not the regular one. The magic gets handled in close. */
1312                 fsp->initial_delete_on_close = True;
1313         }
1314
1315         /*
1316          * Take care of inherited ACLs on created files - if default ACL not
1317          * selected.
1318          * May be necessary depending on acl policies.
1319          */
1320         if (!posix_open && !file_existed && !def_acl &&
1321             !(VALID_STAT(smb_fname->st) &&
1322                 (smb_fname->st.st_ex_flags & SF_HASNTFSACL))) {
1323
1324                 int saved_errno = errno; /* We might get ENOSYS in the next
1325                                           * call.. */
1326
1327                 if (SMB_VFS_FCHMOD_ACL(fsp, unx_mode) == -1 &&
1328                     errno == ENOSYS) {
1329                         errno = saved_errno; /* Ignore ENOSYS */
1330                 }
1331
1332         } else if (new_unx_mode) {
1333
1334                 int ret = -1;
1335
1336                 /* Attributes need changing. File already existed. */
1337
1338                 {
1339                         int saved_errno = errno; /* We might get ENOSYS in the
1340                                                   * next call.. */
1341                         ret = SMB_VFS_FCHMOD_ACL(fsp, new_unx_mode);
1342
1343                         if (ret == -1 && errno == ENOSYS) {
1344                                 errno = saved_errno; /* Ignore ENOSYS */
1345                         } else {
1346                                 DEBUG(5, ("onefs_open_file_ntcreate: reset "
1347                                           "attributes of file %s to 0%o\n",
1348                                           smb_fname_str_dbg(smb_fname),
1349                                           (unsigned int)new_unx_mode));
1350                                 ret = 0; /* Don't do the fchmod below. */
1351                         }
1352                 }
1353
1354                 if ((ret == -1) &&
1355                     (SMB_VFS_FCHMOD(fsp, new_unx_mode) == -1))
1356                         DEBUG(5, ("onefs_open_file_ntcreate: failed to reset "
1357                                   "attributes of file %s to 0%o\n",
1358                                   smb_fname_str_dbg(smb_fname),
1359                                   (unsigned int)new_unx_mode));
1360         }
1361
1362         /* If this is a successful open, we must remove any deferred open
1363          * records. */
1364         if (req != NULL) {
1365                 del_deferred_open_entry(lck, req->mid);
1366         }
1367         TALLOC_FREE(lck);
1368
1369         return NT_STATUS_OK;
1370 }
1371
1372
1373 /****************************************************************************
1374  Open a directory from an NT SMB call.
1375 ****************************************************************************/
1376 static NTSTATUS onefs_open_directory(connection_struct *conn,
1377                                      struct smb_request *req,
1378                                      struct smb_filename *smb_dname,
1379                                      uint32 access_mask,
1380                                      uint32 share_access,
1381                                      uint32 create_disposition,
1382                                      uint32 create_options,
1383                                      uint32 file_attributes,
1384                                      struct security_descriptor *sd,
1385                                      files_struct **result,
1386                                      int *pinfo)
1387 {
1388         files_struct *fsp = NULL;
1389         struct share_mode_lock *lck = NULL;
1390         NTSTATUS status;
1391         struct timespec mtimespec;
1392         int info = 0;
1393         char *parent_dir;
1394         bool posix_open = false;
1395         uint32 create_flags = 0;
1396         uint32 mode = lp_dir_mask(SNUM(conn));
1397
1398         DEBUG(5, ("onefs_open_directory: opening directory %s, "
1399                   "access_mask = 0x%x, "
1400                   "share_access = 0x%x create_options = 0x%x, "
1401                   "create_disposition = 0x%x, file_attributes = 0x%x\n",
1402                   smb_fname_str_dbg(smb_dname), (unsigned int)access_mask,
1403                   (unsigned int)share_access, (unsigned int)create_options,
1404                   (unsigned int)create_disposition,
1405                   (unsigned int)file_attributes));
1406
1407         if (!(file_attributes & FILE_FLAG_POSIX_SEMANTICS) &&
1408             (conn->fs_capabilities & FILE_NAMED_STREAMS) &&
1409             is_ntfs_stream_smb_fname(smb_dname)) {
1410                 DEBUG(2, ("onefs_open_directory: %s is a stream name!\n",
1411                           smb_fname_str_dbg(smb_dname)));
1412                 return NT_STATUS_NOT_A_DIRECTORY;
1413         }
1414
1415         switch (create_disposition) {
1416                 case FILE_OPEN:
1417                         /* If directory exists open. If directory doesn't
1418                          * exist error. */
1419                         create_flags = 0;
1420                         info = FILE_WAS_OPENED;
1421                         break;
1422                 case FILE_CREATE:
1423                         /* If directory exists error. If directory doesn't
1424                          * exist create. */
1425                         create_flags = O_CREAT | O_EXCL;
1426                         info = FILE_WAS_CREATED;
1427                         break;
1428                 case FILE_OPEN_IF:
1429                         /* If directory exists open. If directory doesn't
1430                          * exist create. */
1431
1432                         /* Note: in order to return whether the directory was
1433                          * opened or created, we first try to open and then try
1434                          * to create. */
1435                         create_flags = 0;
1436                         info = FILE_WAS_OPENED;
1437                         break;
1438                 case FILE_SUPERSEDE:
1439                 case FILE_OVERWRITE:
1440                 case FILE_OVERWRITE_IF:
1441                 default:
1442                         DEBUG(5, ("onefs_open_directory: invalid "
1443                                   "create_disposition 0x%x for directory %s\n",
1444                                   (unsigned int)create_disposition,
1445                                   smb_fname_str_dbg(smb_dname)));
1446                         return NT_STATUS_INVALID_PARAMETER;
1447         }
1448
1449         /*
1450          * Check for write access to the share. Done in mkdir_internal() in
1451          * mainline samba.
1452          */
1453         if (!CAN_WRITE(conn) && (create_flags & O_CREAT)) {
1454                 return NT_STATUS_ACCESS_DENIED;
1455         }
1456
1457         /* Get parent dirname */
1458         if (!parent_dirname(talloc_tos(), smb_dname->base_name, &parent_dir,
1459                             NULL)) {
1460                 return NT_STATUS_NO_MEMORY;
1461         }
1462
1463         if (file_attributes & FILE_FLAG_POSIX_SEMANTICS) {
1464                 posix_open = true;
1465                 mode = (mode_t)(file_attributes & ~FILE_FLAG_POSIX_SEMANTICS);
1466                 file_attributes = 0;
1467         } else {
1468                 mode = unix_mode(conn, aDIR, smb_dname, parent_dir);
1469         }
1470
1471         /*
1472          * The NONINDEXED and COMPRESSED bits seem to always be cleared on
1473          * directories, no matter if you specify that they should be set.
1474          */
1475         file_attributes &=
1476             ~(FILE_ATTRIBUTE_NONINDEXED | FILE_ATTRIBUTE_COMPRESSED);
1477
1478         status = file_new(req, conn, &fsp);
1479         if(!NT_STATUS_IS_OK(status)) {
1480                 return status;
1481         }
1482
1483         /*
1484          * Actual open with retry magic to handle FILE_OPEN_IF which is
1485          * unique because the kernel won't tell us if the file was opened or
1486          * created.
1487          */
1488  retry_open:
1489         fsp->fh->fd = onefs_sys_create_file(conn,
1490                                             -1,
1491                                             smb_dname->base_name,
1492                                             access_mask,
1493                                             access_mask,
1494                                             share_access,
1495                                             create_options,
1496                                             create_flags | O_DIRECTORY,
1497                                             mode,
1498                                             0,
1499                                             0,
1500                                             sd,
1501                                             file_attributes,
1502                                             NULL);
1503
1504         if (fsp->fh->fd == -1) {
1505                 DEBUG(3, ("Error opening %s. Errno=%d (%s).\n",
1506                           smb_fname_str_dbg(smb_dname), errno,
1507                           strerror(errno)));
1508                 SMB_ASSERT(errno != EINPROGRESS);
1509
1510                 if (create_disposition == FILE_OPEN_IF) {
1511                         if (errno == ENOENT) {
1512                                 /* Try again, creating it this time. */
1513                                 create_flags = O_CREAT | O_EXCL;
1514                                 info = FILE_WAS_CREATED;
1515                                 goto retry_open;
1516                         } else if (errno == EEXIST) {
1517                                 /* Uggh. Try again again. */
1518                                 create_flags = 0;
1519                                 info = FILE_WAS_OPENED;
1520                                 goto retry_open;
1521                         }
1522                 }
1523
1524                 /* Error cases below: */
1525                 file_free(req, fsp);
1526
1527                 if ((errno == ENOENT) && (create_disposition == FILE_OPEN)) {
1528                         DEBUG(5, ("onefs_open_directory: FILE_OPEN requested "
1529                                   "for directory %s and it doesn't "
1530                                   "exist.\n", smb_fname_str_dbg(smb_dname)));
1531                         return NT_STATUS_OBJECT_NAME_NOT_FOUND;
1532                 } else if ((errno == EEXIST) &&
1533                     (create_disposition == FILE_CREATE)) {
1534                         DEBUG(5, ("onefs_open_directory: FILE_CREATE "
1535                                   "requested for directory %s and it "
1536                                   "already exists.\n",
1537                                   smb_fname_str_dbg(smb_dname)));
1538                         return NT_STATUS_OBJECT_NAME_COLLISION;
1539                 } else if ((errno == EAGAIN) || (errno == EWOULDBLOCK)) {
1540                         /* Catch sharing violations. */
1541                         return NT_STATUS_SHARING_VIOLATION;
1542                 }
1543
1544                 return map_nt_error_from_unix(errno);
1545         }
1546
1547         if (info == FILE_WAS_CREATED) {
1548
1549                 /* Pulled from mkdir_internal() */
1550                 if (SMB_VFS_LSTAT(conn, smb_dname) == -1) {
1551                         DEBUG(2, ("Could not stat directory '%s' just "
1552                                   "created: %s\n",
1553                                   smb_fname_str_dbg(smb_dname),
1554                                   strerror(errno)));
1555                         return map_nt_error_from_unix(errno);
1556                 }
1557
1558                 if (!S_ISDIR(smb_dname->st.st_ex_mode)) {
1559                         DEBUG(0, ("Directory just '%s' created is not a "
1560                                   "directory\n",
1561                                   smb_fname_str_dbg(smb_dname)));
1562                         return NT_STATUS_ACCESS_DENIED;
1563                 }
1564
1565                 if (!posix_open) {
1566                         /*
1567                          * Check if high bits should have been set, then (if
1568                          * bits are missing): add them.  Consider bits
1569                          * automagically set by UNIX, i.e. SGID bit from
1570                          * parent dir.
1571                          */
1572                         if (mode & ~(S_IRWXU|S_IRWXG|S_IRWXO) &&
1573                             (mode & ~smb_dname->st.st_ex_mode)) {
1574                                 SMB_VFS_CHMOD(conn, smb_dname->base_name,
1575                                     (smb_dname->st.st_ex_mode |
1576                                         (mode & ~smb_dname->st.st_ex_mode)));
1577                         }
1578                 }
1579
1580                 /* Change the owner if required. */
1581                 if (lp_inherit_owner(SNUM(conn))) {
1582                         change_dir_owner_to_parent(conn, parent_dir,
1583                                                    smb_dname->base_name,
1584                                                    &smb_dname->st);
1585                 }
1586
1587                 notify_fname(conn, NOTIFY_ACTION_ADDED,
1588                              FILE_NOTIFY_CHANGE_DIR_NAME,
1589                              smb_dname->base_name);
1590         }
1591
1592         /* Stat the fd for Samba bookkeeping. */
1593         if(SMB_VFS_FSTAT(fsp, &smb_dname->st) != 0) {
1594                 fd_close(fsp);
1595                 file_free(req, fsp);
1596                 return map_nt_error_from_unix(errno);
1597         }
1598
1599         /* Setup the files_struct for it. */
1600         fsp->mode = smb_dname->st.st_ex_mode;
1601         fsp->file_id = vfs_file_id_from_sbuf(conn, &smb_dname->st);
1602         fsp->vuid = req ? req->vuid : UID_FIELD_INVALID;
1603         fsp->file_pid = req ? req->smbpid : 0;
1604         fsp->can_lock = False;
1605         fsp->can_read = False;
1606         fsp->can_write = False;
1607
1608         fsp->share_access = share_access;
1609         fsp->fh->private_options = create_options;
1610         /*
1611          * According to Samba4, SEC_FILE_READ_ATTRIBUTE is always granted,
1612          */
1613         fsp->access_mask = access_mask | FILE_READ_ATTRIBUTES;
1614         fsp->print_file = False;
1615         fsp->modified = False;
1616         fsp->oplock_type = NO_OPLOCK;
1617         fsp->sent_oplock_break = NO_BREAK_SENT;
1618         fsp->is_directory = True;
1619         fsp->posix_open = posix_open;
1620
1621         status = fsp_set_smb_fname(fsp, smb_dname);
1622         if (!NT_STATUS_IS_OK(status)) {
1623                 fd_close(fsp);
1624                 file_free(req, fsp);
1625                 return status;
1626         }
1627
1628         mtimespec = smb_dname->st.st_ex_mtime;
1629
1630         /*
1631          * Still set the samba share mode lock for correct delete-on-close
1632          * semantics and to make smbstatus more useful.
1633          */
1634         lck = get_share_mode_lock(talloc_tos(), fsp->file_id,
1635                                   conn->connectpath, smb_dname, &mtimespec);
1636
1637         if (lck == NULL) {
1638                 DEBUG(0, ("onefs_open_directory: Could not get share mode "
1639                           "lock for %s\n", smb_fname_str_dbg(smb_dname)));
1640                 fd_close(fsp);
1641                 file_free(req, fsp);
1642                 return NT_STATUS_SHARING_VIOLATION;
1643         }
1644
1645         if (lck->delete_on_close) {
1646                 TALLOC_FREE(lck);
1647                 fd_close(fsp);
1648                 file_free(req, fsp);
1649                 return NT_STATUS_DELETE_PENDING;
1650         }
1651
1652         set_share_mode(lck, fsp, conn->server_info->utok.uid, 0, NO_OPLOCK);
1653
1654         /*
1655          * For directories the delete on close bit at open time seems
1656          * always to be honored on close... See test 19 in Samba4 BASE-DELETE.
1657          */
1658         if (create_options & FILE_DELETE_ON_CLOSE) {
1659                 status = can_set_delete_on_close(fsp, True, 0);
1660                 if (!NT_STATUS_IS_OK(status) &&
1661                     !NT_STATUS_EQUAL(status, NT_STATUS_DIRECTORY_NOT_EMPTY)) {
1662                         TALLOC_FREE(lck);
1663                         fd_close(fsp);
1664                         file_free(req, fsp);
1665                         return status;
1666                 }
1667
1668                 if (NT_STATUS_IS_OK(status)) {
1669                         /* Note that here we set the *inital* delete on close flag,
1670                            not the regular one. The magic gets handled in close. */
1671                         fsp->initial_delete_on_close = True;
1672                 }
1673         }
1674
1675         TALLOC_FREE(lck);
1676
1677         if (pinfo) {
1678                 *pinfo = info;
1679         }
1680
1681         *result = fsp;
1682         return NT_STATUS_OK;
1683 }
1684
1685 /*
1686  * Wrapper around onefs_open_file_ntcreate and onefs_open_directory.
1687  */
1688 static NTSTATUS onefs_create_file_unixpath(connection_struct *conn,
1689                                            struct smb_request *req,
1690                                            struct smb_filename *smb_fname,
1691                                            uint32_t access_mask,
1692                                            uint32_t share_access,
1693                                            uint32_t create_disposition,
1694                                            uint32_t create_options,
1695                                            uint32_t file_attributes,
1696                                            uint32_t oplock_request,
1697                                            uint64_t allocation_size,
1698                                            struct security_descriptor *sd,
1699                                            struct ea_list *ea_list,
1700                                            files_struct **result,
1701                                            int *pinfo,
1702                                            struct onefs_fsp_data *fsp_data)
1703 {
1704         int info = FILE_WAS_OPENED;
1705         files_struct *base_fsp = NULL;
1706         files_struct *fsp = NULL;
1707         NTSTATUS status;
1708
1709         DEBUG(10,("onefs_create_file_unixpath: access_mask = 0x%x "
1710                   "file_attributes = 0x%x, share_access = 0x%x, "
1711                   "create_disposition = 0x%x create_options = 0x%x "
1712                   "oplock_request = 0x%x ea_list = 0x%p, sd = 0x%p, "
1713                   "fname = %s\n",
1714                   (unsigned int)access_mask,
1715                   (unsigned int)file_attributes,
1716                   (unsigned int)share_access,
1717                   (unsigned int)create_disposition,
1718                   (unsigned int)create_options,
1719                   (unsigned int)oplock_request,
1720                   ea_list, sd, smb_fname_str_dbg(smb_fname)));
1721
1722         if (create_options & FILE_OPEN_BY_FILE_ID) {
1723                 status = NT_STATUS_NOT_SUPPORTED;
1724                 goto fail;
1725         }
1726
1727         if (create_options & NTCREATEX_OPTIONS_INVALID_PARAM_MASK) {
1728                 status = NT_STATUS_INVALID_PARAMETER;
1729                 goto fail;
1730         }
1731
1732         if (req == NULL) {
1733                 SMB_ASSERT((oplock_request & ~SAMBA_PRIVATE_OPLOCK_MASK) ==
1734                             NO_OPLOCK);
1735                 oplock_request |= INTERNAL_OPEN_ONLY;
1736         }
1737
1738         if (lp_parm_bool(SNUM(conn), PARM_ONEFS_TYPE,
1739                 PARM_IGNORE_SACLS, PARM_IGNORE_SACLS_DEFAULT)) {
1740                 access_mask &= ~SYSTEM_SECURITY_ACCESS;
1741         }
1742
1743         if ((conn->fs_capabilities & FILE_NAMED_STREAMS)
1744             && (access_mask & DELETE_ACCESS)
1745             && !is_ntfs_stream_smb_fname(smb_fname)) {
1746                 /*
1747                  * We can't open a file with DELETE access if any of the
1748                  * streams is open without FILE_SHARE_DELETE
1749                  */
1750                 status = open_streams_for_delete(conn, smb_fname->base_name);
1751
1752                 if (!NT_STATUS_IS_OK(status)) {
1753                         goto fail;
1754                 }
1755         }
1756
1757         if ((conn->fs_capabilities & FILE_NAMED_STREAMS)
1758             && is_ntfs_stream_smb_fname(smb_fname)) {
1759                 uint32 base_create_disposition;
1760                 struct smb_filename *smb_fname_base = NULL;
1761
1762                 if (create_options & FILE_DIRECTORY_FILE) {
1763                         status = NT_STATUS_NOT_A_DIRECTORY;
1764                         goto fail;
1765                 }
1766
1767                 switch (create_disposition) {
1768                 case FILE_OPEN:
1769                         base_create_disposition = FILE_OPEN;
1770                         break;
1771                 default:
1772                         base_create_disposition = FILE_OPEN_IF;
1773                         break;
1774                 }
1775
1776                 /* Create an smb_filename with stream_name == NULL. */
1777                 status = create_synthetic_smb_fname(talloc_tos(),
1778                                                     smb_fname->base_name,
1779                                                     NULL, NULL,
1780                                                     &smb_fname_base);
1781                 if (!NT_STATUS_IS_OK(status)) {
1782                         goto fail;
1783                 }
1784
1785                 if (SMB_VFS_STAT(conn, smb_fname_base) == -1) {
1786                         DEBUG(10, ("Unable to stat stream: %s\n",
1787                                    smb_fname_str_dbg(smb_fname_base)));
1788                 }
1789
1790                 status = onefs_create_file_unixpath(
1791                         conn,                           /* conn */
1792                         NULL,                           /* req */
1793                         smb_fname_base,                 /* fname */
1794                         SYNCHRONIZE_ACCESS,             /* access_mask */
1795                         (FILE_SHARE_READ |
1796                             FILE_SHARE_WRITE |
1797                             FILE_SHARE_DELETE),         /* share_access */
1798                         base_create_disposition,        /* create_disposition*/
1799                         0,                              /* create_options */
1800                         file_attributes,                /* file_attributes */
1801                         NO_OPLOCK,                      /* oplock_request */
1802                         0,                              /* allocation_size */
1803                         NULL,                           /* sd */
1804                         NULL,                           /* ea_list */
1805                         &base_fsp,                      /* result */
1806                         NULL,                           /* pinfo */
1807                         NULL);                          /* fsp_data */
1808
1809                 TALLOC_FREE(smb_fname_base);
1810
1811                 if (!NT_STATUS_IS_OK(status)) {
1812                         DEBUG(10, ("onefs_create_file_unixpath for base %s "
1813                                    "failed: %s\n", smb_fname->base_name,
1814                                    nt_errstr(status)));
1815                         goto fail;
1816                 }
1817
1818                 /*
1819                  * Testing against windows xp/2003/vista shows that oplocks
1820                  * can actually be requested and granted on streams (see the
1821                  * RAW-OPLOCK-STREAM1 smbtorture test).
1822                  */
1823                 if ((oplock_request & ~SAMBA_PRIVATE_OPLOCK_MASK) !=
1824                      NO_OPLOCK) {
1825                         DEBUG(5, ("Oplock(%d) being requested on a stream! "
1826                                   "Ignoring oplock request: fname=%s\n",
1827                                   oplock_request & ~SAMBA_PRIVATE_OPLOCK_MASK,
1828                                 smb_fname_str_dbg(smb_fname)));
1829                         /* Request NO_OPLOCK instead. */
1830                         oplock_request &= SAMBA_PRIVATE_OPLOCK_MASK;
1831                 }
1832         }
1833
1834         /* Covert generic bits in the security descriptor. */
1835         if (sd != NULL) {
1836                 security_acl_map_generic(sd->dacl, &file_generic_mapping);
1837                 security_acl_map_generic(sd->sacl, &file_generic_mapping);
1838         }
1839
1840         /*
1841          * If it's a request for a directory open, deal with it separately.
1842          */
1843
1844         if (create_options & FILE_DIRECTORY_FILE) {
1845
1846                 if (create_options & FILE_NON_DIRECTORY_FILE) {
1847                         status = NT_STATUS_INVALID_PARAMETER;
1848                         goto fail;
1849                 }
1850
1851                 /* Can't open a temp directory. IFS kit test. */
1852                 if (!(file_attributes & FILE_FLAG_POSIX_SEMANTICS) &&
1853                      (file_attributes & FILE_ATTRIBUTE_TEMPORARY)) {
1854                         status = NT_STATUS_INVALID_PARAMETER;
1855                         goto fail;
1856                 }
1857
1858                 /*
1859                  * We will get a create directory here if the Win32
1860                  * app specified a security descriptor in the
1861                  * CreateDirectory() call.
1862                  */
1863
1864                 status = onefs_open_directory(
1865                         conn,                           /* conn */
1866                         req,                            /* req */
1867                         smb_fname,                      /* fname */
1868                         access_mask,                    /* access_mask */
1869                         share_access,                   /* share_access */
1870                         create_disposition,             /* create_disposition*/
1871                         create_options,                 /* create_options */
1872                         file_attributes,                /* file_attributes */
1873                         sd,                             /* sd */
1874                         &fsp,                           /* result */
1875                         &info);                         /* pinfo */
1876         } else {
1877
1878                 /*
1879                  * Ordinary file case.
1880                  */
1881
1882                 status = file_new(req, conn, &fsp);
1883                 if(!NT_STATUS_IS_OK(status)) {
1884                         goto fail;
1885                 }
1886
1887                 /*
1888                  * We're opening the stream element of a base_fsp
1889                  * we already opened. Set up the base_fsp pointer.
1890                  */
1891                 if (base_fsp) {
1892                         fsp->base_fsp = base_fsp;
1893                 }
1894
1895                 status = onefs_open_file_ntcreate(
1896                         conn,                           /* conn */
1897                         req,                            /* req */
1898                         smb_fname,                      /* fname */
1899                         access_mask,                    /* access_mask */
1900                         share_access,                   /* share_access */
1901                         create_disposition,             /* create_disposition*/
1902                         create_options,                 /* create_options */
1903                         file_attributes,                /* file_attributes */
1904                         oplock_request,                 /* oplock_request */
1905                         sd,                             /* sd */
1906                         fsp,                            /* result */
1907                         &info,                          /* pinfo */
1908                         fsp_data);                      /* fsp_data */
1909
1910                 if(!NT_STATUS_IS_OK(status)) {
1911                         file_free(req, fsp);
1912                         fsp = NULL;
1913                 }
1914
1915                 if (NT_STATUS_EQUAL(status, NT_STATUS_FILE_IS_A_DIRECTORY)) {
1916
1917                         /* A stream open never opens a directory */
1918
1919                         if (base_fsp) {
1920                                 status = NT_STATUS_FILE_IS_A_DIRECTORY;
1921                                 goto fail;
1922                         }
1923
1924                         /*
1925                          * Fail the open if it was explicitly a non-directory
1926                          * file.
1927                          */
1928
1929                         if (create_options & FILE_NON_DIRECTORY_FILE) {
1930                                 status = NT_STATUS_FILE_IS_A_DIRECTORY;
1931                                 goto fail;
1932                         }
1933
1934                         create_options |= FILE_DIRECTORY_FILE;
1935
1936                         status = onefs_open_directory(
1937                                 conn,                   /* conn */
1938                                 req,                    /* req */
1939                                 smb_fname,              /* fname */
1940                                 access_mask,            /* access_mask */
1941                                 share_access,           /* share_access */
1942                                 create_disposition,     /* create_disposition*/
1943                                 create_options,         /* create_options */
1944                                 file_attributes,        /* file_attributes */
1945                                 sd,                     /* sd */
1946                                 &fsp,                   /* result */
1947                                 &info);                 /* pinfo */
1948                 }
1949         }
1950
1951         if (!NT_STATUS_IS_OK(status)) {
1952                 goto fail;
1953         }
1954
1955         fsp->base_fsp = base_fsp;
1956
1957         SMB_ASSERT(fsp);
1958
1959         if ((ea_list != NULL) && (info == FILE_WAS_CREATED)) {
1960                 status = set_ea(conn, fsp, smb_fname, ea_list);
1961                 if (!NT_STATUS_IS_OK(status)) {
1962                         goto fail;
1963                 }
1964         }
1965
1966         if (!fsp->is_directory && S_ISDIR(smb_fname->st.st_ex_mode)) {
1967                 status = NT_STATUS_ACCESS_DENIED;
1968                 goto fail;
1969         }
1970
1971         /* Save the requested allocation size. */
1972         if ((info == FILE_WAS_CREATED) || (info == FILE_WAS_OVERWRITTEN)) {
1973                 if (allocation_size
1974                     && (allocation_size > smb_fname->st.st_ex_size)) {
1975                         fsp->initial_allocation_size = smb_roundup(
1976                                 fsp->conn, allocation_size);
1977                         if (fsp->is_directory) {
1978                                 /* Can't set allocation size on a directory. */
1979                                 status = NT_STATUS_ACCESS_DENIED;
1980                                 goto fail;
1981                         }
1982                         if (vfs_allocate_file_space(
1983                                     fsp, fsp->initial_allocation_size) == -1) {
1984                                 status = NT_STATUS_DISK_FULL;
1985                                 goto fail;
1986                         }
1987                 } else {
1988                         fsp->initial_allocation_size = smb_roundup(
1989                                 fsp->conn, (uint64_t)smb_fname->st.st_ex_size);
1990                 }
1991         }
1992
1993         DEBUG(10, ("onefs_create_file_unixpath: info=%d\n", info));
1994
1995         *result = fsp;
1996         if (pinfo != NULL) {
1997                 *pinfo = info;
1998         }
1999         if ((fsp->fh != NULL) && (fsp->fh->fd != -1)) {
2000                 SMB_VFS_FSTAT(fsp, &smb_fname->st);
2001         }
2002         return NT_STATUS_OK;
2003
2004  fail:
2005         DEBUG(10, ("onefs_create_file_unixpath: %s\n", nt_errstr(status)));
2006
2007         if (fsp != NULL) {
2008                 if (base_fsp && fsp->base_fsp == base_fsp) {
2009                         /*
2010                          * The close_file below will close
2011                          * fsp->base_fsp.
2012                          */
2013                         base_fsp = NULL;
2014                 }
2015                 close_file(req, fsp, ERROR_CLOSE);
2016                 fsp = NULL;
2017         }
2018         if (base_fsp != NULL) {
2019                 close_file(req, base_fsp, ERROR_CLOSE);
2020                 base_fsp = NULL;
2021         }
2022         return status;
2023 }
2024
2025 static void destroy_onefs_fsp_data(void *p_data)
2026 {
2027         struct onefs_fsp_data *fsp_data = (struct onefs_fsp_data *)p_data;
2028
2029         destroy_onefs_callback_record(fsp_data->oplock_callback_id);
2030 }
2031
2032 /**
2033  * SMB_VFS_CREATE_FILE interface to onefs.
2034  */
2035 NTSTATUS onefs_create_file(vfs_handle_struct *handle,
2036                            struct smb_request *req,
2037                            uint16_t root_dir_fid,
2038                            struct smb_filename *smb_fname,
2039                            uint32_t access_mask,
2040                            uint32_t share_access,
2041                            uint32_t create_disposition,
2042                            uint32_t create_options,
2043                            uint32_t file_attributes,
2044                            uint32_t oplock_request,
2045                            uint64_t allocation_size,
2046                            struct security_descriptor *sd,
2047                            struct ea_list *ea_list,
2048                            files_struct **result,
2049                            int *pinfo)
2050 {
2051         connection_struct *conn = handle->conn;
2052         struct onefs_fsp_data fsp_data = {};
2053         int info = FILE_WAS_OPENED;
2054         files_struct *fsp = NULL;
2055         NTSTATUS status;
2056
2057         DEBUG(10,("onefs_create_file: access_mask = 0x%x "
2058                   "file_attributes = 0x%x, share_access = 0x%x, "
2059                   "create_disposition = 0x%x create_options = 0x%x "
2060                   "oplock_request = 0x%x "
2061                   "root_dir_fid = 0x%x, ea_list = 0x%p, sd = 0x%p, "
2062                   "fname = %s\n",
2063                   (unsigned int)access_mask,
2064                   (unsigned int)file_attributes,
2065                   (unsigned int)share_access,
2066                   (unsigned int)create_disposition,
2067                   (unsigned int)create_options,
2068                   (unsigned int)oplock_request,
2069                   (unsigned int)root_dir_fid,
2070                   ea_list, sd, smb_fname_str_dbg(smb_fname)));
2071
2072         /* Get the file name if root_dir_fid was specified. */
2073         if (root_dir_fid != 0) {
2074                 status = get_relative_fid_filename(conn, req, root_dir_fid,
2075                                                    smb_fname);
2076                 if (!NT_STATUS_IS_OK(status)) {
2077                         goto fail;
2078                 }
2079         }
2080
2081         /* All file access must go through check_name() */
2082         status = check_name(conn, smb_fname->base_name);
2083         if (!NT_STATUS_IS_OK(status)) {
2084                 goto fail;
2085         }
2086
2087         status = onefs_create_file_unixpath(
2088                 conn,                                   /* conn */
2089                 req,                                    /* req */
2090                 smb_fname,                              /* fname */
2091                 access_mask,                            /* access_mask */
2092                 share_access,                           /* share_access */
2093                 create_disposition,                     /* create_disposition*/
2094                 create_options,                         /* create_options */
2095                 file_attributes,                        /* file_attributes */
2096                 oplock_request,                         /* oplock_request */
2097                 allocation_size,                        /* allocation_size */
2098                 sd,                                     /* sd */
2099                 ea_list,                                /* ea_list */
2100                 &fsp,                                   /* result */
2101                 &info,                                  /* pinfo */
2102                 &fsp_data);                             /* psbuf */
2103
2104         if (!NT_STATUS_IS_OK(status)) {
2105                 goto fail;
2106         }
2107
2108         DEBUG(10, ("onefs_create_file: info=%d\n", info));
2109
2110         /*
2111          * Setup private onefs_fsp_data.  Currently the private data struct is
2112          * only used to store the oplock_callback_id so that when the file is
2113          * closed, the onefs_callback_record can be properly cleaned up in the
2114          * oplock_onefs sub-system.
2115          */
2116         if (fsp) {
2117                 struct onefs_fsp_data *fsp_data_tmp = NULL;
2118                 fsp_data_tmp = (struct onefs_fsp_data *)
2119                     VFS_ADD_FSP_EXTENSION(handle, fsp, struct onefs_fsp_data,
2120                         &destroy_onefs_fsp_data);
2121
2122                 if (fsp_data_tmp == NULL) {
2123                         status = NT_STATUS_NO_MEMORY;
2124                         goto fail;
2125                 }
2126
2127                 *fsp_data_tmp = fsp_data;
2128         }
2129
2130         *result = fsp;
2131         if (pinfo != NULL) {
2132                 *pinfo = info;
2133         }
2134         return NT_STATUS_OK;
2135
2136  fail:
2137         DEBUG(10, ("onefs_create_file: %s\n", nt_errstr(status)));
2138
2139         if (fsp != NULL) {
2140                 close_file(req, fsp, ERROR_CLOSE);
2141                 fsp = NULL;
2142         }
2143         return status;
2144 }