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