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