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