/* @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; }
CURLcode SSLImpl::connect(int sockfd, int nonblocking, int *done, int ssl_verify_peer, void *storage, char* host_name) { ssl_data_t *data = (ssl_data_t*)storage; CFStreamCreatePairWithSocket(kCFAllocatorDefault, sockfd, &data->readStream, &data->writeStream); // Indicate that the connection needs to be done in secure manner CFReadStreamSetProperty(data->readStream, kCFStreamPropertySocketSecurityLevel, kCFStreamSocketSecurityLevelSSLv3); CFWriteStreamSetProperty(data->writeStream, kCFStreamPropertySocketSecurityLevel, kCFStreamSocketSecurityLevelSSLv3); CFMutableDictionaryRef dict = CFDictionaryCreateMutable(kCFAllocatorDefault, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); if (!dict) { RAWLOG_ERROR("Can not allocate CFMutableDictionaryRef"); return CURLE_SSL_CONNECT_ERROR; } CFDictionarySetValue(dict, kCFStreamSSLValidatesCertificateChain, ssl_verify_peer ? kCFBooleanTrue : kCFBooleanFalse); CFReadStreamSetProperty(data->readStream, kCFStreamPropertySSLSettings, dict); CFWriteStreamSetProperty(data->writeStream, kCFStreamPropertySSLSettings, dict); CFRelease(dict); if (!CFReadStreamOpen(data->readStream) || !CFWriteStreamOpen(data->writeStream)) { RAWLOG_ERROR("SSL connection error"); return CURLE_SSL_CONNECT_ERROR; } CFReadStreamScheduleWithRunLoop( data->readStream, CFRunLoopGetCurrent(), kCFRunLoopCommonModes); CFWriteStreamScheduleWithRunLoop( data->writeStream, CFRunLoopGetCurrent(), kCFRunLoopCommonModes); *done = 1; return CURLE_OK; }
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(); } }
static void nc_trigger(int argc, char **argv) { Boolean background = FALSE; int i; CFStringRef hostName = NULL; int port = 80; for (i = 0; i < 3 && i < argc; i++) { /* Parse host name. Must be first arg. */ if (i == 0) { hostName = CFStringCreateWithCString(NULL, argv[i], kCFStringEncodingUTF8); continue; } /* Check for optional background flag */ if (strcmp(argv[i], "background") == 0) { background = TRUE; continue; } /* Parse optional port number */ CFStringRef str = CFStringCreateWithCString(NULL, argv[i], kCFStringEncodingUTF8); if (str) { int num = CFStringGetIntValue(str); if (num) { port = num; } my_CFRelease(&str); } } if (hostName) { CFReadStreamRef readStream = NULL; CFWriteStreamRef writeStream = NULL; CFStreamCreatePairWithSocketToHost(kCFAllocatorDefault, hostName, port, &readStream, &writeStream); if (background) { CFReadStreamSetProperty(readStream, CFSTR("kCFStreamNetworkServiceType"), CFSTR("kCFStreamNetworkServiceTypeBackground")); CFWriteStreamSetProperty(writeStream, CFSTR("kCFStreamNetworkServiceType"), CFSTR("kCFStreamNetworkServiceTypeBackground")); } if (readStream && writeStream) { CFReadStreamOpen(readStream); CFWriteStreamOpen(writeStream); SCPrint(TRUE, stdout, CFSTR("Opened stream to %@, port %d%s\n"), hostName, port, background ? ", background traffic class" : ""); sleep(1); } my_CFRelease(&readStream); my_CFRelease(&writeStream); } else { SCPrint(TRUE, stderr, CFSTR("Invalid or missing host name\n")); } my_CFRelease(&hostName); exit(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); }
void SocketStreamHandle::scheduleStreams() { ASSERT(m_readStream); ASSERT(m_writeStream); CFStreamClientContext clientContext = { 0, this, 0, 0, copyCFStreamDescription }; // FIXME: Pass specific events we're interested in instead of -1. CFReadStreamSetClient(m_readStream.get(), static_cast<CFOptionFlags>(-1), readStreamCallback, &clientContext); CFWriteStreamSetClient(m_writeStream.get(), static_cast<CFOptionFlags>(-1), writeStreamCallback, &clientContext); #if PLATFORM(WIN) CFReadStreamScheduleWithRunLoop(m_readStream.get(), loaderRunLoop(), kCFRunLoopDefaultMode); CFWriteStreamScheduleWithRunLoop(m_writeStream.get(), loaderRunLoop(), kCFRunLoopDefaultMode); #else CFReadStreamScheduleWithRunLoop(m_readStream.get(), CFRunLoopGetCurrent(), kCFRunLoopCommonModes); CFWriteStreamScheduleWithRunLoop(m_writeStream.get(), CFRunLoopGetCurrent(), kCFRunLoopCommonModes); #endif CFReadStreamOpen(m_readStream.get()); CFWriteStreamOpen(m_writeStream.get()); #ifndef BUILDING_ON_TIGER if (m_pacRunLoopSource) removePACRunLoopSource(); #endif m_connectingSubstate = WaitingForConnect; }
RetainPtr<CFDataRef> LegacyWebArchive::rawDataRepresentation() { RetainPtr<CFDictionaryRef> propertyList = createPropertyListRepresentation(this); ASSERT(propertyList); if (!propertyList) { LOG(Archives, "LegacyWebArchive - Failed to create property list for archive, returning no data"); return 0; } RetainPtr<CFWriteStreamRef> stream(AdoptCF, CFWriteStreamCreateWithAllocatedBuffers(0, 0)); CFWriteStreamOpen(stream.get()); CFPropertyListWriteToStream(propertyList.get(), stream.get(), kCFPropertyListBinaryFormat_v1_0, 0); RetainPtr<CFDataRef> plistData(AdoptCF, static_cast<CFDataRef>(CFWriteStreamCopyProperty(stream.get(), kCFStreamPropertyDataWritten))); ASSERT(plistData); CFWriteStreamClose(stream.get()); if (!plistData) { LOG(Archives, "LegacyWebArchive - Failed to convert property list into raw data, returning no data"); return 0; } return plistData; }
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); }
tsk_size_t tnet_transport_send(const tnet_transport_handle_t *handle, tnet_fd_t from, const void* buf, tsk_size_t size) { tnet_transport_t *transport = (tnet_transport_t*)handle; int numberOfBytesSent = 0; if (!transport) { TSK_DEBUG_ERROR("Invalid transport handle."); goto bail; } const transport_socket_t* sock = getSocket(transport->context, from); if (TNET_SOCKET_TYPE_IS_STREAM(sock->type)) { if (!sock->cf_write_stream) { TNET_PRINT_LAST_ERROR("No stream found."); goto bail; } if (CFWriteStreamGetStatus(sock->cf_write_stream) == kCFStreamStatusNotOpen) { CFWriteStreamOpen(sock->cf_write_stream); } if ((numberOfBytesSent = CFWriteStreamWrite(sock->cf_write_stream, buf, (CFIndex) size)) <= 0) { TNET_PRINT_LAST_ERROR("Send have failed."); goto bail; } } else { if ((numberOfBytesSent = send(from, buf, size, 0)) <= 0) { TNET_PRINT_LAST_ERROR("Send have failed."); goto bail; } } bail: return numberOfBytesSent; }
void write_buffer(CFStringRef inData) { #ifdef DEBUG syslog(LOG_ERR,"Writing buffer to file."); #endif if (CFWriteStreamGetStatus(logStream)!=kCFStreamStatusOpen) { CFWriteStreamSetProperty(logStream,kCFStreamPropertyAppendToFile,kCFBooleanTrue); CFWriteStreamOpen(logStream); } if (!CFBooleanGetValue(doEncrypt)) { CFWriteStreamWrite(logStream,(const UInt8*)CFStringGetCStringPtr(inData,CFStringGetFastestEncoding(inData)),CFStringGetLength(inData)); return; } int buff_pos = 0; while (1) { int avail_space = 8-CFDataGetLength(encrypt_buffer); //space rem in buffer int rem_to_copy = CFStringGetLength(inData)-buff_pos; //stuff in data that needs to be copied int to_copy = rem_to_copy<avail_space?rem_to_copy:avail_space; //amount left to encryp, or avail space if (avail_space) { UInt8 tmp_buff[8]; CFStringGetBytes(inData,CFRangeMake(buff_pos,to_copy),kCFStringEncodingNonLossyASCII,0,false,tmp_buff,8,NULL); CFDataAppendBytes(encrypt_buffer,tmp_buff,to_copy); avail_space -= to_copy; if (avail_space>0) // small buffer? still space left? break; buff_pos += to_copy; //move along the buffer } UInt8 enc_buff[8]; BF_ecb_encrypt(CFDataGetBytePtr(encrypt_buffer),enc_buff,&encrypt_bf_key,BF_ENCRYPT); CFWriteStreamWrite(logStream,enc_buff,8); CFDataDeleteBytes(encrypt_buffer,CFRangeMake(0,8)); if (buff_pos==CFStringGetLength(inData)) //just in case buffer happens to fit perfectly break; } return; }
RefPtr<API::Data> encodeLegacySessionState(const SessionState& sessionState) { auto sessionHistoryDictionary = encodeSessionHistory(sessionState.backForwardListState); auto provisionalURLString = sessionState.provisionalURL.isNull() ? nullptr : sessionState.provisionalURL.string().createCFString(); RetainPtr<CFNumberRef> renderTreeSizeNumber(adoptCF(CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt64Type, &sessionState.renderTreeSize))); RetainPtr<CFDictionaryRef> stateDictionary; if (provisionalURLString) { stateDictionary = createDictionary({ { sessionHistoryKey, sessionHistoryDictionary.get() }, { provisionalURLKey, provisionalURLString.get() }, { renderTreeSizeKey, renderTreeSizeNumber.get() } }); } else { stateDictionary = createDictionary({ { sessionHistoryKey, sessionHistoryDictionary.get() }, { renderTreeSizeKey, renderTreeSizeNumber.get() } }); } auto writeStream = adoptCF(CFWriteStreamCreateWithAllocatedBuffers(kCFAllocatorDefault, nullptr)); if (!writeStream) return nullptr; if (!CFWriteStreamOpen(writeStream.get())) return nullptr; if (!CFPropertyListWrite(stateDictionary.get(), writeStream.get(), kCFPropertyListBinaryFormat_v1_0, 0, nullptr)) return nullptr; auto data = adoptCF(static_cast<CFDataRef>(CFWriteStreamCopyProperty(writeStream.get(), kCFStreamPropertyDataWritten))); CFIndex length = CFDataGetLength(data.get()); size_t bufferSize = length + sizeof(uint32_t); auto buffer = MallocPtr<uint8_t>::malloc(bufferSize); // Put the session state version number at the start of the buffer buffer.get()[0] = (sessionStateDataVersion & 0xff000000) >> 24; buffer.get()[1] = (sessionStateDataVersion & 0x00ff0000) >> 16; buffer.get()[2] = (sessionStateDataVersion & 0x0000ff00) >> 8; buffer.get()[3] = (sessionStateDataVersion & 0x000000ff); // Copy in the actual session state data CFDataGetBytes(data.get(), CFRangeMake(0, length), buffer.get() + sizeof(uint32_t)); return API::Data::createWithoutCopying(buffer.leakPtr(), bufferSize, [] (unsigned char* buffer, const void* context) { fastFree(buffer); }, nullptr); }
sdmmd_return_t SDMMD_ServiceSendStream(SocketConnection handle, CFPropertyListRef data, CFPropertyListFormat format) { CFStringRef errStr; CFWriteStreamRef write = CFWriteStreamCreateWithAllocatedBuffers(kCFAllocatorDefault, kCFAllocatorDefault); CFWriteStreamOpen(write); uint32_t length = CFPropertyListWriteToStream(data, write, format, &errStr); CFDataRef xmlData = CFWriteStreamCopyProperty(write, kCFStreamPropertyDataWritten); sdmmd_return_t result = kAMDInvalidArgumentError; if (length == CFDataGetLength(xmlData)) { result = ((data) ? SDMMD_ServiceSend(handle, xmlData) : kAMDInvalidArgumentError); } if (xmlData) CFRelease(xmlData); CFWriteStreamClose(write); if (write) CFRelease(write); return result; }
bool TCPStream_CFNetwork::connect() { state = Stream::State::Opening; CFStringRef host_cfstring = CFStringCreateWithCString(kCFAllocatorDefault, remoteHostName.c_str(), kCFStringEncodingUTF8); CFStreamCreatePairWithSocketToHost(kCFAllocatorDefault, host_cfstring, remotePortNumber, &inputStream, &outputStream); CFRelease(host_cfstring); CFStreamClientContext inputStreamContext; memset(&inputStreamContext, 0, sizeof(inputStreamContext)); inputStreamContext.info = reinterpret_cast<void *>(this); CFReadStreamSetClient(inputStream, kCFStreamEventHasBytesAvailable | kCFStreamEventEndEncountered | kCFStreamEventErrorOccurred, inputStreamCallback, &inputStreamContext); CFReadStreamScheduleWithRunLoop(inputStream, CFRunLoopGetMain(), kCFRunLoopDefaultMode); if (CFReadStreamOpen(inputStream) && CFWriteStreamOpen(outputStream)) { state = Stream::State::Open; return true; } else { CFRelease(outputStream); CFRelease(inputStream); outputStream = nullptr; inputStream = nullptr; state = Stream::State::NotOpen; return false; } }
static int low_open(mailstream_low * s) { struct mailstream_cfstream_data * cfstream_data; int r; cfstream_data = (struct mailstream_cfstream_data *) s->data; CFReadStreamOpen(cfstream_data->readStream); CFWriteStreamOpen(cfstream_data->writeStream); r = wait_runloop(s, STATE_WAIT_OPEN); if (r != WAIT_RUNLOOP_EXIT_NO_ERROR) { return -1; } if (cfstream_data->writeOpenResult < 0) return -1; if (cfstream_data->readOpenResult < 0) return -1; return 0; }
CFNetDiagnosticStatus CFNetDiagnosticDiagnoseProblemInteractively(CFNetDiagnosticRef details) { SInt32 retval = 0; mach_port_t port = MACH_PORT_NULL; CFDataRef msgData = NULL; kern_return_t err; //build message CFWriteStreamRef stream = CFWriteStreamCreateWithAllocatedBuffers(kCFAllocatorDefault, kCFAllocatorDefault); CFWriteStreamOpen(stream); CFIndex len = CFPropertyListWriteToStream(details, stream, kCFPropertyListBinaryFormat_v1_0, NULL); CFWriteStreamClose(stream); if(len > 0) { msgData = CFWriteStreamCopyProperty(stream, kCFStreamPropertyDataWritten); } CFRelease(stream); if(msgData) { err = bootstrap_look_up(bootstrap_port, *((name_t*)(&_CFNetDiagnosticMachPortName)), &port); if (err == KERN_SUCCESS) { err = _CFNetDiagnosticClient_passDescriptor( port, _CFNetDiagnosticMachProtocolVersion, (vm_address_t)CFDataGetBytePtr(msgData), CFDataGetLength(msgData)); if (err == KERN_SUCCESS) { //FIXME Yay!!! } } CFRelease(msgData); } return (CFNetDiagnosticStatus)retval; }
File_Output::File_Output(CFURLRef fileURL) : m_writeStream(CFWriteStreamCreateWithFile(kCFAllocatorDefault, fileURL)) { CFWriteStreamOpen(m_writeStream); }
/* extern */ Boolean HttpContextOpen(HttpContextRef context) { do { Boolean didSet; CFRunLoopRef runLoop = CFRunLoopGetCurrent(); CFStreamClientContext streamCtxt = {0, context, (void*(*)(void*))&HttpContextRetain, (void(*)(void*))&HttpContextRelease, NULL}; CFRunLoopTimerContext timerCtxt = {0, context, (const void*(*)(const void*))&HttpContextRetain, (void(*)(const void*))&HttpContextRelease, NULL}; // Set the client on the read stream. didSet = CFReadStreamSetClient(context->_inStream, kReadEvents, (CFReadStreamClientCallBack)&_ReadStreamCallBack, &streamCtxt); // Fail if unable to set the client. if (!didSet) break; // Set the client on the write stream. didSet = CFWriteStreamSetClient(context->_outStream, kWriteEvents, (CFWriteStreamClientCallBack)&_WriteStreamCallBack, &streamCtxt); // Fail if unable to set the client. if (!didSet) break; // Schedule the streams on the current run loop and default mode. CFReadStreamScheduleWithRunLoop(context->_inStream, runLoop, kCFRunLoopCommonModes); CFWriteStreamScheduleWithRunLoop(context->_outStream, runLoop, kCFRunLoopCommonModes); // Open the stream for reading. if (!CFReadStreamOpen(context->_inStream)) break; // Open the stream for writing. if (!CFWriteStreamOpen(context->_outStream)) break; // Create the timeout timer context->_timer = CFRunLoopTimerCreate(CFGetAllocator(context->_inStream), CFAbsoluteTimeGetCurrent() + kTimeOutInSeconds, 0, // interval 0, // flags 0, // order (CFRunLoopTimerCallBack)_TimerCallBack, &timerCtxt); // Fail if unable to create the timer. if (context->_timer == NULL) break; CFRunLoopAddTimer(runLoop, context->_timer, kCFRunLoopCommonModes); return TRUE; } while (0); // Something failed, so clean up. HttpContextClose(context); return FALSE; }
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; }
// domain should already be locked. static Boolean _writeXMLFile(CFURLRef url, CFMutableDictionaryRef dict, Boolean isWorldReadable, Boolean *tryAgain) { Boolean success = false; CFAllocatorRef alloc = __CFPreferencesAllocator(); *tryAgain = false; if (CFDictionaryGetCount(dict) == 0) { // Destroy the file CFBooleanRef val = (CFBooleanRef) CFURLCreatePropertyFromResource(alloc, url, kCFURLFileExists, NULL); if (val && CFBooleanGetValue(val)) { success = CFURLDestroyResource(url, NULL); } else { success = true; } if (val) CFRelease(val); } else { CFPropertyListFormat desiredFormat = __CFPreferencesShouldWriteXML() ? kCFPropertyListXMLFormat_v1_0 : kCFPropertyListBinaryFormat_v1_0; CFWriteStreamRef binStream = CFWriteStreamCreateWithAllocatedBuffers(alloc, alloc); CFWriteStreamOpen(binStream); CFPropertyListWriteToStream(dict, binStream, desiredFormat, NULL); CFWriteStreamClose(binStream); CFDataRef data = (CFDataRef) CFWriteStreamCopyProperty(binStream, kCFStreamPropertyDataWritten); CFRelease(binStream); if (data) { SInt32 mode; #if DEPLOYMENT_TARGET_MACOSX mode = isWorldReadable ? S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH : S_IRUSR|S_IWUSR; #else mode = 0666; #endif #if DEPLOYMENT_TARGET_MACOSX { // Try quick atomic way first, then fallback to slower ways and error cases CFStringRef scheme = CFURLCopyScheme(url); if (!scheme) { *tryAgain = false; CFRelease(data); return false; } else if (CFStringCompare(scheme, CFSTR("file"), 0) == kCFCompareEqualTo) { SInt32 length = CFDataGetLength(data); const void *bytes = (0 == length) ? (const void *)"" : CFDataGetBytePtr(data); Boolean atomicWriteSuccess = __CFWriteBytesToFileWithAtomicity(url, bytes, length, mode, true); if (atomicWriteSuccess) { CFRelease(scheme); *tryAgain = false; CFRelease(data); return true; } if (!atomicWriteSuccess && thread_errno() == ENOSPC) { CFRelease(scheme); *tryAgain = false; CFRelease(data); return false; } } CFRelease(scheme); } #endif success = CFURLWriteDataAndPropertiesToResource(url, data, URLPropertyDictForPOSIXMode(mode), NULL); URLPropertyDictRelease(); if (success) { CFDataRef readData; if (!CFURLCreateDataAndPropertiesFromResource(alloc, url, &readData, NULL, NULL, NULL) || !CFEqual(readData, data)) { success = false; *tryAgain = true; } if (readData) CFRelease(readData); } else { CFBooleanRef val = (CFBooleanRef) CFURLCreatePropertyFromResource(alloc, url, kCFURLFileExists, NULL); if (!val || !CFBooleanGetValue(val)) { CFURLRef tmpURL = CFURLCreateWithFileSystemPathRelativeToBase(alloc, CFSTR("."), kCFURLPOSIXPathStyle, true, url); // Just "." because url is not a directory URL CFURLRef parentURL = tmpURL ? CFURLCopyAbsoluteURL(tmpURL) : NULL; if (tmpURL) CFRelease(tmpURL); if (val) CFRelease(val); val = (CFBooleanRef) CFURLCreatePropertyFromResource(alloc, parentURL, kCFURLFileExists, NULL); if ((!val || !CFBooleanGetValue(val)) && _createDirectory(parentURL, isWorldReadable)) { // parent directory didn't exist; now it does; try again to write success = CFURLWriteDataAndPropertiesToResource(url, data, URLPropertyDictForPOSIXMode(mode), NULL); URLPropertyDictRelease(); if (success) { CFDataRef rdData; if (!CFURLCreateDataAndPropertiesFromResource(alloc, url, &rdData, NULL, NULL, NULL) || !CFEqual(rdData, data)) { success = false; *tryAgain = true; } if (rdData) CFRelease(rdData); } } if (parentURL) CFRelease(parentURL); } if (val) CFRelease(val); } CFRelease(data); } else { // ??? This should never happen CFLog(__kCFLogAssertion, CFSTR("Could not generate XML data for property list")); success = false; } } return success; }
int tnet_transport_wrap(tnet_transport_t *transport, int index) { transport_context_t *context = transport->context; transport_socket_t *sock = context->sockets[index]; // If the socket is already wrapped in a CFSocket then return. if (sock->cf_socket || sock->cf_read_stream) { return 1; } // Put a reference to the transport context const CFSocketContext socket_context = { 0, transport, NULL, NULL, NULL }; if (TNET_SOCKET_TYPE_IS_DGRAM(sock->type)) { // Create a CFSocket from the native socket and register for Read events sock->cf_socket = CFSocketCreateWithNative(kCFAllocatorDefault, sock->fd, kCFSocketReadCallBack, &__CFSocketCallBack, &socket_context); // Don't close the socket if the CFSocket is invalidated CFOptionFlags flags = CFSocketGetSocketFlags(sock->cf_socket); flags = flags & ~kCFSocketCloseOnInvalidate; CFSocketSetSocketFlags(sock->cf_socket, flags); // Create a new RunLoopSource and register it with the main thread RunLoop sock->cf_run_loop_source = CFSocketCreateRunLoopSource(kCFAllocatorDefault, sock->cf_socket, 0); CFRunLoopAddSource(context->cf_run_loop, sock->cf_run_loop_source, kCFRunLoopDefaultMode); CFRelease(sock->cf_run_loop_source); } else if (TNET_SOCKET_TYPE_IS_STREAM(sock->type)) { // Create a pair of streams (read/write) from the socket CFStreamCreatePairWithSocket(kCFAllocatorDefault, sock->fd, &sock->cf_read_stream, &sock->cf_write_stream); // Don't close underlying socket CFReadStreamSetProperty(sock->cf_read_stream, kCFStreamPropertyShouldCloseNativeSocket, kCFBooleanFalse); CFWriteStreamSetProperty(sock->cf_write_stream, kCFStreamPropertyShouldCloseNativeSocket, kCFBooleanFalse); if (TNET_SOCKET_TYPE_IS_SECURE(sock->type)) { CFMutableDictionaryRef settings = CFDictionaryCreateMutable(kCFAllocatorDefault, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); CFDictionaryAddValue(settings, kCFStreamSSLAllowsExpiredCertificates, kCFBooleanTrue); CFDictionaryAddValue(settings, kCFStreamSSLAllowsAnyRoot, kCFBooleanTrue); CFDictionaryAddValue(settings, kCFStreamSSLValidatesCertificateChain, kCFBooleanFalse); CFDictionaryAddValue(settings, kCFStreamSSLPeerName, kCFNull); // Set the SSL settings CFReadStreamSetProperty(sock->cf_read_stream, kCFStreamPropertySocketSecurityLevel, kCFStreamSocketSecurityLevelNegotiatedSSL); CFReadStreamSetProperty(sock->cf_read_stream, kCFStreamPropertySSLSettings, settings); CFWriteStreamSetProperty(sock->cf_write_stream, kCFStreamPropertySocketSecurityLevel, kCFStreamSocketSecurityLevelNegotiatedSSL); CFWriteStreamSetProperty(sock->cf_write_stream, kCFStreamPropertySSLSettings, settings); CFRelease(settings); } #if __IPHONE_4_0 // Mark the stream for VoIP usage CFReadStreamSetProperty(sock->cf_read_stream, kCFStreamNetworkServiceType, kCFStreamNetworkServiceTypeVoIP); CFWriteStreamSetProperty(sock->cf_write_stream, kCFStreamNetworkServiceType, kCFStreamNetworkServiceTypeVoIP); #endif // Setup a context for the streams CFStreamClientContext streamContext = { 0, transport, NULL, NULL, NULL }; // Set the client callback for the stream CFReadStreamSetClient(sock->cf_read_stream, kCFStreamEventOpenCompleted | kCFStreamEventHasBytesAvailable | kCFStreamEventErrorOccurred | kCFStreamEventEndEncountered, &__CFReadStreamClientCallBack, &streamContext); CFWriteStreamSetClient(sock->cf_write_stream, kCFStreamEventOpenCompleted | kCFStreamEventErrorOccurred | kCFStreamEventEndEncountered, &__CFWriteStreamClientCallBack, &streamContext); // Enroll streams in the run-loop CFReadStreamScheduleWithRunLoop(sock->cf_read_stream, context->cf_run_loop, kCFRunLoopDefaultMode); CFWriteStreamScheduleWithRunLoop(sock->cf_write_stream, context->cf_run_loop, kCFRunLoopDefaultMode); // Release references CFRelease(sock->cf_read_stream); CFRelease(sock->cf_write_stream); CFReadStreamOpen(sock->cf_read_stream); CFWriteStreamOpen(sock->cf_write_stream); } return 0; }
/* MySimpleUpload implements the upload command. It sets up a MyStreamInfo 'object' with the read stream being a file stream of the file to upload and the write stream being an FTP 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 MySimpleUpload(CFStringRef uploadDirectory, CFURLRef fileURL, CFStringRef username, CFStringRef password) { CFWriteStreamRef writeStream; CFReadStreamRef readStream; CFStreamClientContext context = { 0, NULL, NULL, NULL, NULL }; CFURLRef uploadURL, destinationURL; CFStringRef fileName; Boolean success = true; MyStreamInfo *streamInfo; assert(uploadDirectory != NULL); assert(fileURL != NULL); assert( (username != NULL) || (password == NULL) ); /* Create a CFURL from the upload directory string */ destinationURL = CFURLCreateWithString(kCFAllocatorDefault, uploadDirectory, NULL); assert(destinationURL != NULL); /* Copy the end of the file path and use it as the file name. */ fileName = CFURLCopyLastPathComponent(fileURL); assert(fileName != NULL); /* Create the destination URL by taking the upload directory and appending the file name. */ uploadURL = CFURLCreateCopyAppendingPathComponent(kCFAllocatorDefault, destinationURL, fileName, false); assert(uploadURL != NULL); CFRelease(destinationURL); CFRelease(fileName); /* Create a CFReadStream from the local file being uploaded. */ readStream = CFReadStreamCreateWithFile(kCFAllocatorDefault, fileURL); assert(readStream != NULL); /* Create an FTP write stream for uploading operation to a FTP URL. If the URL specifies a directory, the open will be followed by a close event/state and the directory will have been created. Intermediary directory structure is not created. */ writeStream = CFWriteStreamCreateWithFTPURL(kCFAllocatorDefault, uploadURL); assert(writeStream != NULL); CFRelease(uploadURL); /* Initialize our MyStreamInfo structure, which we use to store some information about the stream. */ MyStreamInfoCreate(&streamInfo, readStream, writeStream); context.info = (void *)streamInfo; /* 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) { /* CFWriteStreamSetClient registers a callback to hear about interesting events that occur on a stream. */ success = CFWriteStreamSetClient(writeStream, kNetworkEvents, MyUploadCallBack, &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. */ CFWriteStreamScheduleWithRunLoop(writeStream, CFRunLoopGetCurrent(), kCFRunLoopCommonModes); MyCFStreamSetUsernamePassword(writeStream, username, password); MyCFStreamSetFTPProxy(writeStream, &streamInfo->proxyDict); /* 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 == false) { fprintf(stderr, "CFWriteStreamOpen failed\n"); MyStreamInfoDestroy(streamInfo); } } else { fprintf(stderr, "CFWriteStreamSetClient failed\n"); MyStreamInfoDestroy(streamInfo); } } else { fprintf(stderr, "CFReadStreamOpen failed\n"); MyStreamInfoDestroy(streamInfo); } return success; }
extern MyInfoRef StartWWAN(ConnectClientCallBack clientCB, void *refCon) { char host[] = kTestHost; int portNum = kTestPort; CFDataRef addressData; MyStreamInfoPtr myInfoPtr; CFStreamClientContext ctxt = {0, NULL, NULL, NULL, NULL}; Boolean errorOccurred = FALSE; myInfoPtr = malloc(sizeof(MyStreamInfo)); if (!myInfoPtr) { return NULL; } // init the allocated memory memset(myInfoPtr, 0, sizeof(MyStreamInfo)); myInfoPtr->clientCB = clientCB; myInfoPtr->refCon = refCon; ctxt.info = myInfoPtr; // Check for a dotted-quad address, if so skip any host lookups in_addr_t addr = inet_addr(host); if (addr != INADDR_NONE) { // Create the streams from numberical host struct sockaddr_in sin; memset(&sin, 0, sizeof(sin)); sin.sin_len= sizeof(sin); sin.sin_family = AF_INET; sin.sin_addr.s_addr = addr; sin.sin_port = htons(portNum); addressData = CFDataCreate(NULL, (UInt8 *)&sin, sizeof(sin)); CFSocketSignature sig = { AF_INET, SOCK_STREAM, IPPROTO_TCP, addressData }; // Create the streams. CFStreamCreatePairWithPeerSocketSignature(kCFAllocatorDefault, &sig, &(myInfoPtr->rStreamRef), &(myInfoPtr->wStreamRef)); CFRelease(addressData); } else { // Create the streams from ascii host name CFStringRef hostStr = CFStringCreateWithCStringNoCopy(kCFAllocatorDefault, host, kCFStringEncodingUTF8, kCFAllocatorNull); CFStreamCreatePairWithSocketToHost(kCFAllocatorDefault, hostStr, portNum, &(myInfoPtr->rStreamRef), &(myInfoPtr->wStreamRef)); //hostStr = NULL; if(hostStr) { CFRelease(hostStr); } } myInfoPtr->isConnected = FALSE; myInfoPtr->isStreamInitd = TRUE; myInfoPtr->isClientSet = FALSE; // Inform the streams to kill the socket when it is done with it. // This effects the write stream too since the pair shares the // one socket. CFWriteStreamSetProperty(myInfoPtr->wStreamRef, kCFStreamPropertyShouldCloseNativeSocket, kCFBooleanTrue); // set up the client if (!CFWriteStreamSetClient(myInfoPtr->wStreamRef, kCFStreamEventOpenCompleted | kCFStreamEventErrorOccurred | kCFStreamEventEndEncountered, MyCFWriteStreamClientCallBack, &ctxt)) { printf("CFWriteStreamSetClient failed\n"); errorOccurred = TRUE; } else myInfoPtr->isClientSet = TRUE; if (!errorOccurred) { // schedule the stream CFWriteStreamScheduleWithRunLoop(myInfoPtr->wStreamRef, CFRunLoopGetCurrent(), kCFRunLoopCommonModes); // Try to open the stream. if (!CFWriteStreamOpen(myInfoPtr->wStreamRef)) { printf("CFWriteStreamOpen failed\n"); errorOccurred = TRUE; } } if (!errorOccurred) { // everything worked so far, so run the runloop - when the callback gets called, it will stop the run loop printf("CFWriteStreamOpen returned with no error - calling CFRunLoopRun\n"); CFRunLoopRun(); if (myInfoPtr->errorOccurred) errorOccurred = TRUE; printf("after CFRunLoopRun - returning\n"); } if (errorOccurred) { myInfoPtr->isConnected = FALSE; CleanupAfterWAAN(myInfoPtr); CloseStreams(myInfoPtr); if (myInfoPtr->isStreamInitd) { if(myInfoPtr->rStreamRef) CFRelease(myInfoPtr->rStreamRef); if(myInfoPtr->wStreamRef) CFRelease(myInfoPtr->wStreamRef); myInfoPtr->isStreamInitd = FALSE; } free(myInfoPtr); return NULL; } return (MyInfoRef)myInfoPtr; }
/* 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; }