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