static void advanceCurrentStream(FormStreamFields *form)
{
    closeCurrentStream(form);

    if (form->remainingElements.isEmpty())
        return;

    // Create the new stream.
    FormDataElement& nextInput = form->remainingElements.last();
    if (nextInput.m_type == FormDataElement::data) {
        size_t size = nextInput.m_data.size();
        char* data = nextInput.m_data.releaseBuffer();
        form->currentStream = CFReadStreamCreateWithBytesNoCopy(0, reinterpret_cast<const UInt8*>(data), size, kCFAllocatorNull);
        form->currentData = data;
    } else {
        CFStringRef filename = nextInput.m_filename.createCFString();
#if PLATFORM(WIN)
        CFURLRef fileURL = CFURLCreateWithFileSystemPath(0, filename, kCFURLWindowsPathStyle, FALSE);
#else
        CFURLRef fileURL = CFURLCreateWithFileSystemPath(0, filename, kCFURLPOSIXPathStyle, FALSE);
#endif
        CFRelease(filename);
        form->currentStream = CFReadStreamCreateWithFile(0, fileURL);
        CFRelease(fileURL);
    }
    form->remainingElements.removeLast();

    // Set up the callback.
    CFStreamClientContext context = { 0, form, NULL, NULL, NULL };
    CFReadStreamSetClient(form->currentStream, kCFStreamEventHasBytesAvailable | kCFStreamEventErrorOccurred | kCFStreamEventEndEncountered,
        formEventCallback, &context);

    // Schedule with the current set of run loops.
    CFSetApplyFunction(form->scheduledRunLoopPairs, scheduleWithPair, form->currentStream);
}
Example #2
0
void updateKeymap()
{
	CFReadStreamRef	readStream;

	if (!fileExists(CFSTR(KEYMAP_PATH)))
	{
		stamp_file(CFSTR("Error: Keymap file is missing"));
		keymap = NULL;
		return;
	}
	
	readStream = CFReadStreamCreateWithFile(kCFAllocatorDefault,CFURLCreateWithFileSystemPath(kCFAllocatorDefault,CFSTR(KEYMAP_PATH),kCFURLPOSIXPathStyle,false));
	if (!readStream||!(CFReadStreamOpen(readStream)))
	{
		stamp_file(CFSTR("Error: Can't open keymap file"));
		keymap = NULL;
		return;
	}
	keymap = (CFDictionaryRef)CFPropertyListCreateFromStream(kCFAllocatorDefault,readStream,0,kCFPropertyListImmutable,NULL,NULL);
	CFReadStreamClose(readStream);
	if (!keymap)
	{
		stamp_file(CFSTR("Error: Can't read keymap file"));
		return;
	}
	
	Boolean validKey;
	showMods = (CFPreferencesGetAppBooleanValue(CFSTR("Mods"),PREF_DOMAIN,&validKey))?kCFBooleanTrue:kCFBooleanFalse;
	if (!validKey)
	{
		showMods = kCFBooleanTrue;
		CFPreferencesSetAppValue(CFSTR("Mods"),showMods,PREF_DOMAIN);
	}
}
CFDataRef WebApiClientMD5DigestCreateWithFilePath(CFStringRef filePath, size_t bufferSize) {
	
	// Declare needed variables
	CFDataRef result = NULL;
	CFReadStreamRef readStream = NULL;
	
	// Get the file URL
	CFURLRef fileURL = CFURLCreateWithFileSystemPath(kCFAllocatorDefault, (CFStringRef)filePath, kCFURLPOSIXPathStyle, (Boolean)false);
	if ( fileURL ) {
		// Create and open the read stream
		readStream = CFReadStreamCreateWithFile(kCFAllocatorDefault, fileURL);
		if ( readStream ) {
			Boolean didSucceed = CFReadStreamOpen(readStream);
			if ( didSucceed ) {
				// Initialize the hash object
				CC_MD5_CTX hashObject;
				CC_MD5_Init(&hashObject);
				
				// Make sure chunkSizeForReadingData is valid
				if ( bufferSize < 1 ) {
					bufferSize = FileHashDefaultChunkSizeForReadingData;
				}
				
				// Feed the data to the hash object
				bool hasMoreData = true;
				while ( hasMoreData ) {
					uint8_t buffer[bufferSize];
					CFIndex readBytesCount = CFReadStreamRead(readStream, (UInt8 *)buffer, (CFIndex)sizeof(buffer));
					if ( readBytesCount == -1 ) break;
					if ( readBytesCount == 0 ) {
						hasMoreData = false;
						continue;
					}
					CC_MD5_Update(&hashObject, (const void *)buffer, (CC_LONG)readBytesCount);
				}
				
				// Check if the read operation succeeded
				didSucceed = !hasMoreData;
				
				// Compute the hash digest
				unsigned char digest[CC_MD5_DIGEST_LENGTH];
				CC_MD5_Final(digest, &hashObject);
				
				// Abort if the read operation failed
				if ( didSucceed ) {
					result = CFDataCreate(kCFAllocatorDefault, digest, CC_MD5_DIGEST_LENGTH);
				}
			}
		}
	}
	
	if ( readStream ) {
		CFReadStreamClose(readStream);
		CFRelease(readStream);
	}
	if ( fileURL ) {
		CFRelease(fileURL);
	}
	return result;
}
Example #4
0
extern CFDictionaryRef GPPropertyListCopyLocalizableStringsDictionary(CFURLRef fileURL) {
	CFReadStreamRef stream = CFReadStreamCreateWithFile(NULL, fileURL);
	if (stream == NULL)
		return NULL;
	if (!CFReadStreamOpen(stream)) {
		CFRelease(stream);
		return NULL;
	}
	CFDictionaryRef dict = CFPropertyListCreateFromStream(NULL, stream, 0, kCFPropertyListImmutable, NULL, NULL);
	CFReadStreamClose(stream);
	CFRelease(stream);
	if (dict == NULL)
		return NULL;
	if (CFGetTypeID(dict) != CFDictionaryGetTypeID()) {
		CFRelease(dict);
		return NULL;
	}
	CFDictionaryRef localizedStringsDict = CFDictionaryGetValue(dict, CFSTR("Localizations"));
	if (localizedStringsDict == NULL || CFGetTypeID(localizedStringsDict) != CFDictionaryGetTypeID()) {
		CFRelease(dict);
		return NULL;
	}
	CFIndex langCount = CFDictionaryGetCount(localizedStringsDict);
	CFStringRef keys[langCount];	// assume we don't have 4000 languages :p
	CFDictionaryGetKeysAndValues(localizedStringsDict, (const void**)keys, NULL);
	CFArrayCallBacks languagesCallbacks = {0, NULL, NULL, NULL, &CFEqual};
	CFArrayRef languages = CFArrayCreate(NULL, (const void**)keys, langCount, &languagesCallbacks);
	CFArrayRef preferedLanguages = CFBundleCopyPreferredLocalizationsFromArray(languages);
	CFDictionaryRef retval = CFRetain(CFDictionaryGetValue(localizedStringsDict, CFArrayGetValueAtIndex(preferedLanguages, 0)));
	CFRelease(languages);
	CFRelease(preferedLanguages);
	CFRelease(dict);
	
	return retval;
}
Example #5
0
// Return false if we cannot advance the stream. Currently the only possible failure is that the underlying file has been removed or changed since File.slice.
static bool advanceCurrentStream(FormStreamFields* form)
{
    closeCurrentStream(form);

    if (form->remainingElements.isEmpty())
        return true;

    // Create the new stream.
    FormDataElement& nextInput = form->remainingElements.last();

    if (nextInput.m_type == FormDataElement::data) {
        size_t size = nextInput.m_data.size();
        MallocPtr<char> data = nextInput.m_data.releaseBuffer();
        form->currentStream = CFReadStreamCreateWithBytesNoCopy(0, reinterpret_cast<const UInt8*>(data.get()), size, kCFAllocatorNull);
        form->currentData = std::move(data);
    } else {
#if ENABLE(BLOB)
        // Check if the file has been changed or not if required.
        if (isValidFileTime(nextInput.m_expectedFileModificationTime)) {
            time_t fileModificationTime;
            if (!getFileModificationTime(nextInput.m_filename, fileModificationTime) || fileModificationTime != static_cast<time_t>(nextInput.m_expectedFileModificationTime))
                return false;
        }
#endif
        const String& path = nextInput.m_shouldGenerateFile ? nextInput.m_generatedFilename : nextInput.m_filename;
        form->currentStream = CFReadStreamCreateWithFile(0, pathAsURL(path).get());
        if (!form->currentStream) {
            // The file must have been removed or become unreadable.
            return false;
        }
#if ENABLE(BLOB)
        if (nextInput.m_fileStart > 0) {
            RetainPtr<CFNumberRef> position = adoptCF(CFNumberCreate(0, kCFNumberLongLongType, &nextInput.m_fileStart));
            CFReadStreamSetProperty(form->currentStream, kCFStreamPropertyFileCurrentOffset, position.get());
        }
        form->currentStreamRangeLength = nextInput.m_fileLength;
#endif
    }
    form->remainingElements.removeLast();

    // Set up the callback.
    CFStreamClientContext context = { 0, form, 0, 0, 0 };
    CFReadStreamSetClient(form->currentStream, kCFStreamEventHasBytesAvailable | kCFStreamEventErrorOccurred | kCFStreamEventEndEncountered,
        formEventCallback, &context);

    // Schedule with the current set of run loops.
    SchedulePairHashSet::iterator end = form->scheduledRunLoopPairs.end();
    for (SchedulePairHashSet::iterator it = form->scheduledRunLoopPairs.begin(); it != end; ++it)
        CFReadStreamScheduleWithRunLoop(form->currentStream, (*it)->runLoop(), (*it)->mode());

    return true;
}
Example #6
0
CFStringRef copy_disk_app_identifier(CFURLRef disk_app_url) {
    CFURLRef plist_url = CFURLCreateCopyAppendingPathComponent(NULL, disk_app_url, CFSTR("Info.plist"), false);
    CFReadStreamRef plist_stream = CFReadStreamCreateWithFile(NULL, plist_url);
    CFReadStreamOpen(plist_stream);
    CFPropertyListRef plist = CFPropertyListCreateWithStream(NULL, plist_stream, 0, kCFPropertyListImmutable, NULL, NULL);
    CFStringRef bundle_identifier = CFRetain(CFDictionaryGetValue(plist, CFSTR("CFBundleIdentifier")));
    CFReadStreamClose(plist_stream);
	
    CFRelease(plist_url);
    CFRelease(plist_stream);
    CFRelease(plist);
	
    return bundle_identifier;
}
Example #7
0
static bool OnLionOrLater()
{
  if (sOnLionOrLater < 0) {
    SInt32 major = 0, minor = 0;

    CFURLRef url =
      CFURLCreateWithString(kCFAllocatorDefault,
                            CFSTR("file:///System/Library/CoreServices/SystemVersion.plist"),
                            NULL);
    CFReadStreamRef stream =
      CFReadStreamCreateWithFile(kCFAllocatorDefault, url);
    CFReadStreamOpen(stream);
    CFDictionaryRef sysVersionPlist = (CFDictionaryRef)
      CFPropertyListCreateWithStream(kCFAllocatorDefault,
                                     stream, 0, kCFPropertyListImmutable,
                                     NULL, NULL);
    CFReadStreamClose(stream);
    CFRelease(stream);
    CFRelease(url);

    CFStringRef versionString = (CFStringRef)
      CFDictionaryGetValue(sysVersionPlist, CFSTR("ProductVersion"));
    CFArrayRef versions =
      CFStringCreateArrayBySeparatingStrings(kCFAllocatorDefault,
                                             versionString, CFSTR("."));
    CFIndex count = CFArrayGetCount(versions);
    if (count > 0) {
      CFStringRef component = (CFStringRef) CFArrayGetValueAtIndex(versions, 0);
      major = CFStringGetIntValue(component);
      if (count > 1) {
        component = (CFStringRef) CFArrayGetValueAtIndex(versions, 1);
        minor = CFStringGetIntValue(component);
      }
    }
    CFRelease(sysVersionPlist);
    CFRelease(versions);

    if (major < 10) {
      sOnLionOrLater = 0;
    } else {
      int version = 0x1000 + (minor << 4);
      sOnLionOrLater = version >= MAC_OS_X_VERSION_10_7_HEX ? 1 : 0;
    }
  }

  return sOnLionOrLater > 0 ? true : false;
}
Example #8
0
CFStringRef get_bundle_id(const char *app_path)
{
  CFURLRef app_url = get_absolute_file_url(app_path);
  if (app_url == NULL)
  {
    return NULL;
  }

  CFURLRef url = CFURLCreateCopyAppendingPathComponent(NULL, app_url,
                                                       CFSTR("Info.plist"), false);
  CFRelease(app_url);
  if (url == NULL)
  {
    return NULL;
  }

  CFReadStreamRef stream = CFReadStreamCreateWithFile(NULL, url);
  CFRelease(url);
  if (stream == NULL)
  {
    return NULL;
  }

  CFPropertyListRef plist = NULL;
  if (CFReadStreamOpen(stream) == TRUE)
  {
    plist = CFPropertyListCreateWithStream(NULL, stream, 0,
                                           kCFPropertyListImmutable, NULL, NULL);
  }
  CFReadStreamClose(stream);
  CFRelease(stream);

  if (plist == NULL)
  {
    return NULL;
  }

  const void *value = CFDictionaryGetValue(plist, CFSTR("CFBundleIdentifier"));
  CFStringRef bundle_id = NULL;
  if (value != NULL)
  {
    bundle_id = CFRetain(value);
  }
  CFRelease(plist);
  return bundle_id;
}
static CFTypeRef
CopyKeyFromFile(CFStringRef domain, CFStringRef key)
{
    CFReadStreamRef s;
    CFDictionaryRef d;
    CFStringRef file;
    CFErrorRef e;
    CFURLRef url;
    CFTypeRef val;
    
    file = CFStringCreateWithFormat(NULL, 0, CFSTR("/Library/Preferences/%@.plist"), domain);
    if (file == NULL)
	return NULL;
    
    url = CFURLCreateWithFileSystemPath(kCFAllocatorDefault, domain, kCFURLPOSIXPathStyle, false);
    CFRelease(file);
    if (url == NULL)
	return NULL;
    
    s = CFReadStreamCreateWithFile(kCFAllocatorDefault, url);
    CFRelease(url);
    if (s == NULL)
	return NULL;
    
    if (!CFReadStreamOpen(s)) {
	CFRelease(s);
	return NULL;
    }
    
    d = (CFDictionaryRef)CFPropertyListCreateWithStream (kCFAllocatorDefault, s, 0, kCFPropertyListImmutable, NULL, &e);
    CFRelease(s);
    if (d == NULL)
	return NULL;
    
    if (CFGetTypeID(d) != CFDictionaryGetTypeID()) {
	CFRelease(d);
	return NULL;
    }
    
    val = CFDictionaryGetValue(d, key);
    if (val)
	CFRetain(val);
    CFRelease(d);
    return val;
}
Example #10
0
static krb5_error_code
parse_plist_config(krb5_context context, const char *path, krb5_config_section **parent)
{
    CFReadStreamRef s;
    CFDictionaryRef d;
    CFURLRef url;

    url = CFURLCreateFromFileSystemRepresentation(kCFAllocatorDefault, (UInt8 *)path, strlen(path), FALSE);
    if (url == NULL) {
        krb5_clear_error_message(context);
        return ENOMEM;
    }

    s = CFReadStreamCreateWithFile(kCFAllocatorDefault, url);
    CFRelease(url);
    if (s == NULL) {
        krb5_clear_error_message(context);
        return ENOMEM;
    }

    if (!CFReadStreamOpen(s)) {
        CFRelease(s);
        krb5_clear_error_message(context);
        return ENOENT;
    }

#ifdef HAVE_CFPROPERTYLISTCREATEWITHSTREAM
    d = (CFDictionaryRef)CFPropertyListCreateWithStream(NULL, s, 0, kCFPropertyListImmutable, NULL, NULL);
#else
    d = (CFDictionaryRef)CFPropertyListCreateFromStream(NULL, s, 0, kCFPropertyListImmutable, NULL, NULL);
#endif
    CFRelease(s);
    if (d == NULL) {
        krb5_clear_error_message(context);
        return ENOENT;
    }

    CFDictionaryApplyFunction(d, convert_content, parent);
    CFRelease(d);

    return 0;
}
Example #11
0
CFPropertyListRef createPropertyListFromURL(CFURLRef file, u_int32_t mutability, CFPropertyListFormat *outFormat, CFStringRef *outErrorString) {
	CFPropertyListRef plist = NULL;

	if (!file)
		NSLog(CFSTR("in createPropertyListFromURL in CFGrowlAdditions: cannot read from a NULL URL"));
	else {
		CFReadStreamRef stream = CFReadStreamCreateWithFile(kCFAllocatorDefault, file);
		if (!stream)
			NSLog(CFSTR("in createPropertyListFromURL in CFGrowlAdditions: could not create stream for reading from URL %@"), file);
		else {
			if (!CFReadStreamOpen(stream))
				NSLog(CFSTR("in createPropertyListFromURL in CFGrowlAdditions: could not open stream for reading from URL %@"), file);
			else {
				CFPropertyListFormat format;
				CFStringRef errorString = NULL;

				plist = CFPropertyListCreateFromStream(kCFAllocatorDefault,
													   stream,
													   /*streamLength*/ 0,
													   mutability,
													   &format,
													   &errorString);
				if (!plist)
					NSLog(CFSTR("in createPropertyListFromURL in CFGrowlAdditions: could not read property list from URL %@ (error string: %@)"), file, errorString);

				if (outFormat) *outFormat = format;
				if (errorString) {
					if (outErrorString)
						*outErrorString = errorString;
					else
						CFRelease(errorString);
				}

				CFReadStreamClose(stream);
			}

			CFRelease(stream);
		}
	}

	return plist;
}
CFDictionaryRef download_file(int socket, CFDictionaryRef dict)
{
    UInt8 buffer[8192];
    CFIndex bytesRead;

    CFStringRef path = CFDictionaryGetValue(dict, CFSTR("Path"));
    if(path == NULL || CFGetTypeID(path) != CFStringGetTypeID())
        return NULL;
    CFMutableDictionaryRef out  = CFDictionaryCreateMutable(kCFAllocatorDefault, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);	

    CFURLRef fileURL = CFURLCreateWithFileSystemPath(kCFAllocatorDefault, path, kCFURLPOSIXPathStyle, FALSE);
    CFReadStreamRef stream = CFReadStreamCreateWithFile(kCFAllocatorDefault, fileURL);
    CFRelease(fileURL);
    if(!CFReadStreamOpen(stream))
    {
        CFErrorRef error = CFReadStreamCopyError(stream);
        if (error != NULL)
        {
            CFStringRef errorDesc = CFErrorCopyDescription(error);
            CFDictionaryAddValue(out, CFSTR("Error"), errorDesc);
            CFRelease(errorDesc);
            CFRelease(error);
        }
        CFRelease(stream);
        return out;
    }
    CFMutableDataRef data = CFDataCreateMutable(kCFAllocatorDefault, 0);

    while(CFReadStreamHasBytesAvailable(stream))
    {
        if((bytesRead = CFReadStreamRead(stream, buffer, 8192)) <= 0)
            break;
        CFDataAppendBytes(data, buffer, bytesRead);
    }
    CFReadStreamClose(stream);
    CFRelease(stream);

    CFDictionaryAddValue(out, CFSTR("Data"), data);
    CFRelease(data);

    return out;
}
CFDictionaryRef get_escrow_record(int socket, CFDictionaryRef dict)
{
    CFStringRef hostid = CFDictionaryGetValue(dict, CFSTR("HostID"));
    if(hostid == NULL || CFGetTypeID(hostid) != CFStringGetTypeID())
        return NULL;
    
    //TODO: check return values...
    CFStringRef path = CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR("/mnt2/root/Library/Lockdown/escrow_records/%@.plist"), hostid);
    //CFStringRef path = CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR("/private/var/root/Library/Lockdown/escrow_records/%@.plist"), hostid);

    CFURLRef fileURL = CFURLCreateWithFileSystemPath(kCFAllocatorDefault, path, kCFURLPOSIXPathStyle, FALSE);
    CFReadStreamRef stream = CFReadStreamCreateWithFile(kCFAllocatorDefault, fileURL);
    CFReadStreamOpen(stream);
    CFPropertyListRef plist = CFPropertyListCreateWithStream(kCFAllocatorDefault,
                        stream, 0, kCFPropertyListImmutable, NULL, NULL);

    CFRelease(fileURL);
    CFRelease(stream);
    CFRelease(path);
    return plist;
}
Example #14
0
CFDataRef createDataFromURL( CFURLRef url )
{
	CFMutableDataRef fileContent = CFDataCreateMutable(kCFAllocatorDefault, 0);
    CFReadStreamRef stream = CFReadStreamCreateWithFile(kCFAllocatorDefault, url);

    if (stream) {
        if (CFReadStreamOpen(stream)) {
            UInt8 buffer[BUFFERSIZE];
            CFIndex bytesRead;
            do {
                bytesRead = CFReadStreamRead(stream, buffer, sizeof(buffer));
                if (bytesRead > 0) {
                    CFDataAppendBytes(fileContent, buffer, bytesRead);
                }
            } while (bytesRead > 0);
            CFReadStreamClose(stream);
        }
        CFRelease(stream);
    }
    
	return fileContent;
}
Example #15
0
static RetainPtr<CFPropertyListRef> readFontPlist()
{
    CString plistPath = fontsPlistPath().utf8();

    RetainPtr<CFURLRef> url(AdoptCF, CFURLCreateFromFileSystemRepresentation(0, reinterpret_cast<const UInt8*>(plistPath.data()), plistPath.length(), false));
    if (!url)
        return 0;

    RetainPtr<CFReadStreamRef> stream(AdoptCF, CFReadStreamCreateWithFile(0, url.get()));
    if (!stream)
        return 0;

    if (!CFReadStreamOpen(stream.get()))
        return 0;

    CFPropertyListFormat format = kCFPropertyListBinaryFormat_v1_0 | kCFPropertyListXMLFormat_v1_0;
    RetainPtr<CFPropertyListRef> plist(AdoptCF, CFPropertyListCreateFromStream(0, stream.get(), 0, kCFPropertyListMutableContainersAndLeaves, &format, 0));

    CFReadStreamClose(stream.get());

    return plist;
}
Example #16
0
void Caching_Stream::readMetaData()
{
    if (!m_metaDataUrl) {
        return;
    }
    
    CFReadStreamRef readStream = CFReadStreamCreateWithFile(kCFAllocatorDefault, m_metaDataUrl);
    
    if (readStream) {
        if (CFReadStreamOpen(readStream)) {
            
            UInt8 buf[1024];
            
            CFIndex bytesRead = CFReadStreamRead(readStream, buf, 1024);
            
            if (bytesRead > 0) {
                CFStringRef contentType = CFStringCreateWithBytes(kCFAllocatorDefault, buf, bytesRead, kCFStringEncodingUTF8, false);
                
                if (contentType) {
                    if (m_fileStream) {
                        CS_TRACE("Setting the content type of the file stream based on the meta data\n");
                        CS_TRACE_CFSTRING(contentType);
                        
                        m_fileStream->setContentType(contentType);
                    }
                    
                    CFRelease(contentType);
                }
            }
            
            CFReadStreamClose(readStream);
        }
        
        CFRelease(readStream);
    }
}
bool
_mongoc_secure_transport_import_pem (const char *filename, const char *passphrase, CFArrayRef *items, SecExternalItemType *type)
{
   SecExternalFormat format = kSecFormatPEMSequence;
   SecItemImportExportKeyParameters params;
   SecTransformRef sec_transform;
   CFReadStreamRef read_stream;
   CFDataRef dataref;
   CFErrorRef error;
   CFURLRef url;
   OSStatus res;


   if (!filename) {
      MONGOC_INFO ("%s", "No certificate provided");
      return false;
   }

   params.version = SEC_KEY_IMPORT_EXPORT_PARAMS_VERSION;
   params.flags = 0;
   params.passphrase = NULL;
   params.alertTitle = NULL;
   params.alertPrompt = NULL;
   params.accessRef = NULL;
   params.keyUsage = NULL;
   params.keyAttributes = NULL;

   if (passphrase) {
      params.passphrase = CFStringCreateWithCString (kCFAllocatorDefault, passphrase, kCFStringEncodingUTF8);
   }

   url = CFURLCreateFromFileSystemRepresentation (kCFAllocatorDefault, (const UInt8 *)filename, strlen (filename), false);
   read_stream = CFReadStreamCreateWithFile (kCFAllocatorDefault, url);
   sec_transform = SecTransformCreateReadTransformWithReadStream (read_stream);
   dataref = SecTransformExecute (sec_transform, &error);


   if (error) {
      CFStringRef str = CFErrorCopyDescription (error);
      MONGOC_ERROR ("Failed importing PEM '%s': %s", filename, CFStringGetCStringPtr (str, CFStringGetFastestEncoding(str)));
      CFRelease (str);
      CFRelease (sec_transform);
      CFRelease (read_stream);
      CFRelease (url);

      if (passphrase) {
         CFRelease (params.passphrase);
      }
      return false;
   }

   res = SecItemImport (dataref, CFSTR(".pem"), &format, type, 0, &params, NULL, items);
   CFRelease (dataref);
   CFRelease (sec_transform);
   CFRelease (read_stream);
   CFRelease (url);

   if (passphrase) {
      CFRelease (params.passphrase);
   }
   if (res) {
      MONGOC_ERROR ("Failed importing PEM '%s' (code: %d)", filename, res);
      return false;
   }

   return true;
}
Boolean GetMetadataForFile(void* thisInterface, 
			   CFMutableDictionaryRef attributes, 
			   CFStringRef contentTypeUTI,
			   CFStringRef pathToFile)
{
    /* Pull any available metadata from the file at the specified path */
    /* Return the attribute keys and attribute values in the dict */
    /* Return TRUE if successful, FALSE if there was no data provided */
  Boolean success;
  CFURLRef fileURL = CFURLCreateWithFileSystemPath(kCFAllocatorDefault, pathToFile, kCFURLPOSIXPathStyle, false);
  CFReadStreamRef stream = CFReadStreamCreateWithFile(kCFAllocatorDefault, fileURL);
  CFReadStreamOpen(stream);

  CFPropertyListFormat format;
  CFStringRef errorString = NULL;
  CFPropertyListRef ticket = CFPropertyListCreateFromStream(kCFAllocatorDefault,
                             stream,
                             /*streamLength*/ 0,
                             kCFPropertyListImmutable,
                              &format,
                             &errorString
                             );
  if (errorString)
  {
    printf("failed creating property list from stream\n");
    printf("error = %s\n", (const char*) errorString);
    success = FALSE;
  } 
  else
  {
    CFTypeRef value;
    value = CFDictionaryGetValue(ticket, kMDItemTitle);
     if (value)
     {
       CFDictionarySetValue(attributes, kMDItemTitle, value);
     }
     value = CFDictionaryGetValue(ticket, kMDItemTextContent);
     if (value)
     {
       CFDictionarySetValue(attributes, kMDItemTextContent, value);
       
     }
     value = CFDictionaryGetValue(ticket, kMDItemDisplayName);
     if (value)
       CFDictionarySetValue(attributes, kMDItemDisplayName, value);
        
     CFDateFormatterRef dateFormatter = CFDateFormatterCreate(NULL, NULL, kCFDateFormatterLongStyle, kCFDateFormatterLongStyle);
                                              
     value = CFDictionaryGetValue(ticket, kMDItemLastUsedDate);

     if (value && dateFormatter)
     {
       printf("trying to parse date \n");
       CFDateRef curDate = CFDateFormatterCreateDateFromString(NULL, dateFormatter, value, NULL);
       printf("got cur date\n");
       if (curDate)
         CFDictionarySetValue(attributes, kMDItemLastUsedDate, curDate);
     }
                                                   
     success = TRUE;
  }
  // contents are kMDItemTextContent
  
  CFReadStreamClose(stream);
  CFRelease(stream);
  CFRelease(fileURL);
  return success;    
}
Example #19
0
    int
read_plist( char *plpath, CFDictionaryRef *dr )
{
    CFURLRef		cfurl = NULL;
    CFReadStreamRef	cfrs = NULL;
    CFDictionaryRef	cfdict = NULL;
    CFPropertyListFormat	fmt = kCFPropertyListXMLFormat_v1_0;
    CFStreamError	err;

    int			rc = 0;
    char		respath[ MAXPATHLEN ];
    
    if ( plpath == NULL ) {
	fprintf( stderr, "%s: Invalid plist path\n", __FUNCTION__ );
	return( -1 );
    }

    if ( realpath( plpath, respath ) == NULL ) {
	fprintf( stderr, "%s: realpath failed: %s\n",
		__FUNCTION__, strerror( errno ));
	return( -1 );
    }

    /*
     * must convert C string path to CFURL to read the plist
     * from disk. no convenience methods here like Cocoa's
     * -dictionaryWithContentsOfFile:
     */
    if (( cfurl = CFURLCreateFromFileSystemRepresentation(
			kCFAllocatorDefault, ( const UInt8 * )respath,
			( CFIndex )strlen( respath ), false )) == NULL ) {
	fprintf( stderr, "%s: failed to create URL for %s\n",
			__FUNCTION__, respath );
	return( -1 );
    }

    if (( cfrs = CFReadStreamCreateWithFile( kCFAllocatorDefault,
			cfurl )) == NULL ) {
	fprintf( stderr, "%s: failed to create read stream\n", __FUNCTION__ );
	rc = -1;
	goto cleanup;
    }
    if ( CFReadStreamOpen( cfrs ) == false ) {
	err = CFReadStreamGetError( cfrs );
	fprintf( stderr, "%s: failed to open read stream\n", __FUNCTION__ );
	if ( err.domain == kCFStreamErrorDomainPOSIX ) {
	    fprintf( stderr, "%s: %s\n", plpath, strerror( errno ));
	} else {
	    fprintf( stderr, "domain %d, error %d\n",
			( int )err.domain, ( int )err.error );
	}
	rc = -1;
	goto cleanup;
    }

    if (( cfdict = CFPropertyListCreateWithStream( kCFAllocatorDefault, cfrs,
			0, kCFPropertyListImmutable, &fmt, NULL )) == NULL ) {
	fprintf( stderr, "%s: failed to read plist\n", __FUNCTION__ );
	rc = -1;
	goto cleanup;
    }

    if ( !CFPropertyListIsValid( cfdict, fmt )) {
	fprintf( stderr, "%s: invalid plist\n", plpath );
	CFRelease( cfdict );
	cfdict = NULL;
	rc = -1;
    }

cleanup:
    if ( cfurl != NULL ) {
	CFRelease( cfurl );
    }
    if ( cfrs != NULL ) {
	CFReadStreamClose( cfrs );
	CFRelease( cfrs );
    }

    *dr = cfdict;

    return( rc );
}
Example #20
0
static cups_array_t *			/* O - Message catalog */
appleMessageLoad(const char *locale)	/* I - Locale ID */
{
  char			filename[1024],	/* Path to cups.strings file */
			applelang[256],	/* Apple language ID */
			baselang[3];	/* Base language */
  CFURLRef		url;		/* URL to cups.strings file */
  CFReadStreamRef	stream = NULL;	/* File stream */
  CFPropertyListRef	plist = NULL;	/* Localization file */
#ifdef DEBUG
  CFErrorRef		error = NULL;	/* Error when opening file */
#endif /* DEBUG */


  DEBUG_printf(("appleMessageLoad(locale=\"%s\")", locale));

 /*
  * Load the cups.strings file...
  */

  snprintf(filename, sizeof(filename),
           CUPS_BUNDLEDIR "/Resources/%s.lproj/cups.strings",
	   _cupsAppleLanguage(locale, applelang, sizeof(applelang)));

  if (access(filename, 0))
  {
   /*
    * <rdar://problem/22086642>
    *
    * Try with original locale string...
    */

    snprintf(filename, sizeof(filename), CUPS_BUNDLEDIR "/Resources/%s.lproj/cups.strings", locale);
  }

  DEBUG_printf(("1appleMessageLoad: filename=\"%s\"", filename));

  if (access(filename, 0))
  {
   /*
    * Try alternate lproj directory names...
    */

    if (!strncmp(locale, "en", 2))
      locale = "English";
    else if (!strncmp(locale, "nb", 2) || !strncmp(locale, "nl", 2))
      locale = "Dutch";
    else if (!strncmp(locale, "fr", 2))
      locale = "French";
    else if (!strncmp(locale, "de", 2))
      locale = "German";
    else if (!strncmp(locale, "it", 2))
      locale = "Italian";
    else if (!strncmp(locale, "ja", 2))
      locale = "Japanese";
    else if (!strncmp(locale, "es", 2))
      locale = "Spanish";
    else if (!strcmp(locale, "zh_HK"))
    {
     /*
      * <rdar://problem/22130168>
      *
      * Try zh_TW first, then zh...  Sigh...
      */

      if (!access(CUPS_BUNDLEDIR "/Resources/zh_TW.lproj/cups.strings", 0))
        locale = "zh_TW";
      else
        locale = "zh";
    }
    else if (strstr(locale, "_") != NULL || strstr(locale, "-") != NULL)
    {
     /*
      * Drop country code, just try language...
      */

      strlcpy(baselang, locale, sizeof(baselang));
      locale = baselang;
    }

    snprintf(filename, sizeof(filename),
	     CUPS_BUNDLEDIR "/Resources/%s.lproj/cups.strings", locale);
    DEBUG_printf(("1appleMessageLoad: alternate filename=\"%s\"", filename));
  }

  url = CFURLCreateFromFileSystemRepresentation(kCFAllocatorDefault,
                                                (UInt8 *)filename,
						(CFIndex)strlen(filename), false);
  if (url)
  {
    stream = CFReadStreamCreateWithFile(kCFAllocatorDefault, url);
    if (stream)
    {
     /*
      * Read the property list containing the localization data.
      *
      * NOTE: This code currently generates a clang "potential leak"
      * warning, but the object is released in _cupsMessageFree().
      */

      CFReadStreamOpen(stream);

#ifdef DEBUG
      plist = CFPropertyListCreateWithStream(kCFAllocatorDefault, stream, 0,
                                             kCFPropertyListImmutable, NULL,
                                             &error);
      if (error)
      {
        CFStringRef	msg = CFErrorCopyDescription(error);
    					/* Error message */

        CFStringGetCString(msg, filename, sizeof(filename),
                           kCFStringEncodingUTF8);
        DEBUG_printf(("1appleMessageLoad: %s", filename));

	CFRelease(msg);
        CFRelease(error);
      }

#else
      plist = CFPropertyListCreateWithStream(kCFAllocatorDefault, stream, 0,
                                             kCFPropertyListImmutable, NULL,
                                             NULL);
#endif /* DEBUG */

      if (plist && CFGetTypeID(plist) != CFDictionaryGetTypeID())
      {
         CFRelease(plist);
         plist = NULL;
      }

      CFRelease(stream);
    }

    CFRelease(url);
  }

  DEBUG_printf(("1appleMessageLoad: url=%p, stream=%p, plist=%p", url, stream,
                plist));

 /*
  * Create and return an empty array to act as a cache for messages, passing the
  * plist as the user data.
  */

  return (_cupsMessageNew((void *)plist));
}
EMFInfo* EMF_init(Volume* volume, char* imagePath)
{
	uint8_t* emfk = NULL;
	uint8_t* dkey = NULL;
	
	uint64_t volume_id = *((uint64_t*) (&volume->volumeHeader->finderInfo[6]));
	FLIPENDIAN(volume_id);
	
	if(imagePath == NULL)
		imagePath = ".";
		
	printf("Volume identifier : %llx\n", volume_id);
	printf("Searching for %s/%llx.plist\n", imagePath, volume_id);
	
	CFStringRef path = CFStringCreateWithFormat(NULL, NULL, CFSTR("%s/%llx.plist"), imagePath, volume_id);
	
	CFURLRef fileURL = CFURLCreateWithFileSystemPath(NULL, path, kCFURLPOSIXPathStyle, FALSE);
	CFRelease(path);
	
	CFReadStreamRef stream = CFReadStreamCreateWithFile(NULL, fileURL);
	CFRelease(fileURL);
	
	if(stream == NULL)
	{
		return NULL;
	}
	if(!CFReadStreamOpen(stream))
	{
		fprintf(stderr, "Cannot open file\n");
		return NULL;
	}
	CFPropertyListRef dict = CFPropertyListCreateWithStream(NULL, stream, 0, kCFPropertyListImmutable, NULL, NULL);

	CFRelease(stream);
	
	if (dict == NULL || CFGetTypeID(dict) != CFDictionaryGetTypeID())
		return NULL;
	
	CFStringRef emfHex = CFDictionaryGetValue(dict, CFSTR("EMF"));
	CFStringRef dkeyHex = CFDictionaryGetValue(dict, CFSTR("DKey"));
	CFNumberRef dataVolumeOffset = CFDictionaryGetValue (dict, CFSTR("dataVolumeOffset"));
	
	if (emfHex == NULL || CFGetTypeID(emfHex) != CFStringGetTypeID())
		return NULL;
	if (dkeyHex == NULL || CFGetTypeID(dkeyHex) != CFStringGetTypeID())
		return NULL;
	if (dataVolumeOffset == NULL || CFGetTypeID(dataVolumeOffset) != CFNumberGetTypeID())
		return NULL;

	EMFInfo* emf = malloc(sizeof(EMFInfo));
	
	if(emf == NULL)
		return NULL;

	memset(emf, 0, sizeof(EMFInfo));
	
	emf->volume = volume;
	
	CFNumberGetValue(dataVolumeOffset, kCFNumberLongType, &emf->volume_offset);
	
	printf("Data partition offset = %llx\n", emf->volume_offset);
	
	if(ConvertHexaCFString(emfHex, &emfk) != 32)
	{
		fprintf(stderr, "Invalid EMF key\n");
		free(emf);
		return NULL;
	}
	if(ConvertHexaCFString(dkeyHex, &dkey) != 32)
	{
		fprintf(stderr, "Invalid DKey key\n");
		free(emf);
		return NULL;
	}
	
	AES_set_encrypt_key(emfk, 32*8, &(emf->emfkey));
	AES_set_decrypt_key(dkey, 32*8, &(emf->classKeys[CLASS_DKEY-1]));
	emf->classKeys_bitset |= 1 << CLASS_DKEY;
	
	CFDictionaryRef classKeys = CFDictionaryGetValue(dict, CFSTR("classKeys"));
	
	if(classKeys != NULL && CFGetTypeID(classKeys) == CFDictionaryGetTypeID())
	{
		printf("Reading class keys, NSProtectionComplete files should be decrypted OK\n");
		CFDictionaryApplyFunction(classKeys, grabClassKey, (void*) emf);
	}
	else
	{
		printf("Only NSProtectionNone files will be decrypted\n");
	}
	
	free(emfk);
	free(dkey);
	return emf;
}
Example #22
0
/*
 * Get the OS X version information, and append it to the GString.
 * Return TRUE if we succeed, FALSE if we fail.
 */
static gboolean
get_os_x_version_info(GString *str)
{
	static const UInt8 server_version_plist_path[] =
	    "/System/Library/CoreServices/ServerVersion.plist";
	static const UInt8 system_version_plist_path[] =
	    "/System/Library/CoreServices/SystemVersion.plist";
	CFURLRef version_plist_file_url;
	CFReadStreamRef version_plist_stream;
	CFDictionaryRef version_dict;
	char *string;

	/*
	 * On OS X, report the OS X version number as the OS, and put
	 * the Darwin information in parentheses.
	 *
	 * Alas, Gestalt() is deprecated in Mountain Lion, so the build
	 * fails if you treat deprecation warnings as fatal.  I don't
	 * know of any replacement API, so we fall back on reading
	 * /System/Library/CoreServices/ServerVersion.plist if it
	 * exists, otherwise /System/Library/CoreServices/SystemVersion.plist,
	 * and using ProductUserVisibleVersion.  We also get the build
	 * version from ProductBuildVersion and the product name from
	 * ProductName.
	 */
	version_plist_file_url = CFURLCreateFromFileSystemRepresentation(NULL,
	    server_version_plist_path, sizeof server_version_plist_path - 1,
	    false);
	if (version_plist_file_url == NULL)
		return FALSE;
	version_plist_stream = CFReadStreamCreateWithFile(NULL,
	    version_plist_file_url);
	CFRelease(version_plist_file_url);
	if (version_plist_stream == NULL)
		return FALSE;
	if (!CFReadStreamOpen(version_plist_stream)) {
		CFRelease(version_plist_stream);

		/*
		 * Try SystemVersion.plist.
		 */
		version_plist_file_url = CFURLCreateFromFileSystemRepresentation(NULL,
		    system_version_plist_path, sizeof system_version_plist_path - 1,
		    false);
		if (version_plist_file_url == NULL)
			return FALSE;
		version_plist_stream = CFReadStreamCreateWithFile(NULL,
		    version_plist_file_url);
		CFRelease(version_plist_file_url);
		if (version_plist_stream == NULL)
			return FALSE;
		if (!CFReadStreamOpen(version_plist_stream)) {
			CFRelease(version_plist_stream);
			return FALSE;
		}
	}
#ifdef HAVE_CFPROPERTYLISTCREATEWITHSTREAM
	version_dict = (CFDictionaryRef)CFPropertyListCreateWithStream(NULL,
	    version_plist_stream, 0, kCFPropertyListImmutable,
	    NULL, NULL);
#else
	version_dict = (CFDictionaryRef)CFPropertyListCreateFromStream(NULL,
	    version_plist_stream, 0, kCFPropertyListImmutable,
	    NULL, NULL);
#endif
	if (version_dict == NULL) {
		CFRelease(version_plist_stream);
		return FALSE;
	}
	if (CFGetTypeID(version_dict) != CFDictionaryGetTypeID()) {
		/* This is *supposed* to be a dictionary.  Punt. */
		CFRelease(version_dict);
		CFReadStreamClose(version_plist_stream);
		CFRelease(version_plist_stream);
		return FALSE;
	}
	/* Get the product name string. */
	string = get_string_from_dictionary(version_dict,
	    CFSTR("ProductName"));
	if (string == NULL) {
		CFRelease(version_dict);
		CFReadStreamClose(version_plist_stream);
		CFRelease(version_plist_stream);
		return FALSE;
	}
	g_string_append_printf(str, "%s", string);
	g_free(string);

	/* Get the OS version string. */
	string = get_string_from_dictionary(version_dict,
	    CFSTR("ProductUserVisibleVersion"));
	if (string == NULL) {
		CFRelease(version_dict);
		CFReadStreamClose(version_plist_stream);
		CFRelease(version_plist_stream);
		return FALSE;
	}
	g_string_append_printf(str, " %s", string);
	g_free(string);

	/* Get the build string */
	string = get_string_from_dictionary(version_dict,
	    CFSTR("ProductBuildVersion"));
	if (string == NULL) {
		CFRelease(version_dict);
		CFReadStreamClose(version_plist_stream);
		CFRelease(version_plist_stream);
		return FALSE;
	}
	g_string_append_printf(str, ", build %s", string);
	g_free(string);
	CFRelease(version_dict);
	CFReadStreamClose(version_plist_stream);
	CFRelease(version_plist_stream);
	return TRUE;
}
Example #23
0
int main (int argc, const char* argv[]) {
	if (argc <= 1) {
		fprintf(stderr, "Usage: visualize-archived-object <archived-file>\n\n");
		return 0;
	}
	
	CFStringRef fileNameAsCFString = CFStringCreateWithCString(NULL, argv[1], 0);
	CFURLRef fileURL = CFURLCreateWithFileSystemPath(NULL, fileNameAsCFString, kCFURLPOSIXPathStyle, false);
	CFRelease(fileNameAsCFString);
	
	CFReadStreamRef readStream = CFReadStreamCreateWithFile(NULL, fileURL);
	CFRelease(fileURL);
	if (!readStream) {
		fprintf(stderr, "Error: Cannot open file for reading.\n\n");
		return 1;
	}
	if (!CFReadStreamOpen(readStream)) {
		fprintf(stderr, "Error: Cannot open file for reading.\n\n");
		CFRelease(readStream);
		return 2;
	}
	
	CFStringRef errStr = NULL;
	CFPropertyListRef val = CFPropertyListCreateFromStream(NULL, readStream, 0, kCFPropertyListImmutable, NULL, &errStr);
	CFReadStreamClose(readStream);
	CFRelease(readStream);
	if (errStr != NULL) {
		CFIndex strlength = CFStringGetLength(errStr)*3+1;
		char* res_cstring = malloc(strlength);
		CFStringGetCString(errStr, res_cstring, strlength, 0);
		fprintf(stderr, "Error: Cannot parse file as serialized property list.\n%s\n\n", res_cstring);
		CFRelease(errStr);
		free(res_cstring);
		if (val != NULL)
			CFRelease(val);
		return 3;
	}
	
	if (CFGetTypeID(val) != CFDictionaryGetTypeID()) {
		fprintf(stderr, "Error: Not a dictionary.");
		CFRelease(val);
		return 4;
	}
	
	CFStringRef archiver = CFDictionaryGetValue(val, CFSTR("$archiver"));
	if (archiver == NULL || !CFEqual(archiver, CFSTR("NSKeyedArchiver"))) {
		fprintf(stderr, "Error: Not encoded using an NSKeyedArchiver.");
		CFRelease(val);
		return 5;
	}
	
	CFArrayRef objs = CFDictionaryGetValue(val, CFSTR("$objects"));
	if (objs == NULL || CFGetTypeID(objs) != CFArrayGetTypeID()) {
		fprintf(stderr, "Error: $objects is not an array.");
		CFRelease(val);
		return 6;
	}
	CFIndex objsCount = CFArrayGetCount(objs);
	
	CFDictionaryRef topObj = CFDictionaryGetValue(val, CFSTR("$top"));
	if (topObj == NULL || CFGetTypeID(topObj) != CFDictionaryGetTypeID()) {
		CFShow(topObj);
		fprintf(stderr, "Error: $top is not a dictionary.");
		CFRelease(val);
		return 7;
	}
	
	int* refCount = calloc(objsCount, sizeof(int));
	CFArrayApplyFunction(objs, CFRangeMake(0, objsCount), (CFArrayApplierFunction)&refCounter, refCount);
	
	struct printContext c;
	c.tabs = 0;
	c.refCount = refCount;
	c.objs = objs;
	
	printf("%s", "top = ");
	printObj(topObj, &c);
	printf(";\n\n");
	
	for (CFIndex i = 0; i < objsCount; ++ i)
		if (refCount[i] > 1) {
			CFPropertyListRef refObj = CFArrayGetValueAtIndex(objs, i);
			if (isComplexObj(refObj)) {
				printf("/*CF$UID; referenced %u times*/ %ld = ", refCount[i], i);
				printObj(refObj, &c);
				printf(";\n\n");
			}
		}
	
	free(refCount);
	CFRelease(val);
	
	return 0;
}
Example #24
0
CFStringRef FileMD5HashCreateWithPath(CFStringRef filePath, size_t chunkSizeForReadingData)
{
    CFStringRef result = NULL;
    CFReadStreamRef readStream = NULL;
    
    CFURLRef fileURL = CFURLCreateWithFileSystemPath(kCFAllocatorDefault,
                                                     (CFStringRef)filePath,
                                                     kCFURLPOSIXPathStyle,
                                                     (Boolean) false);
    
    if (!fileURL) {
        goto done;
    }
    
    readStream = CFReadStreamCreateWithFile(kCFAllocatorDefault,
                                            (CFURLRef)fileURL);
    
    if (!readStream) {
        goto done;
    }
    
    bool didSucceed = (bool)CFReadStreamOpen(readStream);
    
    if (!didSucceed) {
        goto done;
    }
    
    // Initialize the hash object
    CC_MD5_CTX hashObject;
    CC_MD5_Init(&hashObject);
    
    // Make sure the chunkSizeForReadindData is valid
    if (!chunkSizeForReadingData) {
        chunkSizeForReadingData = FileHashDefaultChunksSizeForReadingData;
    }
    
    // Feed the data to the hash object
    bool hasMoreData = true;
    while (hasMoreData) {
        uint8_t buffer[chunkSizeForReadingData];
        CFIndex readBytesCount = CFReadStreamRead(readStream,
                                                  (UInt8 *)buffer,
                                                  (CFIndex)sizeof(buffer));
        
        if (readBytesCount == -1) {
            break;
        }
        
        if (readBytesCount == 0) {
            hasMoreData = false;
            continue;
        }
        
        CC_MD5_Update(&hashObject, (const void *)buffer, (CC_LONG)readBytesCount);
    }
    
    // Check if the read operation has succeded
    didSucceed = !hasMoreData;
    
    // Compute the hash digest
    unsigned char digest[CC_MD5_DIGEST_LENGTH];
    CC_MD5_Final(digest, &hashObject);
    
    // Abort if the read operation fails
    if (!didSucceed) {
        goto done;
    }
    
    // Compute the string result
    char hash[2 * sizeof(digest) + 1];
    for (size_t i = 0; i < sizeof(digest); ++i) {
        snprintf(hash + (2 * i), 3, "%02x", (int)(digest[i]));
    }
    
    result = CFStringCreateWithCString(kCFAllocatorDefault, (const char *)hash, kCFStringEncodingUTF8);
    
    
    
done:
    if (readStream) {
        CFReadStreamClose(readStream);
        CFRelease(readStream);
    }
    
    if (fileURL) {
        CFRelease(fileURL);
    }
    
    return result;
}
CFDataRef
TSystemUtils::ReadDataFromURL ( CFURLRef url )
{

    CFMutableDataRef    data            = NULL;
    Boolean				result			= false;
	CFNumberRef         fileSizeNumber  = NULL;
    CFIndex             fileSize        = 0;
    UInt8 *             dataPtr         = NULL;
    UInt8 *             endPtr          = NULL;
    CFReadStreamRef     readStream      = NULL;
    CFIndex             bytesRead       = 0;
    
    result = CFURLCopyResourcePropertyForKey ( url, kCFURLFileSizeKey, &fileSizeNumber, NULL );
    require ( result, ErrorExit );
    
    result = CFNumberGetValue ( fileSizeNumber, kCFNumberCFIndexType, &fileSize );
    require ( result, ReleaseNumber );
    
    data = CFDataCreateMutable ( kCFAllocatorDefault, fileSize );
    require ( data, ReleaseNumber );
    
    CFDataSetLength ( data, fileSize );
    
    dataPtr = CFDataGetMutableBytePtr ( data );
    require ( dataPtr, ReleaseNumber );
    
    readStream = CFReadStreamCreateWithFile ( kCFAllocatorDefault, url );
    require ( readStream, ErrorExit );
    
    result = CFReadStreamOpen ( readStream );
    require ( result, ReleaseStream );
    
    endPtr  = ( UInt8 * ) dataPtr + fileSize;
    
    while ( dataPtr < endPtr )
    {

        bytesRead = CFReadStreamRead ( readStream, dataPtr, endPtr - dataPtr );

        if ( bytesRead > 0 )
        {
            
            dataPtr += bytesRead;
            
        }
        
    }
    
    CFReadStreamClose ( readStream );
    
    
ReleaseStream:
    
    
    CFRelease ( readStream );
    readStream = NULL;
    
    
ReleaseNumber:
    
    
    CFRelease ( fileSizeNumber );
    fileSizeNumber = NULL;
    
    
ErrorExit:
    
    
    return data;
    
}
Example #26
0
CryptoX_Result
CryptoMac_LoadPublicKey(const unsigned char* aCertData,
                        CryptoX_PublicKey* aPublicKey,
                        const char* aCertName,
                        CryptoX_Certificate* aCert)
{
  if (!aPublicKey ||
      (OnLionOrLater() && !aCertData) ||
      (!OnLionOrLater() && !aCertName)) {
    return CryptoX_Error;
  }

  if (!OnLionOrLater()) {
    return NSS_LoadPublicKey(aCertName,
                             (SECKEYPublicKey**)aPublicKey,
                             (CERTCertificate**)aCert);
  }

  CFURLRef url =
    CFURLCreateFromFileSystemRepresentation(kCFAllocatorDefault,
                                            aCertData,
                                            strlen((char*)aCertData),
                                            false);
  if (!url) {
    return CryptoX_Error;
  }

  CFReadStreamRef stream = CFReadStreamCreateWithFile(kCFAllocatorDefault, url);
  if (!stream) {
    CFRelease(url);
    return CryptoX_Error;
  }

  SecTransformRef readTransform =
    SecTransformCreateReadTransformWithReadStreamPtr(stream);
  if (!readTransform) {
    CFRelease(url);
    CFRelease(stream);
    return CryptoX_Error;
  }

  CFErrorRef error;
  CFDataRef tempCertData = (CFDataRef)SecTransformExecutePtr(readTransform,
                                                             &error);
  if (!tempCertData || error) {
    CFRelease(url);
    CFRelease(stream);
    CFRelease(readTransform);
    return CryptoX_Error;
  }

  SecCertificateRef cert = SecCertificateCreateWithDataPtr(kCFAllocatorDefault,
                                                           tempCertData);
  if (!cert) {
    CFRelease(url);
    CFRelease(stream);
    CFRelease(readTransform);
    CFRelease(tempCertData);
    return CryptoX_Error;
  }

  CryptoX_Result result = CryptoX_Error;
  OSStatus status = SecCertificateCopyPublicKeyPtr(cert,
                                                   (SecKeyRef*)aPublicKey);
  if (status == 0) {
    result = CryptoX_Success;
  }

  CFRelease(url);
  CFRelease(stream);
  CFRelease(readTransform);
  CFRelease(tempCertData);
  CFRelease(cert);

  return result;
}
CFStringRef GCCreateMD5HashWithPath(CFStringRef filePath)
{
    
    CFStringRef result = NULL;
    CFReadStreamRef readStream = NULL;
    
    CFURLRef fileURL =
    CFURLCreateWithFileSystemPath(kCFAllocatorDefault,
                                  (CFStringRef)filePath,
                                  kCFURLPOSIXPathStyle,
                                  (Boolean)false);
    if (!fileURL) goto done;
    
    readStream = CFReadStreamCreateWithFile(kCFAllocatorDefault,
                                            (CFURLRef)fileURL);
    if (!readStream) goto done;
    bool didSucceed = (bool)CFReadStreamOpen(readStream);
    if (!didSucceed) goto done;
    
    CC_MD5_CTX hashObject;
    CC_MD5_Init(&hashObject);
    
    bool hasMoreData = true;
    while (hasMoreData) {
        uint8_t buffer[GCFileChunkSize];
        CFIndex readBytesCount = CFReadStreamRead(readStream,
                                                  (UInt8 *)buffer,
                                                  (CFIndex)sizeof(buffer));
        if (readBytesCount == -1) break;
        if (readBytesCount == 0) {
            hasMoreData = false;
            continue;
        }
        CC_MD5_Update(&hashObject,
                      (const void *)buffer,
                      (CC_LONG)readBytesCount);
    }
    
    didSucceed = !hasMoreData;
    
    unsigned char digest[CC_MD5_DIGEST_LENGTH];
    CC_MD5_Final(digest, &hashObject);
    
    if (!didSucceed) goto done;
    
    char hash[2 * sizeof(digest) + 1];
    for (size_t i = 0; i < sizeof(digest); ++i) {
        snprintf(hash + (2 * i), 3, "%02x", (int)(digest[i]));
    }
    result = CFStringCreateWithCString(kCFAllocatorDefault,
                                       (const char *)hash,
                                       kCFStringEncodingUTF8);
    
done:
    
    if (readStream) {
        CFReadStreamClose(readStream);
        CFRelease(readStream);
    }
    if (fileURL) {
        CFRelease(fileURL);
    }
    return result;
}
Example #28
0
static int
fuse_system_get_version(int *major, int *minor, int *bugfix)
{
    int ret = 0;

    CFStringRef plist_path = CFSTR(SYSTEM_VERSION_PATH);

    CFURLRef plist_url = CFURLCreateWithFileSystemPath(
            kCFAllocatorDefault, plist_path, kCFURLPOSIXPathStyle, false);
    CFReadStreamRef plist_stream = CFReadStreamCreateWithFile(
            kCFAllocatorDefault, plist_url);

    CFRelease(plist_url);
    if (!plist_stream) {
        return 1;
    }
    if (!CFReadStreamOpen(plist_stream)) {
        CFRelease(plist_stream);
        return 1;
    }

    CFPropertyListRef plist = CFPropertyListCreateWithStream(
            kCFAllocatorDefault, plist_stream, 0, kCFPropertyListImmutable,
            NULL, NULL);

    CFReadStreamClose(plist_stream);
    CFRelease(plist_stream);
    if (!plist) {
        return 1;
    }

    CFStringRef version = CFDictionaryGetValue(plist, CFSTR("ProductVersion"));
    if (!version) {
        ret = 1;
        goto out_plist;
    }

    CFArrayRef components = CFStringCreateArrayBySeparatingStrings(
            kCFAllocatorDefault, version, CFSTR("."));
    if (!components) {
        ret = 1;
        goto out_plist;
    }

    CFIndex count = CFArrayGetCount(components);

#define component_get(components, count, index) \
        ((index) < (count) \
         ? CFStringGetIntValue(CFArrayGetValueAtIndex((components), (index))) \
         : 0)

    if (major) {
        *major = component_get(components, count, 0);
    }
    if (minor) {
        *minor = component_get(components, count, 1);
    }
    if (bugfix) {
        *bugfix = component_get(components, count, 2);
    }

#undef component_get

    CFRelease(components);

out_plist:
    CFRelease(plist);

    return ret;
}
static void perform_upload_request__string(
    SG_context* pCtx,
    CFHTTPMessageRef myRequest,
    SG_pathname* pPath,
    CFHTTPMessageRef* pmyResponse,
    SG_string** ppstr
)
{
    CFReadStreamRef myReadStream = NULL;
    CFHTTPMessageRef myResponse = NULL;
    SG_string* pstr = NULL;
    CFReadStreamRef upload = NULL;
    CFURLRef upload_file_url = NULL;

    // set the content-length header
    {
        SG_uint64 len = 0;
        SG_ERR_CHECK(  SG_fsobj__length__pathname(pCtx, pPath, &len, NULL)  );

        CFStringRef headerFieldName = CFSTR("Content-Length");
        CFStringRef headerFieldValue = CFStringCreateWithFormat (kCFAllocatorDefault, NULL,  CFSTR("%d"), len);
        CFHTTPMessageSetHeaderFieldValue(myRequest, headerFieldName, headerFieldValue);
        CFRelease(headerFieldValue);
    }

    upload_file_url = CFURLCreateFromFileSystemRepresentation(kCFAllocatorDefault, (UInt8*) SG_pathname__sz(pPath), SG_STRLEN(SG_pathname__sz(pPath)), SG_FALSE);
    upload = CFReadStreamCreateWithFile(kCFAllocatorDefault, upload_file_url);
    CFRelease(upload_file_url);
    if (!CFReadStreamOpen(upload))
    {
        CFStreamError myErr = CFReadStreamGetError(upload);

        if (myErr.domain == kCFStreamErrorDomainPOSIX)
        {
            // Interpret myErr.error as a UNIX errno.
            SG_ERR_THROW(  SG_ERR_ERRNO(myErr.error)  );
        }
        else if (myErr.domain == kCFStreamErrorDomainMacOSStatus)
        {
            // Interpret myErr.error as a MacOS error code.
            // TODO SG_ERR_THROW(  SG_ERR_MAC((OSStatus) myErr.error)  );
            SG_ERR_THROW(  SG_ERR_UNSPECIFIED  );
        }
    }

    SG_ERR_CHECK(  send_upload_request(pCtx, myRequest, upload, &myReadStream)  );
    SG_ERR_CHECK(  read_entire_stream__string(pCtx, myReadStream, &pstr, &myResponse)  );

    *ppstr = pstr;
    pstr = NULL;

    *pmyResponse = myResponse;
    myResponse = NULL;

fail:
    if (upload)
    {
        CFRelease(upload);
    }
    if (myReadStream)
    {
        CFReadStreamClose(myReadStream);
        CFRelease(myReadStream);
        myReadStream = NULL;
    }

    if (myResponse)
    {
        CFRelease(myResponse);
        myResponse = NULL;
    }

    SG_STRING_NULLFREE(pCtx, pstr);
}
Example #30
0
int ReadHashStateFile( const char *inFilePath, sHashState *inOutHashState )
{
	CFStringRef myReplicaDataFilePathRef;
	CFURLRef myReplicaDataFileRef;
	CFReadStreamRef myReadStreamRef;
	CFPropertyListRef myPropertyListRef;
	CFStringRef errorString;
	CFPropertyListFormat myPLFormat;
	struct stat sb;
	CFMutableDictionaryRef stateDict = NULL;
	CFStringRef keyString = NULL;
	CFDateRef dateValue = NULL;
	CFNumberRef numberValue = NULL;
	long aLongValue;
	short aShortValue;
	int returnValue = 0;
	
	if ( inFilePath == NULL || inOutHashState == NULL )
		return -1;
	
	do
	{
		if ( stat( inFilePath, &sb ) != 0 )
		{
			time_t now;
			
			// initialize the creation date.
			time( &now );
			gmtime_r( &now, &inOutHashState->creationDate );
			returnValue = -1;
			break;
		}
		
		myReplicaDataFilePathRef = CFStringCreateWithCString( kCFAllocatorDefault, inFilePath, kCFStringEncodingUTF8 );
		if ( myReplicaDataFilePathRef == NULL )
		{
			returnValue = -1;
			break;
		}
	
		myReplicaDataFileRef = CFURLCreateWithFileSystemPath( kCFAllocatorDefault, myReplicaDataFilePathRef,
			kCFURLPOSIXPathStyle, false );
	
		CFRelease( myReplicaDataFilePathRef );
	
		if ( myReplicaDataFileRef == NULL )
		{
			returnValue = -1;
			break;
		}
		
		myReadStreamRef = CFReadStreamCreateWithFile( kCFAllocatorDefault, myReplicaDataFileRef );
	
		CFRelease( myReplicaDataFileRef );
	
		if ( myReadStreamRef == NULL )
		{
			returnValue = -1;
			break;
		}
		
		CFReadStreamOpen( myReadStreamRef );
	
		errorString = NULL;
		myPLFormat = kCFPropertyListXMLFormat_v1_0;
		myPropertyListRef = CFPropertyListCreateFromStream( kCFAllocatorDefault, myReadStreamRef, 0,
			kCFPropertyListMutableContainersAndLeaves, &myPLFormat, &errorString );
		
		CFReadStreamClose( myReadStreamRef );
		CFRelease( myReadStreamRef );
		
		if ( errorString != NULL )
		{
			char errMsg[256];
			
			if ( CFStringGetCString( errorString, errMsg, sizeof(errMsg), kCFStringEncodingUTF8 ) )
				DbgLog(kLogPlugin, "ReadHashStateFile: could not load the state file, error = %s", errMsg );
			CFRelease( errorString );
		}
		
		if ( myPropertyListRef == NULL )
		{
			DbgLog(kLogPlugin, "ReadHashStateFile: could not load the hash state file because the property list is empty." );
			returnValue = -1;
			break;
		}
		
		if ( CFGetTypeID(myPropertyListRef) != CFDictionaryGetTypeID() )
		{
			CFRelease( myPropertyListRef );
			DbgLog(kLogPlugin, "ReadHashStateFile: could not load the hash state file because the property list is not a dictionary." );
			returnValue = -1;
			break;
		}
		
		stateDict = (CFMutableDictionaryRef)myPropertyListRef;
					
		keyString = CFStringCreateWithCString( kCFAllocatorDefault, "CreationDate", kCFStringEncodingUTF8 );
		if ( keyString != NULL )
		{
			if ( CFDictionaryGetValueIfPresent( stateDict, keyString, (const void **)&dateValue ) )
			{
				pwsf_ConvertCFDateToBSDTime( dateValue, &inOutHashState->creationDate );
			}
			CFRelease( keyString );
		}
		keyString = CFStringCreateWithCString( kCFAllocatorDefault, "LastLoginDate", kCFStringEncodingUTF8 );
		if ( keyString != NULL )
		{
			if ( CFDictionaryGetValueIfPresent( stateDict, keyString, (const void **)&dateValue ) )
			{
				pwsf_ConvertCFDateToBSDTime( dateValue, &inOutHashState->lastLoginDate );
			}
			CFRelease( keyString );
		}
		keyString = CFStringCreateWithCString( kCFAllocatorDefault, "FailedLoginCount", kCFStringEncodingUTF8 );
		if ( keyString != NULL )
		{
			if ( CFDictionaryGetValueIfPresent( stateDict, keyString, (const void **)&numberValue ) &&
					CFGetTypeID(numberValue) == CFNumberGetTypeID() &&
					CFNumberGetValue( (CFNumberRef)numberValue, kCFNumberLongType, &aLongValue) )
			{
				inOutHashState->failedLoginAttempts = (UInt16)aLongValue;
			}
			CFRelease( keyString );
		}
		keyString = CFStringCreateWithCString( kCFAllocatorDefault, "NewPasswordRequired", kCFStringEncodingUTF8 );
		if ( keyString != NULL )
		{
			if ( CFDictionaryGetValueIfPresent( stateDict, keyString, (const void **)&numberValue ) &&
					CFGetTypeID(numberValue) == CFNumberGetTypeID() &&
					CFNumberGetValue( (CFNumberRef)numberValue, kCFNumberSInt16Type, &aShortValue) )
			{
				inOutHashState->newPasswordRequired = (UInt16)aShortValue;
			}
			CFRelease( keyString );
		}
	
		CFRelease( stateDict );
		
	} while( false );
	
	return returnValue;
}