Patch from Stephan Metzmacher to add default arguments to lp_parm() smb.conf
[ira/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 *mem_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 typedef struct recycle_bin_connections {
52         int conn;
53         recycle_bin_struct *data;
54         struct recycle_bin_connections *next;
55 } recycle_bin_connections;
56
57 typedef struct recycle_bin_private_data {
58         TALLOC_CTX *mem_ctx;
59         recycle_bin_connections *conns;
60 } recycle_bin_private_data;
61
62 struct smb_vfs_handle_struct *recycle_bin_private_handle;
63
64 /* VFS operations */
65 static struct vfs_ops default_vfs_ops;   /* For passthrough operation */
66
67 static int recycle_connect(struct connection_struct *conn, const char *service, const char *user);
68 static void recycle_disconnect(struct connection_struct *conn);
69 static int recycle_unlink(connection_struct *, const char *);
70
71 #define VFS_OP(x) ((void *) x)
72
73 static vfs_op_tuple recycle_ops[] = {
74
75         /* Disk operations */
76         {VFS_OP(recycle_connect),       SMB_VFS_OP_CONNECT,     SMB_VFS_LAYER_TRANSPARENT},
77         {VFS_OP(recycle_disconnect),    SMB_VFS_OP_DISCONNECT,  SMB_VFS_LAYER_TRANSPARENT},
78
79         /* File operations */
80         {VFS_OP(recycle_unlink),        SMB_VFS_OP_UNLINK,      SMB_VFS_LAYER_TRANSPARENT},
81
82         {NULL,                          SMB_VFS_OP_NOOP,        SMB_VFS_LAYER_NOOP}
83 };
84
85 /**
86  * VFS initialisation function.
87  *
88  * @retval initialised vfs_op_tuple array
89  **/
90 static vfs_op_tuple *recycle_init(const struct vfs_ops *def_vfs_ops,
91                         struct smb_vfs_handle_struct *vfs_handle)
92 {
93         TALLOC_CTX *mem_ctx = NULL;
94
95         DEBUG(10, ("Initializing VFS module recycle\n"));
96         memcpy(&default_vfs_ops, def_vfs_ops, sizeof(struct vfs_ops));
97         vfs_recycle_debug_level = debug_add_class("vfs_recycle_bin");
98         if (vfs_recycle_debug_level == -1) {
99                 vfs_recycle_debug_level = DBGC_VFS;
100                 DEBUG(0, ("vfs_recycle: Couldn't register custom debugging class!\n"));
101         } else {
102                 DEBUG(0, ("vfs_recycle: Debug class number of 'vfs_recycle': %d\n", vfs_recycle_debug_level));
103         }
104
105         recycle_bin_private_handle = vfs_handle;
106         if (!(mem_ctx = talloc_init("recycle bin data"))) {
107                 DEBUG(0, ("Failed to allocate memory in VFS module recycle_bin\n"));
108                 return NULL;
109         }
110
111         recycle_bin_private_handle->data = talloc(mem_ctx, sizeof(recycle_bin_private_data));
112         if (recycle_bin_private_handle->data == NULL) {
113                 DEBUG(0, ("Failed to allocate memory in VFS module recycle_bin\n"));
114                 return NULL;
115         }
116         ((recycle_bin_private_data *)(recycle_bin_private_handle->data))->mem_ctx = mem_ctx;
117         ((recycle_bin_private_data *)(recycle_bin_private_handle->data))->conns = NULL;
118
119         return recycle_ops;
120 }
121
122 static int recycle_connect(struct connection_struct *conn, const char *service, const char *user)
123 {
124         TALLOC_CTX *ctx = NULL;
125         recycle_bin_struct *recbin;
126         recycle_bin_connections *recconn;
127         recycle_bin_connections *recconnbase;
128         recycle_bin_private_data *recdata;
129         const char *tmp_str;
130
131         DEBUG(10, ("Called for service %s (%d) as user %s\n", service, SNUM(conn), user));
132
133         if (recycle_bin_private_handle)
134                 recdata = (recycle_bin_private_data *)(recycle_bin_private_handle->data);
135         else {
136                 DEBUG(0, ("Recycle bin not initialized!\n"));
137                 return -1;
138         }
139
140         if (!(ctx = talloc_init("recycle bin connection"))) {
141                 DEBUG(0, ("Failed to allocate memory in VFS module recycle_bin\n"));
142                 return -1;
143         }
144
145         recbin = talloc_zero(ctx, sizeof(recycle_bin_struct));
146         if (recbin == NULL) {
147                 DEBUG(0, ("Failed to allocate memory in VFS module recycle_bin\n"));
148                 return -1;
149         }
150         recbin->mem_ctx = ctx;
151
152         /* parse configuration options */
153         if ((tmp_str = lp_parm_const_string(SNUM(conn), "vfs_recycle_bin", "repository", ".recycle")) != NULL) {
154                 recbin->repository = talloc_sub_conn(recbin->mem_ctx, conn, tmp_str);
155                 ALLOC_CHECK(recbin->repository, error);
156                 trim_string(recbin->repository, "/", "/");
157                 DEBUG(5, ("recycle.bin: repository = %s\n", recbin->repository));
158         } else {
159                 DEBUG(0,("recycle.bin: no repository found (fail) !\n"));
160                 goto error;
161         }
162         
163         recbin->keep_dir_tree = lp_parm_bool(SNUM(conn), "vfs_recycle_bin", "keeptree", False);
164         DEBUG(5, ("recycle.bin: keeptree = %d\n", recbin->keep_dir_tree));
165         
166         recbin->versions = lp_parm_bool(SNUM(conn), "vfs_recycle_bin", "versions", False);
167         DEBUG(5, ("recycle.bin: versions = %d\n", recbin->versions));
168         
169         recbin->touch = lp_parm_bool(SNUM(conn), "vfs_recycle_bin", "touch", False);
170         DEBUG(5, ("recycle.bin: touch = %d\n", recbin->touch));
171
172         recbin->maxsize = lp_parm_ulong(SNUM(conn), "vfs_recycle_bin", "maxsize" , 0);
173         if (recbin->maxsize == 0) {
174                 recbin->maxsize = -1;
175                 DEBUG(5, ("recycle.bin: maxsize = -infinite-\n"));
176         } else {
177                 DEBUG(5, ("recycle.bin: maxsize = %ld\n", (long int)recbin->maxsize));
178         }
179
180         if ((tmp_str = lp_parm_const_string(SNUM(conn), "vfs_recycle_bin", "exclude", "")) != NULL) {
181                 recbin->exclude = talloc_strdup(recbin->mem_ctx, tmp_str);
182                 ALLOC_CHECK(recbin->exclude, error);
183                 DEBUG(5, ("recycle.bin: exclude = %s\n", recbin->exclude));
184         }
185         if ((tmp_str = lp_parm_const_string(SNUM(conn), "vfs_recycle_bin", "exclude_dir", "")) != NULL) {
186                 recbin->exclude_dir = talloc_strdup(recbin->mem_ctx, tmp_str);
187                 ALLOC_CHECK(recbin->exclude_dir, error);
188                 DEBUG(5, ("recycle.bin: exclude_dir = %s\n", recbin->exclude_dir));
189         }
190         if ((tmp_str = lp_parm_const_string(SNUM(conn), "vfs_recycle_bin", "noversions", "")) != NULL) {
191                 recbin->noversions = talloc_strdup(recbin->mem_ctx, tmp_str);
192                 ALLOC_CHECK(recbin->noversions, error);
193                 DEBUG(5, ("recycle.bin: noversions = %s\n", recbin->noversions));
194         }
195
196         recconn = talloc(recdata->mem_ctx, sizeof(recycle_bin_connections));
197         if (recconn == NULL) {
198                 DEBUG(0, ("Failed to allocate memory in VFS module recycle_bin\n"));
199                 goto error;
200         }
201         recconn->conn = SNUM(conn);
202         recconn->data = recbin;
203         recconn->next = NULL;
204         if (recdata->conns) {
205                 recconnbase = recdata->conns;
206                 while (recconnbase->next != NULL) recconnbase = recconnbase->next;
207                 recconnbase->next = recconn;
208         } else {
209                 recdata->conns = recconn;
210         }
211         return default_vfs_ops.connect(conn, service, user);
212
213 error:
214         talloc_destroy(ctx);
215         return -1;
216 }
217
218 static void recycle_disconnect(struct connection_struct *conn)
219 {
220         recycle_bin_private_data *recdata;
221         recycle_bin_connections *recconn;
222
223         DEBUG(10, ("Disconnecting VFS module recycle bin\n"));
224
225         if (recycle_bin_private_handle)
226                 recdata = (recycle_bin_private_data *)(recycle_bin_private_handle->data);
227         else {
228                 DEBUG(0, ("Recycle bin not initialized!\n"));
229                 return;
230         }
231
232         if (recdata) {
233                 if (recdata->conns) {
234                         if (recdata->conns->conn == SNUM(conn)) {
235                                 talloc_destroy(recdata->conns->data->mem_ctx);
236                                 recdata->conns = recdata->conns->next;
237                         } else {
238                                 recconn = recdata->conns;
239                                 while (recconn->next) {
240                                         if (recconn->next->conn == SNUM(conn)) {
241                                                 talloc_destroy(recconn->next->data->mem_ctx);
242                                                 recconn->next = recconn->next->next;
243                                                 break;
244                                         }
245                                         recconn = recconn->next;
246                                 }
247                         }
248                 }
249         }
250         default_vfs_ops.disconnect(conn);
251 }
252
253 static BOOL recycle_directory_exist(connection_struct *conn, const char *dname)
254 {
255         SMB_STRUCT_STAT st;
256
257         if (default_vfs_ops.stat(conn, dname, &st) == 0) {
258                 if (S_ISDIR(st.st_mode)) {
259                         return True;
260                 }
261         }
262
263         return False;
264 }
265
266 static BOOL recycle_file_exist(connection_struct *conn, const char *fname)
267 {
268         SMB_STRUCT_STAT st;
269
270         if (default_vfs_ops.stat(conn, fname, &st) == 0) {
271                 if (S_ISREG(st.st_mode)) {
272                         return True;
273                 }
274         }
275
276         return False;
277 }
278
279 /**
280  * Return file size
281  * @param conn connection
282  * @param fname file name
283  * @return size in bytes
284  **/
285 static SMB_OFF_T recycle_get_file_size(connection_struct *conn, const char *fname)
286 {
287         SMB_STRUCT_STAT st;
288         if (default_vfs_ops.stat(conn, fname, &st) != 0) {
289                 DEBUG(0,("recycle.bin: stat for %s returned %s\n", fname, strerror(errno)));
290                 return (SMB_OFF_T)0;
291         }
292         return(st.st_size);
293 }
294
295 /**
296  * Create directory tree
297  * @param conn connection
298  * @param dname Directory tree to be created
299  * @return Returns True for success
300  **/
301 static BOOL recycle_create_dir(connection_struct *conn, const char *dname)
302 {
303         int len;
304         mode_t mode;
305         char *new_dir = NULL;
306         char *tmp_str = NULL;
307         char *token;
308         char *tok_str;
309         BOOL ret = False;
310
311         mode = S_IREAD | S_IWRITE | S_IEXEC;
312
313         tmp_str = strdup(dname);
314         ALLOC_CHECK(tmp_str, done);
315         tok_str = tmp_str;
316
317         len = strlen(dname);
318         new_dir = (char *)malloc(len + 1);
319         ALLOC_CHECK(new_dir, done);
320         *new_dir = '\0';
321
322         /* Create directory tree if neccessary */
323         for(token = strtok(tok_str, "/"); token; token = strtok(NULL, "/")) {
324                 safe_strcat(new_dir, token, len);
325                 if (recycle_directory_exist(conn, new_dir))
326                         DEBUG(10, ("recycle.bin: dir %s already exists\n", new_dir));
327                 else {
328                         DEBUG(5, ("recycle.bin: creating new dir %s\n", new_dir));
329                         if (default_vfs_ops.mkdir(conn, new_dir, mode) != 0) {
330                                 DEBUG(1,("recycle.bin: mkdir failed for %s with error: %s\n", new_dir, strerror(errno)));
331                                 ret = False;
332                                 goto done;
333                         }
334                 }
335                 safe_strcat(new_dir, "/", len);
336                 }
337
338         ret = True;
339 done:
340         SAFE_FREE(tmp_str);
341         SAFE_FREE(new_dir);
342         return ret;
343 }
344
345 /**
346  * Check if needle is contained exactly in haystack
347  * @param haystack list of parameters separated by delimimiter character
348  * @param needle string to be matched exactly to haystack
349  * @return True if found
350  **/
351 static BOOL checkparam(const char *haystack, const char *needle)
352 {
353         char *token;
354         char *tok_str;
355         char *tmp_str;
356         BOOL ret = False;
357
358         if (haystack == NULL || strlen(haystack) == 0 || needle == NULL || strlen(needle) == 0) {
359                 return False;
360         }
361
362         tmp_str = strdup(haystack);
363         ALLOC_CHECK(tmp_str, done);
364         token = tok_str = tmp_str;
365
366         for(token = strtok(tok_str, delimiter); token; token = strtok(NULL, delimiter)) {
367                 if(strcmp(token, needle) == 0) {
368                         ret = True;
369                         goto done;
370                 }
371         }
372 done:
373         SAFE_FREE(tmp_str);
374         return ret;
375 }
376
377 /**
378  * Check if needle is contained in haystack, * and ? patterns are resolved
379  * @param haystack list of parameters separated by delimimiter character
380  * @param needle string to be matched exectly to haystack including pattern matching
381  * @return True if found
382  **/
383 static BOOL matchparam(const char *haystack, const char *needle)
384 {
385         char *token;
386         char *tok_str;
387         char *tmp_str;
388         BOOL ret = False;
389
390         if (haystack == NULL || strlen(haystack) == 0 || needle == NULL || strlen(needle) == 0) {
391                 return False;
392         }
393
394         tmp_str = strdup(haystack);
395         ALLOC_CHECK(tmp_str, done);
396         token = tok_str = tmp_str;
397
398         for(token = strtok(tok_str, delimiter); token; token = strtok(NULL, delimiter)) {
399                 if (!unix_wild_match(token, needle)) {
400                         ret = True;
401                         goto done;
402                 }
403         }
404 done:
405         SAFE_FREE(tmp_str);
406         return ret;
407 }
408
409 /**
410  * Touch access date
411  **/
412 static void recycle_touch(connection_struct *conn, const char *fname)
413 {
414         SMB_STRUCT_STAT st;
415         struct utimbuf tb;
416         time_t currtime;
417
418         if (default_vfs_ops.stat(conn, fname, &st) != 0) {
419                 DEBUG(0,("recycle.bin: stat for %s returned %s\n", fname, strerror(errno)));
420                 return;
421         }
422         currtime = time(&currtime);
423         tb.actime = currtime;
424         tb.modtime = st.st_mtime;
425
426         if (default_vfs_ops.utime(conn, fname, &tb) == -1 )
427                 DEBUG(0, ("recycle.bin: touching %s failed, reason = %s\n", fname, strerror(errno)));
428         }
429
430 /**
431  * Check if file should be recycled
432  **/
433 static int recycle_unlink(connection_struct *conn, const char *file_name)
434 {
435         recycle_bin_private_data *recdata;
436         recycle_bin_connections *recconn;
437         recycle_bin_struct *recbin;
438         char *path_name = NULL;
439         char *temp_name = NULL;
440         char *final_name = NULL;
441         const char *base;
442         int i;
443 /*      SMB_BIG_UINT dfree, dsize, bsize;       */
444         SMB_OFF_T file_size; /* space_avail;    */
445         BOOL exist;
446         int rc = -1;
447
448         recbin = NULL;
449         if (recycle_bin_private_handle) {
450                 recdata = (recycle_bin_private_data *)(recycle_bin_private_handle->data);
451                 if (recdata) {
452                         if (recdata->conns) {
453                                 recconn = recdata->conns;
454                                 while (recconn && recconn->conn != SNUM(conn)) recconn = recconn->next;
455                                 if (recconn != NULL) {
456                                         recbin = recconn->data;
457                                 }
458                         }
459                 }
460         }
461         if (recbin == NULL) {
462                 DEBUG(0, ("Recycle bin not initialized!\n"));
463                 rc = default_vfs_ops.unlink(conn, file_name);
464                 goto done;
465         }
466
467         if(!recbin->repository || *(recbin->repository) == '\0') {
468                 DEBUG(3, ("Recycle path not set, purging %s...\n", file_name));
469                 rc = default_vfs_ops.unlink(conn, file_name);
470                 goto done;
471         }
472
473         /* we don't recycle the recycle bin... */
474         if (strncmp(file_name, recbin->repository, strlen(recbin->repository)) == 0) {
475                 DEBUG(3, ("File is within recycling bin, unlinking ...\n"));
476                 rc = default_vfs_ops.unlink(conn, file_name);
477                 goto done;
478         }
479
480         file_size = recycle_get_file_size(conn, file_name);
481         /* it is wrong to purge filenames only because they are empty imho
482          *   --- simo
483          *
484         if(fsize == 0) {
485                 DEBUG(3, ("File %s is empty, purging...\n", file_name));
486                 rc = default_vfs_ops.unlink(conn,file_name);
487                 goto done;
488         }
489          */
490
491         /* FIXME: this is wrong, we should check the hole size of the recycle bin is
492          * not greater then maxsize, not the size of the single file, also it is better
493          * to remove older files
494          */
495         if(recbin->maxsize > 0 && file_size > recbin->maxsize) {
496                 DEBUG(3, ("File %s exceeds maximum recycle size, purging... \n", file_name));
497                 rc = default_vfs_ops.unlink(conn, file_name);
498                 goto done;
499         }
500
501         /* FIXME: this is wrong: moving files with rename does not change the disk space
502          * allocation
503          *
504         space_avail = default_vfs_ops.disk_free(conn, ".", True, &bsize, &dfree, &dsize) * 1024L;
505         DEBUG(5, ("space_avail = %Lu, file_size = %Lu\n", space_avail, file_size));
506         if(space_avail < file_size) {
507                 DEBUG(3, ("Not enough diskspace, purging file %s\n", file_name));
508                 rc = default_vfs_ops.unlink(conn, file_name);
509                 goto done;
510         }
511          */
512
513         /* extract filename and path */
514         base = strrchr(file_name, '/');
515         if (base == NULL) {
516                 base = file_name;
517                 path_name = strdup("/");
518                 ALLOC_CHECK(path_name, done);
519         }
520         else {
521                 path_name = strdup(file_name);
522                 ALLOC_CHECK(path_name, done);
523                 path_name[base - file_name] = '\0';
524                 base++;
525         }
526
527         DEBUG(10, ("recycle.bin: fname = %s\n", file_name));    /* original filename with path */
528         DEBUG(10, ("recycle.bin: fpath = %s\n", path_name));    /* original path */
529         DEBUG(10, ("recycle.bin: base = %s\n", base));          /* filename without path */
530
531         if (matchparam(recbin->exclude, base)) {
532                 DEBUG(3, ("recycle.bin: file %s is excluded \n", base));
533                 rc = default_vfs_ops.unlink(conn, file_name);
534                 goto done;
535         }
536
537         /* FIXME: this check will fail if we have more than one level of directories,
538          * we shoud check for every level 1, 1/2, 1/2/3, 1/2/3/4 .... 
539          *      ---simo
540          */
541         if (checkparam(recbin->exclude_dir, path_name)) {
542                 DEBUG(3, ("recycle.bin: directory %s is excluded \n", path_name));
543                 rc = default_vfs_ops.unlink(conn, file_name);
544                 goto done;
545         }
546
547         /* see if we need to recreate the original directory structure in the recycle bin */
548         if (recbin->keep_dir_tree == True) {
549                 asprintf(&temp_name, "%s/%s", recbin->repository, path_name);
550         } else {
551                 temp_name = strdup(recbin->repository);
552         }
553         ALLOC_CHECK(temp_name, done);
554
555         exist = recycle_directory_exist(conn, temp_name);
556         if (exist) {
557                 DEBUG(10, ("recycle.bin: Directory already exists\n"));
558         } else {
559                 DEBUG(10, ("recycle.bin: Creating directory %s\n", temp_name));
560                 if (recycle_create_dir(conn, temp_name) == False) {
561                         DEBUG(3, ("Could not create directory, purging %s...\n", file_name));
562                         rc = default_vfs_ops.unlink(conn, file_name);
563                         goto done;
564                 }
565         }
566
567         asprintf(&final_name, "%s/%s", temp_name, base);
568         ALLOC_CHECK(final_name, done);
569         DEBUG(10, ("recycle.bin: recycled file name: %s\n", temp_name));                /* new filename with path */
570
571         /* check if we should delete file from recycle bin */
572         if (recycle_file_exist(conn, final_name)) {
573                 if (recbin->versions == False || matchparam(recbin->noversions, base) == True) {
574                         DEBUG(3, ("recycle.bin: Removing old file %s from recycle bin\n", final_name));
575                         if (default_vfs_ops.unlink(conn, final_name) != 0) {
576                                 DEBUG(1, ("recycle.bin: Error deleting old file: %s\n", strerror(errno)));
577                         }
578                 }
579         }
580
581         /* rename file we move to recycle bin */
582         i = 1;
583         while (recycle_file_exist(conn, final_name)) {
584                 snprintf(final_name, PATH_MAX, "%s/Copy #%d of %s", temp_name, i++, base);
585         }
586
587         DEBUG(10, ("recycle.bin: Moving %s to %s\n", file_name, final_name));
588         rc = default_vfs_ops.rename(conn, file_name, final_name);
589         if (rc != 0) {
590                 DEBUG(3, ("recycle.bin: Move error %d (%s), purging file %s (%s)\n", errno, strerror(errno), file_name, final_name));
591                 rc = default_vfs_ops.unlink(conn, file_name);
592                 goto done;
593         }
594
595         /* touch access date of moved file */
596         if (recbin->touch == True )
597                 recycle_touch(conn, final_name);
598
599 done:
600         SAFE_FREE(path_name);
601         SAFE_FREE(temp_name);
602         SAFE_FREE(final_name);
603         return rc;
604 }
605
606 int vfs_recycle_init(void)
607 {
608         return smb_register_vfs("recycle", recycle_init, SMB_VFS_INTERFACE_VERSION);
609 }