e62480d69da3628302ac2bc99598529a74ddb074
[samba.git] / source3 / smbd / close.c
1 /*
2    Unix SMB/CIFS implementation.
3    file closing
4    Copyright (C) Andrew Tridgell 1992-1998
5    Copyright (C) Jeremy Allison 1992-2007.
6    Copyright (C) Volker Lendecke 2005
7
8    This program is free software; you can redistribute it and/or modify
9    it under the terms of the GNU General Public License as published by
10    the Free Software Foundation; either version 3 of the License, or
11    (at your option) any later version.
12
13    This program is distributed in the hope that it will be useful,
14    but WITHOUT ANY WARRANTY; without even the implied warranty of
15    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16    GNU General Public License for more details.
17
18    You should have received a copy of the GNU General Public License
19    along with this program.  If not, see <http://www.gnu.org/licenses/>.
20 */
21
22 #include "includes.h"
23 #include "system/filesys.h"
24 #include "lib/util/server_id.h"
25 #include "printing.h"
26 #include "smbd/smbd.h"
27 #include "smbd/globals.h"
28 #include "smbd/scavenger.h"
29 #include "fake_file.h"
30 #include "transfer_file.h"
31 #include "auth.h"
32 #include "messages.h"
33 #include "../librpc/gen_ndr/open_files.h"
34
35 /****************************************************************************
36  Run a file if it is a magic script.
37 ****************************************************************************/
38
39 static NTSTATUS check_magic(struct files_struct *fsp)
40 {
41         int ret;
42         const char *magic_output = NULL;
43         SMB_STRUCT_STAT st;
44         int tmp_fd, outfd;
45         TALLOC_CTX *ctx = NULL;
46         const char *p;
47         struct connection_struct *conn = fsp->conn;
48         char *fname = NULL;
49         NTSTATUS status;
50
51         if (!*lp_magic_script(talloc_tos(), SNUM(conn))) {
52                 return NT_STATUS_OK;
53         }
54
55         DEBUG(5,("checking magic for %s\n", fsp_str_dbg(fsp)));
56
57         ctx = talloc_stackframe();
58
59         fname = fsp->fsp_name->base_name;
60
61         if (!(p = strrchr_m(fname,'/'))) {
62                 p = fname;
63         } else {
64                 p++;
65         }
66
67         if (!strequal(lp_magic_script(talloc_tos(), SNUM(conn)),p)) {
68                 status = NT_STATUS_OK;
69                 goto out;
70         }
71
72         if (*lp_magic_output(talloc_tos(), SNUM(conn))) {
73                 magic_output = lp_magic_output(talloc_tos(), SNUM(conn));
74         } else {
75                 magic_output = talloc_asprintf(ctx,
76                                 "%s.out",
77                                 fname);
78         }
79         if (!magic_output) {
80                 status = NT_STATUS_NO_MEMORY;
81                 goto out;
82         }
83
84         /* Ensure we don't depend on user's PATH. */
85         p = talloc_asprintf(ctx, "./%s", fname);
86         if (!p) {
87                 status = NT_STATUS_NO_MEMORY;
88                 goto out;
89         }
90
91         if (chmod(fname, 0755) == -1) {
92                 status = map_nt_error_from_unix(errno);
93                 goto out;
94         }
95         ret = smbrun(p, &tmp_fd, NULL);
96         DEBUG(3,("Invoking magic command %s gave %d\n",
97                 p,ret));
98
99         unlink(fname);
100         if (ret != 0 || tmp_fd == -1) {
101                 if (tmp_fd != -1) {
102                         close(tmp_fd);
103                 }
104                 status = NT_STATUS_UNSUCCESSFUL;
105                 goto out;
106         }
107         outfd = open(magic_output, O_CREAT|O_EXCL|O_RDWR, 0600);
108         if (outfd == -1) {
109                 int err = errno;
110                 close(tmp_fd);
111                 status = map_nt_error_from_unix(err);
112                 goto out;
113         }
114
115         if (sys_fstat(tmp_fd, &st, false) == -1) {
116                 int err = errno;
117                 close(tmp_fd);
118                 close(outfd);
119                 status = map_nt_error_from_unix(err);
120                 goto out;
121         }
122
123         if (transfer_file(tmp_fd,outfd,(off_t)st.st_ex_size) == (off_t)-1) {
124                 int err = errno;
125                 close(tmp_fd);
126                 close(outfd);
127                 status = map_nt_error_from_unix(err);
128                 goto out;
129         }
130         close(tmp_fd);
131         if (close(outfd) == -1) {
132                 status = map_nt_error_from_unix(errno);
133                 goto out;
134         }
135
136         status = NT_STATUS_OK;
137
138  out:
139         TALLOC_FREE(ctx);
140         return status;
141 }
142
143 /****************************************************************************
144   Common code to close a file or a directory.
145 ****************************************************************************/
146
147 static NTSTATUS close_filestruct(files_struct *fsp)
148 {
149         NTSTATUS status = NT_STATUS_OK;
150
151         if (fsp->fh->fd != -1) {
152                 if(flush_write_cache(fsp, SAMBA_CLOSE_FLUSH) == -1) {
153                         status = map_nt_error_from_unix(errno);
154                 }
155                 delete_write_cache(fsp);
156         }
157
158         return status;
159 }
160
161 /****************************************************************************
162  Delete all streams
163 ****************************************************************************/
164
165 NTSTATUS delete_all_streams(connection_struct *conn,
166                         const struct smb_filename *smb_fname)
167 {
168         struct stream_struct *stream_info = NULL;
169         unsigned int i;
170         unsigned int num_streams = 0;
171         TALLOC_CTX *frame = talloc_stackframe();
172         NTSTATUS status;
173
174         status = vfs_streaminfo(conn, NULL, smb_fname, talloc_tos(),
175                                 &num_streams, &stream_info);
176
177         if (NT_STATUS_EQUAL(status, NT_STATUS_NOT_IMPLEMENTED)) {
178                 DEBUG(10, ("no streams around\n"));
179                 TALLOC_FREE(frame);
180                 return NT_STATUS_OK;
181         }
182
183         if (!NT_STATUS_IS_OK(status)) {
184                 DEBUG(10, ("vfs_streaminfo failed: %s\n",
185                            nt_errstr(status)));
186                 goto fail;
187         }
188
189         DEBUG(10, ("delete_all_streams found %d streams\n",
190                    num_streams));
191
192         if (num_streams == 0) {
193                 TALLOC_FREE(frame);
194                 return NT_STATUS_OK;
195         }
196
197         for (i=0; i<num_streams; i++) {
198                 int res;
199                 struct smb_filename *smb_fname_stream;
200
201                 if (strequal(stream_info[i].name, "::$DATA")) {
202                         continue;
203                 }
204
205                 smb_fname_stream = synthetic_smb_fname(talloc_tos(),
206                                         smb_fname->base_name,
207                                         stream_info[i].name,
208                                         NULL,
209                                         (smb_fname->flags &
210                                                 ~SMB_FILENAME_POSIX_PATH));
211
212                 if (smb_fname_stream == NULL) {
213                         DEBUG(0, ("talloc_aprintf failed\n"));
214                         status = NT_STATUS_NO_MEMORY;
215                         goto fail;
216                 }
217
218                 res = SMB_VFS_UNLINKAT(conn,
219                                 conn->cwd_fsp,
220                                 smb_fname_stream,
221                                 0);
222
223                 if (res == -1) {
224                         status = map_nt_error_from_unix(errno);
225                         DEBUG(10, ("Could not delete stream %s: %s\n",
226                                    smb_fname_str_dbg(smb_fname_stream),
227                                    strerror(errno)));
228                         TALLOC_FREE(smb_fname_stream);
229                         break;
230                 }
231                 TALLOC_FREE(smb_fname_stream);
232         }
233
234  fail:
235         TALLOC_FREE(frame);
236         return status;
237 }
238
239 struct has_other_nonposix_opens_state {
240         files_struct *fsp;
241         bool found_another;
242 };
243
244 static bool has_other_nonposix_opens_fn(
245         struct share_mode_entry *e,
246         bool *modified,
247         void *private_data)
248 {
249         struct has_other_nonposix_opens_state *state = private_data;
250         struct files_struct *fsp = state->fsp;
251
252         if (e->name_hash != fsp->name_hash) {
253                 return false;
254         }
255         if ((fsp->posix_flags & FSP_POSIX_FLAGS_OPEN) &&
256             (e->flags & SHARE_MODE_FLAG_POSIX_OPEN)) {
257                 return false;
258         }
259         if (e->share_file_id == fsp->fh->gen_id) {
260                 struct server_id self = messaging_server_id(
261                         fsp->conn->sconn->msg_ctx);
262                 if (server_id_equal(&self, &e->pid)) {
263                         return false;
264                 }
265         }
266         if (share_entry_stale_pid(e)) {
267                 return false;
268         }
269
270         state->found_another = true;
271         return true;
272 }
273
274 bool has_other_nonposix_opens(struct share_mode_lock *lck,
275                               struct files_struct *fsp)
276 {
277         struct has_other_nonposix_opens_state state = { .fsp = fsp };
278         bool ok;
279
280         ok = share_mode_forall_entries(
281                 lck, has_other_nonposix_opens_fn, &state);
282         if (!ok) {
283                 return false;
284         }
285         return state.found_another;
286 }
287
288 /****************************************************************************
289  Deal with removing a share mode on last close.
290 ****************************************************************************/
291
292 static NTSTATUS close_remove_share_mode(files_struct *fsp,
293                                         enum file_close_type close_type)
294 {
295         connection_struct *conn = fsp->conn;
296         bool delete_file = false;
297         bool changed_user = false;
298         struct share_mode_lock *lck = NULL;
299         NTSTATUS status = NT_STATUS_OK;
300         NTSTATUS tmp_status;
301         struct file_id id;
302         const struct security_unix_token *del_token = NULL;
303         const struct security_token *del_nt_token = NULL;
304         bool got_tokens = false;
305         bool normal_close;
306         int ret;
307
308         /* Ensure any pending write time updates are done. */
309         if (fsp->update_write_time_event) {
310                 fsp_flush_write_time_update(fsp);
311         }
312
313         /*
314          * Lock the share entries, and determine if we should delete
315          * on close. If so delete whilst the lock is still in effect.
316          * This prevents race conditions with the file being created. JRA.
317          */
318
319         lck = get_existing_share_mode_lock(talloc_tos(), fsp->file_id);
320         if (lck == NULL) {
321                 DEBUG(0, ("close_remove_share_mode: Could not get share mode "
322                           "lock for file %s\n", fsp_str_dbg(fsp)));
323                 return NT_STATUS_INVALID_PARAMETER;
324         }
325
326         /* Remove the oplock before potentially deleting the file. */
327         if(fsp->oplock_type) {
328                 remove_oplock(fsp);
329         }
330
331         if (fsp->write_time_forced) {
332                 DEBUG(10,("close_remove_share_mode: write time forced "
333                         "for file %s\n",
334                         fsp_str_dbg(fsp)));
335                 set_close_write_time(fsp, lck->data->changed_write_time);
336         } else if (fsp->update_write_time_on_close) {
337                 /* Someone had a pending write. */
338                 if (null_timespec(fsp->close_write_time)) {
339                         DEBUG(10,("close_remove_share_mode: update to current time "
340                                 "for file %s\n",
341                                 fsp_str_dbg(fsp)));
342                         /* Update to current time due to "normal" write. */
343                         set_close_write_time(fsp, timespec_current());
344                 } else {
345                         DEBUG(10,("close_remove_share_mode: write time pending "
346                                 "for file %s\n",
347                                 fsp_str_dbg(fsp)));
348                         /* Update to time set on close call. */
349                         set_close_write_time(fsp, fsp->close_write_time);
350                 }
351         }
352
353         if (fsp->initial_delete_on_close &&
354                         !is_delete_on_close_set(lck, fsp->name_hash)) {
355                 bool became_user = False;
356
357                 /* Initial delete on close was set and no one else
358                  * wrote a real delete on close. */
359
360                 if (get_current_vuid(conn) != fsp->vuid) {
361                         become_user_without_service(conn, fsp->vuid);
362                         became_user = True;
363                 }
364                 fsp->delete_on_close = true;
365                 set_delete_on_close_lck(fsp, lck,
366                                 get_current_nttok(conn),
367                                 get_current_utok(conn));
368                 if (became_user) {
369                         unbecome_user_without_service();
370                 }
371         }
372
373         delete_file = is_delete_on_close_set(lck, fsp->name_hash) &&
374                 !has_other_nonposix_opens(lck, fsp);
375
376         /*
377          * NT can set delete_on_close of the last open
378          * reference to a file.
379          */
380
381         normal_close = (close_type == NORMAL_CLOSE || close_type == SHUTDOWN_CLOSE);
382
383         if (!normal_close || !delete_file) {
384                 status = NT_STATUS_OK;
385                 goto done;
386         }
387
388         /*
389          * Ok, we have to delete the file
390          */
391
392         DEBUG(5,("close_remove_share_mode: file %s. Delete on close was set "
393                  "- deleting file.\n", fsp_str_dbg(fsp)));
394
395         /*
396          * Don't try to update the write time when we delete the file
397          */
398         fsp->update_write_time_on_close = false;
399
400         got_tokens = get_delete_on_close_token(lck, fsp->name_hash,
401                                         &del_nt_token, &del_token);
402         SMB_ASSERT(got_tokens);
403
404         if (!unix_token_equal(del_token, get_current_utok(conn))) {
405                 /* Become the user who requested the delete. */
406
407                 DEBUG(5,("close_remove_share_mode: file %s. "
408                         "Change user to uid %u\n",
409                         fsp_str_dbg(fsp),
410                         (unsigned int)del_token->uid));
411
412                 if (!push_sec_ctx()) {
413                         smb_panic("close_remove_share_mode: file %s. failed to push "
414                                   "sec_ctx.\n");
415                 }
416
417                 set_sec_ctx(del_token->uid,
418                             del_token->gid,
419                             del_token->ngroups,
420                             del_token->groups,
421                             del_nt_token);
422
423                 changed_user = true;
424         }
425
426         /* We can only delete the file if the name we have is still valid and
427            hasn't been renamed. */
428
429         tmp_status = vfs_stat_fsp(fsp);
430         if (!NT_STATUS_IS_OK(tmp_status)) {
431                 DEBUG(5,("close_remove_share_mode: file %s. Delete on close "
432                          "was set and stat failed with error %s\n",
433                          fsp_str_dbg(fsp), nt_errstr(tmp_status)));
434                 /*
435                  * Don't save the errno here, we ignore this error
436                  */
437                 goto done;
438         }
439
440         id = vfs_file_id_from_sbuf(conn, &fsp->fsp_name->st);
441
442         if (!file_id_equal(&fsp->file_id, &id)) {
443                 struct file_id_buf ftmp1, ftmp2;
444                 DEBUG(5,("close_remove_share_mode: file %s. Delete on close "
445                          "was set and dev and/or inode does not match\n",
446                          fsp_str_dbg(fsp)));
447                 DEBUG(5,("close_remove_share_mode: file %s. stored file_id %s, "
448                          "stat file_id %s\n",
449                          fsp_str_dbg(fsp),
450                          file_id_str_buf(fsp->file_id, &ftmp1),
451                          file_id_str_buf(id, &ftmp2)));
452                 /*
453                  * Don't save the errno here, we ignore this error
454                  */
455                 goto done;
456         }
457
458         if ((conn->fs_capabilities & FILE_NAMED_STREAMS)
459             && !is_ntfs_stream_smb_fname(fsp->fsp_name)) {
460
461                 status = delete_all_streams(conn, fsp->fsp_name);
462
463                 if (!NT_STATUS_IS_OK(status)) {
464                         DEBUG(5, ("delete_all_streams failed: %s\n",
465                                   nt_errstr(status)));
466                         goto done;
467                 }
468         }
469
470         if (fsp->kernel_share_modes_taken) {
471                 int ret_flock;
472
473                 /*
474                  * A file system sharemode could block the unlink;
475                  * remove filesystem sharemodes first.
476                  */
477                 ret_flock = SMB_VFS_KERNEL_FLOCK(fsp, 0, 0);
478                 if (ret_flock == -1) {
479                         DBG_INFO("removing kernel flock for %s failed: %s\n",
480                                   fsp_str_dbg(fsp), strerror(errno));
481                 }
482
483                 fsp->kernel_share_modes_taken = false;
484         }
485
486
487         ret = SMB_VFS_UNLINKAT(conn,
488                         conn->cwd_fsp,
489                         fsp->fsp_name,
490                         0);
491         if (ret != 0) {
492                 /*
493                  * This call can potentially fail as another smbd may
494                  * have had the file open with delete on close set and
495                  * deleted it when its last reference to this file
496                  * went away. Hence we log this but not at debug level
497                  * zero.
498                  */
499
500                 DEBUG(5,("close_remove_share_mode: file %s. Delete on close "
501                          "was set and unlink failed with error %s\n",
502                          fsp_str_dbg(fsp), strerror(errno)));
503
504                 status = map_nt_error_from_unix(errno);
505         }
506
507         /* As we now have POSIX opens which can unlink
508          * with other open files we may have taken
509          * this code path with more than one share mode
510          * entry - ensure we only delete once by resetting
511          * the delete on close flag. JRA.
512          */
513
514         fsp->delete_on_close = false;
515         reset_delete_on_close_lck(fsp, lck);
516
517  done:
518
519         if (changed_user) {
520                 /* unbecome user. */
521                 pop_sec_ctx();
522         }
523
524         if (fsp->kernel_share_modes_taken) {
525                 int ret_flock;
526
527                 /* remove filesystem sharemodes */
528                 ret_flock = SMB_VFS_KERNEL_FLOCK(fsp, 0, 0);
529                 if (ret_flock == -1) {
530                         DEBUG(2, ("close_remove_share_mode: removing kernel "
531                                   "flock for %s failed: %s\n",
532                                   fsp_str_dbg(fsp), strerror(errno)));
533                 }
534         }
535
536         if (!del_share_mode(lck, fsp)) {
537                 DEBUG(0, ("close_remove_share_mode: Could not delete share "
538                           "entry for file %s\n", fsp_str_dbg(fsp)));
539         }
540
541         TALLOC_FREE(lck);
542
543         if (delete_file) {
544                 /*
545                  * Do the notification after we released the share
546                  * mode lock. Inside notify_fname we take out another
547                  * tdb lock. With ctdb also accessing our databases,
548                  * this can lead to deadlocks. Putting this notify
549                  * after the TALLOC_FREE(lck) above we avoid locking
550                  * two records simultaneously. Notifies are async and
551                  * informational only, so calling the notify_fname
552                  * without holding the share mode lock should not do
553                  * any harm.
554                  */
555                 notify_fname(conn, NOTIFY_ACTION_REMOVED,
556                              FILE_NOTIFY_CHANGE_FILE_NAME,
557                              fsp->fsp_name->base_name);
558         }
559
560         return status;
561 }
562
563 void set_close_write_time(struct files_struct *fsp, struct timespec ts)
564 {
565         DEBUG(6,("close_write_time: %s" , time_to_asc(convert_timespec_to_time_t(ts))));
566
567         if (null_timespec(ts)) {
568                 return;
569         }
570         fsp->write_time_forced = false;
571         fsp->update_write_time_on_close = true;
572         fsp->close_write_time = ts;
573 }
574
575 static NTSTATUS update_write_time_on_close(struct files_struct *fsp)
576 {
577         struct smb_file_time ft;
578         NTSTATUS status;
579         struct share_mode_lock *lck = NULL;
580
581         ZERO_STRUCT(ft);
582
583         if (!fsp->update_write_time_on_close) {
584                 return NT_STATUS_OK;
585         }
586
587         if (null_timespec(fsp->close_write_time)) {
588                 fsp->close_write_time = timespec_current();
589         }
590
591         /* Ensure we have a valid stat struct for the source. */
592         status = vfs_stat_fsp(fsp);
593         if (!NT_STATUS_IS_OK(status)) {
594                 return status;
595         }
596
597         if (!VALID_STAT(fsp->fsp_name->st)) {
598                 /* if it doesn't seem to be a real file */
599                 return NT_STATUS_OK;
600         }
601
602         /*
603          * get_existing_share_mode_lock() isn't really the right
604          * call here, as we're being called after
605          * close_remove_share_mode() inside close_normal_file()
606          * so it's quite normal to not have an existing share
607          * mode here. However, get_share_mode_lock() doesn't
608          * work because that will create a new share mode if
609          * one doesn't exist - so stick with this call (just
610          * ignore any error we get if the share mode doesn't
611          * exist.
612          */
613
614         lck = get_existing_share_mode_lock(talloc_tos(), fsp->file_id);
615         if (lck) {
616                 /* On close if we're changing the real file time we
617                  * must update it in the open file db too. */
618                 (void)set_write_time(fsp->file_id, fsp->close_write_time);
619
620                 /* Close write times overwrite sticky write times
621                    so we must replace any sticky write time here. */
622                 if (!null_timespec(lck->data->changed_write_time)) {
623                         (void)set_sticky_write_time(fsp->file_id, fsp->close_write_time);
624                 }
625                 TALLOC_FREE(lck);
626         }
627
628         ft.mtime = fsp->close_write_time;
629         /* As this is a close based update, we are not directly changing the
630            file attributes from a client call, but indirectly from a write. */
631         status = smb_set_file_time(fsp->conn, fsp, fsp->fsp_name, &ft, false);
632         if (!NT_STATUS_IS_OK(status)) {
633                 DEBUG(10,("update_write_time_on_close: smb_set_file_time "
634                         "on file %s returned %s\n",
635                         fsp_str_dbg(fsp),
636                         nt_errstr(status)));
637                 return status;
638         }
639
640         return status;
641 }
642
643 static NTSTATUS ntstatus_keeperror(NTSTATUS s1, NTSTATUS s2)
644 {
645         if (!NT_STATUS_IS_OK(s1)) {
646                 return s1;
647         }
648         return s2;
649 }
650
651 /****************************************************************************
652  Close a file.
653
654  close_type can be NORMAL_CLOSE=0,SHUTDOWN_CLOSE,ERROR_CLOSE.
655  printing and magic scripts are only run on normal close.
656  delete on close is done on normal and shutdown close.
657 ****************************************************************************/
658
659 static NTSTATUS close_normal_file(struct smb_request *req, files_struct *fsp,
660                                   enum file_close_type close_type)
661 {
662         NTSTATUS status = NT_STATUS_OK;
663         NTSTATUS tmp;
664         connection_struct *conn = fsp->conn;
665         bool is_durable = false;
666
667         if (fsp->num_aio_requests != 0) {
668
669                 if (close_type != SHUTDOWN_CLOSE) {
670                         /*
671                          * reply_close and the smb2 close must have
672                          * taken care of this. No other callers of
673                          * close_file should ever have created async
674                          * I/O.
675                          *
676                          * We need to panic here because if we close()
677                          * the fd while we have outstanding async I/O
678                          * requests, in the worst case we could end up
679                          * writing to the wrong file.
680                          */
681                         DEBUG(0, ("fsp->num_aio_requests=%u\n",
682                                   fsp->num_aio_requests));
683                         smb_panic("can not close with outstanding aio "
684                                   "requests");
685                 }
686
687                 /*
688                  * For shutdown close, just drop the async requests
689                  * including a potential close request pending for
690                  * this fsp. Drop the close request first, the
691                  * destructor for the aio_requests would execute it.
692                  */
693                 TALLOC_FREE(fsp->deferred_close);
694
695                 while (fsp->num_aio_requests != 0) {
696                         /*
697                          * The destructor of the req will remove
698                          * itself from the fsp.
699                          * Don't use TALLOC_FREE here, this will overwrite
700                          * what the destructor just wrote into
701                          * aio_requests[0].
702                          */
703                         talloc_free(fsp->aio_requests[0]);
704                 }
705         }
706
707         while (talloc_array_length(fsp->blocked_smb1_lock_reqs) != 0) {
708                 smbd_smb1_brl_finish_by_req(
709                         fsp->blocked_smb1_lock_reqs[0],
710                         NT_STATUS_RANGE_NOT_LOCKED);
711         }
712
713         /*
714          * If we're flushing on a close we can get a write
715          * error here, we must remember this.
716          */
717
718         tmp = close_filestruct(fsp);
719         status = ntstatus_keeperror(status, tmp);
720
721         if (NT_STATUS_IS_OK(status) && fsp->op != NULL) {
722                 is_durable = fsp->op->global->durable;
723         }
724
725         if (close_type != SHUTDOWN_CLOSE) {
726                 is_durable = false;
727         }
728
729         if (is_durable) {
730                 DATA_BLOB new_cookie = data_blob_null;
731
732                 tmp = SMB_VFS_DURABLE_DISCONNECT(fsp,
733                                         fsp->op->global->backend_cookie,
734                                         fsp->op,
735                                         &new_cookie);
736                 if (NT_STATUS_IS_OK(tmp)) {
737                         struct timeval tv;
738                         NTTIME now;
739
740                         if (req != NULL) {
741                                 tv = req->request_time;
742                         } else {
743                                 tv = timeval_current();
744                         }
745                         now = timeval_to_nttime(&tv);
746
747                         data_blob_free(&fsp->op->global->backend_cookie);
748                         fsp->op->global->backend_cookie = new_cookie;
749
750                         fsp->op->compat = NULL;
751                         tmp = smbXsrv_open_close(fsp->op, now);
752                         if (!NT_STATUS_IS_OK(tmp)) {
753                                 DEBUG(1, ("Failed to update smbXsrv_open "
754                                           "record when disconnecting durable "
755                                           "handle for file %s: %s - "
756                                           "proceeding with normal close\n",
757                                           fsp_str_dbg(fsp), nt_errstr(tmp)));
758                         }
759                         scavenger_schedule_disconnected(fsp);
760                 } else {
761                         DEBUG(1, ("Failed to disconnect durable handle for "
762                                   "file %s: %s - proceeding with normal "
763                                   "close\n", fsp_str_dbg(fsp), nt_errstr(tmp)));
764                 }
765                 if (!NT_STATUS_IS_OK(tmp)) {
766                         is_durable = false;
767                 }
768         }
769
770         if (is_durable) {
771                 /*
772                  * This is the case where we successfully disconnected
773                  * a durable handle and closed the underlying file.
774                  * In all other cases, we proceed with a genuine close.
775                  */
776                 DEBUG(10, ("%s disconnected durable handle for file %s\n",
777                            conn->session_info->unix_info->unix_name,
778                            fsp_str_dbg(fsp)));
779                 file_free(req, fsp);
780                 return NT_STATUS_OK;
781         }
782
783         if (fsp->op != NULL) {
784                 /*
785                  * Make sure the handle is not marked as durable anymore
786                  */
787                 fsp->op->global->durable = false;
788         }
789
790         if (fsp->print_file) {
791                 /* FIXME: return spool errors */
792                 print_spool_end(fsp, close_type);
793                 file_free(req, fsp);
794                 return NT_STATUS_OK;
795         }
796
797         /* If this is an old DOS or FCB open and we have multiple opens on
798            the same handle we only have one share mode. Ensure we only remove
799            the share mode on the last close. */
800
801         if (fsp->fh->ref_count == 1) {
802                 /* Should we return on error here... ? */
803                 tmp = close_remove_share_mode(fsp, close_type);
804                 status = ntstatus_keeperror(status, tmp);
805         }
806
807         locking_close_file(fsp, close_type);
808
809         tmp = fd_close(fsp);
810         status = ntstatus_keeperror(status, tmp);
811
812         /* check for magic scripts */
813         if (close_type == NORMAL_CLOSE) {
814                 tmp = check_magic(fsp);
815                 status = ntstatus_keeperror(status, tmp);
816         }
817
818         /*
819          * Ensure pending modtime is set after close.
820          */
821
822         tmp = update_write_time_on_close(fsp);
823         if (NT_STATUS_EQUAL(tmp, NT_STATUS_OBJECT_NAME_NOT_FOUND)) {
824                 /* Someone renamed the file or a parent directory containing
825                  * this file. We can't do anything about this, we don't have
826                  * an "update timestamp by fd" call in POSIX. Eat the error. */
827
828                 tmp = NT_STATUS_OK;
829         }
830
831         status = ntstatus_keeperror(status, tmp);
832
833         DEBUG(2,("%s closed file %s (numopen=%d) %s\n",
834                 conn->session_info->unix_info->unix_name, fsp_str_dbg(fsp),
835                 conn->num_files_open - 1,
836                 nt_errstr(status) ));
837
838         file_free(req, fsp);
839         return status;
840 }
841 /****************************************************************************
842  Function used by reply_rmdir to delete an entire directory
843  tree recursively. Return True on ok, False on fail.
844 ****************************************************************************/
845
846 bool recursive_rmdir(TALLOC_CTX *ctx,
847                      connection_struct *conn,
848                      struct smb_filename *smb_dname)
849 {
850         const char *dname = NULL;
851         char *talloced = NULL;
852         bool ret = True;
853         long offset = 0;
854         SMB_STRUCT_STAT st;
855         struct smb_Dir *dir_hnd;
856         int retval;
857
858         SMB_ASSERT(!is_ntfs_stream_smb_fname(smb_dname));
859
860         dir_hnd = OpenDir(talloc_tos(), conn, smb_dname, NULL, 0);
861         if(dir_hnd == NULL)
862                 return False;
863
864         while((dname = ReadDirName(dir_hnd, &offset, &st, &talloced))) {
865                 struct smb_filename *smb_dname_full = NULL;
866                 char *fullname = NULL;
867                 bool do_break = true;
868
869                 if (ISDOT(dname) || ISDOTDOT(dname)) {
870                         TALLOC_FREE(talloced);
871                         continue;
872                 }
873
874                 if (!is_visible_file(conn, smb_dname->base_name, dname, &st,
875                                      false)) {
876                         TALLOC_FREE(talloced);
877                         continue;
878                 }
879
880                 /* Construct the full name. */
881                 fullname = talloc_asprintf(ctx,
882                                 "%s/%s",
883                                 smb_dname->base_name,
884                                 dname);
885                 if (!fullname) {
886                         errno = ENOMEM;
887                         goto err_break;
888                 }
889
890                 smb_dname_full = synthetic_smb_fname(talloc_tos(),
891                                                 fullname,
892                                                 NULL,
893                                                 NULL,
894                                                 smb_dname->flags);
895                 if (smb_dname_full == NULL) {
896                         errno = ENOMEM;
897                         goto err_break;
898                 }
899
900                 if(SMB_VFS_LSTAT(conn, smb_dname_full) != 0) {
901                         goto err_break;
902                 }
903
904                 if(smb_dname_full->st.st_ex_mode & S_IFDIR) {
905                         if(!recursive_rmdir(ctx, conn, smb_dname_full)) {
906                                 goto err_break;
907                         }
908                         retval = SMB_VFS_UNLINKAT(conn,
909                                         conn->cwd_fsp,
910                                         smb_dname_full,
911                                         AT_REMOVEDIR);
912                         if (retval != 0) {
913                                 goto err_break;
914                         }
915                 } else {
916                         retval = SMB_VFS_UNLINKAT(conn,
917                                         conn->cwd_fsp,
918                                         smb_dname_full,
919                                         0);
920                         if (retval != 0) {
921                                 goto err_break;
922                         }
923                 }
924
925                 /* Successful iteration. */
926                 do_break = false;
927
928          err_break:
929                 TALLOC_FREE(smb_dname_full);
930                 TALLOC_FREE(fullname);
931                 TALLOC_FREE(talloced);
932                 if (do_break) {
933                         ret = false;
934                         break;
935                 }
936         }
937         TALLOC_FREE(dir_hnd);
938         return ret;
939 }
940
941 /****************************************************************************
942  The internals of the rmdir code - called elsewhere.
943 ****************************************************************************/
944
945 static NTSTATUS rmdir_internals(TALLOC_CTX *ctx, files_struct *fsp)
946 {
947         connection_struct *conn = fsp->conn;
948         struct smb_filename *smb_dname = fsp->fsp_name;
949         int ret;
950
951         SMB_ASSERT(!is_ntfs_stream_smb_fname(smb_dname));
952
953         /* Might be a symlink. */
954         if(SMB_VFS_LSTAT(conn, smb_dname) != 0) {
955                 return map_nt_error_from_unix(errno);
956         }
957
958         if (S_ISLNK(smb_dname->st.st_ex_mode)) {
959                 /* Is what it points to a directory ? */
960                 if(SMB_VFS_STAT(conn, smb_dname) != 0) {
961                         return map_nt_error_from_unix(errno);
962                 }
963                 if (!(S_ISDIR(smb_dname->st.st_ex_mode))) {
964                         return NT_STATUS_NOT_A_DIRECTORY;
965                 }
966                 ret = SMB_VFS_UNLINKAT(conn,
967                                 conn->cwd_fsp,
968                                 smb_dname,
969                                 0);
970         } else {
971                 ret = SMB_VFS_UNLINKAT(conn,
972                                 conn->cwd_fsp,
973                                 smb_dname,
974                                 AT_REMOVEDIR);
975         }
976         if (ret == 0) {
977                 notify_fname(conn, NOTIFY_ACTION_REMOVED,
978                              FILE_NOTIFY_CHANGE_DIR_NAME,
979                              smb_dname->base_name);
980                 return NT_STATUS_OK;
981         }
982
983         if(((errno == ENOTEMPTY)||(errno == EEXIST)) && *lp_veto_files(talloc_tos(), SNUM(conn))) {
984                 /*
985                  * Check to see if the only thing in this directory are
986                  * vetoed files/directories. If so then delete them and
987                  * retry. If we fail to delete any of them (and we *don't*
988                  * do a recursive delete) then fail the rmdir.
989                  */
990                 SMB_STRUCT_STAT st;
991                 const char *dname = NULL;
992                 char *talloced = NULL;
993                 long dirpos = 0;
994                 struct smb_Dir *dir_hnd = OpenDir(talloc_tos(), conn,
995                                                   smb_dname, NULL,
996                                                   0);
997
998                 if(dir_hnd == NULL) {
999                         errno = ENOTEMPTY;
1000                         goto err;
1001                 }
1002
1003                 while ((dname = ReadDirName(dir_hnd, &dirpos, &st,
1004                                             &talloced)) != NULL) {
1005                         if((strcmp(dname, ".") == 0) || (strcmp(dname, "..")==0)) {
1006                                 TALLOC_FREE(talloced);
1007                                 continue;
1008                         }
1009                         if (!is_visible_file(conn, smb_dname->base_name, dname,
1010                                              &st, false)) {
1011                                 TALLOC_FREE(talloced);
1012                                 continue;
1013                         }
1014                         if(!IS_VETO_PATH(conn, dname)) {
1015                                 TALLOC_FREE(dir_hnd);
1016                                 TALLOC_FREE(talloced);
1017                                 errno = ENOTEMPTY;
1018                                 goto err;
1019                         }
1020                         TALLOC_FREE(talloced);
1021                 }
1022
1023                 /* We only have veto files/directories.
1024                  * Are we allowed to delete them ? */
1025
1026                 if(!lp_delete_veto_files(SNUM(conn))) {
1027                         TALLOC_FREE(dir_hnd);
1028                         errno = ENOTEMPTY;
1029                         goto err;
1030                 }
1031
1032                 /* Do a recursive delete. */
1033                 RewindDir(dir_hnd,&dirpos);
1034                 while ((dname = ReadDirName(dir_hnd, &dirpos, &st,
1035                                             &talloced)) != NULL) {
1036                         struct smb_filename *smb_dname_full = NULL;
1037                         char *fullname = NULL;
1038                         bool do_break = true;
1039
1040                         if (ISDOT(dname) || ISDOTDOT(dname)) {
1041                                 TALLOC_FREE(talloced);
1042                                 continue;
1043                         }
1044                         if (!is_visible_file(conn, smb_dname->base_name, dname,
1045                                              &st, false)) {
1046                                 TALLOC_FREE(talloced);
1047                                 continue;
1048                         }
1049
1050                         fullname = talloc_asprintf(ctx,
1051                                         "%s/%s",
1052                                         smb_dname->base_name,
1053                                         dname);
1054
1055                         if(!fullname) {
1056                                 errno = ENOMEM;
1057                                 goto err_break;
1058                         }
1059
1060                         smb_dname_full = synthetic_smb_fname(talloc_tos(),
1061                                                         fullname,
1062                                                         NULL,
1063                                                         NULL,
1064                                                         smb_dname->flags);
1065                         if (smb_dname_full == NULL) {
1066                                 errno = ENOMEM;
1067                                 goto err_break;
1068                         }
1069
1070                         if(SMB_VFS_LSTAT(conn, smb_dname_full) != 0) {
1071                                 goto err_break;
1072                         }
1073                         if(smb_dname_full->st.st_ex_mode & S_IFDIR) {
1074                                 int retval;
1075                                 if(!recursive_rmdir(ctx, conn,
1076                                                     smb_dname_full)) {
1077                                         goto err_break;
1078                                 }
1079                                 retval = SMB_VFS_UNLINKAT(conn,
1080                                                 conn->cwd_fsp,
1081                                                 smb_dname_full,
1082                                                 AT_REMOVEDIR);
1083                                 if(retval != 0) {
1084                                         goto err_break;
1085                                 }
1086                         } else {
1087                                 int retval = SMB_VFS_UNLINKAT(conn,
1088                                                 conn->cwd_fsp,
1089                                                 smb_dname_full,
1090                                                 0);
1091                                 if(retval != 0) {
1092                                         goto err_break;
1093                                 }
1094                         }
1095
1096                         /* Successful iteration. */
1097                         do_break = false;
1098
1099                  err_break:
1100                         TALLOC_FREE(fullname);
1101                         TALLOC_FREE(smb_dname_full);
1102                         TALLOC_FREE(talloced);
1103                         if (do_break)
1104                                 break;
1105                 }
1106                 TALLOC_FREE(dir_hnd);
1107                 /* Retry the rmdir */
1108                 ret = SMB_VFS_UNLINKAT(conn,
1109                                 conn->cwd_fsp,
1110                                 smb_dname,
1111                                 AT_REMOVEDIR);
1112         }
1113
1114   err:
1115
1116         if (ret != 0) {
1117                 DEBUG(3,("rmdir_internals: couldn't remove directory %s : "
1118                          "%s\n", smb_fname_str_dbg(smb_dname),
1119                          strerror(errno)));
1120                 return map_nt_error_from_unix(errno);
1121         }
1122
1123         notify_fname(conn, NOTIFY_ACTION_REMOVED,
1124                      FILE_NOTIFY_CHANGE_DIR_NAME,
1125                      smb_dname->base_name);
1126
1127         return NT_STATUS_OK;
1128 }
1129
1130 /****************************************************************************
1131  Close a directory opened by an NT SMB call. 
1132 ****************************************************************************/
1133   
1134 static NTSTATUS close_directory(struct smb_request *req, files_struct *fsp,
1135                                 enum file_close_type close_type)
1136 {
1137         struct share_mode_lock *lck = NULL;
1138         bool delete_dir = False;
1139         NTSTATUS status = NT_STATUS_OK;
1140         NTSTATUS status1 = NT_STATUS_OK;
1141         const struct security_token *del_nt_token = NULL;
1142         const struct security_unix_token *del_token = NULL;
1143         NTSTATUS notify_status;
1144
1145         if (fsp->conn->sconn->using_smb2) {
1146                 notify_status = STATUS_NOTIFY_CLEANUP;
1147         } else {
1148                 notify_status = NT_STATUS_OK;
1149         }
1150
1151         if (fsp->num_aio_requests != 0) {
1152                 if (close_type != SHUTDOWN_CLOSE) {
1153                         /*
1154                          * We panic here because if we close() the fd while we
1155                          * have outstanding async I/O requests, an async IO
1156                          * request might use the fd. For directories the fd is
1157                          * read-only, so this is not as bad as with files, but
1158                          * still, better safe then sorry.
1159                          */
1160                         DBG_ERR("fsp->num_aio_requests=%u\n",
1161                                 fsp->num_aio_requests);
1162                         smb_panic("close with outstanding aio requests");
1163                         return NT_STATUS_INTERNAL_ERROR;
1164                 }
1165
1166                 while (fsp->num_aio_requests != 0) {
1167                         /*
1168                          * The destructor of the req will remove itself from the
1169                          * fsp.  Don't use TALLOC_FREE here, this will overwrite
1170                          * what the destructor just wrote into aio_requests[0].
1171                          */
1172                         talloc_free(fsp->aio_requests[0]);
1173                 }
1174         }
1175
1176         /*
1177          * NT can set delete_on_close of the last open
1178          * reference to a directory also.
1179          */
1180
1181         lck = get_existing_share_mode_lock(talloc_tos(), fsp->file_id);
1182         if (lck == NULL) {
1183                 DEBUG(0, ("close_directory: Could not get share mode lock for "
1184                           "%s\n", fsp_str_dbg(fsp)));
1185                 close_filestruct(fsp);
1186                 file_free(req, fsp);
1187                 return NT_STATUS_INVALID_PARAMETER;
1188         }
1189
1190         if (fsp->initial_delete_on_close) {
1191                 bool became_user = False;
1192
1193                 /* Initial delete on close was set - for
1194                  * directories we don't care if anyone else
1195                  * wrote a real delete on close. */
1196
1197                 if (get_current_vuid(fsp->conn) != fsp->vuid) {
1198                         become_user_without_service(fsp->conn, fsp->vuid);
1199                         became_user = True;
1200                 }
1201                 send_stat_cache_delete_message(fsp->conn->sconn->msg_ctx,
1202                                                fsp->fsp_name->base_name);
1203                 set_delete_on_close_lck(fsp, lck,
1204                                 get_current_nttok(fsp->conn),
1205                                 get_current_utok(fsp->conn));
1206                 fsp->delete_on_close = true;
1207                 if (became_user) {
1208                         unbecome_user_without_service();
1209                 }
1210         }
1211
1212         delete_dir = get_delete_on_close_token(
1213                 lck, fsp->name_hash, &del_nt_token, &del_token) &&
1214                 !has_other_nonposix_opens(lck, fsp);
1215
1216         if ((close_type == NORMAL_CLOSE || close_type == SHUTDOWN_CLOSE) &&
1217                                 delete_dir) {
1218         
1219                 /* Become the user who requested the delete. */
1220
1221                 if (!push_sec_ctx()) {
1222                         smb_panic("close_directory: failed to push sec_ctx.\n");
1223                 }
1224
1225                 set_sec_ctx(del_token->uid,
1226                                 del_token->gid,
1227                                 del_token->ngroups,
1228                                 del_token->groups,
1229                                 del_nt_token);
1230
1231                 if (!del_share_mode(lck, fsp)) {
1232                         DEBUG(0, ("close_directory: Could not delete share entry for "
1233                                   "%s\n", fsp_str_dbg(fsp)));
1234                 }
1235
1236                 TALLOC_FREE(lck);
1237
1238                 if ((fsp->conn->fs_capabilities & FILE_NAMED_STREAMS)
1239                     && !is_ntfs_stream_smb_fname(fsp->fsp_name)) {
1240
1241                         status = delete_all_streams(fsp->conn, fsp->fsp_name);
1242                         if (!NT_STATUS_IS_OK(status)) {
1243                                 DEBUG(5, ("delete_all_streams failed: %s\n",
1244                                           nt_errstr(status)));
1245                                 close_filestruct(fsp);
1246                                 file_free(req, fsp);
1247                                 return status;
1248                         }
1249                 }
1250
1251                 status = rmdir_internals(talloc_tos(), fsp);
1252
1253                 DEBUG(5,("close_directory: %s. Delete on close was set - "
1254                          "deleting directory returned %s.\n",
1255                          fsp_str_dbg(fsp), nt_errstr(status)));
1256
1257                 /* unbecome user. */
1258                 pop_sec_ctx();
1259
1260                 /*
1261                  * Ensure we remove any change notify requests that would
1262                  * now fail as the directory has been deleted.
1263                  */
1264
1265                 if (NT_STATUS_IS_OK(status)) {
1266                         notify_status = NT_STATUS_DELETE_PENDING;
1267                 }
1268         } else {
1269                 if (!del_share_mode(lck, fsp)) {
1270                         DEBUG(0, ("close_directory: Could not delete share entry for "
1271                                   "%s\n", fsp_str_dbg(fsp)));
1272                 }
1273
1274                 TALLOC_FREE(lck);
1275         }
1276
1277         remove_pending_change_notify_requests_by_fid(fsp, notify_status);
1278
1279         status1 = fd_close(fsp);
1280
1281         if (!NT_STATUS_IS_OK(status1)) {
1282                 DEBUG(0, ("Could not close dir! fname=%s, fd=%d, err=%d=%s\n",
1283                           fsp_str_dbg(fsp), fsp->fh->fd, errno,
1284                           strerror(errno)));
1285         }
1286
1287         /*
1288          * Do the code common to files and directories.
1289          */
1290         close_filestruct(fsp);
1291         file_free(req, fsp);
1292
1293         if (NT_STATUS_IS_OK(status) && !NT_STATUS_IS_OK(status1)) {
1294                 status = status1;
1295         }
1296         return status;
1297 }
1298
1299 /****************************************************************************
1300  Close a files_struct.
1301 ****************************************************************************/
1302   
1303 NTSTATUS close_file(struct smb_request *req, files_struct *fsp,
1304                     enum file_close_type close_type)
1305 {
1306         NTSTATUS status;
1307         struct files_struct *base_fsp = fsp->base_fsp;
1308
1309         if(fsp->is_directory) {
1310                 status = close_directory(req, fsp, close_type);
1311         } else if (fsp->fake_file_handle != NULL) {
1312                 status = close_fake_file(req, fsp);
1313         } else {
1314                 status = close_normal_file(req, fsp, close_type);
1315         }
1316
1317         if ((base_fsp != NULL) && (close_type != SHUTDOWN_CLOSE)) {
1318
1319                 /*
1320                  * fsp was a stream, the base fsp can't be a stream as well
1321                  *
1322                  * For SHUTDOWN_CLOSE this is not possible here, because
1323                  * SHUTDOWN_CLOSE only happens from files.c which walks the
1324                  * complete list of files. If we mess with more than one fsp
1325                  * those loops will become confused.
1326                  */
1327
1328                 SMB_ASSERT(base_fsp->base_fsp == NULL);
1329                 close_file(req, base_fsp, close_type);
1330         }
1331
1332         return status;
1333 }
1334
1335 /****************************************************************************
1336  Deal with an (authorized) message to close a file given the share mode
1337  entry.
1338 ****************************************************************************/
1339
1340 void msg_close_file(struct messaging_context *msg_ctx,
1341                         void *private_data,
1342                         uint32_t msg_type,
1343                         struct server_id server_id,
1344                         DATA_BLOB *data)
1345 {
1346         files_struct *fsp = NULL;
1347         struct file_id id;
1348         struct share_mode_entry e;
1349         struct smbd_server_connection *sconn =
1350                 talloc_get_type_abort(private_data,
1351                 struct smbd_server_connection);
1352
1353         message_to_share_mode_entry(&id, &e, (char *)data->data);
1354
1355         if(DEBUGLVL(10)) {
1356                 char *sm_str = share_mode_str(NULL, 0, &id, &e);
1357                 if (!sm_str) {
1358                         smb_panic("talloc failed");
1359                 }
1360                 DEBUG(10,("msg_close_file: got request to close share mode "
1361                         "entry %s\n", sm_str));
1362                 TALLOC_FREE(sm_str);
1363         }
1364
1365         fsp = file_find_dif(sconn, id, e.share_file_id);
1366         if (!fsp) {
1367                 DEBUG(10,("msg_close_file: failed to find file.\n"));
1368                 return;
1369         }
1370         close_file(NULL, fsp, NORMAL_CLOSE);
1371 }