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