s3:printing: Fix size type in printing_db
[nivanova/samba-autobuild/.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         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_UNLINK(conn, smb_fname_stream);
219
220                 if (res == -1) {
221                         status = map_nt_error_from_unix(errno);
222                         DEBUG(10, ("Could not delete stream %s: %s\n",
223                                    smb_fname_str_dbg(smb_fname_stream),
224                                    strerror(errno)));
225                         TALLOC_FREE(smb_fname_stream);
226                         break;
227                 }
228                 TALLOC_FREE(smb_fname_stream);
229         }
230
231  fail:
232         TALLOC_FREE(frame);
233         return status;
234 }
235
236 /****************************************************************************
237  Deal with removing a share mode on last close.
238 ****************************************************************************/
239
240 static NTSTATUS close_remove_share_mode(files_struct *fsp,
241                                         enum file_close_type close_type)
242 {
243         connection_struct *conn = fsp->conn;
244         struct server_id self = messaging_server_id(conn->sconn->msg_ctx);
245         bool delete_file = false;
246         bool changed_user = false;
247         struct share_mode_lock *lck = NULL;
248         NTSTATUS status = NT_STATUS_OK;
249         NTSTATUS tmp_status;
250         struct file_id id;
251         const struct security_unix_token *del_token = NULL;
252         const struct security_token *del_nt_token = NULL;
253         bool got_tokens = false;
254         bool normal_close;
255
256         /* Ensure any pending write time updates are done. */
257         if (fsp->update_write_time_event) {
258                 update_write_time_handler(fsp->conn->sconn->ev_ctx,
259                                         fsp->update_write_time_event,
260                                         timeval_current(),
261                                         (void *)fsp);
262         }
263
264         /*
265          * Lock the share entries, and determine if we should delete
266          * on close. If so delete whilst the lock is still in effect.
267          * This prevents race conditions with the file being created. JRA.
268          */
269
270         lck = get_existing_share_mode_lock(talloc_tos(), fsp->file_id);
271         if (lck == NULL) {
272                 DEBUG(0, ("close_remove_share_mode: Could not get share mode "
273                           "lock for file %s\n", fsp_str_dbg(fsp)));
274                 return NT_STATUS_INVALID_PARAMETER;
275         }
276
277         /* Remove the oplock before potentially deleting the file. */
278         if(fsp->oplock_type) {
279                 remove_oplock_under_lock(fsp, lck);
280         }
281
282         if (fsp->write_time_forced) {
283                 DEBUG(10,("close_remove_share_mode: write time forced "
284                         "for file %s\n",
285                         fsp_str_dbg(fsp)));
286                 set_close_write_time(fsp, lck->data->changed_write_time);
287         } else if (fsp->update_write_time_on_close) {
288                 /* Someone had a pending write. */
289                 if (null_timespec(fsp->close_write_time)) {
290                         DEBUG(10,("close_remove_share_mode: update to current time "
291                                 "for file %s\n",
292                                 fsp_str_dbg(fsp)));
293                         /* Update to current time due to "normal" write. */
294                         set_close_write_time(fsp, timespec_current());
295                 } else {
296                         DEBUG(10,("close_remove_share_mode: write time pending "
297                                 "for file %s\n",
298                                 fsp_str_dbg(fsp)));
299                         /* Update to time set on close call. */
300                         set_close_write_time(fsp, fsp->close_write_time);
301                 }
302         }
303
304         if (fsp->initial_delete_on_close &&
305                         !is_delete_on_close_set(lck, fsp->name_hash)) {
306                 bool became_user = False;
307
308                 /* Initial delete on close was set and no one else
309                  * wrote a real delete on close. */
310
311                 if (get_current_vuid(conn) != fsp->vuid) {
312                         become_user(conn, fsp->vuid);
313                         became_user = True;
314                 }
315                 fsp->delete_on_close = true;
316                 set_delete_on_close_lck(fsp, lck,
317                                 get_current_nttok(conn),
318                                 get_current_utok(conn));
319                 if (became_user) {
320                         unbecome_user();
321                 }
322         }
323
324         delete_file = is_delete_on_close_set(lck, fsp->name_hash);
325
326         if (delete_file) {
327                 int i;
328                 /* See if others still have the file open via this pathname.
329                    If this is the case, then don't delete. If all opens are
330                    POSIX delete now. */
331                 for (i=0; i<lck->data->num_share_modes; i++) {
332                         struct share_mode_entry *e = &lck->data->share_modes[i];
333
334                         if (!is_valid_share_mode_entry(e)) {
335                                 continue;
336                         }
337                         if (e->name_hash != fsp->name_hash) {
338                                 continue;
339                         }
340                         if ((fsp->posix_flags & FSP_POSIX_FLAGS_OPEN)
341                             && (e->flags & SHARE_MODE_FLAG_POSIX_OPEN)) {
342                                 continue;
343                         }
344                         if (serverid_equal(&self, &e->pid) &&
345                             (e->share_file_id == fsp->fh->gen_id)) {
346                                 continue;
347                         }
348                         if (share_mode_stale_pid(lck->data, i)) {
349                                 continue;
350                         }
351                         delete_file = False;
352                         break;
353                 }
354         }
355
356         /*
357          * NT can set delete_on_close of the last open
358          * reference to a file.
359          */
360
361         normal_close = (close_type == NORMAL_CLOSE || close_type == SHUTDOWN_CLOSE);
362
363         if (!normal_close || !delete_file) {
364                 status = NT_STATUS_OK;
365                 goto done;
366         }
367
368         /*
369          * Ok, we have to delete the file
370          */
371
372         DEBUG(5,("close_remove_share_mode: file %s. Delete on close was set "
373                  "- deleting file.\n", fsp_str_dbg(fsp)));
374
375         /*
376          * Don't try to update the write time when we delete the file
377          */
378         fsp->update_write_time_on_close = false;
379
380         got_tokens = get_delete_on_close_token(lck, fsp->name_hash,
381                                         &del_nt_token, &del_token);
382         SMB_ASSERT(got_tokens);
383
384         if (!unix_token_equal(del_token, get_current_utok(conn))) {
385                 /* Become the user who requested the delete. */
386
387                 DEBUG(5,("close_remove_share_mode: file %s. "
388                         "Change user to uid %u\n",
389                         fsp_str_dbg(fsp),
390                         (unsigned int)del_token->uid));
391
392                 if (!push_sec_ctx()) {
393                         smb_panic("close_remove_share_mode: file %s. failed to push "
394                                   "sec_ctx.\n");
395                 }
396
397                 set_sec_ctx(del_token->uid,
398                             del_token->gid,
399                             del_token->ngroups,
400                             del_token->groups,
401                             del_nt_token);
402
403                 changed_user = true;
404         }
405
406         /* We can only delete the file if the name we have is still valid and
407            hasn't been renamed. */
408
409         tmp_status = vfs_stat_fsp(fsp);
410         if (!NT_STATUS_IS_OK(tmp_status)) {
411                 DEBUG(5,("close_remove_share_mode: file %s. Delete on close "
412                          "was set and stat failed with error %s\n",
413                          fsp_str_dbg(fsp), nt_errstr(tmp_status)));
414                 /*
415                  * Don't save the errno here, we ignore this error
416                  */
417                 goto done;
418         }
419
420         id = vfs_file_id_from_sbuf(conn, &fsp->fsp_name->st);
421
422         if (!file_id_equal(&fsp->file_id, &id)) {
423                 DEBUG(5,("close_remove_share_mode: file %s. Delete on close "
424                          "was set and dev and/or inode does not match\n",
425                          fsp_str_dbg(fsp)));
426                 DEBUG(5,("close_remove_share_mode: file %s. stored file_id %s, "
427                          "stat file_id %s\n",
428                          fsp_str_dbg(fsp),
429                          file_id_string_tos(&fsp->file_id),
430                          file_id_string_tos(&id)));
431                 /*
432                  * Don't save the errno here, we ignore this error
433                  */
434                 goto done;
435         }
436
437         if ((conn->fs_capabilities & FILE_NAMED_STREAMS)
438             && !is_ntfs_stream_smb_fname(fsp->fsp_name)) {
439
440                 status = delete_all_streams(conn, fsp->fsp_name);
441
442                 if (!NT_STATUS_IS_OK(status)) {
443                         DEBUG(5, ("delete_all_streams failed: %s\n",
444                                   nt_errstr(status)));
445                         goto done;
446                 }
447         }
448
449         if (fsp->kernel_share_modes_taken) {
450                 int ret_flock;
451
452                 /*
453                  * A file system sharemode could block the unlink;
454                  * remove filesystem sharemodes first.
455                  */
456                 ret_flock = SMB_VFS_KERNEL_FLOCK(fsp, 0, 0);
457                 if (ret_flock == -1) {
458                         DBG_INFO("removing kernel flock for %s failed: %s\n",
459                                   fsp_str_dbg(fsp), strerror(errno));
460                 }
461
462                 fsp->kernel_share_modes_taken = false;
463         }
464
465
466         if (SMB_VFS_UNLINK(conn, fsp->fsp_name) != 0) {
467                 /*
468                  * This call can potentially fail as another smbd may
469                  * have had the file open with delete on close set and
470                  * deleted it when its last reference to this file
471                  * went away. Hence we log this but not at debug level
472                  * zero.
473                  */
474
475                 DEBUG(5,("close_remove_share_mode: file %s. Delete on close "
476                          "was set and unlink failed with error %s\n",
477                          fsp_str_dbg(fsp), strerror(errno)));
478
479                 status = map_nt_error_from_unix(errno);
480         }
481
482         /* As we now have POSIX opens which can unlink
483          * with other open files we may have taken
484          * this code path with more than one share mode
485          * entry - ensure we only delete once by resetting
486          * the delete on close flag. JRA.
487          */
488
489         fsp->delete_on_close = false;
490         reset_delete_on_close_lck(fsp, lck);
491
492  done:
493
494         if (changed_user) {
495                 /* unbecome user. */
496                 pop_sec_ctx();
497         }
498
499         if (fsp->kernel_share_modes_taken) {
500                 int ret_flock;
501
502                 /* remove filesystem sharemodes */
503                 ret_flock = SMB_VFS_KERNEL_FLOCK(fsp, 0, 0);
504                 if (ret_flock == -1) {
505                         DEBUG(2, ("close_remove_share_mode: removing kernel "
506                                   "flock for %s failed: %s\n",
507                                   fsp_str_dbg(fsp), strerror(errno)));
508                 }
509         }
510
511         if (!del_share_mode(lck, fsp)) {
512                 DEBUG(0, ("close_remove_share_mode: Could not delete share "
513                           "entry for file %s\n", fsp_str_dbg(fsp)));
514         }
515
516         TALLOC_FREE(lck);
517
518         if (delete_file) {
519                 /*
520                  * Do the notification after we released the share
521                  * mode lock. Inside notify_fname we take out another
522                  * tdb lock. With ctdb also accessing our databases,
523                  * this can lead to deadlocks. Putting this notify
524                  * after the TALLOC_FREE(lck) above we avoid locking
525                  * two records simultaneously. Notifies are async and
526                  * informational only, so calling the notify_fname
527                  * without holding the share mode lock should not do
528                  * any harm.
529                  */
530                 notify_fname(conn, NOTIFY_ACTION_REMOVED,
531                              FILE_NOTIFY_CHANGE_FILE_NAME,
532                              fsp->fsp_name->base_name);
533         }
534
535         return status;
536 }
537
538 void set_close_write_time(struct files_struct *fsp, struct timespec ts)
539 {
540         DEBUG(6,("close_write_time: %s" , time_to_asc(convert_timespec_to_time_t(ts))));
541
542         if (null_timespec(ts)) {
543                 return;
544         }
545         fsp->write_time_forced = false;
546         fsp->update_write_time_on_close = true;
547         fsp->close_write_time = ts;
548 }
549
550 static NTSTATUS update_write_time_on_close(struct files_struct *fsp)
551 {
552         struct smb_file_time ft;
553         NTSTATUS status;
554         struct share_mode_lock *lck = NULL;
555
556         ZERO_STRUCT(ft);
557
558         if (!fsp->update_write_time_on_close) {
559                 return NT_STATUS_OK;
560         }
561
562         if (null_timespec(fsp->close_write_time)) {
563                 fsp->close_write_time = timespec_current();
564         }
565
566         /* Ensure we have a valid stat struct for the source. */
567         status = vfs_stat_fsp(fsp);
568         if (!NT_STATUS_IS_OK(status)) {
569                 return status;
570         }
571
572         if (!VALID_STAT(fsp->fsp_name->st)) {
573                 /* if it doesn't seem to be a real file */
574                 return NT_STATUS_OK;
575         }
576
577         /*
578          * get_existing_share_mode_lock() isn't really the right
579          * call here, as we're being called after
580          * close_remove_share_mode() inside close_normal_file()
581          * so it's quite normal to not have an existing share
582          * mode here. However, get_share_mode_lock() doesn't
583          * work because that will create a new share mode if
584          * one doesn't exist - so stick with this call (just
585          * ignore any error we get if the share mode doesn't
586          * exist.
587          */
588
589         lck = get_existing_share_mode_lock(talloc_tos(), fsp->file_id);
590         if (lck) {
591                 /* On close if we're changing the real file time we
592                  * must update it in the open file db too. */
593                 (void)set_write_time(fsp->file_id, fsp->close_write_time);
594
595                 /* Close write times overwrite sticky write times
596                    so we must replace any sticky write time here. */
597                 if (!null_timespec(lck->data->changed_write_time)) {
598                         (void)set_sticky_write_time(fsp->file_id, fsp->close_write_time);
599                 }
600                 TALLOC_FREE(lck);
601         }
602
603         ft.mtime = fsp->close_write_time;
604         /* As this is a close based update, we are not directly changing the
605            file attributes from a client call, but indirectly from a write. */
606         status = smb_set_file_time(fsp->conn, fsp, fsp->fsp_name, &ft, false);
607         if (!NT_STATUS_IS_OK(status)) {
608                 DEBUG(10,("update_write_time_on_close: smb_set_file_time "
609                         "on file %s returned %s\n",
610                         fsp_str_dbg(fsp),
611                         nt_errstr(status)));
612                 return status;
613         }
614
615         return status;
616 }
617
618 static NTSTATUS ntstatus_keeperror(NTSTATUS s1, NTSTATUS s2)
619 {
620         if (!NT_STATUS_IS_OK(s1)) {
621                 return s1;
622         }
623         return s2;
624 }
625
626 /****************************************************************************
627  Close a file.
628
629  close_type can be NORMAL_CLOSE=0,SHUTDOWN_CLOSE,ERROR_CLOSE.
630  printing and magic scripts are only run on normal close.
631  delete on close is done on normal and shutdown close.
632 ****************************************************************************/
633
634 static NTSTATUS close_normal_file(struct smb_request *req, files_struct *fsp,
635                                   enum file_close_type close_type)
636 {
637         NTSTATUS status = NT_STATUS_OK;
638         NTSTATUS tmp;
639         connection_struct *conn = fsp->conn;
640         bool is_durable = false;
641
642         if (fsp->num_aio_requests != 0) {
643
644                 if (close_type != SHUTDOWN_CLOSE) {
645                         /*
646                          * reply_close and the smb2 close must have
647                          * taken care of this. No other callers of
648                          * close_file should ever have created async
649                          * I/O.
650                          *
651                          * We need to panic here because if we close()
652                          * the fd while we have outstanding async I/O
653                          * requests, in the worst case we could end up
654                          * writing to the wrong file.
655                          */
656                         DEBUG(0, ("fsp->num_aio_requests=%u\n",
657                                   fsp->num_aio_requests));
658                         smb_panic("can not close with outstanding aio "
659                                   "requests");
660                 }
661
662                 /*
663                  * For shutdown close, just drop the async requests
664                  * including a potential close request pending for
665                  * this fsp. Drop the close request first, the
666                  * destructor for the aio_requests would execute it.
667                  */
668                 TALLOC_FREE(fsp->deferred_close);
669
670                 while (fsp->num_aio_requests != 0) {
671                         /*
672                          * The destructor of the req will remove
673                          * itself from the fsp.
674                          * Don't use TALLOC_FREE here, this will overwrite
675                          * what the destructor just wrote into
676                          * aio_requests[0].
677                          */
678                         talloc_free(fsp->aio_requests[0]);
679                 }
680         }
681
682         /*
683          * If we're flushing on a close we can get a write
684          * error here, we must remember this.
685          */
686
687         tmp = close_filestruct(fsp);
688         status = ntstatus_keeperror(status, tmp);
689
690         if (NT_STATUS_IS_OK(status) && fsp->op != NULL) {
691                 is_durable = fsp->op->global->durable;
692         }
693
694         if (close_type != SHUTDOWN_CLOSE) {
695                 is_durable = false;
696         }
697
698         if (is_durable) {
699                 DATA_BLOB new_cookie = data_blob_null;
700
701                 tmp = SMB_VFS_DURABLE_DISCONNECT(fsp,
702                                         fsp->op->global->backend_cookie,
703                                         fsp->op,
704                                         &new_cookie);
705                 if (NT_STATUS_IS_OK(tmp)) {
706                         struct timeval tv;
707                         NTTIME now;
708
709                         if (req != NULL) {
710                                 tv = req->request_time;
711                         } else {
712                                 tv = timeval_current();
713                         }
714                         now = timeval_to_nttime(&tv);
715
716                         data_blob_free(&fsp->op->global->backend_cookie);
717                         fsp->op->global->backend_cookie = new_cookie;
718
719                         fsp->op->compat = NULL;
720                         tmp = smbXsrv_open_close(fsp->op, now);
721                         if (!NT_STATUS_IS_OK(tmp)) {
722                                 DEBUG(1, ("Failed to update smbXsrv_open "
723                                           "record when disconnecting durable "
724                                           "handle for file %s: %s - "
725                                           "proceeding with normal close\n",
726                                           fsp_str_dbg(fsp), nt_errstr(tmp)));
727                         }
728                         scavenger_schedule_disconnected(fsp);
729                 } else {
730                         DEBUG(1, ("Failed to disconnect durable handle for "
731                                   "file %s: %s - proceeding with normal "
732                                   "close\n", fsp_str_dbg(fsp), nt_errstr(tmp)));
733                 }
734                 if (!NT_STATUS_IS_OK(tmp)) {
735                         is_durable = false;
736                 }
737         }
738
739         if (is_durable) {
740                 /*
741                  * This is the case where we successfully disconnected
742                  * a durable handle and closed the underlying file.
743                  * In all other cases, we proceed with a genuine close.
744                  */
745                 DEBUG(10, ("%s disconnected durable handle for file %s\n",
746                            conn->session_info->unix_info->unix_name,
747                            fsp_str_dbg(fsp)));
748                 file_free(req, fsp);
749                 return NT_STATUS_OK;
750         }
751
752         if (fsp->op != NULL) {
753                 /*
754                  * Make sure the handle is not marked as durable anymore
755                  */
756                 fsp->op->global->durable = false;
757         }
758
759         if (fsp->print_file) {
760                 /* FIXME: return spool errors */
761                 print_spool_end(fsp, close_type);
762                 file_free(req, fsp);
763                 return NT_STATUS_OK;
764         }
765
766         /* If this is an old DOS or FCB open and we have multiple opens on
767            the same handle we only have one share mode. Ensure we only remove
768            the share mode on the last close. */
769
770         if (fsp->fh->ref_count == 1) {
771                 /* Should we return on error here... ? */
772                 tmp = close_remove_share_mode(fsp, close_type);
773                 status = ntstatus_keeperror(status, tmp);
774         }
775
776         locking_close_file(conn->sconn->msg_ctx, fsp, close_type);
777
778         tmp = fd_close(fsp);
779         status = ntstatus_keeperror(status, tmp);
780
781         /* check for magic scripts */
782         if (close_type == NORMAL_CLOSE) {
783                 tmp = check_magic(fsp);
784                 status = ntstatus_keeperror(status, tmp);
785         }
786
787         /*
788          * Ensure pending modtime is set after close.
789          */
790
791         tmp = update_write_time_on_close(fsp);
792         if (NT_STATUS_EQUAL(tmp, NT_STATUS_OBJECT_NAME_NOT_FOUND)) {
793                 /* Someone renamed the file or a parent directory containing
794                  * this file. We can't do anything about this, we don't have
795                  * an "update timestamp by fd" call in POSIX. Eat the error. */
796
797                 tmp = NT_STATUS_OK;
798         }
799
800         status = ntstatus_keeperror(status, tmp);
801
802         DEBUG(2,("%s closed file %s (numopen=%d) %s\n",
803                 conn->session_info->unix_info->unix_name, fsp_str_dbg(fsp),
804                 conn->num_files_open - 1,
805                 nt_errstr(status) ));
806
807         file_free(req, fsp);
808         return status;
809 }
810 /****************************************************************************
811  Function used by reply_rmdir to delete an entire directory
812  tree recursively. Return True on ok, False on fail.
813 ****************************************************************************/
814
815 bool recursive_rmdir(TALLOC_CTX *ctx,
816                      connection_struct *conn,
817                      struct smb_filename *smb_dname)
818 {
819         const char *dname = NULL;
820         char *talloced = NULL;
821         bool ret = True;
822         long offset = 0;
823         SMB_STRUCT_STAT st;
824         struct smb_Dir *dir_hnd;
825
826         SMB_ASSERT(!is_ntfs_stream_smb_fname(smb_dname));
827
828         dir_hnd = OpenDir(talloc_tos(), conn, smb_dname, NULL, 0);
829         if(dir_hnd == NULL)
830                 return False;
831
832         while((dname = ReadDirName(dir_hnd, &offset, &st, &talloced))) {
833                 struct smb_filename *smb_dname_full = NULL;
834                 char *fullname = NULL;
835                 bool do_break = true;
836
837                 if (ISDOT(dname) || ISDOTDOT(dname)) {
838                         TALLOC_FREE(talloced);
839                         continue;
840                 }
841
842                 if (!is_visible_file(conn, smb_dname->base_name, dname, &st,
843                                      false)) {
844                         TALLOC_FREE(talloced);
845                         continue;
846                 }
847
848                 /* Construct the full name. */
849                 fullname = talloc_asprintf(ctx,
850                                 "%s/%s",
851                                 smb_dname->base_name,
852                                 dname);
853                 if (!fullname) {
854                         errno = ENOMEM;
855                         goto err_break;
856                 }
857
858                 smb_dname_full = synthetic_smb_fname(talloc_tos(),
859                                                 fullname,
860                                                 NULL,
861                                                 NULL,
862                                                 smb_dname->flags);
863                 if (smb_dname_full == NULL) {
864                         errno = ENOMEM;
865                         goto err_break;
866                 }
867
868                 if(SMB_VFS_LSTAT(conn, smb_dname_full) != 0) {
869                         goto err_break;
870                 }
871
872                 if(smb_dname_full->st.st_ex_mode & S_IFDIR) {
873                         if(!recursive_rmdir(ctx, conn, smb_dname_full)) {
874                                 goto err_break;
875                         }
876                         if(SMB_VFS_RMDIR(conn, smb_dname_full) != 0) {
877                                 goto err_break;
878                         }
879                 } else if(SMB_VFS_UNLINK(conn, smb_dname_full) != 0) {
880                         goto err_break;
881                 }
882
883                 /* Successful iteration. */
884                 do_break = false;
885
886          err_break:
887                 TALLOC_FREE(smb_dname_full);
888                 TALLOC_FREE(fullname);
889                 TALLOC_FREE(talloced);
890                 if (do_break) {
891                         ret = false;
892                         break;
893                 }
894         }
895         TALLOC_FREE(dir_hnd);
896         return ret;
897 }
898
899 /****************************************************************************
900  The internals of the rmdir code - called elsewhere.
901 ****************************************************************************/
902
903 static NTSTATUS rmdir_internals(TALLOC_CTX *ctx, files_struct *fsp)
904 {
905         connection_struct *conn = fsp->conn;
906         struct smb_filename *smb_dname = fsp->fsp_name;
907         int ret;
908
909         SMB_ASSERT(!is_ntfs_stream_smb_fname(smb_dname));
910
911         /* Might be a symlink. */
912         if(SMB_VFS_LSTAT(conn, smb_dname) != 0) {
913                 return map_nt_error_from_unix(errno);
914         }
915
916         if (S_ISLNK(smb_dname->st.st_ex_mode)) {
917                 /* Is what it points to a directory ? */
918                 if(SMB_VFS_STAT(conn, smb_dname) != 0) {
919                         return map_nt_error_from_unix(errno);
920                 }
921                 if (!(S_ISDIR(smb_dname->st.st_ex_mode))) {
922                         return NT_STATUS_NOT_A_DIRECTORY;
923                 }
924                 ret = SMB_VFS_UNLINK(conn, smb_dname);
925         } else {
926                 ret = SMB_VFS_RMDIR(conn, smb_dname);
927         }
928         if (ret == 0) {
929                 notify_fname(conn, NOTIFY_ACTION_REMOVED,
930                              FILE_NOTIFY_CHANGE_DIR_NAME,
931                              smb_dname->base_name);
932                 return NT_STATUS_OK;
933         }
934
935         if(((errno == ENOTEMPTY)||(errno == EEXIST)) && *lp_veto_files(talloc_tos(), SNUM(conn))) {
936                 /*
937                  * Check to see if the only thing in this directory are
938                  * vetoed files/directories. If so then delete them and
939                  * retry. If we fail to delete any of them (and we *don't*
940                  * do a recursive delete) then fail the rmdir.
941                  */
942                 SMB_STRUCT_STAT st;
943                 const char *dname = NULL;
944                 char *talloced = NULL;
945                 long dirpos = 0;
946                 struct smb_Dir *dir_hnd = OpenDir(talloc_tos(), conn,
947                                                   smb_dname, NULL,
948                                                   0);
949
950                 if(dir_hnd == NULL) {
951                         errno = ENOTEMPTY;
952                         goto err;
953                 }
954
955                 while ((dname = ReadDirName(dir_hnd, &dirpos, &st,
956                                             &talloced)) != NULL) {
957                         if((strcmp(dname, ".") == 0) || (strcmp(dname, "..")==0)) {
958                                 TALLOC_FREE(talloced);
959                                 continue;
960                         }
961                         if (!is_visible_file(conn, smb_dname->base_name, dname,
962                                              &st, false)) {
963                                 TALLOC_FREE(talloced);
964                                 continue;
965                         }
966                         if(!IS_VETO_PATH(conn, dname)) {
967                                 TALLOC_FREE(dir_hnd);
968                                 TALLOC_FREE(talloced);
969                                 errno = ENOTEMPTY;
970                                 goto err;
971                         }
972                         TALLOC_FREE(talloced);
973                 }
974
975                 /* We only have veto files/directories.
976                  * Are we allowed to delete them ? */
977
978                 if(!lp_delete_veto_files(SNUM(conn))) {
979                         TALLOC_FREE(dir_hnd);
980                         errno = ENOTEMPTY;
981                         goto err;
982                 }
983
984                 /* Do a recursive delete. */
985                 RewindDir(dir_hnd,&dirpos);
986                 while ((dname = ReadDirName(dir_hnd, &dirpos, &st,
987                                             &talloced)) != NULL) {
988                         struct smb_filename *smb_dname_full = NULL;
989                         char *fullname = NULL;
990                         bool do_break = true;
991
992                         if (ISDOT(dname) || ISDOTDOT(dname)) {
993                                 TALLOC_FREE(talloced);
994                                 continue;
995                         }
996                         if (!is_visible_file(conn, smb_dname->base_name, dname,
997                                              &st, false)) {
998                                 TALLOC_FREE(talloced);
999                                 continue;
1000                         }
1001
1002                         fullname = talloc_asprintf(ctx,
1003                                         "%s/%s",
1004                                         smb_dname->base_name,
1005                                         dname);
1006
1007                         if(!fullname) {
1008                                 errno = ENOMEM;
1009                                 goto err_break;
1010                         }
1011
1012                         smb_dname_full = synthetic_smb_fname(talloc_tos(),
1013                                                         fullname,
1014                                                         NULL,
1015                                                         NULL,
1016                                                         smb_dname->flags);
1017                         if (smb_dname_full == NULL) {
1018                                 errno = ENOMEM;
1019                                 goto err_break;
1020                         }
1021
1022                         if(SMB_VFS_LSTAT(conn, smb_dname_full) != 0) {
1023                                 goto err_break;
1024                         }
1025                         if(smb_dname_full->st.st_ex_mode & S_IFDIR) {
1026                                 if(!recursive_rmdir(ctx, conn,
1027                                                     smb_dname_full)) {
1028                                         goto err_break;
1029                                 }
1030                                 if(SMB_VFS_RMDIR(conn,
1031                                         smb_dname_full) != 0) {
1032                                         goto err_break;
1033                                 }
1034                         } else if(SMB_VFS_UNLINK(conn, smb_dname_full) != 0) {
1035                                 goto err_break;
1036                         }
1037
1038                         /* Successful iteration. */
1039                         do_break = false;
1040
1041                  err_break:
1042                         TALLOC_FREE(fullname);
1043                         TALLOC_FREE(smb_dname_full);
1044                         TALLOC_FREE(talloced);
1045                         if (do_break)
1046                                 break;
1047                 }
1048                 TALLOC_FREE(dir_hnd);
1049                 /* Retry the rmdir */
1050                 ret = SMB_VFS_RMDIR(conn, smb_dname);
1051         }
1052
1053   err:
1054
1055         if (ret != 0) {
1056                 DEBUG(3,("rmdir_internals: couldn't remove directory %s : "
1057                          "%s\n", smb_fname_str_dbg(smb_dname),
1058                          strerror(errno)));
1059                 return map_nt_error_from_unix(errno);
1060         }
1061
1062         notify_fname(conn, NOTIFY_ACTION_REMOVED,
1063                      FILE_NOTIFY_CHANGE_DIR_NAME,
1064                      smb_dname->base_name);
1065
1066         return NT_STATUS_OK;
1067 }
1068
1069 /****************************************************************************
1070  Close a directory opened by an NT SMB call. 
1071 ****************************************************************************/
1072   
1073 static NTSTATUS close_directory(struct smb_request *req, files_struct *fsp,
1074                                 enum file_close_type close_type)
1075 {
1076         struct server_id self = messaging_server_id(fsp->conn->sconn->msg_ctx);
1077         struct share_mode_lock *lck = NULL;
1078         bool delete_dir = False;
1079         NTSTATUS status = NT_STATUS_OK;
1080         NTSTATUS status1 = NT_STATUS_OK;
1081         const struct security_token *del_nt_token = NULL;
1082         const struct security_unix_token *del_token = NULL;
1083         NTSTATUS notify_status;
1084
1085         if (fsp->conn->sconn->using_smb2) {
1086                 notify_status = STATUS_NOTIFY_CLEANUP;
1087         } else {
1088                 notify_status = NT_STATUS_OK;
1089         }
1090
1091         /*
1092          * NT can set delete_on_close of the last open
1093          * reference to a directory also.
1094          */
1095
1096         lck = get_existing_share_mode_lock(talloc_tos(), fsp->file_id);
1097         if (lck == NULL) {
1098                 DEBUG(0, ("close_directory: Could not get share mode lock for "
1099                           "%s\n", fsp_str_dbg(fsp)));
1100                 return NT_STATUS_INVALID_PARAMETER;
1101         }
1102
1103         if (fsp->initial_delete_on_close) {
1104                 bool became_user = False;
1105
1106                 /* Initial delete on close was set - for
1107                  * directories we don't care if anyone else
1108                  * wrote a real delete on close. */
1109
1110                 if (get_current_vuid(fsp->conn) != fsp->vuid) {
1111                         become_user(fsp->conn, fsp->vuid);
1112                         became_user = True;
1113                 }
1114                 send_stat_cache_delete_message(fsp->conn->sconn->msg_ctx,
1115                                                fsp->fsp_name->base_name);
1116                 set_delete_on_close_lck(fsp, lck,
1117                                 get_current_nttok(fsp->conn),
1118                                 get_current_utok(fsp->conn));
1119                 fsp->delete_on_close = true;
1120                 if (became_user) {
1121                         unbecome_user();
1122                 }
1123         }
1124
1125         delete_dir = get_delete_on_close_token(lck, fsp->name_hash,
1126                                         &del_nt_token, &del_token);
1127
1128         if (delete_dir) {
1129                 int i;
1130                 /* See if others still have the dir open. If this is the
1131                  * case, then don't delete. If all opens are POSIX delete now. */
1132                 for (i=0; i<lck->data->num_share_modes; i++) {
1133                         struct share_mode_entry *e = &lck->data->share_modes[i];
1134                         if (is_valid_share_mode_entry(e) &&
1135                                         e->name_hash == fsp->name_hash) {
1136                                 if ((fsp->posix_flags & FSP_POSIX_FLAGS_OPEN) &&
1137                                     (e->flags & SHARE_MODE_FLAG_POSIX_OPEN))
1138                                 {
1139                                         continue;
1140                                 }
1141                                 if (serverid_equal(&self, &e->pid) &&
1142                                     (e->share_file_id == fsp->fh->gen_id)) {
1143                                         continue;
1144                                 }
1145                                 if (share_mode_stale_pid(lck->data, i)) {
1146                                         continue;
1147                                 }
1148                                 delete_dir = False;
1149                                 break;
1150                         }
1151                 }
1152         }
1153
1154         if ((close_type == NORMAL_CLOSE || close_type == SHUTDOWN_CLOSE) &&
1155                                 delete_dir) {
1156         
1157                 /* Become the user who requested the delete. */
1158
1159                 if (!push_sec_ctx()) {
1160                         smb_panic("close_directory: failed to push sec_ctx.\n");
1161                 }
1162
1163                 set_sec_ctx(del_token->uid,
1164                                 del_token->gid,
1165                                 del_token->ngroups,
1166                                 del_token->groups,
1167                                 del_nt_token);
1168
1169                 if (!del_share_mode(lck, fsp)) {
1170                         DEBUG(0, ("close_directory: Could not delete share entry for "
1171                                   "%s\n", fsp_str_dbg(fsp)));
1172                 }
1173
1174                 TALLOC_FREE(lck);
1175
1176                 if ((fsp->conn->fs_capabilities & FILE_NAMED_STREAMS)
1177                     && !is_ntfs_stream_smb_fname(fsp->fsp_name)) {
1178
1179                         status = delete_all_streams(fsp->conn, fsp->fsp_name);
1180                         if (!NT_STATUS_IS_OK(status)) {
1181                                 DEBUG(5, ("delete_all_streams failed: %s\n",
1182                                           nt_errstr(status)));
1183                                 return status;
1184                         }
1185                 }
1186
1187                 status = rmdir_internals(talloc_tos(), fsp);
1188
1189                 DEBUG(5,("close_directory: %s. Delete on close was set - "
1190                          "deleting directory returned %s.\n",
1191                          fsp_str_dbg(fsp), nt_errstr(status)));
1192
1193                 /* unbecome user. */
1194                 pop_sec_ctx();
1195
1196                 /*
1197                  * Ensure we remove any change notify requests that would
1198                  * now fail as the directory has been deleted.
1199                  */
1200
1201                 if (NT_STATUS_IS_OK(status)) {
1202                         notify_status = NT_STATUS_DELETE_PENDING;
1203                 }
1204         } else {
1205                 if (!del_share_mode(lck, fsp)) {
1206                         DEBUG(0, ("close_directory: Could not delete share entry for "
1207                                   "%s\n", fsp_str_dbg(fsp)));
1208                 }
1209
1210                 TALLOC_FREE(lck);
1211         }
1212
1213         remove_pending_change_notify_requests_by_fid(fsp, notify_status);
1214
1215         status1 = fd_close(fsp);
1216
1217         if (!NT_STATUS_IS_OK(status1)) {
1218                 DEBUG(0, ("Could not close dir! fname=%s, fd=%d, err=%d=%s\n",
1219                           fsp_str_dbg(fsp), fsp->fh->fd, errno,
1220                           strerror(errno)));
1221         }
1222
1223         /*
1224          * Do the code common to files and directories.
1225          */
1226         close_filestruct(fsp);
1227         file_free(req, fsp);
1228
1229         if (NT_STATUS_IS_OK(status) && !NT_STATUS_IS_OK(status1)) {
1230                 status = status1;
1231         }
1232         return status;
1233 }
1234
1235 /****************************************************************************
1236  Close a files_struct.
1237 ****************************************************************************/
1238   
1239 NTSTATUS close_file(struct smb_request *req, files_struct *fsp,
1240                     enum file_close_type close_type)
1241 {
1242         NTSTATUS status;
1243         struct files_struct *base_fsp = fsp->base_fsp;
1244
1245         if(fsp->is_directory) {
1246                 status = close_directory(req, fsp, close_type);
1247         } else if (fsp->fake_file_handle != NULL) {
1248                 status = close_fake_file(req, fsp);
1249         } else {
1250                 status = close_normal_file(req, fsp, close_type);
1251         }
1252
1253         if ((base_fsp != NULL) && (close_type != SHUTDOWN_CLOSE)) {
1254
1255                 /*
1256                  * fsp was a stream, the base fsp can't be a stream as well
1257                  *
1258                  * For SHUTDOWN_CLOSE this is not possible here, because
1259                  * SHUTDOWN_CLOSE only happens from files.c which walks the
1260                  * complete list of files. If we mess with more than one fsp
1261                  * those loops will become confused.
1262                  */
1263
1264                 SMB_ASSERT(base_fsp->base_fsp == NULL);
1265                 close_file(req, base_fsp, close_type);
1266         }
1267
1268         return status;
1269 }
1270
1271 /****************************************************************************
1272  Deal with an (authorized) message to close a file given the share mode
1273  entry.
1274 ****************************************************************************/
1275
1276 void msg_close_file(struct messaging_context *msg_ctx,
1277                         void *private_data,
1278                         uint32_t msg_type,
1279                         struct server_id server_id,
1280                         DATA_BLOB *data)
1281 {
1282         files_struct *fsp = NULL;
1283         struct file_id id;
1284         struct share_mode_entry e;
1285         struct smbd_server_connection *sconn =
1286                 talloc_get_type_abort(private_data,
1287                 struct smbd_server_connection);
1288
1289         message_to_share_mode_entry(&id, &e, (char *)data->data);
1290
1291         if(DEBUGLVL(10)) {
1292                 char *sm_str = share_mode_str(NULL, 0, &id, &e);
1293                 if (!sm_str) {
1294                         smb_panic("talloc failed");
1295                 }
1296                 DEBUG(10,("msg_close_file: got request to close share mode "
1297                         "entry %s\n", sm_str));
1298                 TALLOC_FREE(sm_str);
1299         }
1300
1301         fsp = file_find_dif(sconn, id, e.share_file_id);
1302         if (!fsp) {
1303                 DEBUG(10,("msg_close_file: failed to find file.\n"));
1304                 return;
1305         }
1306         close_file(NULL, fsp, NORMAL_CLOSE);
1307 }