Exemple #1
0
int main(int argc, const char * argv[])
{
  CFMutableSetRef favorites;
  
  // Create a set object to keep track of our favorite titles
  favorites = CFSetCreateMutable( NULL, kNumberOfDVDs, &FavoriteSetCallBacks );
  
  // Add A Monster in Paris and A Bug's Life to the set of favorites
  CFSetAddValue( favorites, testArray[0].title );
  CFSetAddValue( favorites, testArray[3].title );
  
  // List the DVDs and determine which ones are favorites
  printf( "Fav Title\n" );
  unsigned int i;
  for ( i=0; i<kNumberOfDVDs; i++ ) {
    char fav = ' ';           // print a space if NOT a favorite
    // Determine if this DVD title is one of our favorites by asking
    //  the set if the title of this DVD is in the collection
    if ( CFSetContainsValue( favorites, testArray[i].title ) )
      fav = '*';
    printf( " %c  %s\n", fav, testArray[i].title );
  }
  
  return 0;
}
const void *Collector::rootObjectClasses()
{
  CFMutableSetRef classes = CFSetCreateMutable(NULL, 0, &kCFTypeSetCallBacks);

#if USE_CONSERVATIVE_GC
  for (int i = 0; i < ProtectedValues::_tableSize; i++) {
    ValueImp *val = ProtectedValues::_table[i].key;
    if (val) {
      const char *mangled_name = typeid(*val).name();
      int status;
      char *demangled_name = __cxxabiv1::__cxa_demangle (mangled_name, NULL, NULL, &status);
      
      CFStringRef className = CFStringCreateWithCString(NULL, demangled_name, kCFStringEncodingASCII);
      free(demangled_name);
      CFSetAddValue(classes, className);
      CFRelease(className);
    }
  }
#else
  for (int block = 0; block < heap.usedBlocks; block++) {
    CollectorBlock *curBlock = heap.blocks[block];
    for (int cell = 0; cell < CELLS_PER_BLOCK; cell++) {
      ValueImp *imp = (ValueImp *)(curBlock->cells + cell);
      
      if (((CollectorCell *)imp)->u.freeCell.zeroIfFree != 0 &&
	  ((imp->_flags & ValueImp::VI_GCALLOWED) == 0 || imp->refcount != 0)) {
	const char *mangled_name = typeid(*imp).name();
	int status;
	char *demangled_name = __cxxabiv1::__cxa_demangle (mangled_name, NULL, NULL, &status);
	
	CFStringRef className = CFStringCreateWithCString(NULL, demangled_name, kCFStringEncodingASCII);
	free(demangled_name);
	CFSetAddValue(classes, className);
	CFRelease(className);
      }
    }
  }
  
  for (int cell = 0; cell < heap.usedOversizeCells; cell++) {
    ValueImp *imp = (ValueImp *)heap.oversizeCells[cell];
    
    if ((imp->_flags & ValueImp::VI_GCALLOWED) == 0 || imp->refcount != 0) {
      const char *mangled_name = typeid(*imp).name();
      int status;
      char *demangled_name = __cxxabiv1::__cxa_demangle (mangled_name, NULL, NULL, &status);
      
      CFStringRef className = CFStringCreateWithCString(NULL, demangled_name, kCFStringEncodingASCII);
      free(demangled_name);
      CFSetAddValue(classes, className);
      CFRelease(className);
    }
  }
#endif
  
  return classes;
}
Exemple #3
0
static void
rb_set_intersect_callback(const void *value, void *context)
{
    CFMutableSetRef *sets = (CFMutableSetRef *)context;
    if (CFSetContainsValue(sets[0], RB2OC(value)))
	CFSetAddValue(sets[1], RB2OC(value));
}
static void SOSAccountRemoveInvalidApplications(SOSAccountRef account, SOSCircleRef circle)
{
    CFMutableSetRef peersToRemove = CFSetCreateMutableForSOSPeerInfosByID(kCFAllocatorDefault);
    SOSCircleForEachApplicant(circle, ^(SOSPeerInfoRef peer) {
        if (!SOSPeerInfoApplicationVerify(peer, account->user_public, NULL))
            CFSetAddValue(peersToRemove, peer);
    });
Exemple #5
0
static void
rb_set_union_callback(const void *value, void *context)
{
    CFMutableSetRef set = context;
    if (!CFSetContainsValue(set, RB2OC(value)))
	CFSetAddValue(set, RB2OC(value));
}
Exemple #6
0
static int dc_readdir(const char *path, void *buf, fuse_fill_dir_t filler,
                      off_t offset, struct fuse_file_info *fi) {
    int path_len = strlen(path);
    bool ends_with_slash = path[path_len-1] == '/';

    lseek(fd, ch.imagesOffset, SEEK_SET);

    CFMutableSetRef heard_of = CFSetCreateMutable(NULL, 0, &kCFTypeSetCallBacks);

    for(int i = 0; i < ch.imagesCount; i++) {
        struct dyld_cache_image_info ii;
        assert(pread(fd, &ii, sizeof(ii), ch.imagesOffset + i*sizeof(ii)) == sizeof(ii));
        char stuff[256];
        pread(fd, &stuff, sizeof(stuff), ii.pathFileOffset);

        if(!memcmp(stuff, path, path_len) && (ends_with_slash || stuff[path_len] == '/')) {
            char *ent = strdup(stuff + path_len + (ends_with_slash?0:1));
            char *slash = strchr(ent, '/');
            if(slash) *slash = 0;
            CFStringRef ents = CFStringCreateWithCString(NULL, ent, kCFStringEncodingASCII);
            if(!CFSetContainsValue(heard_of, ents)) {
                CFSetAddValue(heard_of, ents);
                filler(buf, ent, NULL, 0);
            }
            CFRelease(ents);
        }
    }

    CFRelease(heard_of);

    return 0;
}
__private_extern__ void
__SCBondInterfaceListCollectMembers(CFArrayRef interfaces, CFMutableSetRef set)
{
	CFIndex	i;
	CFIndex	n;

	n = CFArrayGetCount(interfaces);
	for (i = 0; i < n; i++) {
		SCBondInterfaceRef	bondInterface;
		CFArrayRef		members;

		bondInterface = CFArrayGetValueAtIndex(interfaces, i);
		members = SCBondInterfaceGetMemberInterfaces(bondInterface);
		if (members != NULL) {
			CFIndex	j;
			CFIndex	n_members;

			// exclude the member interfaces of this bond
			n_members = CFArrayGetCount(members);
			for (j = 0; j < n_members; j++) {
				SCNetworkInterfaceRef	member;

				member = CFArrayGetValueAtIndex(members, j);
				CFSetAddValue(set, member);
			}
		}

	}
	return;
}
static void formSchedule(CFReadStreamRef stream, CFRunLoopRef runLoop, CFStringRef runLoopMode, void* context)
{
    FormStreamFields* form = static_cast<FormStreamFields*>(context);

    if (form->currentStream)
        CFReadStreamScheduleWithRunLoop(form->currentStream, runLoop, runLoopMode);
    SchedulePair pair = { runLoop, runLoopMode };
    CFSetAddValue(form->scheduledRunLoopPairs, &pair);
}
bool viewcmd(char *itemName, CFErrorRef *err) {
    char *cmd, *viewname;
    SOSViewActionCode ac = kSOSCCViewQuery;
    CFStringRef viewspec;
    
    viewname = strchr(itemName, ':');
    if(viewname == NULL) return false;
    *viewname = 0;
    viewname++;
    cmd = itemName;
    
    if(strcmp(cmd, "enable") == 0) {
        ac = kSOSCCViewEnable;
    } else if(strcmp(cmd, "disable") == 0) {
        ac = kSOSCCViewDisable;
    } else if(strcmp(cmd, "query") == 0) {
        ac = kSOSCCViewQuery;
    } else {
        return false;
    }
    
    if(strchr(viewname, ',') == NULL) { // original single value version
        viewspec = convertStringToView(viewname);
        if(!viewspec) return false;
        
        SOSViewResultCode rc = SOSCCView(viewspec, ac, err);
        CFStringRef resultString = convertViewReturnCodeToString(rc);
        
        printmsg(CFSTR("View Result: %@ : %@\n"), resultString, viewspec);
        return true;
    }
    
    if(ac == kSOSCCViewQuery) return false;
    
    // new multi-view version
    char *viewlist = strdup(viewname);
    char *token;
    char *tofree = viewlist;
    CFMutableSetRef viewSet = CFSetCreateMutable(NULL, 0, &kCFCopyStringSetCallBacks);
    
    while ((token = strsep(&viewlist, ",")) != NULL) {
        CFStringRef resultString = convertStringToView(token);
        CFSetAddValue(viewSet, resultString);
    }
    
    printmsg(CFSTR("viewSet provided is %@\n"), viewSet);
    
    free(tofree);
    
    bool retcode;
    if(ac == kSOSCCViewEnable) retcode = SOSCCViewSet(viewSet, NULL);
    else retcode = SOSCCViewSet(NULL, viewSet);
    
    fprintf(outFile, "SOSCCViewSet returned %s\n", (retcode)? "true": "false");
    
    return true;
}
Exemple #10
0
static VALUE
rb_set_add(VALUE set, SEL sel, VALUE obj)
{
    rb_set_modify_check(set);

    CFSetAddValue((CFMutableSetRef)set, (const void *)RB2OC(obj));

    return set;
}
Exemple #11
0
static VALUE
merge_i(VALUE val, VALUE *args)
{
    VALUE set = (VALUE)args;
    if (!CFSetContainsValue((CFMutableSetRef)set, (const void *)RB2OC(val))) {
	CFSetAddValue((CFMutableSetRef)set, (const void *)RB2OC(val));
    }

    return Qnil;
}
Exemple #12
0
NPIdentifier NPN_GetStringIdentifier(const NPUTF8 *name) {
    //notice("psst: GetStringIdentifier '%s'", name);
    CFDataRef data = CFDataCreate(NULL, (unsigned char *) name, strlen(name));
    CFDataRef ret = CFSetGetValue(identifier_set, data);
    if(!ret) {
        CFSetAddValue(identifier_set, data);
        ret = data;
    }
    CFRelease(data);
    return (NPIdentifier) ret;
}
Exemple #13
0
NPIdentifier NPN_GetIntIdentifier(int32_t intid) {
    notice("Get*INT*Identifier: %d", intid);
    CFNumberRef number = CFNumberCreate(NULL, kCFNumberIntType, &intid);
    CFNumberRef ret = CFSetGetValue(identifier_set, number);
    if(!ret) {
        CFSetAddValue(identifier_set, number);
        ret = number;
    }
    CFRelease(number);
    return (NPIdentifier) ret;
}
Exemple #14
0
static VALUE
rb_set_add2(VALUE set, SEL sel, VALUE obj)
{
    rb_set_modify_check(set);

    if (CFSetContainsValue((CFMutableSetRef)set, (const void *)RB2OC(obj))) {
	return Qnil;
    }
    CFSetAddValue((CFMutableSetRef)set, (const void *)RB2OC(obj));
    return set;
}
Exemple #15
0
static VALUE
rb_set_s_create(int argc, VALUE *argv, VALUE klass)
{
    int i;

    VALUE set = set_alloc(klass);

    for (i = 0; i < argc; i++)
	CFSetAddValue((CFMutableSetRef)set, RB2OC(argv[i]));

    return set;
}
static void __security_debug_init(void) {
	const char *cur_scope = gDebugScope = getenv("DEBUGSCOPE");
	if (cur_scope) {
		if (!strcmp(cur_scope, "all")) {
			scopeSet = NULL;
			negate = true;
		} else if (!strcmp(cur_scope, "none")) {
			scopeSet = NULL;
			negate = false;
		} else {
			scopeSet = CFSetCreateMutable(kCFAllocatorDefault, 0,
				&kCFTypeSetCallBacks);
			if (cur_scope[0] == '-') {
				negate = true;
				cur_scope++;
			} else {
				negate = false;
			}

			const char *sep;
			while ((sep = strchr(cur_scope, ','))) {
				CFStringRef scopeName = copyScopeName(cur_scope,
					sep - cur_scope);
				CFSetAddValue(scopeSet, scopeName);
				CFRelease(scopeName);
				cur_scope = sep + 1;
			}

			CFStringRef scopeName = copyScopeName(cur_scope,
				strlen(cur_scope));
			CFSetAddValue(scopeSet, scopeName);
			CFRelease(scopeName);
		}
	} else {
		scopeSet = NULL;
		negate = false;
	}
}
static void SecMemoryCertificateSourceApplierFunction(const void *value,
	void *context) {
	SecMemoryCertificateSourceRef msource =
		(SecMemoryCertificateSourceRef)context;
	SecCertificateRef certificate = (SecCertificateRef)value;

	/* CFSet's API has no way to combine these 2 operations into 1 sadly. */
	if (CFSetContainsValue(msource->certificates, certificate))
		return;
	CFSetAddValue(msource->certificates, certificate);

	CFDataRef key = SecCertificateGetNormalizedSubjectContent(certificate);
	dictAddValueToArrayForKey(msource->subjects, key, value);
}
void _cfmp_record_intent_to_invalidate(_CFMPLifetimeClient const client, mach_port_t const port) {
    if (port == MACH_PORT_NULL) { return; }

    _cfmp_deallocation_record *pr = calloc(1, sizeof(_cfmp_deallocation_record));
    if (pr == NULL) {
        HALT_MSG("Unable to allocate mach_port deallocation record");
    }
    pr->port = port;
    pr->client = client;
    
    CFMutableSetRef const records = _cfmp_records();
    os_unfair_lock_lock(&_cfmp_records_lock);
    CFSetAddValue(records, pr);
    os_unfair_lock_unlock(&_cfmp_records_lock);
}
/* Given the builder, a partial chain partial and the parents array, construct
   a SecCertificatePath for each parent.  After discarding previously
   considered paths and paths with cycles, sort out which array each path
   should go in, if any. */
static void SecPathBuilderProccessParents(SecPathBuilderRef builder,
    SecCertificatePathRef partial, CFArrayRef parents) {
    CFIndex rootIX = SecCertificatePathGetCount(partial) - 1;
    CFIndex num_parents = parents ? CFArrayGetCount(parents) : 0;
    CFIndex parentIX;
    bool is_anchor = SecCertificatePathGetNextSourceIndex(partial) <=
        CFArrayGetCount(builder->anchorSources);
    secdebug("trust", "found %d candidate %s", num_parents,
             (is_anchor ? "anchors" : "parents"));
    for (parentIX = 0; parentIX < num_parents; ++parentIX) {
        SecCertificateRef parent = (SecCertificateRef)
            CFArrayGetValueAtIndex(parents, parentIX);
        CFIndex ixOfParent = SecCertificatePathGetIndexOfCertificate(partial,
            parent);
        if (ixOfParent != kCFNotFound) {
            /* partial already contains parent.  Let's not add the same
               certificate again. */
            if (ixOfParent == rootIX) {
                /* parent is equal to the root of the partial, so partial
                   looks to be self issued. */
                SecCertificatePathSetSelfIssued(partial);
            }
            continue;
        }

        /* FIXME Add more sanity checks to see that parent really can be
           a parent of partial_root.  subjectKeyID == authorityKeyID,
           signature algorithm matches public key algorithm, etc. */
        SecCertificatePathRef path = SecCertificatePathCreate(partial, parent);
        if (!path)
            continue;
        if (!CFSetContainsValue(builder->allPaths, path)) {
            CFSetAddValue(builder->allPaths, path);
            if (is_anchor)
                SecCertificatePathSetIsAnchored(path);
            if (SecPathBuilderIsPartial(builder, path)) {
                /* Insert path right at the current position since it's a new
                   candiate partial. */
                CFArrayInsertValueAtIndex(builder->partialPaths,
                    ++builder->partialIX, path);
                secdebug("trust", "Adding partial for parent %d/%d %@",
                    parentIX + 1, num_parents, path);
            }
            secdebug("trust", "found new path %@", path);
        }
        CFRelease(path);
    }
}
Exemple #20
0
CFSetRef CFSetCreate(CFAllocatorRef allocator, const void **values, CFIndex numValues, const CFSetCallBacks *callBacks) {
    CFSetRef result;
    UInt32 flags;
    CFIndex idx;
    CFAssert2(0 <= numValues, __kCFLogAssertion, "%s(): numValues (%d) cannot be less than zero", __PRETTY_FUNCTION__, numValues);
    result = __CFSetInit(allocator, __kCFSetImmutable, numValues, callBacks);
    flags = __CFBitfieldGetValue(((const CFRuntimeBase *)result)->_info, 1, 0);
    if (flags == __kCFSetImmutable) {
        __CFBitfieldSetValue(((CFRuntimeBase *)result)->_info, 1, 0, __kCFSetFixedMutable);
    }
    for (idx = 0; idx < numValues; idx++) {
	CFSetAddValue((CFMutableSetRef)result, values[idx]);
    }
    __CFBitfieldSetValue(((CFRuntimeBase *)result)->_info, 1, 0, flags);
    return result;
}
CFErrorRef pick_sign_alg(CFStringRef digest, int digest_length, const CSSM_KEY *ckey, struct digest_mapping **picked) {
	static dispatch_once_t once = 0;
	static CFMutableSetRef algos = NULL;

	dispatch_once(&once, ^{
		struct digest_mapping digest_mappings_stack[] = {
			{CSSM_ALGID_RSA, kSecDigestSHA1, 0,   CSSM_ALGID_SHA1WithRSA, CSSM_ALGID_SHA1},
			{CSSM_ALGID_RSA, kSecDigestSHA1, 160,   CSSM_ALGID_SHA1WithRSA, CSSM_ALGID_SHA1},
			
			{CSSM_ALGID_RSA, kSecDigestMD2, 0,   CSSM_ALGID_MD2WithRSA, CSSM_ALGID_MD2},
			{CSSM_ALGID_RSA, kSecDigestMD2, 128,   CSSM_ALGID_MD2WithRSA, CSSM_ALGID_MD2},
			
			{CSSM_ALGID_RSA, kSecDigestMD5, 0,   CSSM_ALGID_MD5WithRSA, CSSM_ALGID_MD5},
			{CSSM_ALGID_RSA, kSecDigestMD5, 128,   CSSM_ALGID_MD5WithRSA, CSSM_ALGID_MD5},
			
			{CSSM_ALGID_RSA, kSecDigestSHA2, 0,   CSSM_ALGID_SHA512WithRSA, CSSM_ALGID_SHA512},
			{CSSM_ALGID_RSA, kSecDigestSHA2, 512,   CSSM_ALGID_SHA512WithRSA, CSSM_ALGID_SHA512},
			{CSSM_ALGID_RSA, kSecDigestSHA2, 384,   CSSM_ALGID_SHA384WithRSA, CSSM_ALGID_SHA384},
			{CSSM_ALGID_RSA, kSecDigestSHA2, 256,   CSSM_ALGID_SHA256WithRSA, CSSM_ALGID_SHA256},
			{CSSM_ALGID_RSA, kSecDigestSHA2, 224,   CSSM_ALGID_SHA224WithRSA, CSSM_ALGID_SHA224},
			
			
			{CSSM_ALGID_ECDSA, kSecDigestSHA1, 0,   CSSM_ALGID_SHA1WithECDSA, CSSM_ALGID_SHA1},
			{CSSM_ALGID_ECDSA, kSecDigestSHA1, 160,   CSSM_ALGID_SHA1WithECDSA, CSSM_ALGID_SHA1},
			
			{CSSM_ALGID_ECDSA, kSecDigestSHA2, 0,   CSSM_ALGID_SHA512WithECDSA, CSSM_ALGID_SHA512},
			{CSSM_ALGID_ECDSA, kSecDigestSHA2, 512,   CSSM_ALGID_SHA512WithECDSA, CSSM_ALGID_SHA512},
			{CSSM_ALGID_ECDSA, kSecDigestSHA2, 384,   CSSM_ALGID_SHA384WithECDSA, CSSM_ALGID_SHA384},
			{CSSM_ALGID_ECDSA, kSecDigestSHA2, 256,   CSSM_ALGID_SHA256WithECDSA, CSSM_ALGID_SHA256},
			{CSSM_ALGID_ECDSA, kSecDigestSHA2, 224,   CSSM_ALGID_SHA224WithECDSA, CSSM_ALGID_SHA224},
			
			{CSSM_ALGID_DSA, kSecDigestSHA1, 0,   CSSM_ALGID_SHA1WithDSA, CSSM_ALGID_SHA1},
			{CSSM_ALGID_DSA, kSecDigestSHA1, 160,   CSSM_ALGID_SHA1WithDSA, CSSM_ALGID_SHA1},
		};
		
		CFIndex mapping_count = sizeof(digest_mappings_stack)/sizeof(digest_mappings_stack[0]);
		void *digest_mappings = malloc(sizeof(digest_mappings_stack));
		memcpy(digest_mappings, digest_mappings_stack, sizeof(digest_mappings_stack));

		CFSetCallBacks dmcb = { .version = 0, .retain = NULL, .release = NULL, .copyDescription = NULL, .equal = (CFSetEqualCallBack)digest_mapping_equal, .hash = (CFSetHashCallBack)digest_mapping_hash };
		
		algos = CFSetCreateMutable(NULL, mapping_count, &dmcb);
		int i;
		for(i = 0; i < mapping_count; i++) {
			CFSetAddValue(algos, i + (struct digest_mapping *)digest_mappings);
		}
	});
Exemple #22
0
CFMutableSetRef CFSetCreateMutableCopy(CFAllocatorRef allocator, CFIndex capacity, CFSetRef set) {
    CFMutableSetRef result;
    const CFSetCallBacks *cb;
    CFIndex idx, numValues = CFSetGetCount(set);
    const void **list, *buffer[256];
    CFAssert3(0 == capacity || numValues <= capacity, __kCFLogAssertion, "%s(): for fixed-mutable sets, capacity (%d) must be greater than or equal to initial number of values (%d)", __PRETTY_FUNCTION__, capacity, numValues);
    list = (numValues <= 256) ? buffer : CFAllocatorAllocate(allocator, numValues * sizeof(void *), 0);
    if (list != buffer && __CFOASafe) __CFSetLastAllocationEventName(list, "CFSet (temp)");
    CFSetGetValues(set, list);
    cb = CF_IS_OBJC(__kCFSetTypeID, set) ? &kCFTypeSetCallBacks : __CFSetGetCallBacks(set);
    result = CFSetCreateMutable(allocator, capacity, cb);
    if (0 == capacity) _CFSetSetCapacity(result, numValues);
    for (idx = 0; idx < numValues; idx++) {
	CFSetAddValue(result, list[idx]);
    }
    if (list != buffer) CFAllocatorDeallocate(allocator, list);
    return result;
}
Exemple #23
0
/*
 [4]  NameChar ::= Letter | Digit | '.' | '-' | '_' | ':' | CombiningChar | Extender
 [5]  Name ::= (Letter | '_' | ':') (NameChar)*
 [7]  Nmtoken ::= (NameChar)+
 [84] Letter ::= BaseChar | Ideographic

 We don't do this quite right; we rely on the Unicode charsets to do this analysis.  While
 the productions in the XML spec are based on the Unicode character sets, the definitions
 differ slightly to avoid those areas where the Unicode standard is still being resolved.
 At any rate, I'd lay money that using the Unicode charsets, we will be more correct than
 the vast majority of parsers out there.

 Letter == kCFUniCharLetterCharacterSet
 Digit == kCFUniCharDecimalDigitCharacterSet
 CombiningChar == kCFUniCharNonBaseCharacterSet
 Extender - complex, and not represented by a uniform character set.
 */
CF_PRIVATE Boolean _inputStreamScanXMLName(_CFXMLInputStream *stream, Boolean isNMToken, CFStringRef *str) {
    UniChar ch;
    Boolean success = true;
    stream->parserMark = dropMark(stream);
    if (!isNMToken) {
        // Only difference between an NMToken and a Name is Names have a stricter condition on the first character
        if (!getCharacter(stream, &ch, false)) {
            success = false;
        } else if (!CFUniCharIsMemberOf(ch, kCFUniCharLetterCharacterSet) && ch != '_' && ch != ':') {
            success = false;
        } else {
            getCharacter(stream, &ch, true);
        }
    }
    if (success) {
        while (getCharacter(stream, &ch, true)) {
            if (!CFUniCharIsMemberOf(ch, kCFUniCharLetterCharacterSet) && !CFUniCharIsMemberOf(ch, kCFUniCharDecimalDigitCharacterSet)  && ch != '.' && ch != '-' && ch != '_' && ch != ':' && !CFUniCharIsMemberOf(ch, kCFUniCharNonBaseCharacterSet)) {
                _inputStreamReturnCharacter(stream, ch);
                break;
            }
        }
        if (NULL == stream->currentChar || stream->currentChar == stream->parserMark) {
            success = false; // Must have processed at least one character
        }
    }
    if (success) {
        if (str) {
            if (!stream->nameSet) {
                stream->nameSet = CFSetCreateMutable(stream->allocator, 0, &kCFTypeSetCallBacks);
                stream->tempString = CFStringCreateMutableWithExternalCharactersNoCopy(stream->allocator, NULL, 0, 0, kCFAllocatorNull);
            }
            CFStringSetExternalCharactersNoCopy(stream->tempString, stream->parserMark, stream->currentChar-stream->parserMark, stream->currentChar-stream->parserMark);
            if (!CFSetGetValueIfPresent(stream->nameSet, stream->tempString, (const void **)str)) {
                *str = (CFStringRef)CFStringCreateCopy(stream->allocator, stream->tempString);
                CFSetAddValue(stream->nameSet, *str);
                CFRelease(*str);
            }
        }
    } else {
        restoreToMark(stream, stream->parserMark);
    }
    stream->parserMark = NULL;
    return success;
}
Exemple #24
0
__private_extern__
int
__SCDynamicStoreNotifySignal(SCDynamicStoreRef store, pid_t pid, int sig)
{
	SCDynamicStorePrivateRef	storePrivate = (SCDynamicStorePrivateRef)store;
	CFStringRef			sessionKey;
	CFDictionaryRef			info;

	if (storePrivate->notifyStatus != NotifierNotRegistered) {
		/* sorry, you can only have one notification registered at once */
		return kSCStatusNotifierActive;
	}

	if (pid == getpid()) {
		/* sorry, you can't request that configd be signalled */
		return kSCStatusInvalidArgument;
	}

	if ((sig <= 0) || (sig > NSIG)) {
		/* sorry, you must specify a valid signal */
		return kSCStatusInvalidArgument;
	}

	/* push out a notification if any changes are pending */
	sessionKey = CFStringCreateWithFormat(NULL, NULL, CFSTR("%d"), storePrivate->server);
	info = CFDictionaryGetValue(sessionData, sessionKey);
	CFRelease(sessionKey);
	if (info && CFDictionaryContainsKey(info, kSCDChangedKeys)) {
		CFNumberRef	sessionNum;

		if (needsNotification == NULL)
			needsNotification = CFSetCreateMutable(NULL,
							       0,
							       &kCFTypeSetCallBacks);

		sessionNum = CFNumberCreate(NULL, kCFNumberIntType, &storePrivate->server);
		CFSetAddValue(needsNotification, sessionNum);
		CFRelease(sessionNum);
	}

	return kSCStatusOK;
}
Exemple #25
0
QString QFontDatabase::resolveFontFamilyAlias(const QString &family)
{
    QCFString expectedFamily = QCFString(family);

    QCFType<CFMutableDictionaryRef> attributes = CFDictionaryCreateMutable(NULL, 0,
        &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
    CFDictionaryAddValue(attributes, kCTFontFamilyNameAttribute, expectedFamily);
    QCFType<CTFontDescriptorRef> descriptor = CTFontDescriptorCreateWithAttributes(attributes);

    QCFType<CFMutableSetRef> mandatoryAttributes = CFSetCreateMutable(NULL, 0, &kCFTypeSetCallBacks);
    CFSetAddValue(mandatoryAttributes, kCTFontFamilyNameAttribute);

    QCFType<CTFontRef> font = CTFontCreateWithFontDescriptor(descriptor, 0.0, NULL);
    QCFType<CTFontDescriptorRef> matched = CTFontDescriptorCreateMatchingFontDescriptor(descriptor, mandatoryAttributes);
    if (!matched)
        return family;

    QCFString familyName = (CFStringRef) CTFontDescriptorCopyLocalizedAttribute(matched, kCTFontFamilyNameAttribute, NULL);
    return familyName;
}
Exemple #26
0
// FIXME: Make these thread-safe / re-entrant.
extern void GPDuplexClient_AddObserver(GPDuplexClientRef client, void* observer, GPDuplexClientCallback callback, SInt32 type) {
	if (client != NULL) {
		CFNumberRef typeNumber = CFNumberCreate(NULL, kCFNumberSInt32Type, &type);
		CFMutableSetRef observerSet = (CFMutableSetRef)CFDictionaryGetValue(client->observers, typeNumber);
		Boolean needRelease = false;
		if (observerSet == NULL) {
			needRelease = true;
			observerSet = CFSetCreateMutable(NULL, 0, &kCFTypeSetCallBacks);
		}
		
		CFDataRef observerData = GPDuplexClientCreateObserver(observer, callback);
		CFSetAddValue(observerSet, observerData);
		CFRelease(observerData);
		
		CFDictionarySetValue(client->observers, typeNumber, observerSet);
		if (needRelease)
			CFRelease(observerSet);
		
		CFRelease(typeNumber);
	}
}
Exemple #27
0
CFArrayRef CFLocaleCopyAvailableLocaleIdentifiers(void) {
    int32_t locale, localeCount = uloc_countAvailable();
    CFMutableSetRef working = CFSetCreateMutable(kCFAllocatorSystemDefault, 0, &kCFTypeSetCallBacks);
    for (locale = 0; locale < localeCount; ++locale) {
        const char *localeID = uloc_getAvailable(locale);
        CFStringRef string1 = CFStringCreateWithCString(kCFAllocatorSystemDefault, localeID, kCFStringEncodingASCII);
	CFStringRef string2 = CFLocaleCreateCanonicalLocaleIdentifierFromString(kCFAllocatorSystemDefault, string1);
	CFSetAddValue(working, string1);
	// do not include canonicalized version as IntlFormats cannot cope with that in its popup
        CFRelease(string1);
        CFRelease(string2);
    }
    CFIndex cnt = CFSetGetCount(working);
#if DEPLOYMENT_TARGET_MACOSX || DEPLOYMENT_TARGET_LINUX || (DEPLOYMENT_TARGET_WINDOWS && __GNUC__)
    STACK_BUFFER_DECL(const void *, buffer, cnt);
#else
    const void* buffer[BUFFER_SIZE];
#endif
    CFSetGetValues(working, buffer);
    CFArrayRef result = CFArrayCreate(kCFAllocatorSystemDefault, buffer, cnt, &kCFTypeArrayCallBacks);
    CFRelease(working);
    return result;
}
static void SecPathBuilderInit(SecPathBuilderRef builder,
	CFArrayRef certificates, CFArrayRef anchors, bool anchorsOnly,
    CFArrayRef policies, CFAbsoluteTime verifyTime,
    SecPathBuilderCompleted completed, const void *context) {
    secdebug("alloc", "%p", builder);
	CFAllocatorRef allocator = kCFAllocatorDefault;

	builder->nextParentSource = 1;
	builder->considerPartials = false;
    builder->canAccessNetwork = true;

    builder->anchorSources = CFArrayCreateMutable(allocator, 0, NULL);
    builder->parentSources = CFArrayCreateMutable(allocator, 0, NULL);
    builder->allPaths = CFSetCreateMutable(allocator, 0,
		&kCFTypeSetCallBacks);

    builder->partialPaths = CFArrayCreateMutable(allocator, 0, NULL);
    builder->rejectedPaths = CFArrayCreateMutable(allocator, 0, NULL);
    builder->candidatePaths = CFArrayCreateMutable(allocator, 0, NULL);
    builder->partialIX = 0;

    /* Init the policy verification context. */
    SecPVCInit(&builder->path, builder, policies, verifyTime);
	builder->bestPath = NULL;
	builder->bestPathIsEV = false;
	builder->rejectScore = 0;

	/* Let's create all the certificate sources we might want to use. */
	builder->certificateSource =
		SecMemoryCertificateSourceCreate(certificates);
	if (anchors)
		builder->anchorSource = SecMemoryCertificateSourceCreate(anchors);
	else
		builder->anchorSource = NULL;

	/* We always search certificateSource for parents since it includes the
	   leaf itself and it might be self signed. */
	CFArrayAppendValue(builder->parentSources, builder->certificateSource);
	if (builder->anchorSource) {
		CFArrayAppendValue(builder->anchorSources, builder->anchorSource);
	}
	CFArrayAppendValue(builder->parentSources, &kSecItemCertificateSource);
    if (anchorsOnly) {
        /* Add the system and user anchor certificate db to the search list
           if we don't explicitly trust them. */
        CFArrayAppendValue(builder->parentSources, &kSecSystemAnchorSource);
        CFArrayAppendValue(builder->parentSources, &kSecUserAnchorSource);
    } else {
        /* Only add the system and user anchor certificate db to the
           anchorSources if we are supposed to trust them. */
        CFArrayAppendValue(builder->anchorSources, &kSecSystemAnchorSource);
        CFArrayAppendValue(builder->anchorSources, &kSecUserAnchorSource);
    }
    CFArrayAppendValue(builder->parentSources, &kSecCAIssuerSource);

	/* Now let's get the leaf cert and turn it into a path. */
	SecCertificateRef leaf =
		(SecCertificateRef)CFArrayGetValueAtIndex(certificates, 0);
	SecCertificatePathRef path = SecCertificatePathCreate(NULL, leaf);
	CFSetAddValue(builder->allPaths, path);
	CFArrayAppendValue(builder->partialPaths, path);
    if (SecPathBuilderIsAnchor(builder, leaf)) {
        SecCertificatePathSetIsAnchored(path);
        CFArrayAppendValue(builder->candidatePaths, path);
    }
    SecPathBuilderLeafCertificateChecks(builder, path);
	CFRelease(path);

    builder->activations = 0;
    builder->state = SecPathBuilderGetNext;
    builder->completed = completed;
    builder->context = context;
}
Exemple #29
0
static Boolean
__SCNetworkSetEstablishDefaultConfigurationForInterfaces(SCNetworkSetRef set, CFArrayRef interfaces, Boolean excludeHidden)
{
	CFSetRef		excluded	= NULL;
	CFIndex			i;
	CFIndex			n		= 0;
	Boolean			ok		= TRUE;
	CFArrayRef		services;
	SCNetworkSetPrivateRef	setPrivate	= (SCNetworkSetPrivateRef)set;
	Boolean			updated		= FALSE;
	Boolean			updatedIFs	= FALSE;

#if	TARGET_OS_IPHONE
	CFArrayRef		orphans		= NULL;
	CFArrayRef		sets;

	sets = SCNetworkSetCopyAll(setPrivate->prefs);
	if (sets != NULL) {
		if (CFArrayGetCount(sets) == 1) {
			services = SCNetworkSetCopyServices(set);
			if (services != NULL) {
				n = CFArrayGetCount(services);
				CFRelease(services);
			}

			if ((n == 0) && CFEqual(set, CFArrayGetValueAtIndex(sets, 0))) {
				// after a "Reset Network Settings" we need to find (and
				// add back) any VPN services that were orphaned.
				orphans = SCNetworkServiceCopyAll(setPrivate->prefs);
			}
		}

		CFRelease(sets);
	}
#endif	// TARGET_OS_IPHONE

	// copy network services
	services = copyServices(set);

	// copy network interfaces to be excluded
	excluded = copyExcludedInterfaces(setPrivate->prefs);

#if	!TARGET_OS_IPHONE
	// look for interfaces that should auto-magically be added
	// to an Ethernet bridge
	n = (interfaces != NULL) ? CFArrayGetCount(interfaces) : 0;
	for (i = 0; i < n; i++) {
		SCBridgeInterfaceRef	bridge		= NULL;
		SCNetworkInterfaceRef	interface;

		interface = CFArrayGetValueAtIndex(interfaces, i);

		if (excludeHidden && skipInterface(interface)) {
			// if not auto-configure
			continue;
		}

		if ((excluded != NULL)
		    && CFSetContainsValue(excluded, interface)) {
			// if this interface is a member of a Bond or Bridge
			continue;
		}

		if (__SCNetworkServiceExistsForInterface(services, interface)) {
			// if this is not a new interface
			continue;
		}

		if (_SCNetworkInterfaceIsBuiltin(interface) &&
		    _SCNetworkInterfaceIsThunderbolt(interface) &&
		    !isA_SCBridgeInterface(interface)) {
			// add built-in Thunderbolt interfaces to bridge
			bridge = copyAutoBridgeInterface(setPrivate->prefs, CFSTR("thunderbolt-bridge"));
		}

		if (bridge != NULL) {
			CFIndex			bridgeIndex;
			CFArrayRef		members;
			CFMutableArrayRef	newMembers;
			CFMutableSetRef		newExcluded;
			CFMutableArrayRef	newInterfaces;
			CFArrayRef		newServices;

			// track the bridge interface (if it's in our list)
			bridgeIndex = CFArrayGetFirstIndexOfValue(interfaces,
								  CFRangeMake(0, CFArrayGetCount(interfaces)),
								  bridge);

			// add new member interface
			members = SCBridgeInterfaceGetMemberInterfaces(bridge);
			if ((members != NULL) && (CFArrayGetCount(members) > 0)) {
				newMembers = CFArrayCreateMutableCopy(NULL, 0, members);
				updated = TRUE;		// if we're updating an existing bridge
			} else {
				newMembers = CFArrayCreateMutable(NULL, 0, &kCFTypeArrayCallBacks);
			}
			CFArrayAppendValue(newMembers, interface);
			ok = SCBridgeInterfaceSetMemberInterfaces(bridge, newMembers);
			CFRelease(newMembers);
			if (!ok) {
				SC_log(LOG_INFO, "could not update bridge with \"%@\": %s",
				       SCNetworkInterfaceGetLocalizedDisplayName(interface),
				       SCErrorString(SCError()));
				CFRelease(bridge);
				continue;
			}

			// exclude the new member interface
			newExcluded = CFSetCreateMutableCopy(NULL, 0, excluded);
			CFRelease(excluded);
			CFSetAddValue(newExcluded, interface);
			excluded = newExcluded;

			// update the list of interfaces to include the [new or updated] bridge
			newInterfaces = CFArrayCreateMutableCopy(NULL, 0, interfaces);
			if (bridgeIndex != kCFNotFound) {
				CFArraySetValueAtIndex(newInterfaces, bridgeIndex, bridge);
			} else {
				CFArrayAppendValue(newInterfaces, bridge);
			}
			if (updatedIFs) {
				CFRelease(interfaces);
			}
			interfaces = newInterfaces;
			updatedIFs = TRUE;

			// refresh [existing] services
			newServices = updateServices(services, bridge);
			if (newServices != NULL) {
				CFRelease(services);
				services = newServices;
			}

			CFRelease(bridge);
		}
	}
#endif	// !TARGET_OS_IPHONE

	n = (interfaces != NULL) ? CFArrayGetCount(interfaces) : 0;
	for (i = 0; i < n; i++) {
		SCNetworkInterfaceRef	interface;
		CFMutableArrayRef	interface_list;

		interface = CFArrayGetValueAtIndex(interfaces, i);

		if (excludeHidden && skipInterface(interface)) {
			// if not auto-configure
			continue;
		}

		if ((excluded != NULL)
		    && CFSetContainsValue(excluded, interface)) {
			// if this interface is a member of a Bond or Bridge
			continue;
		}

		if (__SCNetworkServiceExistsForInterface(services, interface)) {
			// if this is not a new interface
			continue;
		}

		interface_list = CFArrayCreateMutable(NULL, 0, &kCFTypeArrayCallBacks);
		CFArrayAppendValue(interface_list, interface);

		while (ok && (CFArrayGetCount(interface_list) > 0)) {
			CFArrayRef		protocol_types;

			interface = CFArrayGetValueAtIndex(interface_list, 0);

			protocol_types = SCNetworkInterfaceGetSupportedProtocolTypes(interface);
			if ((protocol_types != NULL) && (CFArrayGetCount(protocol_types) > 0)) {
				SCNetworkServiceRef	service;

				service = SCNetworkServiceCreate(setPrivate->prefs, interface);
				if (service == NULL) {
					SC_log(LOG_INFO, "could not create service for \"%@\": %s",
					       SCNetworkInterfaceGetLocalizedDisplayName(interface),
					       SCErrorString(SCError()));
					ok = FALSE;
					goto nextInterface;
				}

				ok = SCNetworkServiceEstablishDefaultConfiguration(service);
				if (!ok) {
					SC_log(LOG_INFO, "could not estabish default configuration for \"%@\": %s",
					       SCNetworkInterfaceGetLocalizedDisplayName(interface),
					       SCErrorString(SCError()));
					SCNetworkServiceRemove(service);
					CFRelease(service);
					goto nextInterface;
				}

				ok = SCNetworkSetAddService(set, service);
				if (!ok) {
					SC_log(LOG_INFO, "could not add service for \"%@\": %s",
					       SCNetworkInterfaceGetLocalizedDisplayName(interface),
					       SCErrorString(SCError()));
					SCNetworkServiceRemove(service);
					CFRelease(service);
					goto nextInterface;
				}

				CFRelease(service);
				updated = TRUE;
			} else {
				add_supported_interfaces(interface_list, interface);
			}

		    nextInterface :

			CFArrayRemoveValueAtIndex(interface_list, 0);
		}
		CFRelease(interface_list);
	}
	if (updatedIFs)		CFRelease(interfaces);
	if (services != NULL)	CFRelease(services);
	if (excluded != NULL)	CFRelease(excluded);

#if	TARGET_OS_IPHONE
	if (orphans != NULL) {
		if (ok && updated) {
			CFIndex	i;
			CFIndex	n	= CFArrayGetCount(orphans);

			for (i = 0; i < n; i++) {
				SCNetworkServiceRef	service;

				service = CFArrayGetValueAtIndex(orphans, i);
				if (_SCNetworkServiceIsVPN(service)) {
					ok = SCNetworkSetAddService(set, service);
					if (!ok) {
						break;
					}
				}
			}
		}

		CFRelease(orphans);
	}
#endif	// TARGET_OS_IPHONE

	if (ok && !updated) {
		// if no changes were made
		_SCErrorSet(kSCStatusOK);
	}

	return updated;
}
Exemple #30
0
__private_extern__
int
__SCDynamicStoreRemoveValue(SCDynamicStoreRef store, CFStringRef key, Boolean internal)
{
	CFDictionaryRef			dict;
	CFMutableDictionaryRef		newDict;
	SCDynamicStorePrivateRef	storePrivate	= (SCDynamicStorePrivateRef)store;
	int				sc_status	= kSCStatusOK;
	CFStringRef			sessionKey;

	SC_trace(_configd_trace, "%s : %5d : %@\n",
		 internal ? "*remove" : "remove ",
		 storePrivate->server,
		 key);

	/*
	 * Ensure that this key exists.
	 */
	dict = CFDictionaryGetValue(storeData, key);
	if ((dict == NULL) || (CFDictionaryContainsKey(dict, kSCDData) == FALSE)) {
		/* key doesn't exist (or data never defined) */
		sc_status = kSCStatusNoKey;
		goto done;
	}
	newDict = CFDictionaryCreateMutableCopy(NULL, 0, dict);

	/*
	 * Mark this key as "changed". Any "watchers" will be
	 * notified as soon as the lock is released.
	 */
	CFSetAddValue(changedKeys, key);

	/*
	 * Add this key to a deferred cleanup list so that, after
	 * the change notifications are posted, any associated
	 * regex keys can be removed.
	 */
	CFSetAddValue(deferredRemovals, key);

	/*
	 * Check if this is a session key and, if so, add it
	 * to the (session) removal list
	 */
	sessionKey = CFDictionaryGetValue(newDict, kSCDSession);
	if (sessionKey) {
		CFStringRef	removedKey;

		/* We are no longer a session key! */
		CFDictionaryRemoveValue(newDict, kSCDSession);

		/* add this session key to the (session) removal list */
		removedKey = CFStringCreateWithFormat(NULL, 0, CFSTR("%@:%@"), sessionKey, key);
		CFSetAddValue(removedSessionKeys, removedKey);
		CFRelease(removedKey);
	}

	/*
	 * Remove data and update/remove the dictionary store entry.
	 */
	CFDictionaryRemoveValue(newDict, kSCDData);
	if (CFDictionaryGetCount(newDict) > 0) {
		/* this key is still being "watched" */
		CFDictionarySetValue(storeData, key, newDict);
	} else {
		/* no information left, remove the empty dictionary */
		CFDictionaryRemoveValue(storeData, key);
	}
	CFRelease(newDict);

	if (!internal) {
		/* push changes */
		__SCDynamicStorePush();
	}

    done:

	return sc_status;
}