This commit was manufactured by cvs2svn to create branch 'SAMBA_3_0'.(This used to...
[metze/samba/wip.git] / source3 / modules / vfs_recycle.c
1 /*
2  * Recycle bin VFS module for Samba.
3  *
4  * Copyright (C) 2001, Brandon Stone, Amherst College, <bbstone@amherst.edu>.
5  * Copyright (C) 2002, Jeremy Allison - modified to make a VFS module.
6  * Copyright (C) 2002, Alexander Bokovoy - cascaded VFS adoption,
7  * Copyright (C) 2002, Juergen Hasch - added some options.
8  * Copyright (C) 2002, Simo Sorce
9  *
10  * This program is free software; you can redistribute it and/or modify
11  * it under the terms of the GNU General Public License as published by
12  * the Free Software Foundation; either version 2 of the License, or
13  * (at your option) any later version.
14  *
15  * This program is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18  * GNU General Public License for more details.
19  *
20  * You should have received a copy of the GNU General Public License
21  * along with this program; if not, write to the Free Software
22  * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
23  */
24
25 #include "includes.h"
26
27 #define ALLOC_CHECK(ptr, label) do { if ((ptr) == NULL) { DEBUG(0, ("recycle.bin: out of memory!\n")); errno = ENOMEM; goto label; } } while(0)
28
29 static int vfs_recycle_debug_level = DBGC_VFS;
30
31 #undef DBGC_CLASS
32 #define DBGC_CLASS vfs_recycle_debug_level
33
34 static const char *delimiter = "|";             /* delimiter for options */
35
36 /* One per connection */
37
38 typedef struct recycle_bin_struct
39 {
40         TALLOC_CTX *ctx;
41         char    *repository;            /* name of the recycle bin directory */
42         BOOL    keep_dir_tree;          /* keep directory structure of deleted file in recycle bin */
43         BOOL    versions;               /* create versions of deleted files with identical name */
44         BOOL    touch;                  /* touch access date of deleted file */
45         char    *exclude;               /* which files to exclude */
46         char    *exclude_dir;           /* which directories to exclude */
47         char    *noversions;            /* which files to exclude from versioning */
48         SMB_OFF_T maxsize;              /* maximum file size to be saved */
49 } recycle_bin_struct;
50
51 /* VFS operations */
52 static struct vfs_ops default_vfs_ops;   /* For passthrough operation */
53
54 static int recycle_connect(struct connection_struct *conn, const char *service, const char *user);
55 static void recycle_disconnect(struct connection_struct *conn);
56 static int recycle_unlink(connection_struct *, const char *);
57
58 #define VFS_OP(x) ((void *) x)
59
60 static vfs_op_tuple recycle_ops[] = {
61
62         /* Disk operations */
63         {VFS_OP(recycle_connect),       SMB_VFS_OP_CONNECT,     SMB_VFS_LAYER_TRANSPARENT},
64         {VFS_OP(recycle_disconnect),    SMB_VFS_OP_DISCONNECT,  SMB_VFS_LAYER_TRANSPARENT},
65
66         /* File operations */
67         {VFS_OP(recycle_unlink),        SMB_VFS_OP_UNLINK,      SMB_VFS_LAYER_TRANSPARENT},
68
69         {NULL,                          SMB_VFS_OP_NOOP,        SMB_VFS_LAYER_NOOP}
70 };
71
72 static BOOL check_bool_param(const char *value)
73 {
74         if (strwicmp(value, "yes") == 0 ||
75             strwicmp(value, "true") == 0 ||
76             strwicmp(value, "1") == 0)
77                 return True;
78
79         return False;
80 }
81
82 /**
83  * VFS initialisation function.
84  *
85  * @retval initialised vfs_op_tuple array
86  **/
87 static vfs_op_tuple *recycle_init(const struct vfs_ops *def_vfs_ops,
88                         struct smb_vfs_handle_struct *vfs_handle)
89 {
90         DEBUG(10, ("Initializing VFS module recycle\n"));
91         memcpy(&default_vfs_ops, def_vfs_ops, sizeof(struct vfs_ops));
92         vfs_recycle_debug_level = debug_add_class("vfs_recycle_bin");
93         if (vfs_recycle_debug_level == -1) {
94                 vfs_recycle_debug_level = DBGC_VFS;
95                 DEBUG(0, ("vfs_recycle: Couldn't register custom debugging class!\n"));
96         } else {
97                 DEBUG(0, ("vfs_recycle: Debug class number of 'vfs_recycle': %d\n", vfs_recycle_debug_level));
98         }
99
100         return recycle_ops;
101 }
102
103 static int recycle_connect(struct connection_struct *conn, const char *service, const char *user)
104 {
105         TALLOC_CTX *ctx = NULL;
106         recycle_bin_struct *recbin;
107         char *servicename;
108         char *tmp_str;
109
110         DEBUG(10, ("Called for service %s (%d) as user %s\n", service, SNUM(conn), user));
111
112         if (!(ctx = talloc_init("recycle bin"))) {
113                 DEBUG(0, ("Failed to allocate memory in VFS module recycle_bin\n"));
114                 return 0;
115         }
116
117         recbin = talloc(ctx,sizeof(recycle_bin_struct));
118         if ( recbin == NULL) {
119                 DEBUG(0, ("Failed to allocate memory in VFS module recycle_bin\n"));
120                 return -1;
121         }
122         recbin->ctx = ctx;
123
124         /* Set defaults */
125         recbin->repository = talloc_strdup(ctx, ".recycle");
126         ALLOC_CHECK(recbin->repository, error);
127         recbin->keep_dir_tree = False;
128         recbin->versions = False;
129         recbin->touch = False;
130         recbin->exclude = "";
131         recbin->exclude_dir = "";
132         recbin->noversions = "";
133         recbin->maxsize = 0;
134
135         /* parse configuration options */
136         servicename = talloc_strdup(recbin->ctx, lp_servicename(SNUM(conn)));
137         DEBUG(10, ("servicename = %s\n",servicename));
138         if ((tmp_str = lp_parm_string(servicename, "vfs_recycle_bin", "repository")) != NULL) {
139                 recbin->repository = talloc_sub_conn(ctx, conn, tmp_str);
140                 ALLOC_CHECK(recbin->repository, error);
141                 trim_string(recbin->repository, "/", "/");
142                 DEBUG(5, ("recycle.bin: repository = %s\n", recbin->repository));
143         }
144         if ((tmp_str = lp_parm_string(servicename, "vfs_recycle_bin", "keeptree")) != NULL) {
145                 if (check_bool_param(tmp_str) == True)
146                         recbin->keep_dir_tree = True;
147                 DEBUG(5, ("recycle.bin: keeptree = %s\n", tmp_str));
148         }
149         if ((tmp_str = lp_parm_string(servicename, "vfs_recycle_bin", "versions")) != NULL) {
150                 if (check_bool_param(tmp_str) == True)
151                         recbin->versions = True;
152                 DEBUG(5, ("recycle.bin: versions = %s\n", tmp_str));
153         }
154         if ((tmp_str = lp_parm_string(servicename, "vfs_recycle_bin", "touch")) != NULL) {
155                 if (check_bool_param(tmp_str) == True)
156                         recbin->touch = True;
157                 DEBUG(5, ("recycle.bin: touch = %s\n", tmp_str));
158         }
159         if ((tmp_str = lp_parm_string(servicename, "vfs_recycle_bin", "maxsize")) != NULL) {
160                 recbin->maxsize = strtoul(tmp_str, NULL, 10);
161                 if (recbin->maxsize == 0) {
162                         recbin->maxsize = -1;
163                         DEBUG(5, ("recycle.bin: maxsize = -infinite-\n"));
164                 } else {
165                         DEBUG(5, ("recycle.bin: maxsize = %ld\n", (long int)recbin->maxsize));
166                 }
167         }
168         if ((tmp_str = lp_parm_string(servicename, "vfs_recycle_bin", "exclude")) != NULL) {
169                 recbin->exclude = talloc_strdup(ctx, tmp_str);
170                 ALLOC_CHECK(recbin->exclude, error);
171                 DEBUG(5, ("recycle.bin: exclude = %s\n", recbin->exclude));
172         }
173         if ((tmp_str = lp_parm_string(servicename,"vfs_recycle_bin", "exclude_dir")) != NULL) {
174                 recbin->exclude_dir = talloc_strdup(ctx, tmp_str);
175                 ALLOC_CHECK(recbin->exclude_dir, error);
176                 DEBUG(5, ("recycle.bin: exclude_dir = %s\n", recbin->exclude_dir));
177         }
178         if ((tmp_str = lp_parm_string(servicename,"vfs_recycle_bin", "noversions")) != NULL) {
179                 recbin->noversions = talloc_strdup(ctx, tmp_str);
180                 ALLOC_CHECK(recbin->noversions, error);
181                 DEBUG(5, ("recycle.bin: noversions = %s\n", recbin->noversions));
182         }
183
184         conn->vfs_private = (void *)recbin;
185         return default_vfs_ops.connect(conn, service, user);
186
187 error:
188         talloc_destroy(ctx);
189         return -1;
190 }
191
192 static void recycle_disconnect(struct connection_struct *conn)
193 {
194         DEBUG(10, ("Disconnecting VFS module recycle bin\n"));
195         if (conn->vfs_private) {
196                 talloc_destroy(((recycle_bin_struct *)conn->vfs_private)->ctx);
197                 conn->vfs_private = NULL;
198         }
199         default_vfs_ops.disconnect(conn);
200 }
201
202 static BOOL recycle_directory_exist(connection_struct *conn, const char *dname)
203 {
204         SMB_STRUCT_STAT st;
205
206         if (default_vfs_ops.stat(conn, dname, &st) == 0) {
207                 if (S_ISDIR(st.st_mode)) {
208                         return True;
209                 }
210         }
211
212         return False;
213 }
214
215 static BOOL recycle_file_exist(connection_struct *conn, const char *fname)
216 {
217         SMB_STRUCT_STAT st;
218
219         if (default_vfs_ops.stat(conn, fname, &st) == 0) {
220                 if (S_ISREG(st.st_mode)) {
221                         return True;
222                 }
223         }
224
225         return False;
226 }
227
228 /**
229  * Return file size
230  * @param conn connection
231  * @param fname file name
232  * @return size in bytes
233  **/
234 static SMB_OFF_T recycle_get_file_size(connection_struct *conn, const char *fname)
235 {
236         SMB_STRUCT_STAT st;
237         if (default_vfs_ops.stat(conn, fname, &st) != 0) {
238                 DEBUG(0,("recycle.bin: stat for %s returned %s\n", fname, strerror(errno)));
239                 return (SMB_OFF_T)0;
240         }
241         return(st.st_size);
242 }
243
244 /**
245  * Create directory tree
246  * @param conn connection
247  * @param dname Directory tree to be created
248  * @return Returns True for success
249  **/
250 static BOOL recycle_create_dir(connection_struct *conn, const char *dname)
251 {
252         int len;
253         mode_t mode;
254         char *new_dir = NULL;
255         char *tmp_str = NULL;
256         char *token;
257         char *tok_str;
258         BOOL ret = False;
259
260         mode = S_IREAD | S_IWRITE | S_IEXEC;
261
262         tmp_str = strdup(dname);
263         ALLOC_CHECK(tmp_str, done);
264         tok_str = tmp_str;
265
266         len = strlen(dname);
267         new_dir = (char *)malloc(len + 1);
268         ALLOC_CHECK(new_dir, done);
269         *new_dir = '\0';
270
271         /* Create directory tree if neccessary */
272         for(token = strtok(tok_str, "/"); token; token = strtok(NULL, "/")) {
273                 safe_strcat(new_dir, token, len);
274                 if (recycle_directory_exist(conn, new_dir))
275                         DEBUG(10, ("recycle.bin: dir %s already exists\n", new_dir));
276                 else {
277                         DEBUG(5, ("recycle.bin: creating new dir %s\n", new_dir));
278                         if (default_vfs_ops.mkdir(conn, new_dir, mode) != 0) {
279                                 DEBUG(1,("recycle.bin: mkdir failed for %s with error: %s\n", new_dir, strerror(errno)));
280                                 ret = False;
281                                 goto done;
282                         }
283                 }
284                 safe_strcat(new_dir, "/", len);
285                 }
286
287         ret = True;
288 done:
289         SAFE_FREE(tmp_str);
290         SAFE_FREE(new_dir);
291         return ret;
292 }
293
294 /**
295  * Check if needle is contained exactly in haystack
296  * @param haystack list of parameters separated by delimimiter character
297  * @param needle string to be matched exactly to haystack
298  * @return True if found
299  **/
300 static BOOL checkparam(const char *haystack, const char *needle)
301 {
302         char *token;
303         char *tok_str;
304         char *tmp_str;
305         BOOL ret = False;
306
307         if (haystack == NULL || strlen(haystack) == 0 || needle == NULL || strlen(needle) == 0) {
308                 return False;
309         }
310
311         tmp_str = strdup(haystack);
312         ALLOC_CHECK(tmp_str, done);
313         token = tok_str = tmp_str;
314
315         for(token = strtok(tok_str, delimiter); token; token = strtok(NULL, delimiter)) {
316                 if(strcmp(token, needle) == 0) {
317                         ret = True;
318                         goto done;
319                 }
320         }
321 done:
322         SAFE_FREE(tmp_str);
323         return ret;
324 }
325
326 /**
327  * Check if needle is contained in haystack, * and ? patterns are resolved
328  * @param haystack list of parameters separated by delimimiter character
329  * @param needle string to be matched exectly to haystack including pattern matching
330  * @return True if found
331  **/
332 static BOOL matchparam(const char *haystack, const char *needle)
333 {
334         char *token;
335         char *tok_str;
336         char *tmp_str;
337         BOOL ret = False;
338
339         if (haystack == NULL || strlen(haystack) == 0 || needle == NULL || strlen(needle) == 0) {
340                 return False;
341         }
342
343         tmp_str = strdup(haystack);
344         ALLOC_CHECK(tmp_str, done);
345         token = tok_str = tmp_str;
346
347         for(token = strtok(tok_str, delimiter); token; token = strtok(NULL, delimiter)) {
348                 if (!unix_wild_match(token, needle)) {
349                         ret = True;
350                         goto done;
351                 }
352         }
353 done:
354         SAFE_FREE(tmp_str);
355         return ret;
356 }
357
358 /**
359  * Touch access date
360  **/
361 static void recycle_touch(connection_struct *conn, const char *fname)
362 {
363         SMB_STRUCT_STAT st;
364         struct utimbuf tb;
365         time_t currtime;
366
367         if (default_vfs_ops.stat(conn, fname, &st) != 0) {
368                 DEBUG(0,("recycle.bin: stat for %s returned %s\n", fname, strerror(errno)));
369                 return;
370         }
371         currtime = time(&currtime);
372         tb.actime = currtime;
373         tb.modtime = st.st_mtime;
374
375         if (default_vfs_ops.utime(conn, fname, &tb) == -1 )
376                 DEBUG(0, ("recycle.bin: touching %s failed, reason = %s\n", fname, strerror(errno)));
377         }
378
379 /**
380  * Check if file should be recycled
381  **/
382 static int recycle_unlink(connection_struct *conn, const char *inname)
383 {
384         recycle_bin_struct *recbin;
385         char *file_name = NULL;
386         char *path_name = NULL;
387         char *temp_name = NULL;
388         char *final_name = NULL;
389         char *base;
390         int i;
391         SMB_BIG_UINT dfree, dsize, bsize;
392         SMB_OFF_T file_size, space_avail;
393         BOOL exist;
394         int rc = -1;
395
396         file_name = strdup(inname);
397         ALLOC_CHECK(file_name, done);
398
399         if (conn->vfs_private)
400                 recbin = (recycle_bin_struct *)conn->vfs_private;
401         else {
402                 DEBUG(0, ("Recycle bin not initialized!\n"));
403                 rc = default_vfs_ops.unlink(conn, file_name);
404                 goto done;
405         }
406
407         if(!recbin->repository || *(recbin->repository) == '\0') {
408                 DEBUG(3, ("Recycle path not set, purging %s...\n", file_name));
409                 rc = default_vfs_ops.unlink(conn, file_name);
410                 goto done;
411         }
412
413         /* we don't recycle the recycle bin... */
414         if (strncmp(file_name, recbin->repository, strlen(recbin->repository)) == 0) {
415                 DEBUG(3, ("File is within recycling bin, unlinking ...\n"));
416                 rc = default_vfs_ops.unlink(conn, file_name);
417                 goto done;
418         }
419
420         file_size = recycle_get_file_size(conn, file_name);
421         /* it is wrong to purge filenames only because they are empty imho
422          *   --- simo
423          *
424         if(fsize == 0) {
425                 DEBUG(3, ("File %s is empty, purging...\n", file_name));
426                 rc = default_vfs_ops.unlink(conn,file_name);
427                 goto done;
428         }
429          */
430
431         /* FIXME: this is wrong, we should check the hole size of the recycle bin is
432          * not greater then maxsize, not the size of the single file, also it is better
433          * to remove older files
434          */
435         if(recbin->maxsize > 0 && file_size > recbin->maxsize) {
436                 DEBUG(3, ("File %s exceeds maximum recycle size, purging... \n", file_name));
437                 rc = default_vfs_ops.unlink(conn, file_name);
438                 goto done;
439         }
440
441         /* FIXME: this is wrong: moving files with rename does not change the disk space
442          * allocation
443          *
444         space_avail = default_vfs_ops.disk_free(conn, ".", True, &bsize, &dfree, &dsize) * 1024L;
445         DEBUG(5, ("space_avail = %Lu, file_size = %Lu\n", space_avail, file_size));
446         if(space_avail < file_size) {
447                 DEBUG(3, ("Not enough diskspace, purging file %s\n", file_name));
448                 rc = default_vfs_ops.unlink(conn, file_name);
449                 goto done;
450         }
451          */
452
453         /* extract filename and path */
454         base = strrchr(file_name, '/');
455         if (base == NULL) {
456                 base = file_name;
457                 path_name = strdup("/");
458                 ALLOC_CHECK(path_name, done);
459         }
460         else {
461                 path_name = strdup(file_name);
462                 ALLOC_CHECK(path_name, done);
463                 path_name[base - file_name] = '\0';
464                 base++;
465         }
466
467         DEBUG(10, ("recycle.bin: fname = %s\n", file_name));    /* original filename with path */
468         DEBUG(10, ("recycle.bin: fpath = %s\n", path_name));    /* original path */
469         DEBUG(10, ("recycle.bin: base = %s\n", base));          /* filename without path */
470
471         if (matchparam(recbin->exclude, base)) {
472                 DEBUG(3, ("recycle.bin: file %s is excluded \n", base));
473                 rc = default_vfs_ops.unlink(conn, file_name);
474                 goto done;
475         }
476
477         /* FIXME: this check will fail if we have more than one level of directories,
478          * we shoud check for every level 1, 1/2, 1/2/3, 1/2/3/4 .... 
479          *      ---simo
480          */
481         if (checkparam(recbin->exclude_dir, path_name)) {
482                 DEBUG(3, ("recycle.bin: directory %s is excluded \n", path_name));
483                 rc = default_vfs_ops.unlink(conn, file_name);
484                 goto done;
485         }
486
487         /* see if we need to recreate the original directory structure in the recycle bin */
488         if (recbin->keep_dir_tree == True) {
489                 asprintf(&temp_name, "%s/%s", recbin->repository, path_name);
490         } else {
491                 temp_name = strdup(recbin->repository);
492         }
493         ALLOC_CHECK(temp_name, done);
494
495         exist = recycle_directory_exist(conn, temp_name);
496         if (exist) {
497                 DEBUG(10, ("recycle.bin: Directory already exists\n"));
498         } else {
499                 DEBUG(10, ("recycle.bin: Creating directory %s\n", temp_name));
500                 if (recycle_create_dir(conn, temp_name) == False) {
501                         DEBUG(3, ("Could not create directory, purging %s...\n", file_name));
502                         rc = default_vfs_ops.unlink(conn, file_name);
503                         goto done;
504                 }
505         }
506
507         final_name = (char *)malloc(PATH_MAX);
508         ALLOC_CHECK(final_name, done);
509         snprintf(final_name, PATH_MAX, "%s/%s", temp_name, base);
510         DEBUG(10, ("recycle.bin: recycled file name%s\n", temp_name));          /* new filename with path */
511
512         /* check if we should delete file from recycle bin */
513         if (recycle_file_exist(conn, final_name)) {
514                 if (recbin->versions == False || matchparam(recbin->noversions, base) == True) {
515                         DEBUG(3, ("recycle.bin: Removing old file %s from recycle bin\n", final_name));
516                         if (default_vfs_ops.unlink(conn, final_name) != 0) {
517                                 DEBUG(1, ("recycle.bin: Error deleting old file: %s\n", strerror(errno)));
518                         }
519                 }
520         }
521
522         /* rename file we move to recycle bin */
523         i = 1;
524         while (recycle_file_exist(conn, final_name)) {
525                 snprintf(final_name, PATH_MAX, "%s/Copy #%d of %s", temp_name, i++, base);
526         }
527
528         DEBUG(10, ("recycle.bin: Moving %s to %s\n", file_name, final_name));
529         rc = default_vfs_ops.rename(conn, file_name, final_name);
530         if (rc != 0) {
531                 DEBUG(3, ("recycle.bin: Move error %d (%s), purging file %s (%s)\n", errno, strerror(errno), file_name, final_name));
532                 rc = default_vfs_ops.unlink(conn, file_name);
533                 goto done;
534         }
535
536         /* touch access date of moved file */
537         if (recbin->touch == True )
538                 recycle_touch(conn, final_name);
539
540 done:
541         SAFE_FREE(file_name);
542         SAFE_FREE(path_name);
543         SAFE_FREE(temp_name);
544         SAFE_FREE(final_name);
545         return rc;
546 }
547
548 int vfs_recycle_init(void)
549 {  
550    return smb_register_vfs("recycle", recycle_init, SMB_VFS_INTERFACE_VERSION);
551 }