Merge commit 'samba/v3-2-test' into v3-2-stable
[jra/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
24 extern struct current_user current_user;
25
26 /****************************************************************************
27  Run a file if it is a magic script.
28 ****************************************************************************/
29
30 static void check_magic(struct files_struct *fsp)
31 {
32         int ret;
33         const char *magic_output = NULL;
34         SMB_STRUCT_STAT st;
35         int tmp_fd, outfd;
36         TALLOC_CTX *ctx = NULL;
37         const char *p;
38         struct connection_struct *conn = fsp->conn;
39
40         if (!*lp_magicscript(SNUM(conn))) {
41                 return;
42         }
43
44         DEBUG(5,("checking magic for %s\n",fsp->fsp_name));
45
46         if (!(p = strrchr_m(fsp->fsp_name,'/'))) {
47                 p = fsp->fsp_name;
48         } else {
49                 p++;
50         }
51
52         if (!strequal(lp_magicscript(SNUM(conn)),p)) {
53                 return;
54         }
55
56         ctx = talloc_stackframe();
57
58         if (*lp_magicoutput(SNUM(conn))) {
59                 magic_output = lp_magicoutput(SNUM(conn));
60         } else {
61                 magic_output = talloc_asprintf(ctx,
62                                 "%s.out",
63                                 fsp->fsp_name);
64         }
65         if (!magic_output) {
66                 TALLOC_FREE(ctx);
67                 return;
68         }
69
70         chmod(fsp->fsp_name,0755);
71         ret = smbrun(fsp->fsp_name,&tmp_fd);
72         DEBUG(3,("Invoking magic command %s gave %d\n",
73                 fsp->fsp_name,ret));
74
75         unlink(fsp->fsp_name);
76         if (ret != 0 || tmp_fd == -1) {
77                 if (tmp_fd != -1) {
78                         close(tmp_fd);
79                 }
80                 TALLOC_FREE(ctx);
81                 return;
82         }
83         outfd = open(magic_output, O_CREAT|O_EXCL|O_RDWR, 0600);
84         if (outfd == -1) {
85                 close(tmp_fd);
86                 TALLOC_FREE(ctx);
87                 return;
88         }
89
90         if (sys_fstat(tmp_fd,&st) == -1) {
91                 close(tmp_fd);
92                 close(outfd);
93                 return;
94         }
95
96         transfer_file(tmp_fd,outfd,(SMB_OFF_T)st.st_size);
97         close(tmp_fd);
98         close(outfd);
99         TALLOC_FREE(ctx);
100 }
101
102 /****************************************************************************
103   Common code to close a file or a directory.
104 ****************************************************************************/
105
106 static NTSTATUS close_filestruct(files_struct *fsp)
107 {
108         NTSTATUS status = NT_STATUS_OK;
109         connection_struct *conn = fsp->conn;
110     
111         if (fsp->fh->fd != -1) {
112                 if(flush_write_cache(fsp, CLOSE_FLUSH) == -1) {
113                         status = map_nt_error_from_unix(errno);
114                 }
115                 delete_write_cache(fsp);
116         }
117
118         conn->num_files_open--;
119         return status;
120 }    
121
122 /****************************************************************************
123  If any deferred opens are waiting on this close, notify them.
124 ****************************************************************************/
125
126 static void notify_deferred_opens(struct share_mode_lock *lck)
127 {
128         int i;
129  
130         for (i=0; i<lck->num_share_modes; i++) {
131                 struct share_mode_entry *e = &lck->share_modes[i];
132  
133                 if (!is_deferred_open_entry(e)) {
134                         continue;
135                 }
136  
137                 if (procid_is_me(&e->pid)) {
138                         /*
139                          * We need to notify ourself to retry the open.  Do
140                          * this by finding the queued SMB record, moving it to
141                          * the head of the queue and changing the wait time to
142                          * zero.
143                          */
144                         schedule_deferred_open_smb_message(e->op_mid);
145                 } else {
146                         char msg[MSG_SMB_SHARE_MODE_ENTRY_SIZE];
147
148                         share_mode_entry_to_message(msg, e);
149
150                         messaging_send_buf(smbd_messaging_context(),
151                                            e->pid, MSG_SMB_OPEN_RETRY,
152                                            (uint8 *)msg,
153                                            MSG_SMB_SHARE_MODE_ENTRY_SIZE);
154                 }
155         }
156 }
157
158 /****************************************************************************
159  Deal with removing a share mode on last close.
160 ****************************************************************************/
161
162 static NTSTATUS close_remove_share_mode(files_struct *fsp,
163                                         enum file_close_type close_type)
164 {
165         connection_struct *conn = fsp->conn;
166         bool delete_file = false;
167         bool changed_user = false;
168         struct share_mode_lock *lck;
169         SMB_STRUCT_STAT sbuf;
170         NTSTATUS status = NT_STATUS_OK;
171         int ret;
172         struct file_id id;
173
174         /*
175          * Lock the share entries, and determine if we should delete
176          * on close. If so delete whilst the lock is still in effect.
177          * This prevents race conditions with the file being created. JRA.
178          */
179
180         lck = get_share_mode_lock(talloc_tos(), fsp->file_id, NULL, NULL);
181
182         if (lck == NULL) {
183                 DEBUG(0, ("close_remove_share_mode: Could not get share mode "
184                           "lock for file %s\n", fsp->fsp_name));
185                 return NT_STATUS_INVALID_PARAMETER;
186         }
187
188         if (!del_share_mode(lck, fsp)) {
189                 DEBUG(0, ("close_remove_share_mode: Could not delete share "
190                           "entry for file %s\n", fsp->fsp_name));
191         }
192
193         if (fsp->initial_delete_on_close && (lck->delete_token == NULL)) {
194                 bool became_user = False;
195
196                 /* Initial delete on close was set and no one else
197                  * wrote a real delete on close. */
198
199                 if (current_user.vuid != fsp->vuid) {
200                         become_user(conn, fsp->vuid);
201                         became_user = True;
202                 }
203                 set_delete_on_close_lck(lck, True, &current_user.ut);
204                 if (became_user) {
205                         unbecome_user();
206                 }
207         }
208
209         delete_file = lck->delete_on_close;
210
211         if (delete_file) {
212                 int i;
213                 /* See if others still have the file open. If this is the
214                  * case, then don't delete. If all opens are POSIX delete now. */
215                 for (i=0; i<lck->num_share_modes; i++) {
216                         struct share_mode_entry *e = &lck->share_modes[i];
217                         if (is_valid_share_mode_entry(e)) {
218                                 if (fsp->posix_open && (e->flags & SHARE_MODE_FLAG_POSIX_OPEN)) {
219                                         continue;
220                                 }
221                                 delete_file = False;
222                                 break;
223                         }
224                 }
225         }
226
227         /* Notify any deferred opens waiting on this close. */
228         notify_deferred_opens(lck);
229         reply_to_oplock_break_requests(fsp);
230
231         /*
232          * NT can set delete_on_close of the last open
233          * reference to a file.
234          */
235
236         if (!(close_type == NORMAL_CLOSE || close_type == SHUTDOWN_CLOSE)
237             || !delete_file
238             || (lck->delete_token == NULL)) {
239                 TALLOC_FREE(lck);
240                 return NT_STATUS_OK;
241         }
242
243         /*
244          * Ok, we have to delete the file
245          */
246
247         DEBUG(5,("close_remove_share_mode: file %s. Delete on close was set "
248                  "- deleting file.\n", fsp->fsp_name));
249
250         if (!unix_token_equal(lck->delete_token, &current_user.ut)) {
251                 /* Become the user who requested the delete. */
252
253                 DEBUG(5,("close_remove_share_mode: file %s. "
254                         "Change user to uid %u\n",
255                         fsp->fsp_name,
256                         (unsigned int)lck->delete_token->uid));
257
258                 if (!push_sec_ctx()) {
259                         smb_panic("close_remove_share_mode: file %s. failed to push "
260                                   "sec_ctx.\n");
261                 }
262
263                 set_sec_ctx(lck->delete_token->uid,
264                             lck->delete_token->gid,
265                             lck->delete_token->ngroups,
266                             lck->delete_token->groups,
267                             NULL);
268
269                 changed_user = true;
270         }
271
272         /* We can only delete the file if the name we have is still valid and
273            hasn't been renamed. */
274
275         if (fsp->posix_open) {
276                 ret = SMB_VFS_LSTAT(conn,fsp->fsp_name,&sbuf);
277         } else {
278                 ret = SMB_VFS_STAT(conn,fsp->fsp_name,&sbuf);
279         }
280
281         if (ret != 0) {
282                 DEBUG(5,("close_remove_share_mode: file %s. Delete on close "
283                          "was set and stat failed with error %s\n",
284                          fsp->fsp_name, strerror(errno) ));
285                 /*
286                  * Don't save the errno here, we ignore this error
287                  */
288                 goto done;
289         }
290
291         id = vfs_file_id_from_sbuf(conn, &sbuf);
292
293         if (!file_id_equal(&fsp->file_id, &id)) {
294                 DEBUG(5,("close_remove_share_mode: file %s. Delete on close "
295                          "was set and dev and/or inode does not match\n",
296                          fsp->fsp_name ));
297                 DEBUG(5,("close_remove_share_mode: file %s. stored file_id %s, "
298                          "stat file_id %s\n",
299                          fsp->fsp_name,
300                          file_id_string_tos(&fsp->file_id),
301                          file_id_string_tos(&id)));
302                 /*
303                  * Don't save the errno here, we ignore this error
304                  */
305                 goto done;
306         }
307
308         if (SMB_VFS_UNLINK(conn,fsp->fsp_name) != 0) {
309                 /*
310                  * This call can potentially fail as another smbd may
311                  * have had the file open with delete on close set and
312                  * deleted it when its last reference to this file
313                  * went away. Hence we log this but not at debug level
314                  * zero.
315                  */
316
317                 DEBUG(5,("close_remove_share_mode: file %s. Delete on close "
318                          "was set and unlink failed with error %s\n",
319                          fsp->fsp_name, strerror(errno) ));
320
321                 status = map_nt_error_from_unix(errno);
322         }
323
324         notify_fname(conn, NOTIFY_ACTION_REMOVED,
325                      FILE_NOTIFY_CHANGE_FILE_NAME,
326                      fsp->fsp_name);
327
328         /* As we now have POSIX opens which can unlink
329          * with other open files we may have taken
330          * this code path with more than one share mode
331          * entry - ensure we only delete once by resetting
332          * the delete on close flag. JRA.
333          */
334
335         set_delete_on_close_lck(lck, False, NULL);
336
337  done:
338
339         if (changed_user) {
340                 /* unbecome user. */
341                 pop_sec_ctx();
342         }
343
344         TALLOC_FREE(lck);
345         return status;
346 }
347
348 /****************************************************************************
349  Close a file.
350
351  close_type can be NORMAL_CLOSE=0,SHUTDOWN_CLOSE,ERROR_CLOSE.
352  printing and magic scripts are only run on normal close.
353  delete on close is done on normal and shutdown close.
354 ****************************************************************************/
355
356 static NTSTATUS close_normal_file(files_struct *fsp, enum file_close_type close_type)
357 {
358         NTSTATUS status = NT_STATUS_OK;
359         NTSTATUS saved_status1 = NT_STATUS_OK;
360         NTSTATUS saved_status2 = NT_STATUS_OK;
361         NTSTATUS saved_status3 = NT_STATUS_OK;
362         connection_struct *conn = fsp->conn;
363
364         if (fsp->aio_write_behind) {
365                 /*
366                  * If we're finishing write behind on a close we can get a write
367                  * error here, we must remember this.
368                  */
369                 int ret = wait_for_aio_completion(fsp);
370                 if (ret) {
371                         saved_status1 = map_nt_error_from_unix(ret);
372                 }
373         } else {
374                 cancel_aio_by_fsp(fsp);
375         }
376  
377         /*
378          * If we're flushing on a close we can get a write
379          * error here, we must remember this.
380          */
381
382         saved_status2 = close_filestruct(fsp);
383
384         if (fsp->print_file) {
385                 print_fsp_end(fsp, close_type);
386                 file_free(fsp);
387                 return NT_STATUS_OK;
388         }
389
390         /* If this is an old DOS or FCB open and we have multiple opens on
391            the same handle we only have one share mode. Ensure we only remove
392            the share mode on the last close. */
393
394         if (fsp->fh->ref_count == 1) {
395                 /* Should we return on error here... ? */
396                 saved_status3 = close_remove_share_mode(fsp, close_type);
397         }
398
399         if(fsp->oplock_type) {
400                 release_file_oplock(fsp);
401         }
402
403         locking_close_file(smbd_messaging_context(), fsp);
404
405         status = fd_close(fsp);
406
407         /* check for magic scripts */
408         if (close_type == NORMAL_CLOSE) {
409                 check_magic(fsp);
410         }
411
412         /*
413          * Ensure pending modtime is set after close.
414          */
415
416         if (fsp->pending_modtime_owner && !null_timespec(fsp->pending_modtime)) {
417                 set_filetime(conn, fsp->fsp_name, fsp->pending_modtime);
418         } else if (!null_timespec(fsp->last_write_time)) {
419                 set_filetime(conn, fsp->fsp_name, fsp->last_write_time);
420         }
421
422         if (NT_STATUS_IS_OK(status)) {
423                 if (!NT_STATUS_IS_OK(saved_status1)) {
424                         status = saved_status1;
425                 } else if (!NT_STATUS_IS_OK(saved_status2)) {
426                         status = saved_status2;
427                 } else if (!NT_STATUS_IS_OK(saved_status3)) {
428                         status = saved_status3;
429                 }
430         }
431
432         DEBUG(2,("%s closed file %s (numopen=%d) %s\n",
433                 conn->user,fsp->fsp_name,
434                 conn->num_files_open,
435                 nt_errstr(status) ));
436
437         file_free(fsp);
438         return status;
439 }
440
441 /****************************************************************************
442  Close a directory opened by an NT SMB call. 
443 ****************************************************************************/
444   
445 static NTSTATUS close_directory(files_struct *fsp, enum file_close_type close_type)
446 {
447         struct share_mode_lock *lck = 0;
448         bool delete_dir = False;
449         NTSTATUS status = NT_STATUS_OK;
450
451         /*
452          * NT can set delete_on_close of the last open
453          * reference to a directory also.
454          */
455
456         lck = get_share_mode_lock(talloc_tos(), fsp->file_id, NULL, NULL);
457
458         if (lck == NULL) {
459                 DEBUG(0, ("close_directory: Could not get share mode lock for %s\n", fsp->fsp_name));
460                 return NT_STATUS_INVALID_PARAMETER;
461         }
462
463         if (!del_share_mode(lck, fsp)) {
464                 DEBUG(0, ("close_directory: Could not delete share entry for %s\n", fsp->fsp_name));
465         }
466
467         if (fsp->initial_delete_on_close) {
468                 bool became_user = False;
469
470                 /* Initial delete on close was set - for
471                  * directories we don't care if anyone else
472                  * wrote a real delete on close. */
473
474                 if (current_user.vuid != fsp->vuid) {
475                         become_user(fsp->conn, fsp->vuid);
476                         became_user = True;
477                 }
478                 send_stat_cache_delete_message(fsp->fsp_name);
479                 set_delete_on_close_lck(lck, True, &current_user.ut);
480                 if (became_user) {
481                         unbecome_user();
482                 }
483         }
484
485         delete_dir = lck->delete_on_close;
486
487         if (delete_dir) {
488                 int i;
489                 /* See if others still have the dir open. If this is the
490                  * case, then don't delete. If all opens are POSIX delete now. */
491                 for (i=0; i<lck->num_share_modes; i++) {
492                         struct share_mode_entry *e = &lck->share_modes[i];
493                         if (is_valid_share_mode_entry(e)) {
494                                 if (fsp->posix_open && (e->flags & SHARE_MODE_FLAG_POSIX_OPEN)) {
495                                         continue;
496                                 }
497                                 delete_dir = False;
498                                 break;
499                         }
500                 }
501         }
502
503         if ((close_type == NORMAL_CLOSE || close_type == SHUTDOWN_CLOSE) &&
504                                 delete_dir &&
505                                 lck->delete_token) {
506         
507                 /* Become the user who requested the delete. */
508
509                 if (!push_sec_ctx()) {
510                         smb_panic("close_directory: failed to push sec_ctx.\n");
511                 }
512
513                 set_sec_ctx(lck->delete_token->uid,
514                                 lck->delete_token->gid,
515                                 lck->delete_token->ngroups,
516                                 lck->delete_token->groups,
517                                 NULL);
518
519                 TALLOC_FREE(lck);
520
521                 status = rmdir_internals(talloc_tos(),
522                                 fsp->conn, fsp->fsp_name);
523
524                 DEBUG(5,("close_directory: %s. Delete on close was set - "
525                          "deleting directory returned %s.\n",
526                          fsp->fsp_name, nt_errstr(status)));
527
528                 /* unbecome user. */
529                 pop_sec_ctx();
530
531                 /*
532                  * Ensure we remove any change notify requests that would
533                  * now fail as the directory has been deleted.
534                  */
535
536                 if(NT_STATUS_IS_OK(status)) {
537                         remove_pending_change_notify_requests_by_fid(fsp, NT_STATUS_DELETE_PENDING);
538                 }
539         } else {
540                 TALLOC_FREE(lck);
541                 remove_pending_change_notify_requests_by_fid(
542                         fsp, NT_STATUS_OK);
543         }
544
545         /*
546          * Do the code common to files and directories.
547          */
548         close_filestruct(fsp);
549         file_free(fsp);
550         return status;
551 }
552
553 /****************************************************************************
554  Close a 'stat file' opened internally.
555 ****************************************************************************/
556   
557 static NTSTATUS close_stat(files_struct *fsp)
558 {
559         /*
560          * Do the code common to files and directories.
561          */
562         close_filestruct(fsp);
563         file_free(fsp);
564         return NT_STATUS_OK;
565 }
566
567 /****************************************************************************
568  Close a files_struct.
569 ****************************************************************************/
570   
571 NTSTATUS close_file(files_struct *fsp, enum file_close_type close_type)
572 {
573         if(fsp->is_directory) {
574                 return close_directory(fsp, close_type);
575         } else if (fsp->is_stat) {
576                 return close_stat(fsp);
577         } else if (fsp->fake_file_handle != NULL) {
578                 return close_fake_file(fsp);
579         }
580         return close_normal_file(fsp, close_type);
581 }