2 * The freedesktop.org Trash, implemented using the 0.7 spec version
3 * (see http://www.ramendik.ru/docs/trashspec.html)
5 * Copyright (C) 2006 Mikolaj Zalewski
6 * Copyright 2011 Jay Yang
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.
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.
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
25 #ifdef HAVE_CORESERVICES_CORESERVICES_H
26 #define GetCurrentThread MacGetCurrentThread
27 #define LoadResource MacLoadResource
28 #include <CoreServices/CoreServices.h>
29 #undef GetCurrentThread
39 #ifdef HAVE_SYS_STAT_H
40 # include <sys/stat.h>
42 #include <sys/types.h>
57 #include "wine/debug.h"
58 #include "shell32_main.h"
61 WINE_DEFAULT_DEBUG_CHANNEL(trash);
63 #ifdef HAVE_CORESERVICES_CORESERVICES_H
65 BOOL TRASH_CanTrashFile(LPCWSTR wszPath)
70 FSCatalogInfo catalogInfo;
72 TRACE("(%s)\n", debugstr_w(wszPath));
73 if (!(unix_path = wine_get_unix_file_name(wszPath)))
76 status = FSPathMakeRef((UInt8*)unix_path, &ref, NULL);
77 HeapFree(GetProcessHeap(), 0, unix_path);
79 status = FSGetCatalogInfo(&ref, kFSCatInfoVolume, &catalogInfo, NULL,
82 status = FSFindFolder(catalogInfo.volume, kTrashFolderType,
85 return (status == noErr);
88 BOOL TRASH_TrashFile(LPCWSTR wszPath)
93 TRACE("(%s)\n", debugstr_w(wszPath));
94 if (!(unix_path = wine_get_unix_file_name(wszPath)))
97 status = FSPathMoveObjectToTrashSync(unix_path, NULL, kFSFileOperationSkipPreflight);
99 HeapFree(GetProcessHeap(), 0, unix_path);
100 return (status == noErr);
103 HRESULT TRASH_EnumItems(LPITEMIDLIST **pidls, int *count)
109 HRESULT TRASH_UnpackItemID(LPCSHITEMID id, WIN32_FIND_DATAW *data)
115 HRESULT TRASH_RestoreItem(LPCITEMIDLIST pidl)
121 HRESULT TRASH_EraseItem(LPCITEMIDLIST pidl)
127 #else /* HAVE_CORESERVICES_CORESERVICES_H */
129 static CRITICAL_SECTION TRASH_Creating;
130 static CRITICAL_SECTION_DEBUG TRASH_Creating_Debug =
132 0, 0, &TRASH_Creating,
133 { &TRASH_Creating_Debug.ProcessLocksList,
134 &TRASH_Creating_Debug.ProcessLocksList},
135 0, 0, { (DWORD_PTR)__FILE__ ": TRASH_Creating"}
137 static CRITICAL_SECTION TRASH_Creating = { &TRASH_Creating_Debug, -1, 0, 0, 0, 0 };
139 static const char trashinfo_suffix[] = ".trashinfo";
140 static const char trashinfo_header[] = "[Trash Info]\n";
141 static const char trashinfo_group[] = "Trash Info";
150 static TRASH_BUCKET *home_trash=NULL;
152 static char *init_home_dir(const char *subpath)
154 char *path = XDG_BuildPath(XDG_DATA_HOME, subpath);
155 if (path == NULL) return NULL;
156 if (!XDG_MakeDirs(path))
158 ERR("Couldn't create directory %s (errno=%d). Trash won't be available\n", debugstr_a(path), errno);
165 static TRASH_BUCKET *TRASH_CreateHomeBucket(void)
167 TRASH_BUCKET *bucket;
168 struct stat trash_stat;
169 char *trash_path = NULL;
171 bucket = SHAlloc(sizeof(TRASH_BUCKET));
177 memset(bucket, 0, sizeof(*bucket));
178 bucket->info_dir = init_home_dir("Trash/info/");
179 if (bucket->info_dir == NULL) goto error;
180 bucket->files_dir = init_home_dir("Trash/files/");
181 if (bucket->files_dir == NULL) goto error;
183 trash_path = XDG_BuildPath(XDG_DATA_HOME, "Trash/");
184 if (stat(trash_path, &trash_stat) == -1)
186 bucket->device = trash_stat.st_dev;
193 SHFree(bucket->info_dir);
194 SHFree(bucket->files_dir);
200 static BOOL TRASH_EnsureInitialized(void)
202 if (home_trash == NULL)
204 EnterCriticalSection(&TRASH_Creating);
205 if (home_trash == NULL)
206 home_trash = TRASH_CreateHomeBucket();
207 LeaveCriticalSection(&TRASH_Creating);
210 if (home_trash == NULL)
212 ERR("Couldn't initialize home trash (errno=%d)\n", errno);
218 static BOOL file_good_for_bucket(const TRASH_BUCKET *pBucket, const struct stat *file_stat)
220 if (pBucket->device != file_stat->st_dev)
225 BOOL TRASH_CanTrashFile(LPCWSTR wszPath)
227 struct stat file_stat;
230 TRACE("(%s)\n", debugstr_w(wszPath));
231 if (!TRASH_EnsureInitialized()) return FALSE;
232 if (!(unix_path = wine_get_unix_file_name(wszPath)))
234 if (lstat(unix_path, &file_stat)==-1)
236 HeapFree(GetProcessHeap(), 0, unix_path);
239 HeapFree(GetProcessHeap(), 0, unix_path);
240 return file_good_for_bucket(home_trash, &file_stat);
244 * Try to create a single .trashinfo file. Return TRUE if successful, else FALSE
246 static BOOL try_create_trashinfo_file(const char *info_dir, const char *file_name,
247 const char *original_file_name)
249 SYSTEMTIME curr_time;
251 char *path = SHAlloc(strlen(info_dir)+strlen(file_name)+strlen(trashinfo_suffix)+1);
254 if (path==NULL) return FALSE;
255 wsprintfA(path, "%s%s%s", info_dir, file_name, trashinfo_suffix);
256 TRACE("Trying to create '%s'\n", path);
257 writer = open(path, O_CREAT|O_WRONLY|O_TRUNC|O_EXCL, 0600);
258 if (writer==-1) goto error;
260 write(writer, trashinfo_header, strlen(trashinfo_header));
261 if (!XDG_WriteDesktopStringEntry(writer, "Path", XDG_URLENCODE, original_file_name))
264 GetLocalTime( &curr_time );
265 wnsprintfA(datebuf, 200, "%04d-%02d-%02dT%02d:%02d:%02d",
266 curr_time.wYear, curr_time.wMonth, curr_time.wDay,
267 curr_time.wHour, curr_time.wMinute, curr_time.wSecond);
268 if (!XDG_WriteDesktopStringEntry(writer, "DeletionDate", 0, datebuf))
285 * Try to create a .trashinfo file. This function will make several attempts with
286 * different filenames. It will return the filename that succeeded or NULL if a file
287 * couldn't be created.
289 static char *create_trashinfo(const char *info_dir, const char *file_path)
291 const char *base_name;
292 char *filename_buffer;
293 ULONG seed = GetTickCount();
296 errno = ENOMEM; /* out-of-memory is the only case when errno isn't set */
297 base_name = strrchr(file_path, '/');
298 if (base_name == NULL)
299 base_name = file_path;
303 filename_buffer = SHAlloc(strlen(base_name)+9+1);
304 if (filename_buffer == NULL)
306 lstrcpyA(filename_buffer, base_name);
307 if (try_create_trashinfo_file(info_dir, filename_buffer, file_path))
308 return filename_buffer;
311 sprintf(filename_buffer, "%s-%d", base_name, i+1);
312 if (try_create_trashinfo_file(info_dir, filename_buffer, file_path))
313 return filename_buffer;
316 for (i=0; i<1000; i++)
318 sprintf(filename_buffer, "%s-%08x", base_name, RtlRandom(&seed));
319 if (try_create_trashinfo_file(info_dir, filename_buffer, file_path))
320 return filename_buffer;
323 WARN("Couldn't create trashinfo after 1031 tries (errno=%d)\n", errno);
324 SHFree(filename_buffer);
328 static void remove_trashinfo_file(const char *info_dir, const char *base_name)
330 char *filename_buffer;
332 filename_buffer = SHAlloc(lstrlenA(info_dir)+lstrlenA(base_name)+lstrlenA(trashinfo_suffix)+1);
333 if (filename_buffer == NULL) return;
334 sprintf(filename_buffer, "%s%s%s", info_dir, base_name, trashinfo_suffix);
335 unlink(filename_buffer);
336 SHFree(filename_buffer);
339 static BOOL TRASH_MoveFileToBucket(TRASH_BUCKET *pBucket, const char *unix_path)
341 struct stat file_stat;
342 char *trash_file_name = NULL;
343 char *trash_path = NULL;
346 if (lstat(unix_path, &file_stat)==-1)
348 if (!file_good_for_bucket(pBucket, &file_stat))
351 trash_file_name = create_trashinfo(pBucket->info_dir, unix_path);
352 if (trash_file_name == NULL)
355 trash_path = SHAlloc(strlen(pBucket->files_dir)+strlen(trash_file_name)+1);
356 if (trash_path == NULL) goto error;
357 lstrcpyA(trash_path, pBucket->files_dir);
358 lstrcatA(trash_path, trash_file_name);
360 if (rename(unix_path, trash_path)==0)
362 TRACE("rename succeeded\n");
366 /* TODO: try to manually move the file */
367 ERR("Couldn't move file\n");
370 remove_trashinfo_file(pBucket->info_dir, trash_file_name);
372 SHFree(trash_file_name);
377 BOOL TRASH_TrashFile(LPCWSTR wszPath)
382 TRACE("(%s)\n", debugstr_w(wszPath));
383 if (!TRASH_EnsureInitialized()) return FALSE;
384 if (!(unix_path = wine_get_unix_file_name(wszPath)))
386 result = TRASH_MoveFileToBucket(home_trash, unix_path);
387 HeapFree(GetProcessHeap(), 0, unix_path);
392 * The item ID of a trashed element is built as follows:
393 * NUL byte - in most PIDLs the first byte is the type so we keep it constant
394 * WIN32_FIND_DATAW structure - with data about original file attributes
395 * bucket name - currently only an empty string meaning the home bucket is supported
396 * trash file name - a NUL-terminated string
398 static HRESULT TRASH_CreateSimplePIDL(LPCSTR filename, const WIN32_FIND_DATAW *data, LPITEMIDLIST *pidlOut)
400 LPITEMIDLIST pidl = SHAlloc(2+1+sizeof(WIN32_FIND_DATAW)+1+lstrlenA(filename)+1+2);
403 return E_OUTOFMEMORY;
404 pidl->mkid.cb = (USHORT)(2+1+sizeof(WIN32_FIND_DATAW)+1+lstrlenA(filename)+1);
405 pidl->mkid.abID[0] = 0;
406 memcpy(pidl->mkid.abID+1, data, sizeof(WIN32_FIND_DATAW));
407 pidl->mkid.abID[1+sizeof(WIN32_FIND_DATAW)] = 0;
408 lstrcpyA((LPSTR)(pidl->mkid.abID+1+sizeof(WIN32_FIND_DATAW)+1), filename);
409 *(USHORT *)(pidl->mkid.abID+1+sizeof(WIN32_FIND_DATAW)+1+lstrlenA(filename)+1) = 0;
414 /***********************************************************************
415 * TRASH_UnpackItemID [Internal]
418 * Extract the information stored in an Item ID. The WIN32_FIND_DATA contains
419 * the information about the original file. The data->ftLastAccessTime contains
423 * [I] id : the ID of the item
424 * [O] data : the WIN32_FIND_DATA of the original file. Can be NULL is not needed
426 HRESULT TRASH_UnpackItemID(LPCSHITEMID id, WIN32_FIND_DATAW *data)
428 if (id->cb < 2+1+sizeof(WIN32_FIND_DATAW)+2)
430 if (id->abID[0] != 0 || id->abID[1+sizeof(WIN32_FIND_DATAW)] != 0)
432 if (memchr(id->abID+1+sizeof(WIN32_FIND_DATAW)+1, 0, id->cb-(2+1+sizeof(WIN32_FIND_DATAW)+1)) == NULL)
436 *data = *(const WIN32_FIND_DATAW *)(id->abID+1);
440 static HRESULT TRASH_GetDetails(const TRASH_BUCKET *bucket, LPCSTR filename, WIN32_FIND_DATAW *data)
443 XDG_PARSED_FILE *parsed = NULL;
444 char *original_file_name = NULL;
445 char *deletion_date = NULL;
448 HRESULT ret = S_FALSE;
449 LPWSTR original_dos_name;
450 int suffix_length = lstrlenA(trashinfo_suffix);
451 int filename_length = lstrlenA(filename);
452 int files_length = lstrlenA(bucket->files_dir);
453 int path_length = max(lstrlenA(bucket->info_dir), files_length);
455 path = SHAlloc(path_length + filename_length + 1);
456 if (path == NULL) return E_OUTOFMEMORY;
457 wsprintfA(path, "%s%s", bucket->files_dir, filename);
458 path[path_length + filename_length - suffix_length] = 0; /* remove the '.trashinfo' */
459 if (lstat(path, &stats) == -1)
461 ERR("Error accessing data file for trashinfo %s (errno=%d)\n", filename, errno);
465 wsprintfA(path, "%s%s", bucket->info_dir, filename);
466 fd = open(path, O_RDONLY);
469 ERR("Couldn't open trashinfo file %s (errno=%d)\n", path, errno);
473 parsed = XDG_ParseDesktopFile(fd);
476 ERR("Parse error in trashinfo file %s\n", path);
480 original_file_name = XDG_GetStringValue(parsed, trashinfo_group, "Path", XDG_URLENCODE);
481 if (original_file_name == NULL)
483 ERR("No 'Path' entry in trashinfo file\n");
487 ZeroMemory(data, sizeof(*data));
488 data->nFileSizeHigh = (DWORD)((LONGLONG)stats.st_size>>32);
489 data->nFileSizeLow = stats.st_size & 0xffffffff;
490 RtlSecondsSince1970ToTime(stats.st_mtime, (LARGE_INTEGER *)&data->ftLastWriteTime);
492 original_dos_name = wine_get_dos_file_name(original_file_name);
493 if (original_dos_name != NULL)
495 lstrcpynW(data->cFileName, original_dos_name, MAX_PATH);
496 SHFree(original_dos_name);
500 /* show only the file name */
501 char *file = strrchr(original_file_name, '/');
503 file = original_file_name;
504 MultiByteToWideChar(CP_UNIXCP, 0, file, -1, data->cFileName, MAX_PATH);
507 deletion_date = XDG_GetStringValue(parsed, trashinfo_group, "DeletionDate", 0);
513 sscanf(deletion_date, "%d-%d-%dT%d:%d:%d",
514 &del_time.tm_year, &del_time.tm_mon, &del_time.tm_mday,
515 &del_time.tm_hour, &del_time.tm_min, &del_time.tm_sec);
516 del_time.tm_year -= 1900;
518 del_secs = mktime(&del_time);
520 RtlSecondsSince1970ToTime(del_secs, (LARGE_INTEGER *)&data->ftLastAccessTime);
526 SHFree(original_file_name);
527 SHFree(deletion_date);
530 XDG_FreeParsedFile(parsed);
534 static INT CALLBACK free_item_callback(void *item, void *lParam)
540 static HDPA enum_bucket_trashinfos(const TRASH_BUCKET *bucket, int *count)
542 HDPA ret = DPA_Create(32);
543 struct dirent *entry;
548 if (ret == NULL) goto failed;
549 dir = opendir(bucket->info_dir);
550 if (dir == NULL) goto failed;
551 while ((entry = readdir(dir)) != NULL)
554 int namelen = lstrlenA(entry->d_name);
555 int suffixlen = lstrlenA(trashinfo_suffix);
556 if (namelen <= suffixlen ||
557 lstrcmpA(entry->d_name+namelen-suffixlen, trashinfo_suffix) != 0)
560 filename = StrDupA(entry->d_name);
561 if (filename == NULL)
563 if (DPA_InsertPtr(ret, DPA_APPEND, filename) == -1)
573 if (dir) closedir(dir);
575 DPA_DestroyCallback(ret, free_item_callback, NULL);
579 HRESULT TRASH_EnumItems(LPITEMIDLIST **pidls, int *count)
583 HRESULT err = E_OUTOFMEMORY;
586 if (!TRASH_EnsureInitialized()) return E_FAIL;
587 tinfs = enum_bucket_trashinfos(home_trash, &ti_count);
588 if (tinfs == NULL) return E_FAIL;
589 *pidls = SHAlloc(sizeof(LPITEMIDLIST)*ti_count);
590 if (!*pidls) goto failed;
591 for (i=0; i<ti_count; i++)
593 WIN32_FIND_DATAW data;
596 filename = DPA_GetPtr(tinfs, i);
597 if (FAILED(err = TRASH_GetDetails(home_trash, filename, &data)))
601 if (FAILED(err = TRASH_CreateSimplePIDL(filename, &data, &(*pidls)[pos])))
606 DPA_DestroyCallback(tinfs, free_item_callback, NULL);
612 for (j=0; j<pos; j++)
616 DPA_DestroyCallback(tinfs, free_item_callback, NULL);
621 HRESULT TRASH_RestoreItem(LPCITEMIDLIST pidl){
622 int suffix_length = strlen(trashinfo_suffix);
623 LPCSHITEMID id = &(pidl->mkid);
624 const char *bucket_name = (const char*)(id->abID+1+sizeof(WIN32_FIND_DATAW));
625 const char *filename = (const char*)(id->abID+1+sizeof(WIN32_FIND_DATAW)+strlen(bucket_name)+1);
627 WIN32_FIND_DATAW data;
630 TRACE("(%p)\n",pidl);
631 if(strcmp(filename+strlen(filename)-suffix_length,trashinfo_suffix))
633 ERR("pidl at %p is not a valid recycle bin entry\n",pidl);
636 TRASH_UnpackItemID(id,&data);
637 restore_path = wine_get_unix_file_name(data.cFileName);
638 file_path = SHAlloc(max(strlen(home_trash->files_dir),strlen(home_trash->info_dir))+strlen(filename)+1);
639 sprintf(file_path,"%s%s",home_trash->files_dir,filename);
640 file_path[strlen(home_trash->files_dir)+strlen(filename)-suffix_length] = '\0';
641 if(!rename(file_path,restore_path))
643 sprintf(file_path,"%s%s",home_trash->info_dir,filename);
644 if(unlink(file_path))
645 WARN("failed to delete the trashinfo file %s\n",filename);
648 WARN("could not erase %s from the trash (errno=%i)\n",filename,errno);
650 HeapFree(GetProcessHeap(), 0, restore_path);
654 HRESULT TRASH_EraseItem(LPCITEMIDLIST pidl)
656 int suffix_length = strlen(trashinfo_suffix);
658 LPCSHITEMID id = &(pidl->mkid);
659 const char *bucket_name = (const char*)(id->abID+1+sizeof(WIN32_FIND_DATAW));
660 const char *filename = (const char*)(id->abID+1+sizeof(WIN32_FIND_DATAW)+strlen(bucket_name)+1);
663 TRACE("(%p)\n",pidl);
664 if(strcmp(filename+strlen(filename)-suffix_length,trashinfo_suffix))
666 ERR("pidl at %p is not a valid recycle bin entry\n",pidl);
669 file_path = SHAlloc(max(strlen(home_trash->files_dir),strlen(home_trash->info_dir))+strlen(filename)+1);
670 sprintf(file_path,"%s%s",home_trash->info_dir,filename);
671 if(unlink(file_path))
672 WARN("failed to delete the trashinfo file %s\n",filename);
673 sprintf(file_path,"%s%s",home_trash->files_dir,filename);
674 file_path[strlen(home_trash->files_dir)+strlen(filename)-suffix_length] = '\0';
675 if(unlink(file_path))
676 WARN("could not erase %s from the trash (errno=%i)\n",filename,errno);
681 #endif /* HAVE_CORESERVICES_CORESERVICES_H */