/* NSURL+SOExtendedAttributes Copyright 2012 Standard Orbit Software, LLC. All rights reserved. License at the bottom of the file. */#if ! __has_feature(objc_arc)#error This file must be compiled with ARC (set -fobjc_arc flag on file)#endif#import <Foundation/Foundation.h>#import "NSURL+SOExtendedAttributes.h"#import <sys/xattr.h>NSString*constiCloudDoNotBackupAttributeName=@"com.apple.MobileBackup";NSString*constSOExtendedAttributesErrorDomain=@"SOExtendedAttributesErrorDomain";/* Use default options with xattr API that don't resolve symlinks and show the HFS compression extended attribute. */staticintxattrDefaultOptions=XATTR_NOFOLLOW|XATTR_SHOWCOMPRESSION;/* Make an NSError from the global errno and optionally the url */staticinlineNSError*SOPOSIXErrorForURL(NSURL*url){intposixErr=errno;NSString*errDesc=[NSStringstringWithUTF8String:strerror(posixErr)];NSMutableDictionary*errInfo=[NSMutableDictionarydictionary];[errInfosetObject:errDescforKey:NSLocalizedDescriptionKey];if(url){[errInfosetObject:urlforKey:NSURLErrorKey];}return[NSErrorerrorWithDomain:NSPOSIXErrorDomaincode:posixErruserInfo:errInfo];}@implementationNSURL(SOExtendedAttributes)-(NSArray*)namesOfExtendedAttributesWithError:(NSError*__autoreleasing*)outError{if(![selfisFileURL])[NSExceptionraise:NSInternalInconsistencyExceptionformat:@"%s only valid on file URLs",__PRETTY_FUNCTION__];NSMutableArray*attributeNames=[[NSMutableArrayalloc]init];@autoreleasepool{/* Get attributes names. Bail with nil dictionary if problem */constchar*itemPath=[[selfpath]fileSystemRepresentation];/* Get the size of the attributes list, then extract each name as an NSString. */NSMutableData*namesBuffer=nil;ssize_tbufferSize=listxattr(itemPath,NULL,SIZE_MAX,xattrDefaultOptions);if(bufferSize>0){namesBuffer=[NSMutableDatadataWithLength:bufferSize];bufferSize=listxattr(itemPath,[namesBuffermutableBytes],[namesBufferlength],xattrDefaultOptions);}/* No names? Bail now with empty list. */if(bufferSize==0)returnattributeNames;/* Problemo? Bail now with the POSIX error. */if(bufferSize==-1){attributeNames=nil;*outError=SOPOSIXErrorForURL(self);returnnil;}/* Parse the name buffer for attribute names. Iterate the buffer character by character, looking for a NULL byte. When found, collect the range of bytes into an NSString and cache in our names list. */uintptr_tptr_startOfBuffer=(uintptr_t)[namesBuffermutableBytes];uintptr_tptr_startOfName=ptr_startOfBuffer;for(size_tx=0;x<bufferSize;x++){/* Advance current byte pointer */uintptr_tptr_currentByte=ptr_startOfBuffer+x;/* Check for the end of a name */if(*((char*)ptr_currentByte)==0x0){/* Collect the attribute name */NSString*name=[[NSStringalloc]initWithUTF8String:(char*)ptr_startOfName];[attributeNamesaddObject:name];name=nil;/* Reset the start of name pointer */ptr_startOfName=ptr_currentByte+1;}}}returnattributeNames;}#pragma mark -#pragma mark Batch Attributes-(NSDictionary*)extendedAttributesWithError:(NSError*__autoreleasing*)outError{if(![selfisFileURL])[NSExceptionraise:NSInternalInconsistencyExceptionformat:@"%s only valid on file URLs",__PRETTY_FUNCTION__];NSMutableDictionary*xattrs=nil;@autoreleasepool{NSArray*attributeNames=[selfnamesOfExtendedAttributesWithError:outError];if(attributeNames==nil)returnnil;/* Pull the value for each found extended attribute. */xattrs=[[NSMutableDictionaryalloc]initWithCapacity:[attributeNamescount]];NSMutableArray*collectedErrors=[NSMutableArrayarray];for(NSString*nameinattributeNames){NSError*error=nil;idvalue=[selfvalueOfExtendedAttributeWithName:nameerror:&error];if(value){[xattrssetObject:valueforKey:name];}else{if(error)[collectedErrorsaddObject:error];}}/* Did we get any errors? */BOOLhasErrors=[collectedErrorscount]>0;if(hasErrors&&outError){NSMutableDictionary*errInfo=[NSMutableDictionarydictionary];[errInfosetObject:selfforKey:NSURLErrorKey];[errInfosetObject:collectedErrorsforKey:NSUnderlyingErrorKey];*outError=[NSErrorerrorWithDomain:SOExtendedAttributesErrorDomaincode:SOExtendedAttributesGetValueErroruserInfo:errInfo];}}returnxattrs;}-(BOOL)setExtendedAttributes:(NSDictionary*)attributeserror:(NSError*__autoreleasing*)outError{if(![selfisFileURL])[NSExceptionraise:NSInternalInconsistencyExceptionformat:@"%s only valid on file URLs",__PRETTY_FUNCTION__];/* It is OK but silly to pass in empty attributes. */if([attributescount]==0)returnYES;/* Attempt to set all attribute values in the dictionary. Any individual errors are collected and returned as a group. */__blockNSMutableArray*collectedErrors=[NSMutableArrayarray];[attributesenumerateKeysAndObjectsUsingBlock:^(idkey,idobj,BOOL*stop){NSError*error=nil;if(NO==[selfsetExtendedAttributeValue:objforName:keyerror:&error]){[collectedErrorsaddObject:error];}}];/* Did we get any errors? */BOOLhasErrors=[collectedErrorscount]>0;if(hasErrors&&outError){NSMutableDictionary*errInfo=[NSMutableDictionarydictionary];[errInfosetObject:selfforKey:NSURLErrorKey];[errInfosetObject:collectedErrorsforKey:NSUnderlyingErrorKey];*outError=[NSErrorerrorWithDomain:SOExtendedAttributesErrorDomaincode:SOExtendedAttributesSetValueErroruserInfo:errInfo];returnNO;}returnYES;}#pragma mark -#pragma mark Individual Attributes-(BOOL)hasExtendedAttributeWithName:(NSString*)name{if(![selfisFileURL])[NSExceptionraise:NSInternalInconsistencyExceptionformat:@"%s only valid on file URLs",__PRETTY_FUNCTION__];if(!name||[nameisEqualToString:@""])[NSExceptionraise:NSInvalidArgumentExceptionformat:@"%s name parameter can't be nil",__PRETTY_FUNCTION__];NSError*error=nil;NSArray*attributeNames=[selfnamesOfExtendedAttributesWithError:&error];if(attributeNames){NSLog(@"ERROR: Could get list of attributes names: %@; %@",error,[erroruserInfo]);}return[attributeNamescontainsObject:name];}-(id)valueOfExtendedAttributeWithName:(NSString*)nameerror:(NSError*__autoreleasing*)outError{if(![selfisFileURL])[NSExceptionraise:NSInternalInconsistencyExceptionformat:@"%s only valid on file URLs",__PRETTY_FUNCTION__];if(!name||[nameisEqualToString:@""])[NSExceptionraise:NSInvalidArgumentExceptionformat:@"%s name parameter can't be nil",__PRETTY_FUNCTION__];idretrievedValue=nil;@autoreleasepool{/* Get the size of the attribute value and pull it into an NSData is possible */constchar*itemPath=[[selfpath]fileSystemRepresentation];NSMutableData*data=[NSDatadata];ssize_tdataSize=getxattr(itemPath,[nameUTF8String],NULL,SIZE_MAX,0,xattrDefaultOptions);if(dataSize>0){data=[NSMutableDatadataWithLength:dataSize];dataSize=getxattr(itemPath,[nameUTF8String],[datamutableBytes],[datalength],0,xattrDefaultOptions);}/* Problemo? Bail out with error, ditching all collected attributes */if(dataSize==-1){data=nil;if(outError)*outError=SOPOSIXErrorForURL(self);}/* Translate from encoded binary plist */retrievedValue=[NSPropertyListSerializationpropertyListWithData:dataoptions:NSPropertyListImmutableformat:NULLerror:outError];}returnretrievedValue;}-(BOOL)setExtendedAttributeValue:(id)valueforName:(NSString*)nameerror:(NSError*__autoreleasing*)outError{if(![selfisFileURL])[NSExceptionraise:NSInternalInconsistencyExceptionformat:@"%s only valid on file URLs",__PRETTY_FUNCTION__];if(!name||[nameisEqualToString:@""])[NSExceptionraise:NSInvalidArgumentExceptionformat:@"%s name parameter can't be nil",__PRETTY_FUNCTION__];/* If value can be serialized as a binary plist, do so and store in extended attributes */if([NSPropertyListSerializationpropertyList:valueisValidForFormat:NSPropertyListBinaryFormat_v1_0]){NSData*data=[NSPropertyListSerializationdataWithPropertyList:valueformat:NSPropertyListBinaryFormat_v1_0options:0error:outError];interr=setxattr([[selfpath]fileSystemRepresentation],[nameUTF8String],[databytes],[datalength],0,XATTR_NOFOLLOW);if(err!=0){if(outError)*outError=SOPOSIXErrorForURL(self);returnNO;}}else{NSMutableDictionary*errInfo=[NSMutableDictionarydictionary];[errInfosetObject:[NSStringstringWithFormat:@"Value of class %@ cannot be serialized into a plist",NSStringFromClass([valueclass])]forKey:NSLocalizedDescriptionKey];[errInfosetObject:valueforKey:@"value"];*outError=[NSErrorerrorWithDomain:SOExtendedAttributesErrorDomaincode:SOExtendedAttributesValueCantBeSerializeduserInfo:errInfo];returnNO;}returnYES;}-(BOOL)removeExtendedAttributeWithName:(NSString*)nameerror:(NSError*__autoreleasing*)outError{if(![selfisFileURL])[NSExceptionraise:NSInternalInconsistencyExceptionformat:@"%s only valid on file URLs",__PRETTY_FUNCTION__];if(!name||[nameisEqualToString:@""])[NSExceptionraise:NSInvalidArgumentExceptionformat:@"%s name parameter can't be nil",__PRETTY_FUNCTION__];interr=removexattr([[selfpath]fileSystemRepresentation],[nameUTF8String],xattrDefaultOptions);if(err!=0){/* Ignore any ENOATTR error ('attribute not found'), but capture and return all others. */if(errno!=ENOATTR){if(outError)*outError=SOPOSIXErrorForURL(self);returnNO;}}returnYES;}@end/* Copyright (c) 2012, Standard Orbit Software, LLC. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. Neither the name of the Standard Orbit Software, LLC nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */