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; }
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; }
static void addAvailableInterfaces(CFMutableArrayRef available, CFArrayRef interfaces, CFSetRef excluded) { CFIndex i; CFIndex n; n = CFArrayGetCount(interfaces); for (i = 0; i < n; i++) { SCNetworkInterfaceRef interface; SCNetworkInterfacePrivateRef interfacePrivate; interface = CFArrayGetValueAtIndex(interfaces, i); interfacePrivate = (SCNetworkInterfacePrivateRef)interface; if ((excluded != NULL) && CFSetContainsValue(excluded, interface)) { // exclude this interface continue; } if (interfacePrivate->supportsVLAN) { // if this interface is available CFArrayAppendValue(available, interface); } } return; }
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 rb_set_union_callback(const void *value, void *context) { CFMutableSetRef set = context; if (!CFSetContainsValue(set, RB2OC(value))) CFSetAddValue(set, RB2OC(value)); }
static void rb_set_subtract_callback(const void *value, void *context) { CFMutableSetRef *sets = context; if (CFSetContainsValue(sets[0], RB2OC(value))) CFSetRemoveValue(sets[1], RB2OC(value)); }
static int _upsSupports(CFNumberRef whichUPS, CFStringRef command) { #ifdef STANDALONE return true; #else mach_port_t bootstrap_port = MACH_PORT_NULL; mach_port_t connect = MACH_PORT_NULL; int prop_supported; CFSetRef cap_set; int _id; IOReturn ret; if (!IOUPSMIGServerIsRunning(&bootstrap_port, &connect)) { return 0; } if(whichUPS) CFNumberGetValue(whichUPS, kCFNumberIntType, &_id); else _id = 0; ret = IOUPSGetCapabilities(connect, _id, &cap_set); if(kIOReturnSuccess != ret) return false; prop_supported = (int)CFSetContainsValue(cap_set, command); CFRelease(cap_set); return prop_supported; #endif }
static const void * imp_rb_set_member(void *rcv, SEL sel, void *obj) { void *ret; PREPARE_RCV(rcv); ret = CFSetContainsValue((CFSetRef)rcv, obj) ? obj : NULL; RESTORE_RCV(rcv); return ret; }
void __security_debug(const char *scope, const char *function, const char *file, int line, const char *format, ...) { #if !defined(NDEBUG) pthread_once(&__security_debug_once, __security_debug_init); CFStringRef scopeName = NULL; /* Scope NULL is always enabled. */ if (scope) { /* Check if the scope is enabled. */ if (scopeSet) { scopeName = copyScopeName(scope, strlen(scope)); if (negate == CFSetContainsValue(scopeSet, scopeName)) { CFRelease(scopeName); return; } } else if (!negate) { return; } } CFStringRef formatStr = CFStringCreateWithCString(kCFAllocatorDefault, format, kCFStringEncodingUTF8); va_list args; va_start(args, format); CFStringRef message = CFStringCreateWithFormatAndArguments( kCFAllocatorDefault, NULL, formatStr, args); va_end(args); time_t now = time(NULL); char *date = ctime(&now); date[19] = '\0'; CFStringRef logStr = CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR("%s %-*s %s %@\n"), date + 4, MAX_SCOPE_LENGTH - 1, scope ? scope : "", function, message); CFShow(logStr); char logMsg[4096]; if (CFStringGetCString(logStr, logMsg, sizeof(logMsg), kCFStringEncodingUTF8)) { #if 0 asl_log(NULL, NULL, ASL_LEVEL_INFO, logMsg); #else aslmsg msg = asl_new(ASL_TYPE_MSG); if (scope) { asl_set(msg, ASL_KEY_FACILITY, scope); } asl_set(msg, ASL_KEY_LEVEL, ASL_STRING_INFO); asl_set(msg, ASL_KEY_MSG, logMsg); asl_send(NULL, msg); asl_free(msg); #endif } CFRelease(logStr); CFRelease(message); CFRelease(formatStr); if (scopeName) CFRelease(scopeName); #endif }
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; }
static VALUE rb_set_delete2(VALUE set, SEL sel, VALUE obj) { rb_set_modify_check(set); if (CFSetContainsValue((CFMutableSetRef)set, (const void *)RB2OC(obj))) { CFSetRemoveValue((CFMutableSetRef)set, (const void *)RB2OC(obj)); return set; } else return Qnil; }
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; }
bool SOSAccountVerifyAndAcceptHSAApplicants(SOSAccountRef account, SOSCircleRef newCircle, CFErrorRef *error) { SOSFullPeerInfoRef fpi = account->my_identity; __block bool circleChanged = false; CFMutableSetRef approvals = SOSAccountCopyPreApprovedHSA2Info(account); if(approvals && CFSetGetCount(approvals) > 0) { SOSCircleForEachApplicant(newCircle, ^(SOSPeerInfoRef peer) { CFStringRef peerID = SOSPeerInfoGetPeerID(peer); if(CFSetContainsValue(approvals, peerID)) { SOSPeerInfoRef copypi = SOSPeerInfoCreateCopy(NULL, peer, NULL); circleChanged = SOSCircleAcceptRequest(newCircle, SOSAccountGetPrivateCredential(account, NULL), fpi, copypi, error); CFSetRemoveValue(approvals, peerID); } });
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); }
/* 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); } }
KXKextManagerError PreLink(KXKextManagerRef theKextManager, CFDictionaryRef kextDict, const char * kernelCacheFilename, const char * kernel_file_name, const char * platform_name, const char * root_path, CFSetRef kernel_requests, Boolean all_plists, const NXArchInfo * arch, int verbose_level, Boolean debug_mode) { KXKextManagerError result = kKXKextManagerErrorFileAccess; CFIndex kexts_count, i; KXKextRef * kexts = NULL; // must free KXKextRef theKext = NULL; // don't release char symbol_dir[1 + strlen(TEMP_DIR)]; const char * temp_file = "cache.out"; int outfd = -1, curwd = -1; CFBundleRef kextBundle = NULL; // don't release CFMutableArrayRef moduleList; CFMutableDictionaryRef infoDict; vm_offset_t nextKernelVM; Boolean use_existing, kernel_swapped, includeInfo; vm_offset_t kernel_file, kernel_map; off_t kernel_size; vm_size_t kernel_file_size, bytes, totalBytes; vm_size_t totalModuleBytes, totalInfoBytes; vm_size_t totalSymbolBytes, totalSymbolSetBytes, totalSymbolDiscardedBytes; vm_size_t remainingModuleBytes, fileoffset, vmoffset, tailoffset; CFIndex idx, ncmds, cmd; IOReturn err; struct segment_command * seg; struct segment_command * prelinkseg; struct section * prelinksects; struct PrelinkState { kmod_info_t modules[1]; }; struct PrelinkState prelink_state_init; struct PrelinkState * prelink_state; vm_size_t prelink_size; int * prelink_dependencies; vm_size_t prelink_dependencies_size; kmod_info_t * lastInfo; struct FileInfo { vm_offset_t mapped; vm_size_t mappedSize; vm_offset_t symtaboffset; vm_offset_t symbolsetoffset; vm_size_t symtabsize; vm_size_t symtabdiscarded; CFStringRef key; KXKextRef kext; Boolean code; Boolean swapped; }; struct FileInfo * files = NULL; // -- symbol_dir[0] = 0; moduleList = CFArrayCreateMutable( kCFAllocatorDefault, 0, &kCFTypeArrayCallBacks ); if (kKXKextManagerErrorNone != (err = readFile(kernel_file_name, &kernel_file, &kernel_file_size))) goto finish; find_arch( (u_int8_t **) &kernel_map, &kernel_size, arch->cputype, arch->cpusubtype, (u_int8_t *) kernel_file, kernel_file_size); if (!kernel_size) { fprintf(stderr, "can't find architecture %s in %s\n", arch->name, kernel_file_name); err = kKXKextManagerErrorLinkLoad; goto finish; } if (arch->cputype != CPU_TYPE_ANY) kld_set_architecture(arch); kernel_swapped = kld_macho_swap((struct mach_header *)kernel_map); ncmds = ((struct mach_header *)kernel_map)->ncmds; seg = (struct segment_command *)(((struct mach_header *)kernel_map) + 1); for (cmd = 0; cmd < ncmds; cmd++, seg = (struct segment_command *)(((vm_offset_t)seg) + seg->cmdsize)) { if (LC_SEGMENT != seg->cmd) continue; if (strcmp("__PRELINK", seg->segname)) continue; break; } if (cmd >= ncmds) { fprintf(stderr, "no __PRELINK segment in %s\n", kernel_file_name); err = kKXKextManagerErrorLinkLoad; goto finish; } prelinkseg = seg; prelinksects = (struct section *) (prelinkseg + 1); if ((prelinkseg->nsects != 3) || (strcmp("__text", prelinksects[0].sectname)) || (strcmp("__symtab", prelinksects[1].sectname)) || (strcmp("__info", prelinksects[2].sectname))) { fprintf(stderr, "unexpected __PRELINK sections in %s\n", kernel_file_name); err = kKXKextManagerErrorLinkLoad; goto finish; } if (!prelinkseg->fileoff) prelinkseg->fileoff = prelinksects[0].offset; strcpy(symbol_dir, TEMP_DIR); mktemp(symbol_dir); if (0 != mkdir(symbol_dir, 0755)) { fprintf(stderr, "mkdir(%s) failed: %s\n", symbol_dir, strerror(errno)); symbol_dir[0] = 0; err = kKXKextManagerErrorFileAccess; goto finish; } curwd = open(".", O_RDONLY, 0); if (0 != chdir(symbol_dir)) { perror("chdir"); err = kKXKextManagerErrorFileAccess; goto finish; } use_existing = false; if (!use_existing) { int fd; bzero(&prelink_state_init, sizeof(prelink_state_init)); prelink_state_init.modules[0].address = prelinkseg->vmaddr; fd = open("prelinkstate", O_WRONLY|O_CREAT|O_TRUNC, 0755); if (-1 == fd) { perror("create prelinkstate failed"); err = kKXKextManagerErrorFileAccess; goto finish; } err = writeFile(fd, &prelink_state_init, sizeof(prelink_state_init)); close(fd); if (kKXKextManagerErrorNone != err) goto finish; } /* Prepare to iterate over the kexts in the dictionary. */ kexts_count = CFDictionaryGetCount(kextDict); kexts = (KXKextRef *) calloc(kexts_count, sizeof(KXKextRef)); if (!kexts) { fprintf(stderr, "memory allocation failure\n"); err = kKXKextManagerErrorNoMemory; goto finish; } CFDictionaryGetKeysAndValues(kextDict, (const void **)NULL, (const void **)kexts); for (i = 0; i < kexts_count; i++) { Boolean linkit; theKext = (KXKextRef) kexts[i]; linkit = KXKextGetDeclaresExecutable(theKext) && (kextBundle = KXKextGetBundle(theKext)); if (linkit && kernel_requests) { CFStringRef bundleIdentifier = CFBundleGetIdentifier(kextBundle); linkit = (bundleIdentifier && CFSetContainsValue(kernel_requests, bundleIdentifier)); } if (linkit) { result = _KXKextManagerPrepareKextForLoading( theKextManager, theKext, NULL /*kext_name*/, FALSE /*check_loaded_for_dependencies*/, FALSE /*do_load*/, NULL /*inauthenticKexts*/); if (!use_existing && (result == kKXKextManagerErrorNone)) { result = _KXKextManagerLoadKextUsingOptions( theKextManager, theKext, NULL /*kext_name*/, kernel_file_name, NULL /*patch_dir*/, symbol_dir, kKXKextManagerLoadPrelink /*load_options*/, FALSE /*do_start_kmod*/, 0 /*interactive_level*/, FALSE /*ask_overwrite_symbols*/, FALSE /*overwrite_symbols*/, FALSE /*get_addrs_from_kernel*/, 0 /*num_addresses*/, NULL /*addresses*/); } if ((result != kKXKextManagerErrorNone) && (verbose_level > 0)) { const char * kext_path = NULL; // must free kext_path = _KXKextCopyCanonicalPathnameAsCString(theKext); if (kext_path) { fprintf(stderr, kext_path); free((char *)kext_path); } fprintf(stderr, " error 0x%x\n", result); } } } { struct module_header { struct mach_header h; struct segment_command seg[1]; }; struct module_header * header; int num_modules; if (kKXKextManagerErrorNone != (err = readFile("prelinkstate", (vm_offset_t *) &prelink_state, &prelink_size))) goto finish; if (kKXKextManagerErrorNone != (err = readFile("prelinkdependencies", (vm_offset_t *) &prelink_dependencies, &prelink_dependencies_size))) goto finish; num_modules = prelink_state->modules[0].id; nextKernelVM = prelink_state->modules[0].address; if (!num_modules || (prelink_size < ((num_modules + 1) * sizeof(kmod_info_t)))) { fprintf(stderr, "read prelinkstate failed\n"); err = kKXKextManagerErrorFileAccess; goto finish; } if (verbose_level > 0) { verbose_log("%d modules - code VM 0x%lx - 0x%x (0x%lx, %.2f Mb)", num_modules, prelinkseg->vmaddr, nextKernelVM, nextKernelVM - prelinkseg->vmaddr, ((float)(nextKernelVM - prelinkseg->vmaddr)) / 1024.0 / 1024.0 ); } // map files, get sizes files = (struct FileInfo *) calloc(num_modules, sizeof(struct FileInfo)); totalModuleBytes = 0; for (idx = 0; idx < num_modules; idx++) { files[idx].key = CFStringCreateWithCString(kCFAllocatorDefault, prelink_state->modules[1+idx].name, kCFStringEncodingMacRoman); files[idx].kext = KXKextManagerGetKextWithIdentifier(theKextManager, files[idx].key); if (!prelink_state->modules[1+idx].size) continue; if (kKXKextManagerErrorNone != (err = readFile(prelink_state->modules[1+idx].name, &files[idx].mapped, &files[idx].mappedSize))) goto finish; header = (struct module_header *) files[idx].mapped; files[idx].swapped = kld_macho_swap(&header->h); files[idx].code = (LC_SEGMENT == header->seg[0].cmd); if (files[idx].code) totalModuleBytes += header->seg[0].vmaddr + round_page(header->seg[0].vmsize) - prelink_state->modules[1+idx].address; } totalSymbolBytes = 0; totalSymbolDiscardedBytes = 0; totalSymbolSetBytes = 0; remainingModuleBytes = totalModuleBytes; // create prelinked kernel file outfd = open("mach_kernel.prelink", O_WRONLY|O_CREAT|O_TRUNC, 0666); if (-1 == outfd) { fprintf(stderr, "can't create %s: %s\n", "mach_kernel.prelink", strerror(errno)); err = kKXKextManagerErrorFileAccess; goto finish; } // start writing at the prelink segs file offset if (-1 == lseek(outfd, prelinkseg->fileoff, SEEK_SET)) { perror("couldn't write output"); err = kKXKextManagerErrorFileAccess; goto finish; } for (idx = 0, lastInfo = NULL; idx < num_modules; idx++) { kmod_info_t * info; unsigned long modcmd; struct symtab_command * symcmd; struct section * sect; vm_size_t headerOffset; if (!files[idx].code && prelink_state->modules[1+idx].size) { // for symbol sets the whole file ends up in the symbol sect files[idx].symtaboffset = 0; files[idx].symtabsize = prelink_state->modules[1+idx].size; files[idx].symbolsetoffset = totalSymbolBytes; totalSymbolBytes += files[idx].symtabsize; totalSymbolSetBytes += files[idx].symtabsize; continue; } header = (struct module_header *) files[idx].mapped; // patch kmod_info info = (kmod_info_t *) (prelink_state->modules[1+idx].id - header->seg[0].vmaddr + header->seg[0].fileoff + files[idx].mapped); info->next = lastInfo; lastInfo = info; bcopy(prelink_state->modules[1+idx].name, info->name, sizeof(info->name)); bcopy(prelink_state->modules[1+idx].version, info->version, sizeof(info->version)); info->address = prelink_state->modules[1+idx].address; info->size = prelink_state->modules[1+idx].size; info->id = prelink_state->modules[1+idx].id; info->hdr_size = header->seg[0].vmaddr - prelink_state->modules[1+idx].address; // patch offsets // how far back the header moves headerOffset = info->hdr_size - header->seg[0].fileoff; header->seg[0].fileoff += headerOffset; header->seg[0].filesize += headerOffset; // module code size tailoffset = round_page(header->seg[0].vmsize) + info->hdr_size - headerOffset; for (modcmd = 0, sect = (struct section *) &header->seg[1]; modcmd < header->seg[0].nsects; modcmd++, sect++) sect->offset += headerOffset; for (modcmd = 0, seg = &header->seg[0]; (modcmd < header->h.ncmds) && (LC_SYMTAB != seg->cmd); modcmd++, seg = (struct segment_command *)(((vm_offset_t)seg) + seg->cmdsize)) {} if (modcmd >= header->h.ncmds) { fprintf(stderr, "No LC_SYMTAB in %s\n", prelink_state->modules[1+idx].name); err = kKXKextManagerErrorLinkLoad; goto finish; } symcmd = (struct symtab_command *) seg; theKext = files[idx].kext; if (false && theKext && (kextBundle = KXKextGetBundle(theKext)) && CFBundleGetValueForInfoDictionaryKey(kextBundle, CFSTR("OSBundleCompatibleVersion"))) { // keeping symbols for this module struct nlist * sym; long align, lastUsedOffset = 0; const char * lastUsedString; unsigned int strIdx; files[idx].symtaboffset = symcmd->symoff; files[idx].symtabsize = symcmd->nsyms * sizeof(struct nlist); // .. but just the external strings sym = (struct nlist *) (symcmd->symoff + files[idx].mapped); for(strIdx = 0; strIdx < symcmd->nsyms; strIdx++, sym++) { if (!lastUsedOffset) lastUsedOffset = sym->n_un.n_strx; else if (!(sym->n_type & N_EXT)) sym->n_un.n_strx = 0; else if (sym->n_un.n_strx > lastUsedOffset) lastUsedOffset = sym->n_un.n_strx; } lastUsedString = (const char *) (symcmd->stroff + lastUsedOffset + files[idx].mapped); lastUsedOffset += (1 + strlen(lastUsedString)); align = lastUsedOffset % sizeof(long); if (align) { align = sizeof(long) - align; bzero((void *) (symcmd->stroff + lastUsedOffset + files[idx].mapped), align); lastUsedOffset += align; } files[idx].symtabsize += lastUsedOffset; files[idx].symtabdiscarded = symcmd->strsize - lastUsedOffset; symcmd->strsize = lastUsedOffset; // unswap symbols kld_macho_unswap(&header->h, files[idx].swapped, 1); // patch offset to symbols // how far ahead the symtab moves bytes = remainingModuleBytes + totalSymbolBytes; symcmd->symoff = bytes; symcmd->stroff += bytes - files[idx].symtaboffset; totalSymbolBytes += files[idx].symtabsize; totalSymbolDiscardedBytes += files[idx].symtabdiscarded; } else { // ditching symbols for this module files[idx].symtaboffset = 0; files[idx].symtabsize = 0; symcmd->nsyms = 0; symcmd->symoff = 0; symcmd->stroff = 0; } remainingModuleBytes -= prelink_state->modules[1+idx].size; // unswap rest of module if (files[idx].swapped) { info->next = (void *) NXSwapLong((long) info->next); info->address = NXSwapLong(info->address); info->size = NXSwapLong(info->size); info->hdr_size = NXSwapLong(info->hdr_size); info->id = NXSwapLong(info->id); } kld_macho_unswap(&header->h, files[idx].swapped, -1); files[idx].swapped = false; header = 0; info = 0; // copy header to start of VM allocation if (kKXKextManagerErrorNone != (err = writeFile(outfd, (const void *) files[idx].mapped, headerOffset))) goto finish; // write the module if (kKXKextManagerErrorNone != (err = writeFile(outfd, (const void *) files[idx].mapped, tailoffset ))) goto finish; } // write the symtabs, get info, unmap for (idx = 0; idx < num_modules; idx++) { bytes = files[idx].symtabsize; if (bytes && prelink_state->modules[1+idx].size) { if (files[idx].mappedSize < (files[idx].symtaboffset + bytes)) { fprintf(stderr, "%s is truncated\n", prelink_state->modules[1+idx].name); result = kKXKextManagerErrorFileAccess; goto finish; } else if (files[idx].mappedSize > (files[idx].symtaboffset + bytes + files[idx].symtabdiscarded)) fprintf(stderr, "%s has extra data\n", prelink_state->modules[1+idx].name); // write symtab if (kKXKextManagerErrorNone != (err = writeFile(outfd, (const void *) files[idx].mapped + files[idx].symtaboffset, bytes))) goto finish; } // unmap file if (files[idx].mappedSize) { vm_deallocate(mach_task_self(), files[idx].mapped, files[idx].mappedSize); files[idx].mapped = 0; files[idx].mappedSize = 0; } // make info dict theKext = files[idx].kext; infoDict = NULL; includeInfo = (theKext && (kextBundle = KXKextGetBundle(theKext))); if (includeInfo && !all_plists) { CFStringRef str; // check OSBundleRequired to see if safe for boot time matching str = CFBundleGetValueForInfoDictionaryKey(kextBundle, CFSTR("OSBundleRequired")); includeInfo = (str && (kCFCompareEqualTo != CFStringCompare(str, CFSTR("Safe Boot"), 0))); } if (includeInfo) infoDict = copyInfoDict(kextBundle); if (!infoDict) { if (debug_mode > 0) { verbose_log("skip info for %s", prelink_state->modules[1+idx].name); } infoDict = CFDictionaryCreateMutable( kCFAllocatorDefault, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); CFDictionarySetValue(infoDict, CFSTR("CFBundleIdentifier"), files[idx].key); } CFRelease(files[idx].key); files[idx].key = 0; if (prelink_state->modules[1+idx].address) { CFMutableDataRef data; enum { kPrelinkReservedCount = 4 }; UInt32 prelinkInfo[kPrelinkReservedCount]; prelinkInfo[0] = NXSwapHostIntToBig(prelink_state->modules[1+idx].id); prelinkInfo[1] = NXSwapHostIntToBig(0); prelinkInfo[2] = NXSwapHostIntToBig(sizeof(prelinkInfo)); prelinkInfo[3] = NXSwapHostIntToBig( prelink_state->modules[1+idx].reference_count * sizeof(UInt32) + sizeof(prelinkInfo)); data = CFDataCreateMutable(kCFAllocatorDefault, 0); CFDataAppendBytes( data, (const UInt8 *) prelinkInfo, sizeof(prelinkInfo) ); if (prelink_state->modules[1+idx].reference_count) { CFIndex start = (CFIndex) prelink_state->modules[1+idx].reference_list; CFDataAppendBytes( data, (const UInt8 *) &prelink_dependencies[start], prelink_state->modules[1+idx].reference_count * sizeof(CFIndex) ); } CFDictionarySetValue(infoDict, CFSTR("OSBundlePrelink"), data); CFRelease(data); } else if (files[idx].symtabsize) { CFNumberRef num; num = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, (const void *) &files[idx].symbolsetoffset); CFDictionarySetValue(infoDict, CFSTR("OSBundlePrelinkSymbols"), num); CFRelease(num); } CFArrayAppendValue(moduleList, infoDict); CFRelease(infoDict); } bytes = round_page(totalSymbolBytes) - totalSymbolBytes; totalSymbolBytes += bytes; if (-1 == lseek(outfd, bytes, SEEK_CUR)) { perror("couldn't write output"); err = kKXKextManagerErrorFileAccess; goto finish; } // deferred load __info if (!all_plists) for (i = 0; i < kexts_count; i++) { theKext = (KXKextRef) kexts[i]; for (idx = 0; (idx < num_modules) && (theKext != files[idx].kext); idx++) {} if (idx < num_modules) continue; includeInfo = (theKext && (kextBundle = KXKextGetBundle(theKext))); if (includeInfo) { CFStringRef str; // check OSBundleRequired to see if safe for boot time matching str = CFBundleGetValueForInfoDictionaryKey(kextBundle, CFSTR("OSBundleRequired")); includeInfo = (str && (kCFCompareEqualTo != CFStringCompare(str, CFSTR("Safe Boot"), 0))); if (includeInfo) { infoDict = copyInfoDict(kextBundle); if (infoDict) { CFDictionarySetValue(infoDict, CFSTR("OSBundleDefer"), kCFBooleanTrue); CFArrayAppendValue(moduleList, infoDict); CFRelease(infoDict); } } } } // write __info { CFDataRef data; data = IOCFSerialize(moduleList, kNilOptions); if (!data) { fprintf(stderr, "couldn't serialize property lists\n"); err = kKXKextManagerErrorSerialization; goto finish; } totalInfoBytes = round_page(CFDataGetLength(data)); if (kKXKextManagerErrorNone != (err = writeFile(outfd, CFDataGetBytePtr(data), CFDataGetLength(data)))) goto finish; if (-1 == lseek(outfd, totalInfoBytes - CFDataGetLength(data), SEEK_CUR)) { perror("couldn't write output"); err = kKXKextManagerErrorFileAccess; goto finish; } CFRelease(data); } totalBytes = totalModuleBytes + totalSymbolBytes + totalInfoBytes; if (verbose_level > 0) { verbose_log("added 0x%x bytes %.2f Mb (code 0x%x + symbol 0x%x + sets 0x%x - strings 0x%x + info 0x%x)", totalBytes, ((float) totalBytes) / 1024.0 / 1024.0, totalModuleBytes, totalSymbolBytes, totalSymbolSetBytes, totalSymbolDiscardedBytes, totalInfoBytes); } fileoffset = totalBytes - prelinkseg->filesize; vmoffset = totalBytes - round_page(prelinkseg->filesize); // unswap kernel symbols kld_macho_unswap((struct mach_header *)kernel_map, kernel_swapped, 1); // write tail of base kernel tailoffset = prelinkseg->fileoff + prelinkseg->filesize; if (kKXKextManagerErrorNone != (err = writeFile(outfd, (const void *) (kernel_map + tailoffset), kernel_size - tailoffset))) goto finish; // patch prelink sects sizes and offsets prelinkseg->vmsize = totalBytes; prelinkseg->filesize = totalBytes; prelinksects[0].size = totalModuleBytes; prelinksects[1].addr = prelinksects[0].addr + totalModuleBytes; prelinksects[1].size = totalSymbolBytes; prelinksects[1].offset = prelinksects[0].offset + totalModuleBytes; prelinksects[2].addr = prelinksects[1].addr + totalSymbolBytes; prelinksects[2].size = totalInfoBytes; prelinksects[2].offset = prelinksects[1].offset + totalSymbolBytes; // patch following segs address & offsets seg = prelinkseg; for (; cmd < ncmds; cmd++) { seg = (struct segment_command *)(((vm_offset_t)seg) + seg->cmdsize); if (LC_SYMTAB == seg->cmd) { ((struct symtab_command *)seg)->symoff += fileoffset; ((struct symtab_command *)seg)->stroff += fileoffset; } else if (LC_SEGMENT == seg->cmd) { seg->fileoff += fileoffset; seg->vmaddr += vmoffset; } } bytes = prelinkseg->fileoff; // unswap kernel headers kld_macho_unswap((struct mach_header *)kernel_map, kernel_swapped, -1); kernel_swapped = false; prelinkseg = 0; // write head of base kernel, & free it if (-1 == lseek(outfd, 0, SEEK_SET)) { perror("couldn't write output"); err = kKXKextManagerErrorFileAccess; goto finish; } if (kKXKextManagerErrorNone != (err = writeFile(outfd, (const void *) kernel_map, bytes))) goto finish; close(outfd); outfd = -1; vm_deallocate( mach_task_self(), kernel_file, kernel_file_size ); kernel_file = 0; kernel_map = 0; } // compresss { char * buf; char * bufend; vm_size_t bufsize; struct { uint32_t signature; uint32_t compress_type; uint32_t adler32; vm_size_t uncompressed_size; vm_size_t compressed_size; uint32_t reserved[11]; char platform_name[64]; char root_path[256]; char data[0]; } kernel_header = { 0 }; if (kKXKextManagerErrorNone != (err = readFile("mach_kernel.prelink", &kernel_file, &kernel_file_size))) goto finish; bufsize = kernel_file_size; buf = malloc(bufsize); kernel_header.signature = NXSwapHostIntToBig('comp'); kernel_header.compress_type = NXSwapHostIntToBig('lzss'); kernel_header.adler32 = NXSwapHostIntToBig(local_adler32( (u_int8_t *) kernel_file, kernel_file_size)); kernel_header.uncompressed_size = NXSwapHostIntToBig(kernel_file_size); strcpy(kernel_header.platform_name, platform_name); strcpy(kernel_header.root_path, root_path); if (verbose_level > 0) verbose_log("adler32 0x%08x, compressing...", NXSwapBigIntToHost(kernel_header.adler32)); bufend = compress_lzss(buf, bufsize, (u_int8_t *) kernel_file, kernel_file_size); totalBytes = bufend - buf; kernel_header.compressed_size = NXSwapHostIntToBig(totalBytes); if (verbose_level > 0) verbose_log("final size 0x%x bytes %.2f Mb", totalBytes, ((float) totalBytes) / 1024.0 / 1024.0); vm_deallocate( mach_task_self(), kernel_file, kernel_file_size ); outfd = open(temp_file, O_WRONLY|O_CREAT|O_TRUNC, 0666); if (-1 == outfd) { fprintf(stderr, "can't create %s - %s\n", temp_file, strerror(errno)); err = kKXKextManagerErrorFileAccess; goto finish; } // write header if (kKXKextManagerErrorNone != (err = writeFile(outfd, &kernel_header, sizeof(kernel_header)))) goto finish; // write compressed data if (kKXKextManagerErrorNone != (err = writeFile(outfd, buf, bufend - buf))) goto finish; close(outfd); outfd = -1; } // move it to the final destination if (-1 == rename(temp_file, kernelCacheFilename)) { fprintf(stderr, "can't create file %s: %s\n", kernelCacheFilename, strerror(errno)); err = kKXKextManagerErrorFileAccess; goto finish; } if (verbose_level > 0) verbose_log("created cache: %s", kernelCacheFilename); result = kKXKextManagerErrorNone; finish: if (-1 != outfd) close(outfd); if (debug_mode) symbol_dir[0] = 0; if (symbol_dir[0]) { FTS * fts; FTSENT * fts_entry; char * paths[2]; paths[0] = symbol_dir; paths[1] = 0; fts = fts_open(paths, FTS_NOCHDIR, NULL); if (fts) { while ((fts_entry = fts_read(fts))) { if (fts_entry->fts_errno) continue; if (FTS_F != fts_entry->fts_info) continue; if (-1 == unlink(fts_entry->fts_path)) fprintf(stderr, "can't remove file %s: %s\n", fts_entry->fts_path, strerror(errno)); } fts_close(fts); } } if (-1 != curwd) fchdir(curwd); if (symbol_dir[0] && (-1 == rmdir(symbol_dir))) perror("rmdir"); if (kexts) free(kexts); if (files) free(files); return result; }
CFIndex CFSetGetCountOfValue (CFSetRef set, const void *value) { return CFSetContainsValue (set, value) ? 1 : 0; }
static bool SecMemoryCertificateSourceContains(SecCertificateSourceRef source, SecCertificateRef certificate) { SecMemoryCertificateSourceRef msource = (SecMemoryCertificateSourceRef)source; return CFSetContainsValue(msource->certificates, certificate); }
static void __DAStageDispatch( void * info ) { static Boolean fresh = FALSE; CFIndex count; CFIndex index; Boolean quiet = TRUE; count = CFArrayGetCount( gDADiskList ); for ( index = 0; index < count; index++ ) { DADiskRef disk; disk = ( void * ) CFArrayGetValueAtIndex( gDADiskList, index ); if ( DADiskGetState( disk, kDADiskStateCommandActive ) == FALSE ) { if ( DADiskGetState( disk, kDADiskStateStagedProbe ) == FALSE ) { if ( fresh ) { DAFileSystemListRefresh( ); DAMountMapListRefresh1( ); DAMountMapListRefresh2( ); fresh = FALSE; } __DAStageProbe( disk ); } else if ( DADiskGetState( disk, kDADiskStateStagedPeek ) == FALSE ) { __DAStagePeek( disk ); } ///w:start else if ( DADiskGetState( disk, kDADiskStateRequireRepair ) == FALSE ) { if ( DADiskGetState( disk, kDADiskStateStagedApprove ) == FALSE ) { __DAStageMountApproval( disk ); } else if ( DADiskGetState( disk, kDADiskStateStagedAuthorize ) == FALSE ) { __DAStageMountAuthorization( disk ); } else if ( DADiskGetState( disk, kDADiskStateStagedMount ) == FALSE ) { __DAStageMount( disk ); } else if ( DADiskGetState( disk, kDADiskStateStagedAppear ) == FALSE ) { __DAStageAppeared( disk ); } else { ///w:start if ( gDAConsoleUserList == NULL ) { if ( DADiskGetDescription( disk, kDADiskDescriptionMediaTypeKey ) ) { if ( DAUnitGetState( disk, kDAUnitStateStagedUnreadable ) == FALSE ) { if ( _DAUnitIsUnreadable( disk ) ) { DADiskEject( disk, kDADiskEjectOptionDefault, NULL ); } DAUnitSetState( disk, kDAUnitStateStagedUnreadable, TRUE ); } } } ///w:stop continue; } } ///w:stop else if ( DADiskGetState( disk, kDADiskStateStagedAppear ) == FALSE ) { /* * We stall the "appeared" stage if the conditions are not right. */ if ( DADiskGetState( disk, kDADiskStateRequireRepair ) ) { CFIndex subcount; CFIndex subindex; subcount = CFArrayGetCount( gDADiskList ); for ( subindex = 0; subindex < subcount; subindex++ ) { DADiskRef subdisk; subdisk = ( void * ) CFArrayGetValueAtIndex( gDADiskList, subindex ); if ( DADiskGetBSDUnit( disk ) == DADiskGetBSDUnit( subdisk ) ) { if ( DADiskGetState( subdisk, kDADiskStateStagedProbe ) == FALSE ) { break; } if ( DADiskGetState( subdisk, kDADiskStateStagedAppear ) == FALSE ) { if ( DADiskGetState( subdisk, kDADiskStateRequireRepair ) == FALSE ) { break; } } } } if ( subindex == subcount ) { __DAStageAppeared( disk ); } } else { __DAStageAppeared( disk ); } } else if ( DADiskGetState( disk, kDADiskStateStagedApprove ) == FALSE ) { __DAStageMountApproval( disk ); } else if ( DADiskGetState( disk, kDADiskStateStagedAuthorize ) == FALSE ) { __DAStageMountAuthorization( disk ); } else if ( DADiskGetState( disk, kDADiskStateStagedMount ) == FALSE ) { if ( gDAExit ) { continue; } __DAStageMount( disk ); } else { continue; } } quiet = FALSE; } count = CFArrayGetCount( gDARequestList ); if ( count ) { CFMutableSetRef dependencies; dependencies = CFSetCreateMutable( kCFAllocatorDefault, 0, &kCFTypeSetCallBacks ); if ( dependencies ) { for ( index = 0; index < count; index++ ) { DARequestRef request; request = ( void * ) CFArrayGetValueAtIndex( gDARequestList, index ); if ( request ) { DADiskRef disk; Boolean dispatch = TRUE; disk = DARequestGetDisk( request ); /* * Determine whether the request has undispatched dependencies. */ if ( disk ) { CFArrayRef link; link = DARequestGetLink( request ); if ( link ) { CFIndex subcount; CFIndex subindex; subcount = CFArrayGetCount( link ); for ( subindex = 0; subindex < subcount; subindex++ ) { DARequestRef subrequest; subrequest = ( void * ) CFArrayGetValueAtIndex( link, subindex ); if ( CFSetContainsValue( dependencies, DARequestGetDisk( subrequest ) ) ) { break; } } if ( subindex < subcount ) { dispatch = FALSE; } } if ( CFSetContainsValue( dependencies, disk ) ) { dispatch = FALSE; } } else { if ( index ) { break; } } if ( dispatch ) { /* * Prepare to dispatch the request. */ if ( DARequestGetKind( request ) == _kDADiskMount ) { if ( fresh ) { DAFileSystemListRefresh( ); DAMountMapListRefresh1( ); DAMountMapListRefresh2( ); fresh = FALSE; } } /* * Dispatch the request. */ dispatch = DARequestDispatch( request ); } if ( dispatch ) { CFArrayRemoveValueAtIndex( gDARequestList, index ); count--; index--; } else { /* * Add the request to the undispatched dependencies. */ if ( disk ) { CFArrayRef link; link = DARequestGetLink( request ); if ( link ) { CFIndex subcount; CFIndex subindex; subcount = CFArrayGetCount( link ); for ( subindex = 0; subindex < subcount; subindex++ ) { DARequestRef subrequest; subrequest = ( void * ) CFArrayGetValueAtIndex( link, subindex ); CFSetSetValue( dependencies, DARequestGetDisk( subrequest ) ); } } CFSetSetValue( dependencies, disk ); } } } } CFRelease( dependencies ); } quiet = FALSE; } if ( quiet ) { fresh = TRUE; gDAIdle = TRUE; DAIdleCallback( ); ___vproc_transaction_end( ); if ( gDAConsoleUser ) { /* * Determine whether a unit is unreadable or a volume is unrepairable. */ count = CFArrayGetCount( gDADiskList ); for ( index = 0; index < count; index++ ) { DADiskRef disk; disk = ( void * ) CFArrayGetValueAtIndex( gDADiskList, index ); /* * Determine whether a unit is unreadable. */ if ( DADiskGetDescription( disk, kDADiskDescriptionMediaWholeKey ) == kCFBooleanTrue ) { if ( DAUnitGetState( disk, kDAUnitStateStagedUnreadable ) == FALSE ) { if ( _DAUnitIsUnreadable( disk ) ) { DADialogShowDeviceUnreadable( disk ); } DAUnitSetState( disk, kDAUnitStateStagedUnreadable, TRUE ); } } /* * Determine whether a volume is unrepairable. */ if ( DADiskGetDescription( disk, kDADiskDescriptionVolumePathKey ) ) { if ( DADiskGetState( disk, kDADiskStateStagedUnrepairable ) == FALSE ) { if ( DADiskGetState( disk, kDADiskStateRequireRepair ) ) { if ( DADiskGetOption( disk, kDADiskOptionMountAutomatic ) ) { if ( DADiskGetClaim( disk ) == NULL ) { DADialogShowDeviceUnrepairable( disk ); } } } DADiskSetState( disk, kDADiskStateStagedUnrepairable, TRUE ); } } } } } }
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; }
CFArrayRef /* of SCNetworkInterfaceRef's */ SCNetworkSetCopyAvailableInterfaces(SCNetworkSetRef set) { CFMutableArrayRef available; CFMutableSetRef excluded = NULL; int i; CFArrayRef interfaces; CFIndex n_interfaces; CFIndex n_exclusions = 0; SCPreferencesRef prefs; SCNetworkSetPrivateRef setPrivate; setPrivate = (SCNetworkSetPrivateRef)set; prefs = setPrivate->prefs; interfaces = _SCNetworkInterfaceCopyAllWithPreferences(prefs); n_interfaces = CFArrayGetCount(interfaces); if (n_interfaces == 0) { return interfaces; } if (prefs != NULL) { CFArrayRef bridges = NULL; excluded = CFSetCreateMutable(NULL, 0, &kCFTypeSetCallBacks); #if !TARGET_OS_IPHONE CFArrayRef bonds = NULL; bonds = SCBondInterfaceCopyAll(prefs); if (bonds != NULL) { __SCBondInterfaceListCollectMembers(bonds, excluded); CFRelease(bonds); } #endif /* !TARGET_OS_IPHONE */ bridges = SCBridgeInterfaceCopyAll(prefs); if (bridges != NULL) { __SCBridgeInterfaceListCollectMembers(bridges, excluded); CFRelease(bridges); } n_exclusions = CFSetGetCount(excluded); } if (n_exclusions == 0) { if (excluded != NULL) { CFRelease(excluded); } return interfaces; } available = CFArrayCreateMutable(NULL, 0, &kCFTypeArrayCallBacks); for (i = 0; i < n_interfaces; i++) { SCNetworkInterfaceRef interface; interface = CFArrayGetValueAtIndex(interfaces, i); if (CFSetContainsValue(excluded, interface)) { // if excluded continue; } CFArrayAppendValue(available, interface); } CFRelease(interfaces); CFRelease(excluded); return available; }
static VALUE rb_set_include(VALUE set, SEL sel, VALUE obj) { return CFSetContainsValue((CFMutableSetRef)set, (const void *)RB2OC(obj)) ? Qtrue : Qfalse; }
static bool SecSystemAnchorSourceContains(SecCertificateSourceRef source, SecCertificateRef certificate) { SecSystemAnchorSourceRef sasource = (SecSystemAnchorSourceRef)source; CFDataRef digest = SecCertificateGetSHA1Digest(certificate); return CFSetContainsValue(sasource->digests, digest); }
IOReturn CreatePowerManagerUPSEntry(UPSDataRef upsDataRef, CFDictionaryRef properties, CFSetRef capabilities) { CFMutableDictionaryRef upsStoreDict = NULL; CFStringRef upsName = NULL; CFStringRef transport = NULL; CFStringRef upsStoreKey = NULL; CFNumberRef number = NULL; SCDynamicStoreRef upsStore = NULL; IOReturn status = kIOReturnSuccess; int elementValue = 0; char upsLabelString[kInternalUPSLabelLength]; if ( !upsDataRef || !properties || !capabilities) return kIOReturnError; upsStoreDict = CFDictionaryCreateMutable(kCFAllocatorDefault, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); // Set some Store values if ( upsStoreDict ) { // We need to save a name for this device. First, try to see if we have a USB Product Name. If // that fails then use the manufacturer and if that fails, then use a generic name. Couldn't we use // a serial # here? // upsName = (CFStringRef) CFDictionaryGetValue( properties, CFSTR( kIOPSNameKey ) ); if ( !upsName ) upsName = CFSTR(kDefaultUPSName); transport = (CFStringRef) CFDictionaryGetValue( properties, CFSTR( kIOPSTransportTypeKey ) ); CFDictionarySetValue(upsStoreDict, CFSTR(kIOPSNameKey), upsName); CFDictionarySetValue(upsStoreDict, CFSTR(kIOPSTransportTypeKey), transport); CFDictionarySetValue(upsStoreDict, CFSTR(kIOPSIsPresentKey), kCFBooleanTrue); CFDictionarySetValue(upsStoreDict, CFSTR(kIOPSIsChargingKey), kCFBooleanTrue); CFDictionarySetValue(upsStoreDict, CFSTR(kIOPSPowerSourceStateKey), CFSTR(kIOPSACPowerValue)); number = CFNumberCreate(kCFAllocatorDefault, kCFNumberIntType, &upsDataRef->upsID); CFDictionarySetValue(upsStoreDict, CFSTR(kIOPSPowerSourceIDKey), number); CFRelease(number); elementValue = 100; number = CFNumberCreate(kCFAllocatorDefault, kCFNumberIntType, &elementValue); CFDictionarySetValue(upsStoreDict, CFSTR(kIOPSMaxCapacityKey), number); CFRelease(number); if (CFSetContainsValue(capabilities, CFSTR(kIOPSCurrentCapacityKey))) { // Initialize kIOPSCurrentCapacityKey // // For Power Manager, we will be sharing capacity with Power Book battery capacities, so // we want a consistent measure. For now we have settled on percentage of full capacity. // elementValue = 100; number = CFNumberCreate(kCFAllocatorDefault, kCFNumberIntType, &elementValue); CFDictionarySetValue(upsStoreDict, CFSTR(kIOPSCurrentCapacityKey), number); CFRelease(number); } if (CFSetContainsValue(capabilities, CFSTR(kIOPSTimeToEmptyKey))) { // Initialize kIOPSTimeToEmptyKey (OS 9 PowerClass.c assumed 100 milliwatt-hours) // elementValue = 100; number = CFNumberCreate(kCFAllocatorDefault, kCFNumberIntType, &elementValue); CFDictionarySetValue(upsStoreDict, CFSTR(kIOPSTimeToEmptyKey), number); CFRelease(number); } if (CFSetContainsValue(capabilities, CFSTR(kIOPSVoltageKey))) { // Initialize kIOPSVoltageKey (OS 9 PowerClass.c assumed millivolts. // (Shouldn't that be 130,000 millivolts for AC?)) // Actually, Power Devices Usage Tables say units will be in Volts. // However we have to check what exponent is used because that may // make the value we get in centiVolts (exp = -2). So it looks like // OS 9 sources said millivolts, but used centivolts. Our final // answer should device by proper exponent to get back to Volts. // elementValue = 13 * 1000 / 100; number = CFNumberCreate(kCFAllocatorDefault, kCFNumberIntType, &elementValue); CFDictionarySetValue(upsStoreDict, CFSTR(kIOPSVoltageKey), number); CFRelease(number); } if (CFSetContainsValue(capabilities, CFSTR(kIOPSCurrentKey))) { // Initialize kIOPSCurrentKey (What would be a good amperage to // initialize to?) Same discussion as for Volts, where the unit // for current is Amps. But with typical exponents (-2), we get // centiAmps. Hmm... typical current for USB may be 500 milliAmps, // which would be .5 A. Since that is not an integer, that may be // why our displays get larger numbers // elementValue = 1; // Just a guess! number = CFNumberCreate(kCFAllocatorDefault, kCFNumberIntType, &elementValue); CFDictionarySetValue(upsStoreDict, CFSTR(kIOPSCurrentKey), number); CFRelease(number); } } upsStore = SCDynamicStoreCreate(kCFAllocatorDefault, CFSTR("UPS Power Manager"), NULL, NULL); // Uniquely name each Sys Config key // snprintf(upsLabelString, kInternalUPSLabelLength, "/UPS%d", upsDataRef->upsID); #if 0 SCLog(TRUE, LOG_NOTICE, CFSTR("What does CreatePowerManagerUPSEntry think our key name is?")); SCLog(TRUE, LOG_NOTICE, CFSTR(" %@%@%@"), kSCDynamicStoreDomainState, CFSTR(kIOPSDynamicStorePath), CFStringCreateWithCStringNoCopy(NULL, upsLabelString, kCFStringEncodingMacRoman, kCFAllocatorNull)); #endif CFStringRef upsLabelCF = NULL; upsLabelCF = CFStringCreateWithCStringNoCopy(NULL, upsLabelString, kCFStringEncodingMacRoman, kCFAllocatorNull); if (upsLabelCF) { upsStoreKey = SCDynamicStoreKeyCreate(kCFAllocatorDefault, CFSTR("%@%@%@"), kSCDynamicStoreDomainState, CFSTR(kIOPSDynamicStorePath), upsLabelCF); CFRelease(upsLabelCF); } if(!upsStoreKey || !SCDynamicStoreSetValue(upsStore, upsStoreKey, upsStoreDict)) { status = SCError(); #if UPS_DEBUG SCLog(TRUE, LOG_NOTICE, CFSTR("UPSSupport: Encountered SCDynamicStoreSetValue error 0x%x"), status); #endif } if (kIOReturnSuccess == status) { // Store our SystemConfiguration variables in our private data // upsDataRef->upsStoreDict = upsStoreDict; upsDataRef->upsStore = upsStore; upsDataRef->upsStoreKey = upsStoreKey; } else { if (upsStoreDict) CFRelease(upsStoreDict); if (upsStore) CFRelease(upsStore); if (upsStoreKey) CFRelease(upsStoreKey); } return status; }
CFArrayRef /* of SCNetworkInterfaceRef's */ SCBondInterfaceCopyAvailableMemberInterfaces(SCPreferencesRef prefs) { CFMutableArrayRef available; CFMutableSetRef excluded; CFArrayRef interfaces; available = CFArrayCreateMutable(NULL, 0, &kCFTypeArrayCallBacks); excluded = CFSetCreateMutable (NULL, 0, &kCFTypeSetCallBacks); // exclude Bond [member] interfaces interfaces = SCBondInterfaceCopyAll(prefs); if (interfaces != NULL) { __SCBondInterfaceListCollectMembers(interfaces, excluded); CFRelease(interfaces); } // exclude Bridge [member] interfaces interfaces = SCBridgeInterfaceCopyAll(prefs); if (interfaces != NULL) { __SCBridgeInterfaceListCollectMembers(interfaces, excluded); CFRelease(interfaces); } // exclude VLAN [physical] interfaces interfaces = SCVLANInterfaceCopyAll(prefs); if (interfaces != NULL) { CFIndex i; CFIndex n; n = CFArrayGetCount(interfaces); for (i = 0; i < n; i++) { SCVLANInterfaceRef vlanInterface; SCNetworkInterfaceRef physical; // exclude the physical interface of this VLAN vlanInterface = CFArrayGetValueAtIndex(interfaces, i); physical = SCVLANInterfaceGetPhysicalInterface(vlanInterface); CFSetAddValue(excluded, physical); } CFRelease(interfaces); } // identify available interfaces interfaces = __SCNetworkInterfaceCopyAll_IONetworkInterface(); if (interfaces != NULL) { CFIndex i; CFIndex n; n = CFArrayGetCount(interfaces); for (i = 0; i < n; i++) { SCNetworkInterfaceRef interface; SCNetworkInterfacePrivateRef interfacePrivate; interface = CFArrayGetValueAtIndex(interfaces, i); interfacePrivate = (SCNetworkInterfacePrivateRef)interface; if (!interfacePrivate->supportsBond) { // if this interface is not available continue; } if (CFSetContainsValue(excluded, interface)) { // if excluded continue; } CFArrayAppendValue(available, interface); } CFRelease(interfaces); } CFRelease(excluded); return available; }