dlls: Assorted spelling fixes.
[wine] / dlls / shell32 / trash.c
1 /*
2  * The freedesktop.org Trash, implemented using the 0.7 spec version
3  * (see http://www.ramendik.ru/docs/trashspec.html)
4  *
5  * Copyright (C) 2006 Mikolaj Zalewski
6  * Copyright 2011 Jay Yang
7  *
8  * This library is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Lesser General Public
10  * License as published by the Free Software Foundation; either
11  * version 2.1 of the License, or (at your option) any later version.
12  *
13  * This library 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 GNU
16  * Lesser General Public License for more details.
17  *
18  * You should have received a copy of the GNU Lesser General Public
19  * License along with this library; if not, write to the Free Software
20  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
21  */
22
23 #include "config.h"
24
25 #include <stdarg.h>
26 #ifdef HAVE_SYS_STAT_H
27 # include <sys/stat.h>
28 #endif
29 #include <sys/types.h>
30 #include <stdlib.h>
31 #ifdef HAVE_UNISTD_H
32 # include <unistd.h>
33 #endif
34 #ifdef HAVE_DIRENT_H
35 # include <dirent.h>
36 #endif
37
38 #include "windef.h"
39 #include "winbase.h"
40 #include "winerror.h"
41 #include "winreg.h"
42 #include "shlwapi.h"
43 #include "winternl.h"
44
45 #include <stdio.h>
46 #include <fcntl.h>
47 #include <errno.h>
48 #include <time.h>
49 #include "wine/debug.h"
50 #include "shell32_main.h"
51 #include "xdg.h"
52
53 WINE_DEFAULT_DEBUG_CHANNEL(trash);
54
55 static CRITICAL_SECTION TRASH_Creating;
56 static CRITICAL_SECTION_DEBUG TRASH_Creating_Debug =
57 {
58     0, 0, &TRASH_Creating,
59     { &TRASH_Creating_Debug.ProcessLocksList,
60       &TRASH_Creating_Debug.ProcessLocksList},
61     0, 0, { (DWORD_PTR)__FILE__ ": TRASH_Creating"}
62 };
63 static CRITICAL_SECTION TRASH_Creating = { &TRASH_Creating_Debug, -1, 0, 0, 0, 0 };
64
65 static const char trashinfo_suffix[] = ".trashinfo";
66 static const char trashinfo_header[] = "[Trash Info]\n";
67 static const char trashinfo_group[] = "Trash Info";
68
69 typedef struct
70 {
71     char *info_dir;
72     char *files_dir;
73     dev_t device;
74 } TRASH_BUCKET;
75
76 static TRASH_BUCKET *home_trash=NULL;
77
78 static char *init_home_dir(const char *subpath)
79 {
80     char *path = XDG_BuildPath(XDG_DATA_HOME, subpath);
81     if (path == NULL) return NULL;
82     if (!XDG_MakeDirs(path))
83     {
84         ERR("Couldn't create directory %s (errno=%d). Trash won't be available\n", debugstr_a(path), errno);
85         SHFree(path);
86         path=NULL;
87     }
88     return path;
89 }
90
91 static TRASH_BUCKET *TRASH_CreateHomeBucket(void)
92 {
93     TRASH_BUCKET *bucket;
94     struct stat trash_stat;
95     char *trash_path = NULL;
96     
97     bucket = SHAlloc(sizeof(TRASH_BUCKET));
98     if (bucket == NULL)
99     {
100         errno = ENOMEM;
101         goto error;
102     }
103     memset(bucket, 0, sizeof(*bucket));
104     bucket->info_dir = init_home_dir("Trash/info/");
105     if (bucket->info_dir == NULL) goto error;
106     bucket->files_dir = init_home_dir("Trash/files/");
107     if (bucket->files_dir == NULL) goto error;
108     
109     trash_path = XDG_BuildPath(XDG_DATA_HOME, "Trash/");
110     if (stat(trash_path, &trash_stat) == -1)
111         goto error;
112     bucket->device = trash_stat.st_dev;
113     SHFree(trash_path);
114     return bucket;
115 error:
116     SHFree(trash_path);
117     if (bucket)
118     {
119         SHFree(bucket->info_dir);
120         SHFree(bucket->files_dir);
121     }
122     SHFree(bucket);
123     return NULL;
124 }
125
126 static BOOL TRASH_EnsureInitialized(void)
127 {
128     if (home_trash == NULL)
129     {
130         EnterCriticalSection(&TRASH_Creating);
131         if (home_trash == NULL)
132             home_trash = TRASH_CreateHomeBucket();
133         LeaveCriticalSection(&TRASH_Creating);
134     }
135
136     if (home_trash == NULL)
137     {
138         ERR("Couldn't initialize home trash (errno=%d)\n", errno);
139         return FALSE;
140     }
141     return TRUE;
142 }
143
144 static BOOL file_good_for_bucket(const TRASH_BUCKET *pBucket, const struct stat *file_stat)
145 {
146     if (pBucket->device != file_stat->st_dev)
147         return FALSE;
148     return TRUE;
149 }
150
151 BOOL TRASH_CanTrashFile(LPCWSTR wszPath)
152 {
153     struct stat file_stat;
154     char *unix_path;
155     
156     TRACE("(%s)\n", debugstr_w(wszPath));
157     if (!TRASH_EnsureInitialized()) return FALSE;
158     if (!(unix_path = wine_get_unix_file_name(wszPath)))
159         return FALSE;
160     if (lstat(unix_path, &file_stat)==-1)
161     {
162         HeapFree(GetProcessHeap(), 0, unix_path);
163         return FALSE;
164     }
165     HeapFree(GetProcessHeap(), 0, unix_path);
166     return file_good_for_bucket(home_trash, &file_stat);
167 }
168
169 /*
170  * Try to create a single .trashinfo file. Return TRUE if successful, else FALSE
171  */
172 static BOOL try_create_trashinfo_file(const char *info_dir, const char *file_name,
173     const char *original_file_name)
174 {
175     SYSTEMTIME curr_time;
176     char datebuf[200];
177     char *path = SHAlloc(strlen(info_dir)+strlen(file_name)+strlen(trashinfo_suffix)+1);
178     int writer = -1;
179     
180     if (path==NULL) return FALSE;
181     wsprintfA(path, "%s%s%s", info_dir, file_name, trashinfo_suffix);
182     TRACE("Trying to create '%s'\n", path);
183     writer = open(path, O_CREAT|O_WRONLY|O_TRUNC|O_EXCL, 0600);
184     if (writer==-1) goto error;
185     
186     write(writer, trashinfo_header, strlen(trashinfo_header));
187     if (!XDG_WriteDesktopStringEntry(writer, "Path", XDG_URLENCODE, original_file_name))
188         goto error;
189
190     GetLocalTime( &curr_time );
191     wnsprintfA(datebuf, 200, "%04d-%02d-%02dT%02d:%02d:%02d",
192                curr_time.wYear, curr_time.wMonth, curr_time.wDay,
193                curr_time.wHour, curr_time.wMinute, curr_time.wSecond);
194     if (!XDG_WriteDesktopStringEntry(writer, "DeletionDate", 0, datebuf))
195         goto error;
196     close(writer);
197     SHFree(path);
198     return TRUE;
199
200 error:
201     if (writer != -1)
202     {
203         close(writer);
204         unlink(path);
205     }
206     SHFree(path);
207     return FALSE;
208 }
209
210 /*
211  * Try to create a .trashinfo file. This function will make several attempts with
212  * different filenames. It will return the filename that succeeded or NULL if a file
213  * couldn't be created.
214  */
215 static char *create_trashinfo(const char *info_dir, const char *file_path)
216 {
217     const char *base_name;
218     char *filename_buffer;
219     ULONG seed = GetTickCount();
220     int i;
221
222     errno = ENOMEM;       /* out-of-memory is the only case when errno isn't set */
223     base_name = strrchr(file_path, '/');
224     if (base_name == NULL)
225         base_name = file_path;
226     else
227         base_name++;
228
229     filename_buffer = SHAlloc(strlen(base_name)+9+1);
230     if (filename_buffer == NULL)
231         return NULL;
232     lstrcpyA(filename_buffer, base_name);
233     if (try_create_trashinfo_file(info_dir, filename_buffer, file_path))
234         return filename_buffer;
235     for (i=0; i<30; i++)
236     {
237         sprintf(filename_buffer, "%s-%d", base_name, i+1);
238         if (try_create_trashinfo_file(info_dir, filename_buffer, file_path))
239             return filename_buffer;
240     }
241     
242     for (i=0; i<1000; i++)
243     {
244         sprintf(filename_buffer, "%s-%08x", base_name, RtlRandom(&seed));
245         if (try_create_trashinfo_file(info_dir, filename_buffer, file_path))
246             return filename_buffer;
247     }
248     
249     WARN("Couldn't create trashinfo after 1031 tries (errno=%d)\n", errno);
250     SHFree(filename_buffer);
251     return NULL;
252 }
253
254 static void remove_trashinfo_file(const char *info_dir, const char *base_name)
255 {
256     char *filename_buffer;
257     
258     filename_buffer = SHAlloc(lstrlenA(info_dir)+lstrlenA(base_name)+lstrlenA(trashinfo_suffix)+1);
259     if (filename_buffer == NULL) return;
260     sprintf(filename_buffer, "%s%s%s", info_dir, base_name, trashinfo_suffix);
261     unlink(filename_buffer);
262     SHFree(filename_buffer);
263 }
264
265 static BOOL TRASH_MoveFileToBucket(TRASH_BUCKET *pBucket, const char *unix_path)
266 {
267     struct stat file_stat;
268     char *trash_file_name = NULL;
269     char *trash_path = NULL;
270     BOOL ret = TRUE;
271
272     if (lstat(unix_path, &file_stat)==-1)
273         return FALSE;
274     if (!file_good_for_bucket(pBucket, &file_stat))
275         return FALSE;
276         
277     trash_file_name = create_trashinfo(pBucket->info_dir, unix_path);
278     if (trash_file_name == NULL)
279         return FALSE;
280         
281     trash_path = SHAlloc(strlen(pBucket->files_dir)+strlen(trash_file_name)+1);
282     if (trash_path == NULL) goto error;
283     lstrcpyA(trash_path, pBucket->files_dir);
284     lstrcatA(trash_path, trash_file_name);
285     
286     if (rename(unix_path, trash_path)==0)
287     {
288         TRACE("rename succeeded\n");
289         goto cleanup;
290     }
291     
292     /* TODO: try to manually move the file */
293     ERR("Couldn't move file\n");
294 error:
295     ret = FALSE;
296     remove_trashinfo_file(pBucket->info_dir, trash_file_name);
297 cleanup:
298     SHFree(trash_file_name);
299     SHFree(trash_path);
300     return ret;
301 }
302
303 BOOL TRASH_TrashFile(LPCWSTR wszPath)
304 {
305     char *unix_path;
306     BOOL result;
307     
308     TRACE("(%s)\n", debugstr_w(wszPath));
309     if (!TRASH_EnsureInitialized()) return FALSE;
310     if (!(unix_path = wine_get_unix_file_name(wszPath)))
311         return FALSE;
312     result = TRASH_MoveFileToBucket(home_trash, unix_path);
313     HeapFree(GetProcessHeap(), 0, unix_path);
314     return result;
315 }
316
317 /*
318  * The item ID of a trashed element is built as follows:
319  *  NUL byte                    - in most PIDLs the first byte is the type so we keep it constant
320  *  WIN32_FIND_DATAW structure  - with data about original file attributes
321  *  bucket name                 - currently only an empty string meaning the home bucket is supported
322  *  trash file name             - a NUL-terminated string
323  */
324 static HRESULT TRASH_CreateSimplePIDL(LPCSTR filename, const WIN32_FIND_DATAW *data, LPITEMIDLIST *pidlOut)
325 {
326     LPITEMIDLIST pidl = SHAlloc(2+1+sizeof(WIN32_FIND_DATAW)+1+lstrlenA(filename)+1+2);
327     *pidlOut = NULL;
328     if (pidl == NULL)
329         return E_OUTOFMEMORY;
330     pidl->mkid.cb = (USHORT)(2+1+sizeof(WIN32_FIND_DATAW)+1+lstrlenA(filename)+1);
331     pidl->mkid.abID[0] = 0;
332     memcpy(pidl->mkid.abID+1, data, sizeof(WIN32_FIND_DATAW));
333     pidl->mkid.abID[1+sizeof(WIN32_FIND_DATAW)] = 0;
334     lstrcpyA((LPSTR)(pidl->mkid.abID+1+sizeof(WIN32_FIND_DATAW)+1), filename);
335     *(USHORT *)(pidl->mkid.abID+1+sizeof(WIN32_FIND_DATAW)+1+lstrlenA(filename)+1) = 0;
336     *pidlOut = pidl;
337     return S_OK;
338 }
339
340 /***********************************************************************
341  *      TRASH_UnpackItemID [Internal]
342  *
343  * DESCRIPTION:
344  * Extract the information stored in an Item ID. The WIN32_FIND_DATA contains
345  * the information about the original file. The data->ftLastAccessTime contains
346  * the deletion time
347  *
348  * PARAMETER(S):
349  * [I] id : the ID of the item
350  * [O] data : the WIN32_FIND_DATA of the original file. Can be NULL is not needed
351  */                 
352 HRESULT TRASH_UnpackItemID(LPCSHITEMID id, WIN32_FIND_DATAW *data)
353 {
354     if (id->cb < 2+1+sizeof(WIN32_FIND_DATAW)+2)
355         return E_INVALIDARG;
356     if (id->abID[0] != 0 || id->abID[1+sizeof(WIN32_FIND_DATAW)] != 0)
357         return E_INVALIDARG;
358     if (memchr(id->abID+1+sizeof(WIN32_FIND_DATAW)+1, 0, id->cb-(2+1+sizeof(WIN32_FIND_DATAW)+1)) == NULL)
359         return E_INVALIDARG;
360
361     if (data != NULL)
362         *data = *(const WIN32_FIND_DATAW *)(id->abID+1);
363     return S_OK;
364 }
365
366 static HRESULT TRASH_GetDetails(const TRASH_BUCKET *bucket, LPCSTR filename, WIN32_FIND_DATAW *data)
367 {
368     LPSTR path = NULL;
369     XDG_PARSED_FILE *parsed = NULL;
370     char *original_file_name = NULL;
371     char *deletion_date = NULL;
372     int fd = -1;
373     struct stat stats;
374     HRESULT ret = S_FALSE;
375     LPWSTR original_dos_name;
376     int suffix_length = lstrlenA(trashinfo_suffix);
377     int filename_length = lstrlenA(filename);
378     int files_length = lstrlenA(bucket->files_dir);
379     int path_length = max(lstrlenA(bucket->info_dir), files_length);
380     
381     path = SHAlloc(path_length + filename_length + 1);
382     if (path == NULL) return E_OUTOFMEMORY;
383     wsprintfA(path, "%s%s", bucket->files_dir, filename);
384     path[path_length + filename_length - suffix_length] = 0;  /* remove the '.trashinfo' */    
385     if (lstat(path, &stats) == -1)
386     {
387         ERR("Error accessing data file for trashinfo %s (errno=%d)\n", filename, errno);
388         goto failed;
389     }
390     
391     wsprintfA(path, "%s%s", bucket->info_dir, filename);
392     fd = open(path, O_RDONLY);
393     if (fd == -1)
394     {
395         ERR("Couldn't open trashinfo file %s (errno=%d)\n", path, errno);
396         goto failed;
397     }
398     
399     parsed = XDG_ParseDesktopFile(fd);
400     if (parsed == NULL)
401     {
402         ERR("Parse error in trashinfo file %s\n", path);
403         goto failed;
404     }
405     
406     original_file_name = XDG_GetStringValue(parsed, trashinfo_group, "Path", XDG_URLENCODE);
407     if (original_file_name == NULL)
408     {
409         ERR("No 'Path' entry in trashinfo file\n");
410         goto failed;
411     }
412     
413     ZeroMemory(data, sizeof(*data));
414     data->nFileSizeHigh = (DWORD)((LONGLONG)stats.st_size>>32);
415     data->nFileSizeLow = stats.st_size & 0xffffffff;
416     RtlSecondsSince1970ToTime(stats.st_mtime, (LARGE_INTEGER *)&data->ftLastWriteTime);
417     
418     original_dos_name = wine_get_dos_file_name(original_file_name);
419     if (original_dos_name != NULL)
420     {
421         lstrcpynW(data->cFileName, original_dos_name, MAX_PATH);
422         SHFree(original_dos_name);
423     }
424     else
425     {
426         /* show only the file name */
427         char *file = strrchr(original_file_name, '/');
428         if (file == NULL)
429             file = original_file_name;
430         MultiByteToWideChar(CP_UNIXCP, 0, file, -1, data->cFileName, MAX_PATH);
431     }
432     
433     deletion_date = XDG_GetStringValue(parsed, trashinfo_group, "DeletionDate", 0);
434     if (deletion_date)
435     {
436         struct tm del_time;
437         time_t del_secs;
438         
439         sscanf(deletion_date, "%d-%d-%dT%d:%d:%d",
440             &del_time.tm_year, &del_time.tm_mon, &del_time.tm_mday,
441             &del_time.tm_hour, &del_time.tm_min, &del_time.tm_sec);
442         del_time.tm_year -= 1900;
443         del_time.tm_mon--;
444         del_secs = mktime(&del_time);
445         
446         RtlSecondsSince1970ToTime(del_secs, (LARGE_INTEGER *)&data->ftLastAccessTime);
447     }
448     
449     ret = S_OK;
450 failed:
451     SHFree(path);
452     SHFree(original_file_name);
453     SHFree(deletion_date);
454     if (fd != -1)
455         close(fd);
456     XDG_FreeParsedFile(parsed);
457     return ret;
458 }
459
460 static INT CALLBACK free_item_callback(void *item, void *lParam)
461 {
462     SHFree(item);
463     return TRUE;
464 }
465
466 static HDPA enum_bucket_trashinfos(const TRASH_BUCKET *bucket, int *count)
467 {
468     HDPA ret = DPA_Create(32);
469     struct dirent *entry;
470     DIR *dir = NULL;
471     
472     errno = ENOMEM;
473     *count = 0;
474     if (ret == NULL) goto failed;
475     dir = opendir(bucket->info_dir);
476     if (dir == NULL) goto failed;
477     while ((entry = readdir(dir)) != NULL)
478     {
479         LPSTR filename;
480         int namelen = lstrlenA(entry->d_name);
481         int suffixlen = lstrlenA(trashinfo_suffix);
482         if (namelen <= suffixlen ||
483                 lstrcmpA(entry->d_name+namelen-suffixlen, trashinfo_suffix) != 0)
484             continue;
485
486         filename = StrDupA(entry->d_name);
487         if (filename == NULL)
488             goto failed;
489         if (DPA_InsertPtr(ret, DPA_APPEND, filename) == -1)
490         {
491             SHFree(filename);
492             goto failed;
493         }
494         (*count)++;
495     }
496     closedir(dir);
497     return ret;
498 failed:
499     if (dir) closedir(dir);
500     if (ret)
501         DPA_DestroyCallback(ret, free_item_callback, NULL);
502     return NULL;
503 }
504
505 HRESULT TRASH_EnumItems(LPITEMIDLIST **pidls, int *count)
506 {
507     int ti_count;
508     int pos=0, i;
509     HRESULT err = E_OUTOFMEMORY;
510     HDPA tinfs;
511     
512     if (!TRASH_EnsureInitialized()) return E_FAIL;
513     tinfs = enum_bucket_trashinfos(home_trash, &ti_count);
514     if (tinfs == NULL) return E_FAIL;
515     *pidls = SHAlloc(sizeof(LPITEMIDLIST)*ti_count);
516     if (!*pidls) goto failed;
517     for (i=0; i<ti_count; i++)
518     {
519         WIN32_FIND_DATAW data;
520         LPCSTR filename;
521         
522         filename = DPA_GetPtr(tinfs, i);
523         if (FAILED(err = TRASH_GetDetails(home_trash, filename, &data)))
524             goto failed;
525         if (err == S_FALSE)
526             continue;
527         if (FAILED(err = TRASH_CreateSimplePIDL(filename, &data, &(*pidls)[pos])))
528             goto failed;
529         pos++;
530     }
531     *count = pos;
532     DPA_DestroyCallback(tinfs, free_item_callback, NULL);
533     return S_OK;
534 failed:
535     if (*pidls != NULL)
536     {
537         int j;
538         for (j=0; j<pos; j++)
539             SHFree((*pidls)[j]);
540         SHFree(*pidls);
541     }
542     DPA_DestroyCallback(tinfs, free_item_callback, NULL);
543     
544     return err;
545 }
546
547 HRESULT TRASH_RestoreItem(LPCITEMIDLIST pidl){
548     int suffix_length = strlen(trashinfo_suffix);
549     LPCSHITEMID id = &(pidl->mkid);
550     const char *bucket_name = (const char*)(id->abID+1+sizeof(WIN32_FIND_DATAW));
551     const char *filename = (const char*)(id->abID+1+sizeof(WIN32_FIND_DATAW)+strlen(bucket_name)+1);
552     char *restore_path;
553     WIN32_FIND_DATAW data;
554     char *file_path;
555
556     TRACE("(%p)\n",pidl);
557     if(strcmp(filename+strlen(filename)-suffix_length,trashinfo_suffix))
558     {
559         ERR("pidl at %p is not a valid recycle bin entry\n",pidl);
560         return E_INVALIDARG;
561     }
562     TRASH_UnpackItemID(id,&data);
563     restore_path = wine_get_unix_file_name(data.cFileName);
564     file_path = SHAlloc(max(strlen(home_trash->files_dir),strlen(home_trash->info_dir))+strlen(filename)+1);
565     sprintf(file_path,"%s%s",home_trash->files_dir,filename);
566     file_path[strlen(home_trash->files_dir)+strlen(filename)-suffix_length] = '\0';
567     if(!rename(file_path,restore_path))
568     {
569             sprintf(file_path,"%s%s",home_trash->info_dir,filename);
570             if(unlink(file_path))
571                 WARN("failed to delete the trashinfo file %s\n",filename);
572     }
573     else
574         WARN("could not erase %s from the trash (errno=%i)\n",filename,errno);
575     SHFree(file_path);
576     HeapFree(GetProcessHeap(), 0, restore_path);
577     return S_OK;
578 }
579
580 HRESULT TRASH_EraseItem(LPCITEMIDLIST pidl)
581 {
582     int suffix_length = strlen(trashinfo_suffix);
583
584     LPCSHITEMID id = &(pidl->mkid);
585     const char *bucket_name = (const char*)(id->abID+1+sizeof(WIN32_FIND_DATAW));
586     const char *filename = (const char*)(id->abID+1+sizeof(WIN32_FIND_DATAW)+strlen(bucket_name)+1);
587     char *file_path;
588
589     TRACE("(%p)\n",pidl);
590     if(strcmp(filename+strlen(filename)-suffix_length,trashinfo_suffix))
591     {
592         ERR("pidl at %p is not a valid recycle bin entry\n",pidl);
593         return E_INVALIDARG;
594     }
595     file_path = SHAlloc(max(strlen(home_trash->files_dir),strlen(home_trash->info_dir))+strlen(filename)+1);
596     sprintf(file_path,"%s%s",home_trash->info_dir,filename);
597     if(unlink(file_path))
598         WARN("failed to delete the trashinfo file %s\n",filename);
599     sprintf(file_path,"%s%s",home_trash->files_dir,filename);
600     file_path[strlen(home_trash->files_dir)+strlen(filename)-suffix_length] = '\0';
601     if(unlink(file_path))
602         WARN("could not erase %s from the trash (errno=%i)\n",filename,errno);
603     SHFree(file_path);
604     return S_OK;
605 }