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