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