ole32: Register the CLSID_Picture_Metafile and CLSID_Picture_Dib ProgIDs.
[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  *
7  * This library is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * This library is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with this library; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
20  */
21
22 #include <stdarg.h>
23 #include <sys/stat.h>
24 #include <sys/types.h>
25 #include <stdlib.h>
26 #include <unistd.h>
27 #include <dirent.h>
28
29 #include "windef.h"
30 #include "winbase.h"
31 #include "winerror.h"
32 #include "winreg.h"
33 #include "shlwapi.h"
34 #include "winternl.h"
35
36 #include <stdio.h>
37 #include <fcntl.h>
38 #include <errno.h>
39 #include <time.h>
40 #include "wine/debug.h"
41 #include "shell32_main.h"
42 #include "xdg.h"
43
44 WINE_DEFAULT_DEBUG_CHANNEL(trash);
45
46 static CRITICAL_SECTION TRASH_Creating;
47 static CRITICAL_SECTION_DEBUG TRASH_Creating_Debug =
48 {
49     0, 0, &TRASH_Creating,
50     { &TRASH_Creating_Debug.ProcessLocksList,
51       &TRASH_Creating_Debug.ProcessLocksList},
52     0, 0, { (DWORD_PTR)__FILE__ ": TRASH_Creating"}
53 };
54 static CRITICAL_SECTION TRASH_Creating = { &TRASH_Creating_Debug, -1, 0, 0, 0, 0 };
55
56 static const char trashinfo_suffix[] = ".trashinfo";
57 static const char trashinfo_header[] = "[Trash Info]\n";
58
59 typedef struct
60 {
61     char *info_dir;
62     char *files_dir;
63     dev_t device;
64 } TRASH_BUCKET;
65
66 static TRASH_BUCKET *home_trash=NULL;
67
68 static char *init_home_dir(const char *subpath)
69 {
70     char *path = XDG_BuildPath(XDG_DATA_HOME, subpath);
71     if (path == NULL) return NULL;
72     if (!XDG_MakeDirs(path))
73     {
74         ERR("Couldn't create directory %s (errno=%d). Trash won't be available\n", debugstr_a(path), errno);
75         SHFree(path);
76         path=NULL;
77     }
78     return path;
79 }
80
81 static TRASH_BUCKET *TRASH_CreateHomeBucket(void)
82 {
83     TRASH_BUCKET *bucket;
84     struct stat trash_stat;
85     char *trash_path = NULL;
86     
87     bucket = SHAlloc(sizeof(TRASH_BUCKET));
88     if (bucket == NULL)
89     {
90         errno = ENOMEM;
91         goto error;
92     }
93     memset(bucket, 0, sizeof(*bucket));
94     bucket->info_dir = init_home_dir("Trash/info/");
95     if (bucket->info_dir == NULL) goto error;
96     bucket->files_dir = init_home_dir("Trash/files/");
97     if (bucket->files_dir == NULL) goto error;
98     
99     trash_path = XDG_BuildPath(XDG_DATA_HOME, "Trash/");
100     if (stat(trash_path, &trash_stat) == -1)
101         goto error;
102     bucket->device = trash_stat.st_dev;
103     SHFree(trash_path);
104     return bucket;
105 error:
106     SHFree(trash_path);
107     if (bucket)
108     {
109         SHFree(bucket->info_dir);
110         SHFree(bucket->files_dir);
111     }
112     SHFree(bucket);
113     return NULL;
114 }
115
116 static BOOL TRASH_EnsureInitialized(void)
117 {
118     if (home_trash == NULL)
119     {
120         EnterCriticalSection(&TRASH_Creating);
121         if (home_trash == NULL)
122             home_trash = TRASH_CreateHomeBucket();
123         LeaveCriticalSection(&TRASH_Creating);
124     }
125
126     if (home_trash == NULL)
127     {
128         ERR("Couldn't initialize home trash (errno=%d)\n", errno);
129         return FALSE;
130     }
131     return TRUE;
132 }
133
134 static BOOL file_good_for_bucket(TRASH_BUCKET *pBucket, struct stat *file_stat)
135 {
136     if (pBucket->device != file_stat->st_dev)
137         return FALSE;
138     return TRUE;
139 }
140
141 BOOL TRASH_CanTrashFile(LPCWSTR wszPath)
142 {
143     struct stat file_stat;
144     char *unix_path;
145     
146     TRACE("(%s)\n", debugstr_w(wszPath));
147     if (!TRASH_EnsureInitialized()) return FALSE;
148     if (!(unix_path = wine_get_unix_file_name(wszPath)))
149         return FALSE;
150     if (lstat(unix_path, &file_stat)==-1)
151     {
152         HeapFree(GetProcessHeap(), 0, unix_path);
153         return FALSE;
154     }
155     HeapFree(GetProcessHeap(), 0, unix_path);
156     return file_good_for_bucket(home_trash, &file_stat);
157 }
158
159 /*
160  * Try to create a single .trashinfo file. Return TRUE if successful, else FALSE
161  */
162 static BOOL try_create_trashinfo_file(const char *info_dir, const char *file_name,
163     const char *original_file_name)
164 {
165     struct tm curr_time;
166     time_t curr_time_secs;
167     char datebuf[200];
168     char *path = SHAlloc(strlen(info_dir)+strlen(file_name)+strlen(trashinfo_suffix)+1);
169     int writer = -1;
170     
171     if (path==NULL) return FALSE;
172     wsprintfA(path, "%s%s%s", info_dir, file_name, trashinfo_suffix);
173     TRACE("Trying to create '%s'\n", path);
174     writer = open(path, O_CREAT|O_WRONLY|O_TRUNC|O_EXCL, 0600);
175     if (writer==-1) goto error;
176     
177     write(writer, trashinfo_header, strlen(trashinfo_header));
178     if (!XDG_WriteDesktopStringEntry(writer, "Path", XDG_URLENCODE, original_file_name))
179         goto error;
180     
181     time(&curr_time_secs);
182     localtime_r(&curr_time_secs, &curr_time);
183     wnsprintfA(datebuf, 200, "%04d-%02d-%02dT%02d:%02d:%02d",
184         curr_time.tm_year+1900,
185         curr_time.tm_mon+1,
186         curr_time.tm_mday,
187         curr_time.tm_hour,
188         curr_time.tm_min,
189         curr_time.tm_sec);
190     if (!XDG_WriteDesktopStringEntry(writer, "DeletionDate", 0, datebuf))
191         goto error;
192     close(writer);
193     SHFree(path);
194     return TRUE;
195
196 error:
197     if (writer != -1)
198     {
199         close(writer);
200         unlink(path);
201     }
202     SHFree(path);
203     return FALSE;
204 }
205
206 /*
207  * Try to create a .trashinfo file. This function will make several attempts with
208  * different filenames. It will return the filename that succeded or NULL if a file
209  * couldn't be created.
210  */
211 static char *create_trashinfo(const char *info_dir, const char *file_path)
212 {
213     const char *base_name;
214     char *filename_buffer;
215     unsigned int seed = (unsigned int)time(NULL);
216     int i;
217
218     errno = ENOMEM;       /* out-of-memory is the only case when errno isn't set */
219     base_name = strrchr(file_path, '/');
220     if (base_name == NULL)
221         base_name = file_path;
222     else
223         base_name++;
224
225     filename_buffer = SHAlloc(strlen(base_name)+9+1);
226     if (filename_buffer == NULL)
227         return NULL;
228     lstrcpyA(filename_buffer, base_name);
229     if (try_create_trashinfo_file(info_dir, filename_buffer, file_path))
230         return filename_buffer;
231     for (i=0; i<30; i++)
232     {
233         sprintf(filename_buffer, "%s-%d", base_name, i+1);
234         if (try_create_trashinfo_file(info_dir, filename_buffer, file_path))
235             return filename_buffer;
236     }
237     
238     for (i=0; i<1000; i++)
239     {
240         sprintf(filename_buffer, "%s-%08x", base_name, rand_r(&seed));
241         if (try_create_trashinfo_file(info_dir, filename_buffer, file_path))
242             return filename_buffer;
243     }
244     
245     WARN("Couldn't create trashinfo after 1031 tries (errno=%d)\n", errno);
246     SHFree(filename_buffer);
247     return NULL;
248 }
249
250 void remove_trashinfo_file(const char *info_dir, const char *base_name)
251 {
252     char *filename_buffer;
253     
254     filename_buffer = SHAlloc(lstrlenA(info_dir)+lstrlenA(base_name)+lstrlenA(trashinfo_suffix)+1);
255     if (filename_buffer == NULL) return;
256     sprintf(filename_buffer, "%s%s%s", info_dir, base_name, trashinfo_suffix);
257     unlink(filename_buffer);
258     SHFree(filename_buffer);
259 }
260
261 static BOOL TRASH_MoveFileToBucket(TRASH_BUCKET *pBucket, const char *unix_path)
262 {
263     struct stat file_stat;
264     char *trash_file_name = NULL;
265     char *trash_path = NULL;
266     BOOL ret = TRUE;
267
268     if (lstat(unix_path, &file_stat)==-1)
269         return FALSE;
270     if (!file_good_for_bucket(pBucket, &file_stat))
271         return FALSE;
272         
273     trash_file_name = create_trashinfo(pBucket->info_dir, unix_path);
274     if (trash_file_name == NULL)
275         return FALSE;
276         
277     trash_path = SHAlloc(strlen(pBucket->files_dir)+strlen(trash_file_name)+1);
278     if (trash_path == NULL) goto error;
279     lstrcpyA(trash_path, pBucket->files_dir);
280     lstrcatA(trash_path, trash_file_name);
281     
282     if (rename(unix_path, trash_path)==0)
283     {
284         TRACE("rename succeded\n");
285         goto cleanup;
286     }
287     
288     /* TODO: try to manually move the file */
289     ERR("Couldn't move file\n");
290 error:
291     ret = FALSE;
292     remove_trashinfo_file(pBucket->info_dir, trash_file_name);
293 cleanup:
294     SHFree(trash_file_name);
295     SHFree(trash_path);
296     return ret;
297 }
298
299 BOOL TRASH_TrashFile(LPCWSTR wszPath)
300 {
301     char *unix_path;
302     BOOL result;
303     
304     TRACE("(%s)\n", debugstr_w(wszPath));
305     if (!TRASH_EnsureInitialized()) return FALSE;
306     if (!(unix_path = wine_get_unix_file_name(wszPath)))
307         return FALSE;
308     result = TRASH_MoveFileToBucket(home_trash, unix_path);
309     HeapFree(GetProcessHeap(), 0, unix_path);
310     return result;
311 }
312
313 /*
314  * The item ID of a trashed element is built as follows:
315  *  NUL byte                    - in most PIDLs the first byte is the type so we keep it constant
316  *  WIN32_FIND_DATAW structure  - with data about original file attributes
317  *  bucket name                 - currently only an empty string meaning the home bucket is supported
318  *  trash file name             - a NUL-terminated string
319  */
320 struct tagTRASH_ELEMENT
321 {
322     TRASH_BUCKET *bucket;
323     LPSTR filename;
324 };
325
326 static HRESULT TRASH_CreateSimplePIDL(const TRASH_ELEMENT *element, const WIN32_FIND_DATAW *data, LPITEMIDLIST *pidlOut)
327 {
328     LPITEMIDLIST pidl = SHAlloc(2+1+sizeof(WIN32_FIND_DATAW)+1+lstrlenA(element->filename)+1+2);
329     *pidlOut = NULL;
330     if (pidl == NULL)
331         return E_OUTOFMEMORY;
332     pidl->mkid.cb = (USHORT)(2+1+sizeof(WIN32_FIND_DATAW)+1+lstrlenA(element->filename)+1);
333     pidl->mkid.abID[0] = 0;
334     memcpy(pidl->mkid.abID+1, data, sizeof(WIN32_FIND_DATAW));
335     pidl->mkid.abID[1+sizeof(WIN32_FIND_DATAW)] = 0;
336     lstrcpyA((LPSTR)(pidl->mkid.abID+1+sizeof(WIN32_FIND_DATAW)+1), element->filename);
337     *(USHORT *)(pidl->mkid.abID+1+sizeof(WIN32_FIND_DATAW)+1+lstrlenA(element->filename)+1) = 0;
338     *pidlOut = pidl;
339     return S_OK;
340 }
341
342 /***********************************************************************
343  *      TRASH_UnpackItemID [Internal]
344  *
345  * DESCRITION:
346  * Extract the information stored in an Item ID. The TRASH_ELEMENT
347  * identifies the element in the Trash. The WIN32_FIND_DATA contains the
348  * information about the original file. The data->ftLastAccessTime contains
349  * the deletion time
350  *
351  * PARAMETER(S):
352  * [I] id : the ID of the item
353  * [O] element : the trash element this item id contains. Can be NULL if not needed
354  * [O] data : the WIN32_FIND_DATA of the original file. Can be NULL is not needed
355  */                 
356 HRESULT TRASH_UnpackItemID(LPCSHITEMID id, TRASH_ELEMENT *element, WIN32_FIND_DATAW *data)
357 {
358     if (id->cb < 2+1+sizeof(WIN32_FIND_DATAW)+2)
359         return E_INVALIDARG;
360     if (id->abID[0] != 0 || id->abID[1+sizeof(WIN32_FIND_DATAW)] != 0)
361         return E_INVALIDARG;
362     if (memchr(id->abID+1+sizeof(WIN32_FIND_DATAW)+1, 0, id->cb-(2+1+sizeof(WIN32_FIND_DATAW)+1)) == NULL)
363         return E_INVALIDARG;
364
365     if (data != NULL)
366         *data = *(WIN32_FIND_DATAW *)(id->abID+1);
367     if (element != NULL)
368     {
369         element->bucket = home_trash;
370         element->filename = StrDupA((LPCSTR)(id->abID+1+sizeof(WIN32_FIND_DATAW)+1));
371         if (element->filename == NULL)
372             return E_OUTOFMEMORY;
373     }
374     return S_OK;
375 }
376
377 void TRASH_DisposeElement(TRASH_ELEMENT *element)
378 {
379     if (element)
380         SHFree(element->filename);
381 }
382
383 HRESULT TRASH_GetDetails(const TRASH_ELEMENT *element, WIN32_FIND_DATAW *data)
384 {
385     LPSTR path;
386     struct stat stats;
387     int suffix_length = lstrlenA(trashinfo_suffix);
388     int filename_length = lstrlenA(element->filename);
389     int path_length = lstrlenA(element->bucket->files_dir);
390     static const WCHAR fmt[] = {'T','O','D','O','\\','(','%','h','s',')',0};
391     
392     path = SHAlloc(path_length + filename_length + 1);
393     if (path == NULL) return E_OUTOFMEMORY;
394     lstrcpyA(path, element->bucket->files_dir);
395     lstrcpyA(path+path_length, element->filename);
396     path[path_length + filename_length - suffix_length] = 0;  /* remove the '.trashinfo' */
397     if (lstat(path, &stats) == -1)
398     {
399         ERR("Error accessing data file for trashinfo %s (errno=%d)\n", element->filename, errno);
400         return S_FALSE;
401     }
402     
403     ZeroMemory(data, sizeof(*data));
404     data->nFileSizeHigh = (DWORD)((LONGLONG)stats.st_size>>32);
405     data->nFileSizeLow = stats.st_size & 0xffffffff;
406     RtlSecondsSince1970ToTime(stats.st_mtime, (LARGE_INTEGER *)&data->ftLastWriteTime);
407     wnsprintfW(data->cFileName, MAX_PATH, fmt, element->filename);
408     return S_OK;
409 }
410
411 INT CALLBACK free_item_callback(void *item, void *lParam)
412 {
413     SHFree(item);
414     return TRUE;
415 }
416
417 static HDPA enum_bucket_trashinfos(TRASH_BUCKET *bucket, int *count)
418 {
419     HDPA ret = DPA_Create(32);
420     struct dirent *entry;
421     DIR *dir = NULL;
422     
423     errno = ENOMEM;
424     *count = 0;
425     if (ret == NULL) goto failed;
426     dir = opendir(bucket->info_dir);
427     if (dir == NULL) goto failed;
428     while ((entry = readdir(dir)) != NULL)
429     {
430         LPSTR filename;
431         int namelen = lstrlenA(entry->d_name);
432         int suffixlen = lstrlenA(trashinfo_suffix);
433         if (namelen <= suffixlen ||
434                 lstrcmpA(entry->d_name+namelen-suffixlen, trashinfo_suffix) != 0)
435             continue;
436
437         filename = StrDupA(entry->d_name);
438         if (filename == NULL)
439             goto failed;
440         if (DPA_InsertPtr(ret, DPA_APPEND, filename) == -1)
441         {
442             SHFree(filename);
443             goto failed;
444         }
445         (*count)++;
446     }
447     closedir(dir);
448     return ret;
449 failed:
450     if (dir) closedir(dir);
451     if (ret)
452         DPA_DestroyCallback(ret, free_item_callback, NULL);
453     return NULL;
454 }
455
456 HRESULT TRASH_EnumItems(LPITEMIDLIST **pidls, int *count)
457 {
458     int ti_count;
459     int pos=0, i;
460     HRESULT err = E_OUTOFMEMORY;
461     HDPA tinfs;
462     
463     if (!TRASH_EnsureInitialized()) return E_FAIL;
464     tinfs = enum_bucket_trashinfos(home_trash, &ti_count);
465     if (tinfs == NULL) return E_FAIL;
466     *pidls = SHAlloc(sizeof(LPITEMIDLIST)*ti_count);
467     if (!*pidls) goto failed;
468     for (i=0; i<ti_count; i++)
469     {
470         WIN32_FIND_DATAW data;
471         TRASH_ELEMENT elem;
472         
473         elem.bucket = home_trash;
474         elem.filename = DPA_GetPtr(tinfs, i);
475         if (FAILED(err = TRASH_GetDetails(&elem, &data)))
476             goto failed;
477         if (err == S_FALSE)
478             continue;
479         if (FAILED(err = TRASH_CreateSimplePIDL(&elem, &data, &(*pidls)[pos])))
480             goto failed;
481         pos++;
482     }
483     *count = pos;
484     DPA_DestroyCallback(tinfs, free_item_callback, NULL);
485     return S_OK;
486 failed:
487     if (*pidls != NULL)
488     {
489         int j;
490         for (j=0; j<pos; j++)
491             SHFree((*pidls)[j]);
492         SHFree(*pidls);
493     }
494     DPA_DestroyCallback(tinfs, free_item_callback, NULL);
495     
496     return err;
497 }