/** NSFileManager.m Copyright (C) 1997-2002 Free Software Foundation, Inc. Author: Mircea Oancea Author: Ovidiu Predescu Date: Feb 1997 Updates and fixes: Richard Frith-Macdonald Author: Nicola Pero Date: Apr 2001 Rewritten NSDirectoryEnumerator Author: Richard frith-Macdonald Date: Sep 2002 Rewritten attribute handling code This file is part of the GNUstep Base Library. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111 USA. NSFileManager class reference $Date$ $Revision$ */ #if defined(__MINGW32__) #define UNICODE #define _UNICODE #endif #include "config.h" #include #include "GNUstepBase/preface.h" #include "Foundation/NSFileManager.h" #include "Foundation/NSException.h" #include "Foundation/NSAutoreleasePool.h" #include "Foundation/NSLock.h" #include "Foundation/NSDebug.h" #include "Foundation/NSProcessInfo.h" #include "Foundation/NSEnumerator.h" #include "Foundation/NSSet.h" #include "GSPrivate.h" #include /* determine directory reading files */ #if defined(HAVE_DIRENT_H) # include #elif defined(HAVE_SYS_DIR_H) # include #elif defined(HAVE_SYS_NDIR_H) # include #elif defined(HAVE_NDIR_H) # include #endif #ifdef HAVE_UNISTD_H #include #endif #ifdef HAVE_WINDOWS_H # include #endif #if defined(__MINGW__) #include #ifdef UNICODE #include #endif #define WIN32ERR ((DWORD)0xFFFFFFFF) #endif /* determine filesystem max path length */ #if defined(_POSIX_VERSION) || defined(__WIN32__) # include /* for PATH_MAX */ # if defined(__MINGW32__) # include # else # include # endif #else # ifdef HAVE_SYS_PARAM_H # include /* for MAXPATHLEN */ # endif #endif #ifndef PATH_MAX # ifdef _POSIX_VERSION # define PATH_MAX _POSIX_PATH_MAX # else # ifdef MAXPATHLEN # define PATH_MAX MAXPATHLEN # else # define PATH_MAX 1024 # endif # endif #endif /* determine if we have statfs struct and function */ #ifdef HAVE_SYS_VFS_H # include #endif #ifdef HAVE_SYS_STATVFS_H # include #endif #ifdef HAVE_SYS_STATFS_H # include #endif #ifdef HAVE_SYS_FILE_H #include #endif #ifdef HAVE_SYS_MOUNT_H #include #endif #include #ifdef HAVE_SYS_STAT_H #include #endif #include #ifdef HAVE_PWD_H #include /* For struct passwd */ #endif #ifdef HAVE_GRP_H #include /* For struct group */ #endif #ifdef HAVE_UTIME_H # include #endif /* * On systems that have the O_BINARY flag, use it for a binary copy. */ #if defined(O_BINARY) #define GSBINIO O_BINARY #else #define GSBINIO 0 #endif /* include usual headers */ #include "Foundation/NSArray.h" #include "Foundation/NSDictionary.h" #include "Foundation/NSData.h" #include "Foundation/NSDate.h" #include "Foundation/NSString.h" #include "Foundation/NSValue.h" #include "Foundation/NSPathUtilities.h" #include "Foundation/NSFileManager.h" /* * Macros to handle unichar filesystem support. */ #if defined(__MINGW__) && defined(UNICODE) #define _CHMOD(A,B) _wchmod(A,B) #define _CLOSEDIR(A) _wclosedir(A) #define _OPENDIR(A) _wopendir(A) #define _READDIR(A) _wreaddir(A) #define _RENAME(A,B) _wrename(A,B) #define _RMDIR(A) _wrmdir(A) #define _STAT(A,B) _wstat(A,B) #define _UTIME(A,B) _wutime(A,B) #define _CHAR unichar #define _DIR _WDIR #define _DIRENT _wdirent #define _STATB _stat #define _UTIMB _utimbuf #define _NUL L'\0' #define OS2LOCAL(M,P) [[M localFromOpenStepPath: P] unicharString] #else #define _CHMOD(A,B) chmod(A,B) #define _CLOSEDIR(A) closedir(A) #define _OPENDIR(A) opendir(A) #define _READDIR(A) readdir(A) #define _RENAME(A,B) rename(A,B) #define _RMDIR(A) rmdir(A) #define _STAT(A,B) stat(A,B) #define _UTIME(A,B) utime(A,B) #define _CHAR char #define _DIR DIR #define _DIRENT dirent #define _STATB stat #define _UTIMB utimbuf #define _NUL '\0' #define OS2LOCAL(M,P) [M fileSystemRepresentationWithPath: P] #endif /* * GSAttrDictionary is a private NSDictionary subclass used to * handle file attributes efficiently ... using lazy evaluation * to ensure that we only do the minimum work necessary at any time. */ @interface GSAttrDictionary : NSDictionary { struct _STATB statbuf; } + (NSDictionary*) attributesAt: (const _CHAR*)lpath traverseLink: (BOOL)traverse; @end /* * We also need a special enumerator class to enumerate the dictionary. */ @interface GSAttrDictionaryEnumerator : NSEnumerator { NSDictionary *dictionary; NSEnumerator *enumerator; } + (NSEnumerator*) enumeratorFor: (NSDictionary*)d; @end @interface NSFileManager (PrivateMethods) /* Copies the contents of source file to destination file. Assumes source and destination are regular files or symbolic links. */ - (BOOL) _copyFile: (NSString*)source toFile: (NSString*)destination handler: (id)handler; /* Recursively copies the contents of source directory to destination. */ - (BOOL) _copyPath: (NSString*)source toPath: (NSString*)destination handler: (id)handler; /* Recursively links the contents of source directory to destination. */ - (BOOL) _linkPath: (NSString*)source toPath: (NSString*)destination handler: handler; /* encapsulates the will Process check for existence of selector. */ - (void) _sendToHandler: (id) handler willProcessPath: (NSString*) path; /* methods to encapsulates setting up and calling the handler in case of an error */ - (BOOL) _proceedAccordingToHandler: (id) handler forError: (NSString*) error inPath: (NSString*) path; - (BOOL) _proceedAccordingToHandler: (id) handler forError: (NSString*) error inPath: (NSString*) path fromPath: (NSString*) frompath toPath: (NSString*) toPath; @end /* NSFileManager (PrivateMethods) */ /** * This is the main class for platform-independent management of the local * filesystem, which allows you to read and save files, create/list * directories, and move or delete files and directories. In addition to * simply listing directories, you may obtain an [NSDirectoryEnumerator] * instance for recursive directory contents enumeration. */ @implementation NSFileManager // Getting the default manager static NSFileManager* defaultManager = nil; /** * Returns a shared default file manager which may be used throughout an * application. */ + (NSFileManager*) defaultManager { if (defaultManager == nil) { NS_DURING { [gnustep_global_lock lock]; if (defaultManager == nil) { defaultManager = [[self alloc] init]; } [gnustep_global_lock unlock]; } NS_HANDLER { // unlock then re-raise the exception [gnustep_global_lock unlock]; [localException raise]; } NS_ENDHANDLER } return defaultManager; } - (void) dealloc { TEST_RELEASE(_lastError); [super dealloc]; } /** * Changes the current directory used for all subsequent operations.
* All non-absolute paths are interpreted relative to this directory.
* The current directory is set on a per-task basis, so the current * directory for other file manager instances will also be changed * by this method. */ - (BOOL) changeCurrentDirectoryPath: (NSString*)path { const _CHAR *lpath = OS2LOCAL(self, path); #if defined(__MINGW__) return SetCurrentDirectory(lpath) == TRUE ? YES : NO; #else return (chdir(lpath) == 0) ? YES : NO; #endif } /** * Change the attributes of the file at path to those specified.
* Returns YES if all requested changes were made (or if the dictionary * was nil or empty, so no changes were requested), NO otherwise.
* On failure, some fo the requested changes may have taken place.
*/ - (BOOL) changeFileAttributes: (NSDictionary*)attributes atPath: (NSString*)path { const _CHAR *lpath = 0; unsigned long num; NSString *str; NSDate *date; BOOL allOk = YES; if (attributes == nil) { return YES; } lpath = OS2LOCAL(defaultManager, path); #ifndef __MINGW__ num = [attributes fileOwnerAccountID]; if (num != NSNotFound) { if (chown(lpath, num, -1) != 0) { allOk = NO; str = [NSString stringWithFormat: @"Unable to change NSFileOwnerAccountID to '%u' - %s", num, GSLastErrorStr(errno)]; ASSIGN(_lastError, str); } } else { if ((str = [attributes fileOwnerAccountName]) != nil) { BOOL ok = NO; #ifdef HAVE_PWD_H struct passwd *pw = getpwnam([str cString]); if (pw != 0) { ok = (chown(lpath, pw->pw_uid, -1) == 0); chown(lpath, -1, pw->pw_gid); } #endif if (ok == NO) { allOk = NO; str = [NSString stringWithFormat: @"Unable to change NSFileOwnerAccountName to '%@' - %s", str, GSLastErrorStr(errno)]; ASSIGN(_lastError, str); } } } num = [attributes fileGroupOwnerAccountID]; if (num != NSNotFound) { if (chown(lpath, -1, num) != 0) { allOk = NO; str = [NSString stringWithFormat: @"Unable to change NSFileGroupOwnerAccountID to '%u' - %s", num, GSLastErrorStr(errno)]; ASSIGN(_lastError, str); } } else if ((str = [attributes fileGroupOwnerAccountName]) != nil) { BOOL ok = NO; #ifdef HAVE_GRP_H struct group *gp = getgrnam([str cString]); if (gp) { if (chown(lpath, -1, gp->gr_gid) == 0) ok = YES; } #endif if (ok == NO) { allOk = NO; str = [NSString stringWithFormat: @"Unable to change NSFileGroupOwnerAccountName to '%@' - %s", str, GSLastErrorStr(errno)]; ASSIGN(_lastError, str); } } #endif /* __MINGW__ */ num = [attributes filePosixPermissions]; if (num != NSNotFound) { if (_CHMOD(lpath, num) != 0) { allOk = NO; str = [NSString stringWithFormat: @"Unable to change NSFilePosixPermissions to '%o' - %s", num, GSLastErrorStr(errno)]; ASSIGN(_lastError, str); } } date = [attributes fileModificationDate]; if (date != nil) { BOOL ok = NO; struct _STATB sb; #if defined(__WIN32__) || defined(_POSIX_VERSION) struct _UTIMB ub; #else time_t ub[2]; #endif if (_STAT(lpath, &sb) != 0) { ok = NO; } #if defined(__WIN32__) else if (sb.st_mode & _S_IFDIR) { ok = YES; // Directories don't have modification times. } #endif else { #if defined(__WIN32__) || defined(_POSIX_VERSION) ub.actime = sb.st_atime; ub.modtime = [date timeIntervalSince1970]; ok = (_UTIME(lpath, &ub) == 0); #else ub[0] = sb.st_atime; ub[1] = [date timeIntervalSince1970]; ok = (_UTIME(lpath, ub) == 0); #endif } if (ok == NO) { allOk = NO; str = [NSString stringWithFormat: @"Unable to change NSFileModificationDate to '%@' - %s", date, GSLastErrorStr(errno)]; ASSIGN(_lastError, str); } } return allOk; } /** * Returns an array of path components suitably modified for display * to the end user. This modification may render the returned strings * unusable for path manipulation, so you should work with two arrays ... * one returned by this method (for display tio the user), and a * parallel one returned by [NSString-pathComponents] (for path * manipulation). */ - (NSArray*) componentsToDisplayForPath: (NSString*)path { return [path pathComponents]; } /** * Reads the file at path an returns its contents as an NSData object.
* If an error occurs or if path specifies a directory etc then nil is * returned. */ - (NSData*) contentsAtPath: (NSString*)path { return [NSData dataWithContentsOfFile: path]; } /** * Returns YES if the contents of the file or directory at path1 are the same * as those at path2.
* If path1 and path2 are files, this is a simple comparison. If they are * directories, the contents of the files in those subdirectories are * compared recursively.
* Symbolic links are not followed.
* A comparison checks first file identity, then size, then content. */ - (BOOL) contentsEqualAtPath: (NSString*)path1 andPath: (NSString*)path2 { NSDictionary *d1; NSDictionary *d2; NSString *t; if ([path1 isEqual: path2]) return YES; d1 = [self fileAttributesAtPath: path1 traverseLink: NO]; d2 = [self fileAttributesAtPath: path2 traverseLink: NO]; t = [d1 fileType]; if ([t isEqual: [d2 fileType]] == NO) { return NO; } if ([t isEqual: NSFileTypeRegular]) { if ([d1 fileSize] == [d2 fileSize]) { NSData *c1 = [NSData dataWithContentsOfFile: path1]; NSData *c2 = [NSData dataWithContentsOfFile: path2]; if ([c1 isEqual: c2]) { return YES; } } return NO; } else if ([t isEqual: NSFileTypeDirectory]) { NSArray *a1 = [self directoryContentsAtPath: path1]; NSArray *a2 = [self directoryContentsAtPath: path2]; unsigned index, count = [a1 count]; BOOL ok = YES; if ([a1 isEqual: a2] == NO) { return NO; } for (index = 0; ok == YES && index < count; index++) { NSString *n = [a1 objectAtIndex: index]; NSString *p1; NSString *p2; CREATE_AUTORELEASE_POOL(pool); p1 = [path1 stringByAppendingPathComponent: n]; p2 = [path2 stringByAppendingPathComponent: n]; d1 = [self fileAttributesAtPath: p1 traverseLink: NO]; d2 = [self fileAttributesAtPath: p2 traverseLink: NO]; t = [d1 fileType]; if ([t isEqual: [d2 fileType]] == NO) { ok = NO; } else if ([t isEqual: NSFileTypeDirectory]) { ok = [self contentsEqualAtPath: p1 andPath: p2]; } RELEASE(pool); } return ok; } else { return YES; } } /** * Creates a new directory, and sets its attributes as specified.
* Creates other directories in the path as necessary.
* Returns YES on success, NO on failure. */ - (BOOL) createDirectoryAtPath: (NSString*)path attributes: (NSDictionary*)attributes { #if defined(__MINGW__) NSEnumerator *paths = [[path pathComponents] objectEnumerator]; NSString *subPath; NSString *completePath = nil; #else const char *lpath; char dirpath[PATH_MAX+1]; struct _STATB statbuf; int len, cur; NSDictionary *needChown = nil; #endif /* This is consistent with MacOSX - just return NO for an invalid path. */ if ([path length] == 0) return NO; #if defined(__MINGW__) while ((subPath = [paths nextObject])) { BOOL isDir = NO; if (completePath == nil) completePath = subPath; else completePath = [completePath stringByAppendingPathComponent: subPath]; if ([self fileExistsAtPath: completePath isDirectory: &isDir]) { if (!isDir) NSLog(@"WARNING: during creation of directory %@:" @" sub path %@ exists, but is not a directory !", path, completePath); } else { const _CHAR *lpath; lpath = OS2LOCAL(self, completePath); if (CreateDirectory(lpath, 0) == FALSE) { return NO; } } } #else /* * If there is no file owner specified, and we are running setuid to * root, then we assume we need to change ownership to correct user. */ if (attributes == nil || ([attributes fileOwnerAccountID] == NSNotFound && [attributes fileOwnerAccountName] == nil)) { if (geteuid() == 0 && [@"root" isEqualToString: NSUserName()] == NO) { needChown = [NSDictionary dictionaryWithObjectsAndKeys: NSFileOwnerAccountName, NSUserName(), nil]; } } lpath = [self fileSystemRepresentationWithPath: path]; len = strlen(lpath); if (len > PATH_MAX) // name too long { ASSIGN(_lastError, @"Could not create directory - name too long"); return NO; } if (strcmp(lpath, "/") == 0 || len == 0) // cannot use "/" or "" { ASSIGN(_lastError, @"Could not create directory - no name given"); return NO; } strcpy(dirpath, lpath); dirpath[len] = '\0'; if (dirpath[len-1] == '/') dirpath[len-1] = '\0'; cur = 0; do { // find next '/' while (dirpath[cur] != '/' && cur < len) cur++; // if first char is '/' then again; (cur == len) -> last component if (cur == 0) { cur++; continue; } // check if path from 0 to cur is valid dirpath[cur] = '\0'; if (_STAT(dirpath, &statbuf) == 0) { if (cur == len) { ASSIGN(_lastError, @"Could not create directory - already exists"); return NO; } } else { // make new directory if (mkdir(dirpath, 0777) != 0) { NSString *s; s = [NSString stringWithFormat: @"Could not create '%s' - '%s'", dirpath, GSLastErrorStr(errno)]; ASSIGN(_lastError, s); return NO; } // if last directory and attributes then change if (cur == len && attributes != nil) { if ([self changeFileAttributes: attributes atPath: [self stringWithFileSystemRepresentation: dirpath length: cur]] == NO) return NO; if (needChown != nil) { if ([self changeFileAttributes: needChown atPath: [self stringWithFileSystemRepresentation: dirpath length: cur]] == NO) { NSLog(@"Failed to change ownership of '%s' to '%@'", dirpath, NSUserName()); } } return YES; } } dirpath[cur] = '/'; cur++; } while (cur < len); #endif /* !MINGW */ // change attributes of last directory if ([attributes count] == 0) { return YES; } return [self changeFileAttributes: attributes atPath: path]; } /** * Creates a new file, and sets its attributes as specified.
* Initialises the file content with the specified data.
* Returns YES on success, NO on failure. */ - (BOOL) createFileAtPath: (NSString*)path contents: (NSData*)contents attributes: (NSDictionary*)attributes { #if defined(__MINGW__) const _CHAR *lpath = OS2LOCAL(self, path); HANDLE fh; DWORD written = 0; DWORD len = [contents length]; #else const char *lpath; int fd; int len; int written; #endif /* This is consitent with MacOSX - just return NO for an invalid path. */ if ([path length] == 0) return NO; #if defined(__MINGW__) fh = CreateFile(lpath, GENERIC_WRITE, 0, 0, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0); if (fh == INVALID_HANDLE_VALUE) { return NO; } else { if (len > 0) { WriteFile(fh, [contents bytes], len, &written, 0); } CloseHandle(fh); if (attributes != nil && [self changeFileAttributes: attributes atPath: path] == NO) { return NO; } return YES; } #else lpath = [self fileSystemRepresentationWithPath: path]; fd = open(lpath, GSBINIO|O_WRONLY|O_TRUNC|O_CREAT, 0644); if (fd < 0) { return NO; } if (attributes != nil && [self changeFileAttributes: attributes atPath: path] == NO) { close (fd); return NO; } /* * If there is no file owner specified, and we are running setuid to * root, then we assume we need to change ownership to correct user. */ if (attributes == nil || ([attributes fileOwnerAccountID] == NSNotFound && [attributes fileOwnerAccountName] == nil)) { if (geteuid() == 0 && [@"root" isEqualToString: NSUserName()] == NO) { attributes = [NSDictionary dictionaryWithObjectsAndKeys: NSFileOwnerAccountName, NSUserName(), nil]; if (![self changeFileAttributes: attributes atPath: path]) { NSLog(@"Failed to change ownership of '%@' to '%@'", path, NSUserName()); } } } len = [contents length]; if (len > 0) { written = write(fd, [contents bytes], len); } else { written = 0; } close (fd); #endif return written == len; } /** * Returns the current working directory used by all instance of the file * manager in the current task. */ - (NSString*) currentDirectoryPath { NSString *currentDir = nil; #if defined(__MINGW__) int len = GetCurrentDirectory(0, 0); if (len > 0) { _CHAR *lpath = (_CHAR*)calloc(len+10,sizeof(_CHAR)); if (lpath != 0) { if (GetCurrentDirectory(len, lpath)>0) { NSString *path; #ifdef UNICODE path = [NSString stringWithCharacters: lpath length: len]; #else path = [NSString stringWithCString: lpath length: len]; #endif currentDir = [self openStepPathFromLocal: path]; } free(lpath); } } #else char path[PATH_MAX]; #ifdef HAVE_GETCWD if (getcwd(path, PATH_MAX-1) == 0) return nil; #else if (getwd(path) == 0) return nil; #endif /* HAVE_GETCWD */ currentDir = [self stringWithFileSystemRepresentation: path length: strlen(path)]; #endif /* !MINGW */ return currentDir; } /** * Copies the file or directory at source to destination, using a * handler object which should respond to * [NSObject-fileManager:willProcessPath:] and * [NSObject-fileManager:shouldProceedAfterError:] messages.
* Will not copy to a destination which already exists. */ - (BOOL) copyPath: (NSString*)source toPath: (NSString*)destination handler: (id)handler { NSDictionary *attrs; NSString *fileType; if ([self fileExistsAtPath: destination] == YES) { return NO; } attrs = [self fileAttributesAtPath: source traverseLink: NO]; if (attrs == nil) { return NO; } fileType = [attrs fileType]; if ([fileType isEqualToString: NSFileTypeDirectory] == YES) { /* If destination directory is a descendant of source directory copying isn't possible. */ if ([[destination stringByAppendingString: @"/"] hasPrefix: [source stringByAppendingString: @"/"]]) { return NO; } [self _sendToHandler: handler willProcessPath: destination]; if ([self createDirectoryAtPath: destination attributes: attrs] == NO) { return [self _proceedAccordingToHandler: handler forError: _lastError inPath: destination fromPath: source toPath: destination]; } if ([self _copyPath: source toPath: destination handler: handler] == NO) { return NO; } } else if ([fileType isEqualToString: NSFileTypeSymbolicLink] == YES) { NSString *path; BOOL result; [self _sendToHandler: handler willProcessPath: source]; path = [self pathContentOfSymbolicLinkAtPath: source]; result = [self createSymbolicLinkAtPath: destination pathContent: path]; if (result == NO) { result = [self _proceedAccordingToHandler: handler forError: @"cannot link to file" inPath: source fromPath: source toPath: destination]; if (result == NO) { return NO; } } } else { [self _sendToHandler: handler willProcessPath: source]; if ([self _copyFile: source toFile: destination handler: handler] == NO) { return NO; } } [self changeFileAttributes: attrs atPath: destination]; return YES; } /** * Moves the file or directory at source to destination, using a * handler object which should respond to * [NSObject-fileManager:willProcessPath:] and * [NSObject-fileManager:shouldProceedAfterError:] messages. * Will not move to a destination which already exists.
*/ - (BOOL) movePath: (NSString*)source toPath: (NSString*)destination handler: (id)handler { BOOL sourceIsDir; BOOL fileExists; NSString *destinationParent; unsigned int sourceDevice; unsigned int destinationDevice; const _CHAR *sourcePath; const _CHAR *destPath; sourcePath = OS2LOCAL(self, source); destPath = OS2LOCAL(self, destination); if ([self fileExistsAtPath: destination] == YES) { return NO; } fileExists = [self fileExistsAtPath: source isDirectory: &sourceIsDir]; if (!fileExists) { return NO; } /* Check to see if the source and destination's parent are on the same physical device so we can perform a rename syscall directly. */ sourceDevice = [[self fileSystemAttributesAtPath: source] fileSystemNumber]; destinationParent = [destination stringByDeletingLastPathComponent]; if ([destinationParent isEqual: @""]) destinationParent = @"."; destinationDevice = [[self fileSystemAttributesAtPath: destinationParent] fileSystemNumber]; if (sourceDevice != destinationDevice) { /* If destination directory is a descendant of source directory moving isn't possible. */ if (sourceIsDir && [[destination stringByAppendingString: @"/"] hasPrefix: [source stringByAppendingString: @"/"]]) { return NO; } if ([self copyPath: source toPath: destination handler: handler]) { NSDictionary *attributes; attributes = [self fileAttributesAtPath: source traverseLink: NO]; [self changeFileAttributes: attributes atPath: destination]; return [self removeFileAtPath: source handler: handler]; } else { return NO; } } else { /* source and destination are on the same device so we can simply invoke rename on source. */ [self _sendToHandler: handler willProcessPath: source]; if (_RENAME (sourcePath, destPath) == -1) { return [self _proceedAccordingToHandler: handler forError: @"cannot move file" inPath: source fromPath: source toPath: destination]; } return YES; } return NO; } /** *

Links the file or directory at source to destination, using a * handler object which should respond to * [NSObject-fileManager:willProcessPath:] and * [NSObject-fileManager:shouldProceedAfterError:] messages. *

*

If the destination is a directory, the source path is linked * into that directory, otherwise the destination must not exist, * but its parent directory must exist and the source will be linked * into the parent as the name specified by the destination. *

*

If the source is a symbolic link, it is copied to the destination.
* If the source is a directory, it is copied to the destination and its * contents are linked into the new directory.
* Otherwise, a hard link is made from the destination to the source. *

*/ - (BOOL) linkPath: (NSString*)source toPath: (NSString*)destination handler: (id)handler { #ifdef HAVE_LINK NSDictionary *attrs; NSString *fileType; BOOL isDir; if ([self fileExistsAtPath: destination isDirectory: &isDir] == YES && isDir == YES) { destination = [destination stringByAppendingPathComponent: [source lastPathComponent]]; } attrs = [self fileAttributesAtPath: source traverseLink: NO]; if (attrs == nil) { return NO; } [self _sendToHandler: handler willProcessPath: destination]; fileType = [attrs fileType]; if ([fileType isEqualToString: NSFileTypeDirectory] == YES) { /* If destination directory is a descendant of source directory linking isn't possible because of recursion. */ if ([[destination stringByAppendingString: @"/"] hasPrefix: [source stringByAppendingString: @"/"]]) { return NO; } if ([self createDirectoryAtPath: destination attributes: attrs] == NO) { return [self _proceedAccordingToHandler: handler forError: _lastError inPath: destination fromPath: source toPath: destination]; } if ([self _linkPath: source toPath: destination handler: handler] == NO) { return NO; } } else if ([fileType isEqual: NSFileTypeSymbolicLink]) { NSString *path; path = [self pathContentOfSymbolicLinkAtPath: source]; if ([self createSymbolicLinkAtPath: destination pathContent: path] == NO) { if ([self _proceedAccordingToHandler: handler forError: @"cannot create symbolic link" inPath: source fromPath: source toPath: destination] == NO) { return NO; } } } else { if (link([source fileSystemRepresentation], [destination fileSystemRepresentation]) < 0) { if ([self _proceedAccordingToHandler: handler forError: @"cannot create hard link" inPath: source fromPath: source toPath: destination] == NO) { return NO; } } } [self changeFileAttributes: attrs atPath: destination]; return YES; #else return NO; // Links not supported on this platform #endif } /** * Removes the file or directory at path, using a * handler object which should respond to * [NSObject-fileManager:willProcessPath:] and * [NSObject-fileManager:shouldProceedAfterError:] messages. */ - (BOOL) removeFileAtPath: (NSString*)path handler: handler { BOOL is_dir; const _CHAR *lpath; if ([path isEqualToString: @"."] || [path isEqualToString: @".."]) { [NSException raise: NSInvalidArgumentException format: @"Attempt to remove illegal path"]; } [self _sendToHandler: handler willProcessPath: path]; lpath = OS2LOCAL(self, path); if (lpath == 0 || *lpath == 0) { return NO; } else { #if defined(__MINGW__) DWORD res; res = GetFileAttributes(lpath); if (res == WIN32ERR) { return NO; } if (res & FILE_ATTRIBUTE_DIRECTORY) { is_dir = YES; } else { is_dir = NO; } #else struct _STATB statbuf; if (lstat(lpath, &statbuf) != 0) { return NO; } is_dir = ((statbuf.st_mode & S_IFMT) == S_IFDIR); #endif /* MINGW */ } if (!is_dir) { #if defined(__MINGW__) if (DeleteFile(lpath) == FALSE) #else if (unlink(lpath) < 0) #endif { return [self _proceedAccordingToHandler: handler forError: [NSString stringWithCString: GSLastErrorStr (errno)] inPath: path]; } else { return YES; } } else { NSArray *contents = [self directoryContentsAtPath: path]; unsigned count = [contents count]; unsigned i; for (i = 0; i < count; i++) { NSString *item; NSString *next; BOOL result; CREATE_AUTORELEASE_POOL(arp); item = [contents objectAtIndex: i]; next = [path stringByAppendingPathComponent: item]; result = [self removeFileAtPath: next handler: handler]; RELEASE(arp); if (result == NO) { return NO; } } if (_RMDIR(OS2LOCAL(self, path)) < 0) { return [self _proceedAccordingToHandler: handler forError: [NSString stringWithCString: GSLastErrorStr (errno)] inPath: path]; } else { return YES; } } } /** * Returns YES if a file (or directory etc) exists at the specified path. */ - (BOOL) fileExistsAtPath: (NSString*)path { return [self fileExistsAtPath: path isDirectory: 0]; } /** * Returns YES if a file (or directory etc) exists at the specified path.
* If the isDirectory argument is not a nul pointer, stores a flag * in the location it points to, indicating whether the file is a * directory or not.
*/ - (BOOL) fileExistsAtPath: (NSString*)path isDirectory: (BOOL*)isDirectory { const _CHAR *lpath = OS2LOCAL(self, path); if (isDirectory != 0) { *isDirectory = NO; } if (lpath == 0 || *lpath == _NUL) { return NO; } #if defined(__MINGW__) { DWORD res; res = GetFileAttributes(lpath); if (res == WIN32ERR) { return NO; } if (isDirectory != 0) { if (res & FILE_ATTRIBUTE_DIRECTORY) { *isDirectory = YES; } } return YES; } #else { struct _STATB statbuf; if (_STAT(lpath, &statbuf) != 0) { return NO; } if (isDirectory) { if ((statbuf.st_mode & S_IFMT) == S_IFDIR) { *isDirectory = YES; } } return YES; } #endif /* MINGW */ } /** * Returns YES if a file (or directory etc) exists at the specified path * and is readable. */ - (BOOL) isReadableFileAtPath: (NSString*)path { const _CHAR* lpath = OS2LOCAL(self, path); if (lpath == 0 || *lpath == _NUL) { return NO; } #if defined(__MINGW__) { DWORD res = GetFileAttributes(lpath); if (res == WIN32ERR) { return NO; } return YES; } #else { if (access(lpath, R_OK) == 0) { return YES; } return NO; } #endif } /** * Returns YES if a file (or directory etc) exists at the specified path * and is writable. */ - (BOOL) isWritableFileAtPath: (NSString*)path { const _CHAR* lpath = OS2LOCAL(self, path); if (lpath == 0 || *lpath == _NUL) { return NO; } #if defined(__MINGW__) { DWORD res= GetFileAttributes(lpath); if (res == WIN32ERR) { return NO; } if (res & FILE_ATTRIBUTE_READONLY) { return NO; } return YES; } #else { if (access(lpath, W_OK) == 0) { return YES; } return NO; } #endif } /** * Returns YES if a file (or directory etc) exists at the specified path * and is executable (if a directory is executable, you can access its * contents). */ - (BOOL) isExecutableFileAtPath: (NSString*)path { const _CHAR* lpath = OS2LOCAL(self, path); if (lpath == 0 || *lpath == _NUL) { return NO; } #if defined(__MINGW__) { DWORD res= GetFileAttributes(lpath); if (res == WIN32ERR) { return NO; } if ([[[path pathExtension] lowercaseString] isEqualToString: @"exe"]) { return YES; } /* FIXME: On unix, directory accessable == executable, so we simulate that here for Windows. Is there a better check for directory access? */ if (res & FILE_ATTRIBUTE_DIRECTORY) { return YES; } return NO; } #else { if (access(lpath, X_OK) == 0) { return YES; } return NO; } #endif } /** * Returns YES if a file (or directory etc) exists at the specified path * and is deletable. */ - (BOOL) isDeletableFileAtPath: (NSString*)path { const _CHAR* lpath = OS2LOCAL(self, path); if (lpath == 0 || *lpath == _NUL) { return NO; } #if defined(__MINGW__) { // TODO - handle directories DWORD res= GetFileAttributes(lpath); if (res == WIN32ERR) { return NO; } return (res & FILE_ATTRIBUTE_READONLY) ? NO : YES; } #else { // TODO - handle directories path = [path stringByDeletingLastPathComponent]; if ([path length] == 0) { path = @"."; } lpath = OS2LOCAL(self, path); if (access(lpath, X_OK | W_OK) == 0) { return YES; } return NO; } #endif } /** * If a file (or directory etc) exists at the specified path, and can be * queried for its attributes, this method returns a dictionary containing * the various attributes of that file. Otherwise nil is returned.
* If the flag is NO and the file is a symbolic link, the attributes of * the link itself (rather than the file it points to) are returned.
*

* The dictionary keys for attributes are - *

* * NSFileAppendOnly * NSNumber ... boolean * NSFileCreationDate * NSDate when the file was created (if supported) * NSFileDeviceIdentifier * NSNumber (identifies the device on which the file is stored) * NSFileExtensionHidden * NSNumber ... boolean * NSFileGroupOwnerAccountName * NSString name of the file group * NSFileGroupOwnerAccountID * NSNumber ID of the file group * NSFileHFSCreatorCode * NSNumber not used * NSFileHFSTypeCode * NSNumber not used * NSFileImmutable * NSNumber ... boolean * NSFileModificationDate * NSDate when the file was last modified * NSFileOwnerAccountName * NSString name of the file owner * NSFileOwnerAccountID * NSNumber ID of the file owner * NSFilePosixPermissions * NSNumber posix access permissions mask * NSFileReferenceCount * NSNumber number of links to this file * NSFileSize * NSNumber size of the file in bytes * NSFileSystemFileNumber * NSNumber the identifier for the file on the filesystem * NSFileSystemNumber * NSNumber the filesystem on which the file is stored * NSFileType * NSString the type of file * *

* The [NSDictionary] class also has a set of convenience accessor methods * which enable you to get at file attribute information more efficiently * than using the keys above to extract it. You should generally * use the accessor methods where they are available. *

* * [NSDictionary-fileCreationDate] * [NSDictionary-fileExtensionHidden] * [NSDictionary-fileHFSCreatorCode] * [NSDictionary-fileHFSTypeCode] * [NSDictionary-fileIsAppendOnly] * [NSDictionary-fileIsImmutable] * [NSDictionary-fileSize] * [NSDictionary-fileType] * [NSDictionary-fileOwnerAccountName] * [NSDictionary-fileOwnerAccountID] * [NSDictionary-fileGroupOwnerAccountName] * [NSDictionary-fileGroupOwnerAccountID] * [NSDictionary-fileModificationDate] * [NSDictionary-filePosixPermissions] * [NSDictionary-fileSystemNumber] * [NSDictionary-fileSystemFileNumber] * */ - (NSDictionary*) fileAttributesAtPath: (NSString*)path traverseLink: (BOOL)flag { const _CHAR *lpath = OS2LOCAL(self, path); NSDictionary *d; d = [GSAttrDictionary attributesAt: lpath traverseLink: flag]; return d; } /** * Returns a dictionary containing the filesystem attributes for the * specified path (or nil if the path is not valid).
* * NSFileSystemSize * NSNumber the size of the filesystem in bytes * NSFileSystemFreeSize * NSNumber the amount of unused space on the filesystem in bytes * NSFileSystemNodes * NSNumber the number of nodes in use to store files * NSFileSystemFreeNodes * NSNumber the number of nodes available to create files * NSFileSystemNumber * NSNumber the identifying number for the filesystem * */ - (NSDictionary*) fileSystemAttributesAtPath: (NSString*)path { #if defined(__MINGW__) unsigned long long totalsize, freesize; id values[5]; id keys[5] = { NSFileSystemSize, NSFileSystemFreeSize, NSFileSystemNodes, NSFileSystemFreeNodes, NSFileSystemNumber }; DWORD SectorsPerCluster, BytesPerSector, NumberFreeClusters; DWORD TotalNumberClusters; const _CHAR *lpath = OS2LOCAL(self, path); if (!GetDiskFreeSpace(lpath, &SectorsPerCluster, &BytesPerSector, &NumberFreeClusters, &TotalNumberClusters)) { return nil; } totalsize = (unsigned long long)TotalNumberClusters * (unsigned long long)SectorsPerCluster * (unsigned long long)BytesPerSector; freesize = (unsigned long long)NumberFreeClusters * (unsigned long long)SectorsPerCluster * (unsigned long long)BytesPerSector; values[0] = [NSNumber numberWithUnsignedLongLong: totalsize]; values[1] = [NSNumber numberWithUnsignedLongLong: freesize]; values[2] = [NSNumber numberWithLong: LONG_MAX]; values[3] = [NSNumber numberWithLong: LONG_MAX]; values[4] = [NSNumber numberWithUnsignedInt: 0]; return [NSDictionary dictionaryWithObjects: values forKeys: keys count: 5]; #else #if defined(HAVE_SYS_VFS_H) || defined(HAVE_SYS_STATFS_H) \ || defined(HAVE_SYS_MOUNT_H) struct _STATB statbuf; #ifdef HAVE_STATVFS struct statvfs statfsbuf; #else struct statfs statfsbuf; #endif unsigned long long totalsize, freesize; const char* lpath = [self fileSystemRepresentationWithPath: path]; id values[5]; id keys[5] = { NSFileSystemSize, NSFileSystemFreeSize, NSFileSystemNodes, NSFileSystemFreeNodes, NSFileSystemNumber }; if (_STAT(lpath, &statbuf) != 0) { return nil; } #ifdef HAVE_STATVFS if (statvfs(lpath, &statfsbuf) != 0) { return nil; } #else if (statfs(lpath, &statfsbuf) != 0) { return nil; } #endif totalsize = (unsigned long long) statfsbuf.f_bsize * (unsigned long long) statfsbuf.f_blocks; freesize = (unsigned long long) statfsbuf.f_bsize * (unsigned long long) statfsbuf.f_bavail; values[0] = [NSNumber numberWithUnsignedLongLong: totalsize]; values[1] = [NSNumber numberWithUnsignedLongLong: freesize]; values[2] = [NSNumber numberWithLong: statfsbuf.f_files]; values[3] = [NSNumber numberWithLong: statfsbuf.f_ffree]; values[4] = [NSNumber numberWithUnsignedLong: statbuf.st_dev]; return [NSDictionary dictionaryWithObjects: values forKeys: keys count: 5]; #else return nil; #endif #endif /* MINGW */ } /** * Returns an array of the contents of the specified directory.
* The listing does not recursively list subdirectories.
* The special files '.' and '..' are not listed.
* Indicates an error by returning nil (eg. if path is not a directory or * it can't be read for some reason). */ - (NSArray*) directoryContentsAtPath: (NSString*)path { NSDirectoryEnumerator *direnum; NSMutableArray *content; IMP nxtImp; IMP addImp; BOOL is_dir; /* * See if this is a directory (don't follow links). */ if ([self fileExistsAtPath: path isDirectory: &is_dir] == NO || is_dir == NO) { return nil; } /* We initialize the directory enumerator with justContents == YES, which tells the NSDirectoryEnumerator code that we only enumerate the contents non-recursively once, and exit. NSDirectoryEnumerator can perform some optms using this assumption. */ direnum = [[NSDirectoryEnumerator alloc] initWithDirectoryPath: path recurseIntoSubdirectories: NO followSymlinks: NO justContents: YES]; content = [NSMutableArray arrayWithCapacity: 128]; nxtImp = [direnum methodForSelector: @selector(nextObject)]; addImp = [content methodForSelector: @selector(addObject:)]; while ((path = (*nxtImp)(direnum, @selector(nextObject))) != nil) { (*addImp)(content, @selector(addObject:), path); } RELEASE(direnum); return [content makeImmutableCopyOnFail: NO]; } /** * Returns the name of the file or directory at path. Converts it into * a format for display to an end user. This may render it unusable as * part of a file/path name.
* For instance, if a user has elected not to see file extensions, this * method may return filenames with the extension removed.
* The default operation is to return the result of calling * [NSString-lastPathComponent] on the path. */ - (NSString*) displayNameAtPath: (NSString*)path { return [path lastPathComponent]; } /** * Returns an enumerator which can be used to return each item with * the directory at path in turn.
* The enumeration is recursive ... following all nested subdirectories. */ - (NSDirectoryEnumerator*) enumeratorAtPath: (NSString*)path { return AUTORELEASE([[NSDirectoryEnumerator alloc] initWithDirectoryPath: path recurseIntoSubdirectories: YES followSymlinks: NO justContents: NO]); } /** * Returns an array containing the (relative) paths of all the items * in the directory at path.
* The listing follows all subdirectories, so it can produce a very * large array ... use with care. */ - (NSArray*) subpathsAtPath: (NSString*)path { NSDirectoryEnumerator *direnum; NSMutableArray *content; BOOL isDir; IMP nxtImp; IMP addImp; if (![self fileExistsAtPath: path isDirectory: &isDir] || !isDir) { return nil; } direnum = [[NSDirectoryEnumerator alloc] initWithDirectoryPath: path recurseIntoSubdirectories: YES followSymlinks: NO justContents: NO]; content = [NSMutableArray arrayWithCapacity: 128]; nxtImp = [direnum methodForSelector: @selector(nextObject)]; addImp = [content methodForSelector: @selector(addObject:)]; while ((path = (*nxtImp)(direnum, @selector(nextObject))) != nil) { (*addImp)(content, @selector(addObject:), path); } RELEASE(direnum); return [content makeImmutableCopyOnFail: NO]; } /** * Creates a symbolic link at path which links to the location * specified by otherPath. */ - (BOOL) createSymbolicLinkAtPath: (NSString*)path pathContent: (NSString*)otherPath { #ifdef HAVE_SYMLINK const char* newpath = [self fileSystemRepresentationWithPath: path]; const char* oldpath = [self fileSystemRepresentationWithPath: otherPath]; return (symlink(oldpath, newpath) == 0); #else return NO; #endif } /** * Returns the name of the file or directory that the symbolic link * at path points to. */ - (NSString*) pathContentOfSymbolicLinkAtPath: (NSString*)path { #ifdef HAVE_READLINK char buf[PATH_MAX]; const char* lpath = [self fileSystemRepresentationWithPath: path]; int llen = readlink(lpath, buf, PATH_MAX-1); if (llen > 0) { return [self stringWithFileSystemRepresentation: buf length: llen]; } else { return nil; } #else return nil; #endif } /** * Convert from OpenStep internal path format (Unix-style) to a string in * the local filesystem format, suitable for passing to system functions.
* Under Unix, this simply standardizes the path and converts to a * C string.
* Under Windoze, this attempts to use local conventions to convert to a * windows path. In GNUstep, the conventional unix syntax '~user/...' can * be used to indicate a windoze drive specification by using the drive * letter in place of the username, and the syntax '~@server/...' can be used * to indicate a file located on the named windoze network server (the * '~@' maps to the leading '//' in a windoze UNC path specification. */ - (const char*) fileSystemRepresentationWithPath: (NSString*)path { NSString *localPath; const char *local_c_path = 0; localPath = [self localFromOpenStepPath: path]; if (localPath && [localPath canBeConvertedToEncoding: [NSString defaultCStringEncoding]]) { local_c_path = [localPath cString]; } return (local_c_path); } /** * Convert from OpenStep internal path format (Unix-style) to a NSString in * the local filesystem format. * Under Windoze, this attempts to use local conventions to convert to a * windows path. In GNUstep, the conventional unix syntax '~user/...' can * be used to indicate a windoze drive specification by using the drive * letter in place of the username, and the syntax '~@server/...' can be used * to indicate a file located on the named windoze network server (the * '~@' maps to the leading '//' in a windoze UNC path specification. */ - (NSString*) localFromOpenStepPath: (NSString*)path { NSString *newpath = nil; #ifdef __MINGW__ /* * If path is in Unix format, transmogrify it so Windows functions * can handle it */ int wcount; // count unichars unichar *wc_path = 0; int l; path = [path stringByStandardizingPath]; wcount = [path length]; if (wcount != 0) { l = wcount; wc_path = (unichar*)calloc(wcount+10,sizeof(unichar)); [path getCharacters: (unichar *)wc_path]; if (l >= 2 && wc_path[0] == L'~' && wc_path[1] == L'@') { // Convert to windows UNC path. wc_path[0] = L'/'; wc_path[1] = L'/'; newpath = [NSString stringWithCharacters: wc_path length: wcount]; } else if (l >= 2 && wc_path[0] == L'~' && iswalpha(wc_path[1]) && (l == 2 || wc_path[2] == L'/')) { wc_path[0] = wc_path[1]; wc_path[1] = L':'; newpath = [NSString stringWithCharacters: wc_path length: wcount]; } else if (l >= 3 && wc_path[0] == L'/' && wc_path[1] == L'/' && iswalpha(wc_path[2])) { if (l == 3 || wc_path[3] == L'/') { /* Cygwin "//c/" type absolute path */ wc_path[1] = wc_path[2]; wc_path[2] = L':'; newpath = [NSString stringWithCharacters: &wc_path[1] length: wcount-1]; } else { /* Windows absolute UNC path "//name/" */ newpath = path; } } else if (isalpha(wc_path[0]) && wc_path[1] == L':') { /* Windows absolute path */ newpath = path; } else if (wc_path[0] == L'/') { #ifdef __CYGWIN__ if (l > 11 && wcsncmp(wc_path, L"/cygdrive/", 10) == 0 && wc_path[11] == L'/') { wc_path[9] = wc_path[10]; wc_path[10] = L':'; newpath = [NSString stringWithCharacters: &wc_path[9] length: wcount-9]; } else { NSDictionary *env; NSString *cyghome; env = [[NSProcessInfo processInfo] environment]; cyghome = [env objectForKey: @"CYGWIN_HOME"]; if (cyghome != nil) { /* FIXME: Find cygwin drive? */ newpath = cyghome; newpath = [newpath stringByAppendingPathComponent: path]; } else { newpath = path; } } #else if (l >= 2 && wc_path[0] == L'/' && iswalpha(wc_path[1]) && (l == 2 || wc_path[2] == L'/')) { /* Mingw /drive/... format */ wc_path[2] = L':'; newpath = [NSString stringWithCharacters: &wc_path[1] length: wcount-1]; } else { newpath = path; } #endif } else { newpath = path; } newpath = [newpath stringByReplacingString: @"/" withString: @"\\"]; if (wc_path) { free (wc_path); } } else { newpath = path; } #else /* * NB ... Don't standardize path, since that would automatically * follow symbolic links ... and mess up any code wishing to * examine the link itsself. * We just need the path in a form where it can be interpreted by * operating system calls (no '~' abbreviations for user directories). */ newpath = [path stringByExpandingTildeInPath]; #endif return (newpath); } /** * This method converts from a local system specific filename representation * to the internal OpenStep representation (unix-style). This should be used * whenever a filename is read in from the local system.
* In GNUstep, windoze drive specifiers are encoded in the internal path * using the conventuional unix syntax of '~user/...' where the drive letter * is used instead of a username. */ - (NSString*) stringWithFileSystemRepresentation: (const char*)string length: (unsigned int)len { NSString *localPath = nil; if (string != 0) { localPath = [NSString stringWithCString: string length: len]; } return([self openStepPathFromLocal: localPath]); } /** * This method converts from a local system specific filename representation * to the internal OpenStep representation (unix-style). This should be used * whenever a filename is read in from the local system.
* In GNUstep, windoze drive specifiers are encoded in the internal path * using the conventuional unix syntax of '~user/...' where the drive letter * is used instead of a username. */ - (NSString*) openStepPathFromLocal: (NSString*)localPath { #ifdef __MINGW__ int len; // count unichars unichar *wc_path = 0; len = [localPath length]; if (len != 0) { wc_path = (unichar*)calloc(len+10,sizeof(unichar)); [localPath getCharacters: (unichar *)wc_path]; } if (wc_path) { const unichar *ptr = wc_path; unichar buf[len + 20]; unsigned i; unsigned j; /* * If path is in Windows format, transmogrify it so Unix functions * can handle it */ if (len == 0) { free(wc_path); return @""; } if (len >= 2 && ((ptr[1] == L'/' && ptr[0] == L'/') || (ptr[1] == L'\\' && ptr[0] == L'\\'))) { /* * Convert '///' to '~@/' sequences. */ buf[0] = L'~'; buf[1] = L'@'; i = 2; } else if (len >= 2 && ptr[1] == L':' && iswalpha(ptr[0])) { /* * Convert ':' to '~/' sequences. */ buf[0] = L'~'; buf[1] = ptr[0]; buf[2] = L'/'; ptr -= 1; len++; i = 3; } #ifdef __CYGWIN__ else if (len > 9 && wcsncmp(ptr, L"/cygdrive/", 10) == 0) { buf[0] = L'~'; ptr += 9; len -= 9; i = 1; } #else else if (len >= 2 && ptr[0] == L'/' && iswalpha(ptr[1]) && (len == 2 || ptr[2] == L'/')) { /* * Convert '/' to '~' sequences. */ buf[0] = L'~'; i = 1; } #endif else { i = 0; } /* * Convert backslashes to slashes, colaescing adjacent slashes. * Also elide '/./' sequences, because we can do so efficiently. */ j = i; while (i < len) { if (ptr[i] == L'\\') { if (j == 0 || buf[j-1] != L'/') { if (j > 2 && buf[j-2] == L'/' && buf[j-1] == L'.') { j--; } else { buf[j++] = L'/'; } } } else { buf[j++] = ptr[i]; } i++; } buf[j] = _NUL; // NSLog(@"Map '%s' to '%s'", string, buf); free(wc_path); return [NSString stringWithCharacters: buf length: j]; } else { return(@""); } #endif return localPath; } @end /* NSFileManager */ /* A directory to enumerate. We keep a stack of the directories we still have to enumerate. We start by putting the top-level directory into the stack, then we start reading files from it (using readdir). If we find a file which is actually a directory, and if we have to recurse into it, we create a new GSEnumeratedDirectory struct for the subdirectory, open its DIR *pointer for reading, and put it on top of the stack, so next time -nextObject is called, it will read from that directory instead of the top level one. Once all the subdirectory is read, it is removed from the stack, so the top of the stack if the top directory again, and enumeration continues in there. */ typedef struct _GSEnumeratedDirectory { NSString *path; _DIR *pointer; } GSEnumeratedDirectory; inline void gsedRelease(GSEnumeratedDirectory X) { DESTROY(X.path); _CLOSEDIR(X.pointer); } #define GSI_ARRAY_TYPES 0 #define GSI_ARRAY_TYPE GSEnumeratedDirectory #define GSI_ARRAY_RELEASE(A, X) gsedRelease(X.ext) #define GSI_ARRAY_RETAIN(A, X) #include "GNUstepBase/GSIArray.h" static SEL ospfl = 0; /** *

This is a subclass of NSEnumerator which provides a full * listing of all the files beneath a directory and its subdirectories. * Instances can be obtained through [NSFileManager-enumeratorAtPath:], * or through an initializer in this class. (For compatibility with OS X, * use the NSFileManager method.)

* *

This implementation is optimized and performance should be comparable * to the speed of standard Unix tools for large directories.

*/ @implementation NSDirectoryEnumerator /* * The Objective-C interface hides a traditional C implementation. * This was the only way I could get near the speed of standard unix * tools for big directories. */ + (void) initialize { if (self == [NSDirectoryEnumerator class]) { /* Initialize the default manager which we access directly */ [NSFileManager defaultManager]; ospfl = @selector(openStepPathFromLocal:); } } // Initializing /** * Initialize instance to enumerate contents at path, which should be a * directory and can be specified in relative or absolute, and may include * Unix conventions like '~' for user home directory, which will * be appropriately converted on Windoze systems. The justContents flag, if * set, is equivalent to recurseIntoSubdirectories = NO and followSymlinks = * NO, but the implementation will be made more efficient. */ - (id) initWithDirectoryPath: (NSString*)path recurseIntoSubdirectories: (BOOL)recurse followSymlinks: (BOOL)follow justContents: (BOOL)justContents { //TODO: the justContents flag is currently basically useless and should be // removed _DIR *dir_pointer; const _CHAR *localPath; self = [super init]; _openStepPathFromLocalImp = (NSString *(*)(id, SEL,id)) [defaultManager methodForSelector: ospfl]; _stack = NSZoneMalloc([self zone], sizeof(GSIArray_t)); GSIArrayInitWithZoneAndCapacity(_stack, [self zone], 64); _flags.isRecursive = recurse; _flags.isFollowing = follow; _flags.justContents = justContents; _topPath = [[NSString alloc] initWithString: path]; localPath = OS2LOCAL(defaultManager, path); dir_pointer = _OPENDIR(localPath); if (dir_pointer) { GSIArrayItem item; item.ext.path = @""; item.ext.pointer = dir_pointer; GSIArrayAddItem(_stack, item); } else { NSLog(@"Failed to recurse into directory '%@' - %s", path, GSLastErrorStr(errno)); } return self; } - (void) dealloc { GSIArrayEmpty(_stack); NSZoneFree([self zone], _stack); DESTROY(_topPath); DESTROY(_currentFilePath); [super dealloc]; } /** * Returns a dictionary containing the attributes of the directory * at which enumeration started.
* The contents of this dictionary are as produced by * [NSFileManager-fileAttributesAtPath:traverseLink:] */ - (NSDictionary*) directoryAttributes { return [defaultManager fileAttributesAtPath: _topPath traverseLink: _flags.isFollowing]; } /** * Returns a dictionary containing the attributes of the file * currently being enumerated.
* The contents of this dictionary are as produced by * [NSFileManager-fileAttributesAtPath:traverseLink:] */ - (NSDictionary*) fileAttributes { return [defaultManager fileAttributesAtPath: _currentFilePath traverseLink: _flags.isFollowing]; } /** * Informs the receiver that any descendents of the current directory * should be skipped rather than enumerated. Use this to avaoid enumerating * the contents of directories you are not interested in. */ - (void) skipDescendents { if (GSIArrayCount(_stack) > 0) { GSIArrayRemoveLastItem(_stack); if (_currentFilePath != 0) { DESTROY(_currentFilePath); } } } /* * finds the next file according to the top enumerator * - if there is a next file it is put in currentFile * - if the current file is a directory and if isRecursive calls * recurseIntoDirectory: currentFile * - if the current file is a symlink to a directory and if isRecursive * and isFollowing calls recurseIntoDirectory: currentFile * - if at end of current directory pops stack and attempts to * find the next entry in the parent * - sets currentFile to nil if there are no more files to enumerate */ - (id) nextObject { NSString *returnFileName = 0; if (_currentFilePath != 0) { DESTROY(_currentFilePath); } while (GSIArrayCount(_stack) > 0) { GSEnumeratedDirectory dir = GSIArrayLastItem(_stack).ext; struct _DIRENT *dirbuf; struct _STATB statbuf; dirbuf = _READDIR(dir.pointer); if (dirbuf) { #if defined(__MINGW__) && defined(UNICODE) /* Skip "." and ".." directory entries */ if (wcscmp(dirbuf->d_name, L".") == 0 || wcscmp(dirbuf->d_name, L"..") == 0) { continue; } /* Name of file to return */ returnFileName = _openStepPathFromLocalImp(defaultManager, ospfl, [NSString stringWithCharacters: dirbuf->d_name length: wcslen(dirbuf->d_name)]); #else /* Skip "." and ".." directory entries */ if (strcmp(dirbuf->d_name, ".") == 0 || strcmp(dirbuf->d_name, "..") == 0) { continue; } /* Name of file to return */ returnFileName = _openStepPathFromLocalImp(defaultManager, ospfl, [NSString stringWithCString: dirbuf->d_name]); #endif returnFileName = [dir.path stringByAppendingPathComponent: returnFileName]; RETAIN(returnFileName); /* TODO - can this one can be removed ? */ if (!_flags.justContents) _currentFilePath = RETAIN([_topPath stringByAppendingPathComponent: returnFileName]); if (_flags.isRecursive == YES) { // Do not follow links #ifdef S_IFLNK #ifdef __MINGW__ #warning "lstat does not support unichars" #else if (!_flags.isFollowing) { if (lstat([_currentFilePath fileSystemRepresentation], &statbuf) != 0) { break; } // If link then return it as link if (S_IFLNK == (S_IFMT & statbuf.st_mode)) { break; } } else #endif #endif { if (_STAT(OS2LOCAL(defaultManager, _currentFilePath), &statbuf) != 0) { break; } } if (S_IFDIR == (S_IFMT & statbuf.st_mode)) { _DIR* dir_pointer; dir_pointer = _OPENDIR(OS2LOCAL(defaultManager, _currentFilePath)); if (dir_pointer) { GSIArrayItem item; item.ext.path = RETAIN(returnFileName); item.ext.pointer = dir_pointer; GSIArrayAddItem(_stack, item); } else { NSLog(@"Failed to recurse into directory '%@' - %s", _currentFilePath, GSLastErrorStr(errno)); } } } break; // Got a file name - break out of loop } else { GSIArrayRemoveLastItem(_stack); if (_currentFilePath != 0) { DESTROY(_currentFilePath); } } } return AUTORELEASE(returnFileName); } @end /* NSDirectoryEnumerator */ /** * Convenience methods for accessing named file attributes in a dictionary. */ @implementation NSDictionary(NSFileAttributes) /** * Return the file creation date attribute (or nil if not found). */ - (NSDate*) fileCreationDate { return [self objectForKey: NSFileCreationDate]; } /** * Return the file extension hidden attribute (or NO if not found). */ - (BOOL) fileExtensionHidden { return [[self objectForKey: NSFileExtensionHidden] boolValue]; } /** * Returns HFS creator attribute (OS X). */ - (int) fileHFSCreatorCode { return [[self objectForKey: NSFileHFSCreatorCode] intValue]; } /** * Returns HFS type code attribute (OS X). */ - (int) fileHFSTypeCode { return [[self objectForKey: NSFileHFSTypeCode] intValue]; } /** * Return the file append only attribute (or NO if not found). */ - (BOOL) fileIsAppendOnly { return [[self objectForKey: NSFileAppendOnly] boolValue]; } /** * Return the file immutable attribute (or NO if not found). */ - (BOOL) fileIsImmutable { return [[self objectForKey: NSFileImmutable] boolValue]; } /** * Return the size of the file, or NSNotFound if the file size attribute * is not found in the dictionary. */ - (unsigned long long) fileSize { NSNumber *n = [self objectForKey: NSFileSize]; if (n == nil) { return NSNotFound; } return [n unsignedLongLongValue]; } /** * Return the file type attribute or nil if not present. */ - (NSString*) fileType { return [self objectForKey: NSFileType]; } /** * Return the file owner account name attribute or nil if not present. */ - (NSString*) fileOwnerAccountName { return [self objectForKey: NSFileOwnerAccountName]; } /** * Return the numeric value of the NSFileOwnerAccountID attribute * in the dictionary, or NSNotFound if the attribute is not present. */ - (unsigned long) fileOwnerAccountID { NSNumber *n = [self objectForKey: NSFileOwnerAccountID]; if (n == nil) { return NSNotFound; } return [n unsignedIntValue]; } /** * Return the file group owner account name attribute or nil if not present. */ - (NSString*) fileGroupOwnerAccountName { return [self objectForKey: NSFileGroupOwnerAccountName]; } /** * Return the numeric value of the NSFileGroupOwnerAccountID attribute * in the dictionary, or NSNotFound if the attribute is not present. */ - (unsigned long) fileGroupOwnerAccountID { NSNumber *n = [self objectForKey: NSFileGroupOwnerAccountID]; if (n == nil) { return NSNotFound; } return [n unsignedIntValue]; } /** * Return the file modification date attribute (or nil if not found) */ - (NSDate*) fileModificationDate { return [self objectForKey: NSFileModificationDate]; } /** * Return the file posix permissions attribute (or NSNotFound if * the attribute is not present in the dictionary). */ - (unsigned long) filePosixPermissions { NSNumber *n = [self objectForKey: NSFilePosixPermissions]; if (n == nil) { return NSNotFound; } return [n unsignedLongValue]; } /** * Return the file system number attribute (or NSNotFound if * the attribute is not present in the dictionary). */ - (unsigned long) fileSystemNumber { NSNumber *n = [self objectForKey: NSFileSystemNumber]; if (n == nil) { return NSNotFound; } return [n unsignedLongValue]; } /** * Return the file system file identification number attribute * or NSNotFound if the attribute is not present in the dictionary). */ - (unsigned long) fileSystemFileNumber { NSNumber *n = [self objectForKey: NSFileSystemFileNumber]; if (n == nil) { return NSNotFound; } return [n unsignedLongValue]; } @end @implementation NSFileManager (PrivateMethods) - (BOOL) _copyFile: (NSString*)source toFile: (NSString*)destination handler: (id)handler { #if defined(__MINGW__) if (CopyFile(OS2LOCAL(self, source), OS2LOCAL(self, destination), NO)) { return YES; } return [self _proceedAccordingToHandler: handler forError: @"cannot copy file" inPath: source fromPath: source toPath: destination]; #else NSDictionary *attributes; int i; int bufsize = 8096; int sourceFd; int destFd; int fileSize; int fileMode; int rbytes; int wbytes; char buffer[bufsize]; /* Assumes source is a file and exists! */ NSAssert1 ([self fileExistsAtPath: source], @"source file '%@' does not exist!", source); attributes = [self fileAttributesAtPath: source traverseLink: NO]; NSAssert1 (attributes, @"could not get the attributes for file '%@'", source); fileSize = [attributes fileSize]; fileMode = [attributes filePosixPermissions]; /* Open the source file. In case of error call the handler. */ sourceFd = open([self fileSystemRepresentationWithPath: source], GSBINIO|O_RDONLY); if (sourceFd < 0) { return [self _proceedAccordingToHandler: handler forError: @"cannot open file for reading" inPath: source fromPath: source toPath: destination]; } /* Open the destination file. In case of error call the handler. */ destFd = open([self fileSystemRepresentationWithPath: destination], GSBINIO|O_WRONLY|O_CREAT|O_TRUNC, fileMode); if (destFd < 0) { close (sourceFd); return [self _proceedAccordingToHandler: handler forError: @"cannot open file for writing" inPath: destination fromPath: source toPath: destination]; } /* Read bufsize bytes from source file and write them into the destination file. In case of errors call the handler and abort the operation. */ for (i = 0; i < fileSize; i += rbytes) { rbytes = read (sourceFd, buffer, bufsize); if (rbytes < 0) { close (sourceFd); close (destFd); return [self _proceedAccordingToHandler: handler forError: @"cannot read from file" inPath: source fromPath: source toPath: destination]; } wbytes = write (destFd, buffer, rbytes); if (wbytes != rbytes) { close (sourceFd); close (destFd); return [self _proceedAccordingToHandler: handler forError: @"cannot write to file" inPath: destination fromPath: source toPath: destination]; } } close (sourceFd); close (destFd); return YES; #endif } - (BOOL) _copyPath: (NSString*)source toPath: (NSString*)destination handler: handler { NSDirectoryEnumerator *enumerator; NSString *dirEntry; CREATE_AUTORELEASE_POOL(pool); enumerator = [self enumeratorAtPath: source]; while ((dirEntry = [enumerator nextObject])) { NSString *sourceFile; NSString *fileType; NSString *destinationFile; NSDictionary *attributes; attributes = [enumerator fileAttributes]; fileType = [attributes fileType]; sourceFile = [source stringByAppendingPathComponent: dirEntry]; destinationFile = [destination stringByAppendingPathComponent: dirEntry]; [self _sendToHandler: handler willProcessPath: sourceFile]; if ([fileType isEqual: NSFileTypeDirectory]) { if (![self createDirectoryAtPath: destinationFile attributes: attributes]) { if (![self _proceedAccordingToHandler: handler forError: _lastError inPath: destinationFile fromPath: sourceFile toPath: destinationFile]) { return NO; } } else { [enumerator skipDescendents]; if (![self _copyPath: sourceFile toPath: destinationFile handler: handler]) return NO; } } else if ([fileType isEqual: NSFileTypeRegular]) { if (![self _copyFile: sourceFile toFile: destinationFile handler: handler]) return NO; } else if ([fileType isEqual: NSFileTypeSymbolicLink]) { NSString *path; path = [self pathContentOfSymbolicLinkAtPath: sourceFile]; if (![self createSymbolicLinkAtPath: destinationFile pathContent: path]) { if (![self _proceedAccordingToHandler: handler forError: @"cannot create symbolic link" inPath: sourceFile fromPath: sourceFile toPath: destinationFile]) { return NO; } } } else { NSString *s; s = [NSString stringWithFormat: @"cannot copy file type '%@'", fileType]; ASSIGN(_lastError, s); NSLog(@"%@: %@", sourceFile, s); continue; } [self changeFileAttributes: attributes atPath: destinationFile]; } RELEASE(pool); return YES; } - (BOOL) _linkPath: (NSString*)source toPath: (NSString*)destination handler: handler { #ifdef HAVE_LINK NSDirectoryEnumerator *enumerator; NSString *dirEntry; CREATE_AUTORELEASE_POOL(pool); enumerator = [self enumeratorAtPath: source]; while ((dirEntry = [enumerator nextObject])) { NSString *sourceFile; NSString *fileType; NSString *destinationFile; NSDictionary *attributes; attributes = [enumerator fileAttributes]; fileType = [attributes fileType]; sourceFile = [source stringByAppendingPathComponent: dirEntry]; destinationFile = [destination stringByAppendingPathComponent: dirEntry]; [self _sendToHandler: handler willProcessPath: sourceFile]; if ([fileType isEqual: NSFileTypeDirectory] == YES) { if ([self createDirectoryAtPath: destinationFile attributes: attributes] == NO) { if ([self _proceedAccordingToHandler: handler forError: _lastError inPath: destinationFile fromPath: sourceFile toPath: destinationFile] == NO) { return NO; } } else { [enumerator skipDescendents]; if ([self _linkPath: sourceFile toPath: destinationFile handler: handler] == NO) { return NO; } } } else if ([fileType isEqual: NSFileTypeSymbolicLink]) { NSString *path; path = [self pathContentOfSymbolicLinkAtPath: sourceFile]; if ([self createSymbolicLinkAtPath: destinationFile pathContent: path] == NO) { if ([self _proceedAccordingToHandler: handler forError: @"cannot create symbolic link" inPath: sourceFile fromPath: sourceFile toPath: destinationFile] == NO) { return NO; } } } else { if (link([sourceFile fileSystemRepresentation], [destinationFile fileSystemRepresentation]) < 0) { if ([self _proceedAccordingToHandler: handler forError: @"cannot create hard link" inPath: sourceFile fromPath: sourceFile toPath: destinationFile] == NO) { return NO; } } } [self changeFileAttributes: attributes atPath: destinationFile]; } RELEASE(pool); return YES; #else return NO; #endif } - (void) _sendToHandler: (id) handler willProcessPath: (NSString*) path { if ([handler respondsToSelector: @selector (fileManager:willProcessPath:)]) { [handler fileManager: self willProcessPath: path]; } } - (BOOL) _proceedAccordingToHandler: (id) handler forError: (NSString*) error inPath: (NSString*) path { if ([handler respondsToSelector: @selector (fileManager:shouldProceedAfterError:)]) { NSDictionary *errorInfo = [NSDictionary dictionaryWithObjectsAndKeys: path, @"Path", error, @"Error", nil]; return [handler fileManager: self shouldProceedAfterError: errorInfo]; } return NO; } - (BOOL) _proceedAccordingToHandler: (id) handler forError: (NSString*) error inPath: (NSString*) path fromPath: (NSString*) fromPath toPath: (NSString*) toPath { if ([handler respondsToSelector: @selector (fileManager:shouldProceedAfterError:)]) { NSDictionary *errorInfo = [NSDictionary dictionaryWithObjectsAndKeys: path, @"Path", fromPath, @"FromPath", toPath, @"ToPath", error, @"Error", nil]; return [handler fileManager: self shouldProceedAfterError: errorInfo]; } return NO; } @end /* NSFileManager (PrivateMethods) */ @implementation GSAttrDictionary static NSSet *fileKeys = nil; + (NSDictionary*) attributesAt: (const _CHAR*)lpath traverseLink: (BOOL)traverse { GSAttrDictionary *d; if (lpath == 0 || *lpath == 0) { return nil; } d = (GSAttrDictionary*)NSAllocateObject(self, 0, NSDefaultMallocZone()); #if defined(S_IFLNK) && !defined(__MINGW__) if (traverse == NO) { if (lstat(lpath, &d->statbuf) != 0) { DESTROY(d); } } else #endif if (_STAT(lpath, &d->statbuf) != 0) { DESTROY(d); } return AUTORELEASE(d); } + (void) initialize { if (fileKeys == nil) { fileKeys = [NSSet setWithObjects: NSFileAppendOnly, NSFileCreationDate, NSFileDeviceIdentifier, NSFileExtensionHidden, NSFileGroupOwnerAccountName, NSFileGroupOwnerAccountID, NSFileHFSCreatorCode, NSFileHFSTypeCode, NSFileImmutable, NSFileModificationDate, NSFileOwnerAccountName, NSFileOwnerAccountID, NSFilePosixPermissions, NSFileReferenceCount, NSFileSize, NSFileSystemFileNumber, NSFileSystemNumber, NSFileType, nil]; RETAIN(fileKeys); } } - (unsigned int) count { return [fileKeys count]; } - (NSDate*) fileCreationDate { /* * FIXME ... not sure there is any way to get a creation date :-( * Use the earlier of ctime or mtime */ if (statbuf.st_ctime < statbuf.st_mtime) return [NSDate dateWithTimeIntervalSince1970: statbuf.st_ctime]; else return [NSDate dateWithTimeIntervalSince1970: statbuf.st_mtime]; } - (BOOL) fileExtensionHidden { return NO; } - (unsigned long) fileGroupOwnerAccountID { return statbuf.st_gid; } - (NSString*) fileGroupOwnerAccountName { NSString *result = @"UnknownGroup"; #if defined(HAVE_GRP_H) struct group *gp; gp = getgrgid(statbuf.st_gid); if (gp != 0) { result = [NSString stringWithCString: gp->gr_name]; } #endif return result; } - (int) fileHFSCreatorCode { return 0; } - (int) fileHFSTypeCode { return 0; } - (BOOL) fileIsAppendOnly { return 0; } - (BOOL) fileIsImmutable { return 0; } - (NSDate*) fileModificationDate { return [NSDate dateWithTimeIntervalSince1970: statbuf.st_mtime]; } - (unsigned long) filePosixPermissions { return (statbuf.st_mode & ~S_IFMT); } - (unsigned long) fileOwnerAccountID { return statbuf.st_uid; } - (NSString*) fileOwnerAccountName { NSString *result = @"UnknownUser"; #ifdef __MINGW_NOT_AVAILABLE_YET { DWORD dwRtnCode = 0; PSID pSidOwner; BOOL bRtnBool = TRUE; LPTSTR AcctName; LPTSTR DomainName; DWORD dwAcctName = 1; DWORD dwDomainName = 1; SID_NAME_USE eUse = SidTypeUnknown; HANDLE hFile; PSECURITY_DESCRIPTOR pSD; // Get the handle of the file object. hFile = CreateFile( "myfile.txt", GENERIC_READ, FILE_SHARE_READ, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0); // Check GetLastError for CreateFile error code. if (hFile == INVALID_HANDLE_VALUE) { DWORD dwErrorCode = 0; dwErrorCode = GetLastError(); _tprintf(TEXT("CreateFile error = %d\n"), dwErrorCode); return -1; } // Allocate memory for the SID structure. pSidOwner = (PSID)GlobalAlloc( GMEM_FIXED, sizeof(PSID)); // Allocate memory for the security descriptor structure. pSD = (PSECURITY_DESCRIPTOR)GlobalAlloc( GMEM_FIXED, sizeof(PSECURITY_DESCRIPTOR)); // Get the owner SID of the file. dwRtnCode = GetSecurityInfo( hFile, SE_FILE_OBJECT, OWNER_SECURITY_INFORMATION, &pSidOwner, 0, 0, 0, &pSD); // Check GetLastError for GetSecurityInfo error condition. if (dwRtnCode != ERROR_SUCCESS) { DWORD dwErrorCode = 0; dwErrorCode = GetLastError(); _tprintf(TEXT("GetSecurityInfo error = %d\n"), dwErrorCode); return -1; } // First call to LookupAccountSid to get the buffer sizes. bRtnBool = LookupAccountSid( 0, // local computer pSidOwner, AcctName, (LPDWORD)&dwAcctName, DomainName, (LPDWORD)&dwDomainName, &eUse); // Reallocate memory for the buffers. AcctName = (char *)GlobalAlloc( GMEM_FIXED, dwAcctName); // Check GetLastError for GlobalAlloc error condition. if (AcctName == 0) { DWORD dwErrorCode = 0; dwErrorCode = GetLastError(); _tprintf(TEXT("GlobalAlloc error = %d\n"), dwErrorCode); return -1; } DomainName = (char *)GlobalAlloc( GMEM_FIXED, dwDomainName); // Check GetLastError for GlobalAlloc error condition. if (DomainName == 0) { DWORD dwErrorCode = 0; dwErrorCode = GetLastError(); _tprintf(TEXT("GlobalAlloc error = %d\n"), dwErrorCode); return -1; } // Second call to LookupAccountSid to get the account name. bRtnBool = LookupAccountSid( 0, // name of local or remote computer pSidOwner, // security identifier AcctName, // account name buffer (LPDWORD)&dwAcctName, // size of account name buffer DomainName, // domain name (LPDWORD)&dwDomainName, // size of domain name buffer &eUse); // SID type // Check GetLastError for LookupAccountSid error condition. if (bRtnBool == FALSE) { DWORD dwErrorCode = 0; dwErrorCode = GetLastError(); if (dwErrorCode == ERROR_NONE_MAPPED) _tprintf(TEXT("Account owner not found for specified SID.\n")); else _tprintf(TEXT("Error in LookupAccountSid.\n")); return -1; } else if (bRtnBool == TRUE) { // Print the account name. _tprintf(TEXT("Account owner = %s\n"), AcctName); } return 0; } #endif #ifdef HAVE_PWD_H struct passwd *pw; pw = getpwuid(statbuf.st_uid); if (pw != 0) { result = [NSString stringWithCString: pw->pw_name]; } #endif /* HAVE_PWD_H */ return result; } - (unsigned long long) fileSize { return statbuf.st_size; } - (unsigned long) fileSystemFileNumber { return statbuf.st_ino; } - (unsigned long) fileSystemNumber { return statbuf.st_dev; } - (NSString*) fileType { switch (statbuf.st_mode & S_IFMT) { case S_IFREG: return NSFileTypeRegular; case S_IFDIR: return NSFileTypeDirectory; case S_IFCHR: return NSFileTypeCharacterSpecial; case S_IFBLK: return NSFileTypeBlockSpecial; #ifdef S_IFLNK case S_IFLNK: return NSFileTypeSymbolicLink; #endif case S_IFIFO: return NSFileTypeFifo; #ifdef S_IFSOCK case S_IFSOCK: return NSFileTypeSocket; #endif default: return NSFileTypeUnknown; } } - (NSEnumerator*) keyEnumerator { return [fileKeys objectEnumerator]; } - (NSEnumerator*) objectEnumerator { return [GSAttrDictionaryEnumerator enumeratorFor: self]; } - (id) objectForKey: (NSString*)key { int count = 0; while (key != 0 && count < 2) { if (key == NSFileAppendOnly) return [NSNumber numberWithBool: [self fileIsAppendOnly]]; if (key == NSFileCreationDate) return [self fileCreationDate]; if (key == NSFileDeviceIdentifier) return [NSNumber numberWithUnsignedInt: statbuf.st_dev]; if (key == NSFileExtensionHidden) return [NSNumber numberWithBool: [self fileExtensionHidden]]; if (key == NSFileGroupOwnerAccountName) return [self fileGroupOwnerAccountName]; if (key == NSFileGroupOwnerAccountID) return [NSNumber numberWithInt: [self fileGroupOwnerAccountID]]; if (key == NSFileHFSCreatorCode) return [NSNumber numberWithInt: [self fileHFSCreatorCode]]; if (key == NSFileHFSTypeCode) return [NSNumber numberWithInt: [self fileHFSTypeCode]]; if (key == NSFileImmutable) return [NSNumber numberWithBool: [self fileIsImmutable]]; if (key == NSFileModificationDate) return [self fileModificationDate]; if (key == NSFileOwnerAccountName) return [self fileOwnerAccountName]; if (key == NSFileOwnerAccountID) return [NSNumber numberWithInt: [self fileOwnerAccountID]]; if (key == NSFilePosixPermissions) return [NSNumber numberWithUnsignedInt: [self filePosixPermissions]]; if (key == NSFileReferenceCount) return [NSNumber numberWithUnsignedInt: statbuf.st_nlink]; if (key == NSFileSize) return [NSNumber numberWithUnsignedLongLong: [self fileSize]]; if (key == NSFileSystemFileNumber) return [NSNumber numberWithUnsignedInt: [self fileSystemFileNumber]]; if (key == NSFileSystemNumber) return [NSNumber numberWithUnsignedInt: [self fileSystemNumber]]; if (key == NSFileType) return [self fileType]; /* * Now, if we didn't get an exact pointer match, check for * string equalities and ensure we get an exact match next * time round the loop. */ count++; key = [fileKeys member: key]; } if (count >= 2) { NSLog(@"Warning ... key '%@' not handled", key); } return nil; } @end /* GSAttrDictionary */ @implementation GSAttrDictionaryEnumerator + (NSEnumerator*) enumeratorFor: (NSDictionary*)d { GSAttrDictionaryEnumerator *e; e = (GSAttrDictionaryEnumerator*) NSAllocateObject(self, 0, NSDefaultMallocZone()); e->dictionary = RETAIN(d); e->enumerator = RETAIN([fileKeys objectEnumerator]); return AUTORELEASE(e); } - (void) dealloc { RELEASE(enumerator); RELEASE(dictionary); [super dealloc]; } - (id) nextObject { NSString *key = [enumerator nextObject]; id val = nil; if (key != nil) { val = [dictionary objectForKey: key]; } return val; } @end NSString * const NSFileAppendOnly = @"NSFileAppendOnly"; NSString * const NSFileCreationDate = @"NSFileCreationDate"; NSString * const NSFileDeviceIdentifier = @"NSFileDeviceIdentifier"; NSString * const NSFileExtensionHidden = @"NSFileExtensionHidden"; NSString * const NSFileGroupOwnerAccountID = @"NSFileGroupOwnerAccountID"; NSString * const NSFileGroupOwnerAccountName = @"NSFileGroupOwnerAccountName"; NSString * const NSFileHFSCreatorCode = @"NSFileHFSCreatorCode"; NSString * const NSFileHFSTypeCode = @"NSFileHFSTypeCode"; NSString * const NSFileImmutable = @"NSFileImmutable"; NSString * const NSFileModificationDate = @"NSFileModificationDate"; NSString * const NSFileOwnerAccountID = @"NSFileOwnerAccountID"; NSString * const NSFileOwnerAccountName = @"NSFileOwnerAccountName"; NSString * const NSFilePosixPermissions = @"NSFilePosixPermissions"; NSString * const NSFileReferenceCount = @"NSFileReferenceCount"; NSString * const NSFileSize = @"NSFileSize"; NSString * const NSFileSystemFileNumber = @"NSFileSystemFileNumber"; NSString * const NSFileSystemFreeNodes = @"NSFileSystemFreeNodes"; NSString * const NSFileSystemFreeSize = @"NSFileSystemFreeSize"; NSString * const NSFileSystemNodes = @"NSFileSystemNodes"; NSString * const NSFileSystemNumber = @"NSFileSystemNumber"; NSString * const NSFileSystemSize = @"NSFileSystemSize"; NSString * const NSFileType = @"NSFileType"; NSString * const NSFileTypeBlockSpecial = @"NSFileTypeBlockSpecial"; NSString * const NSFileTypeCharacterSpecial = @"NSFileTypeCharacterSpecial"; NSString * const NSFileTypeDirectory = @"NSFileTypeDirectory"; NSString * const NSFileTypeFifo = @"NSFileTypeFifo"; NSString * const NSFileTypeRegular = @"NSFileTypeRegular"; NSString * const NSFileTypeSocket = @"NSFileTypeSocket"; NSString * const NSFileTypeSymbolicLink = @"NSFileTypeSymbolicLink"; NSString * const NSFileTypeUnknown = @"NSFileTypeUnknown";