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