/** * Insert a new item at position n in a #PLIST_ARRAY node. * * @param node the node of type #PLIST_ARRAY * @param item the new item to insert * @param n The position at which the node will be stored. Range is [0, array_size[. Assert if n is not in range. */ void plist_array_insert_item(plist_t node, plist_t item, uint32_t n) { assert(CFGetTypeID(node) == CFArrayGetTypeID()); CFArrayInsertValueAtIndex((CFMutableArrayRef) node, n, item); CFRelease(item); }
void _CFApplicationPreferencesAddDomain(_CFApplicationPreferences *self, CFPreferencesDomainRef domain, Boolean addAtTop) { __CFSpinLock(&__CFApplicationPreferencesLock); if (addAtTop) { CFArrayInsertValueAtIndex(self->_search, 0, domain); } else { CFArrayAppendValue(self->_search, domain); } updateDictRep(self); __CFSpinUnlock(&__CFApplicationPreferencesLock); }
/* 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); } }
bool CACFArray::InsertCFType(UInt32 inIndex, const CFTypeRef inItem) { bool theAnswer = false; if((mCFArray != NULL) && mMutable) { if(inIndex < GetNumberItems()) { CFArrayInsertValueAtIndex(mCFArray, inIndex, inItem); } else { CFArrayAppendValue(mCFArray, inItem); } theAnswer = true; } return theAnswer; }
kern_return_t IOCreatePlugInInterfaceForService(io_service_t service, CFUUIDRef pluginType, CFUUIDRef interfaceType, IOCFPlugInInterface *** theInterface, SInt32 * theScore) { CFDictionaryRef plist = 0; CFArrayRef plists; CFArrayRef factories; CFMutableArrayRef candidates; CFMutableArrayRef scores; CFIndex index; CFIndex insert; CFUUIDRef factoryID; kern_return_t kr; SInt32 score; IOCFPlugInInterface ** interface; Boolean haveOne; kr = IOFindPlugIns( service, pluginType, &factories, &plists ); if( KERN_SUCCESS != kr) { if (factories) CFRelease(factories); if (plists) CFRelease(plists); return( kr ); } if ((KERN_SUCCESS != kr) || (factories == NULL) || (0 == CFArrayGetCount(factories))) { // printf("No factories for type\n"); if (factories) CFRelease(factories); if (plists) CFRelease(plists); return( kIOReturnUnsupported ); } candidates = CFArrayCreateMutable(kCFAllocatorDefault, 0, NULL); scores = CFArrayCreateMutable(kCFAllocatorDefault, 0, NULL); // allocate and Probe all if (candidates && scores) { CFIndex numfactories = CFArrayGetCount(factories); for ( index = 0; index < numfactories; index++ ) { IUnknownVTbl ** iunknown; factoryID = (CFUUIDRef) CFArrayGetValueAtIndex(factories, index); iunknown = (IUnknownVTbl **) CFPlugInInstanceCreate(NULL, factoryID, pluginType); if (!iunknown) { // printf("Failed to create instance (link error?)\n"); continue; } (*iunknown)->QueryInterface(iunknown, CFUUIDGetUUIDBytes(interfaceType), (LPVOID *)&interface); // Now we are done with IUnknown interface (*iunknown)->Release(iunknown); if (!interface) { // printf("Failed to get interface.\n"); continue; } if (plists) plist = (CFDictionaryRef) CFArrayGetValueAtIndex( plists, index ); score = 0; // from property table kr = (*interface)->Probe(interface, plist, service, &score); if (kIOReturnSuccess == kr) { CFIndex numscores = CFArrayGetCount(scores); for (insert = 0; insert < numscores; insert++) { if (score > (SInt32) ((intptr_t) CFArrayGetValueAtIndex(scores, insert))) break; } CFArrayInsertValueAtIndex(candidates, insert, (void *) interface); CFArrayInsertValueAtIndex(scores, insert, (void *) (intptr_t) score); } else (*interface)->Release(interface); } } // Start in score order CFIndex candidatecount = CFArrayGetCount(candidates); for (haveOne = false, index = 0; index < candidatecount; index++) { Boolean freeIt; if (plists) plist = (CFDictionaryRef) CFArrayGetValueAtIndex(plists, index ); interface = (IOCFPlugInInterface **) CFArrayGetValueAtIndex(candidates, index ); if (!haveOne) { haveOne = (kIOReturnSuccess == (*interface)->Start(interface, plist, service)); freeIt = !haveOne; if (haveOne) { *theInterface = interface; *theScore = (SInt32) (intptr_t) CFArrayGetValueAtIndex(scores, index ); } } else freeIt = true; if (freeIt) (*interface)->Release(interface); } if (factories) CFRelease(factories); if (plists) CFRelease(plists); if (candidates) CFRelease(candidates); if (scores) CFRelease(scores); // CFRelease(plugin); return (haveOne ? kIOReturnSuccess : kIOReturnNoResources); }
static bool SecPathBuilderGetNext(SecPathBuilderRef builder) { /* If we have any candidates left to go return those first. */ if (CFArrayGetCount(builder->candidatePaths)) { SecCertificatePathRef path = (SecCertificatePathRef) CFArrayGetValueAtIndex(builder->candidatePaths, 0); CFArrayRemoveValueAtIndex(builder->candidatePaths, 0); secdebug("trust", "SecPathBuilderGetNext returning candidate %@", path); SecPVCSetPath(&builder->path, path, NULL); builder->state = SecPathBuilderValidatePath; return true; } /* If we are considering rejected chains we check each rejected path with SecPathBuilderIsPartial() which checks the signature chain and either drops the path if it's not properly signed, add it as a candidate if it has a trusted anchor, or adds it as a partial to be considered once we finish considering all the rejects. */ if (builder->considerRejected) { CFIndex rejectedIX = CFArrayGetCount(builder->rejectedPaths); if (rejectedIX) { rejectedIX--; SecCertificatePathRef path = (SecCertificatePathRef) CFArrayGetValueAtIndex(builder->rejectedPaths, rejectedIX); if (SecPathBuilderIsPartial(builder, path)) { CFArrayInsertValueAtIndex(builder->partialPaths, ++builder->partialIX, path); } CFArrayRemoveValueAtIndex(builder->rejectedPaths, rejectedIX); /* Keep going until we have moved all rejected partials into the regular partials or candidates array. */ return true; } } /* If builder->partialIX is < 0 we have considered all partial chains this block must ensure partialIX >= 0 if execution continues past it's end. */ if (builder->partialIX < 0) { CFIndex num_sources = CFArrayGetCount(builder->parentSources); if (builder->nextParentSource < num_sources) { builder->nextParentSource++; secdebug("trust", "broading search to %d/%d sources", builder->nextParentSource, num_sources); } else { /* We've run out of new sources to consider so let's look at rejected chains and after that even consider partials directly. FIXME we might not want to consider partial paths that are subsets of other partial paths, or not consider them at all if we already have an anchored reject. */ if (!builder->considerRejected) { builder->considerRejected = true; secdebug("trust", "considering rejected paths"); } else if (!builder->considerPartials) { builder->considerPartials = true; secdebug("trust", "considering partials"); } else { /* We're all out of options, so we can't produce any more candidates. Let's calculate details and return the best path we found. */ builder->state = SecPathBuilderComputeDetails; return true; } } builder->partialIX = CFArrayGetCount(builder->partialPaths) - 1; secdebug("trust", "re-checking %d partials", builder->partialIX + 1); return true; } /* We know builder->partialIX >= 0 if we get here. */ SecCertificatePathRef partial = (SecCertificatePathRef) CFArrayGetValueAtIndex(builder->partialPaths, builder->partialIX); /* Don't try to extend partials anymore once we are in the considerPartials state, since at this point every partial has been extended with every possible parentSource already. */ if (builder->considerPartials) { --builder->partialIX; SecPVCSetPath(&builder->path, partial, NULL); builder->state = SecPathBuilderValidatePath; return true; } /* Attempt to extend this partial path with another certificate. This should give us a list of potential parents to consider. */ secdebug("trust", "looking for parents of partial %d/%d: %@", builder->partialIX + 1, CFArrayGetCount(builder->partialPaths), partial); /* Attempt to extend partial, leaving all possible extended versions of partial in builder->extendedPaths. */ CFIndex sourceIX = SecCertificatePathGetNextSourceIndex(partial); CFIndex num_anchor_sources = CFArrayGetCount(builder->anchorSources); if (sourceIX < num_anchor_sources + builder->nextParentSource) { SecCertificateSourceRef source; if (sourceIX < num_anchor_sources) { source = (SecCertificateSourceRef) CFArrayGetValueAtIndex(builder->anchorSources, sourceIX); secdebug("trust", "searching anchor source %d/%d", sourceIX + 1, num_anchor_sources); } else { CFIndex parentIX = sourceIX - num_anchor_sources; source = (SecCertificateSourceRef) CFArrayGetValueAtIndex(builder->parentSources, parentIX); secdebug("trust", "searching parent source %d/%d", parentIX + 1, builder->nextParentSource); } SecCertificatePathSetNextSourceIndex(partial, sourceIX + 1); SecCertificateRef root = SecCertificatePathGetRoot(partial); return SecCertificateSourceCopyParents(source, root, builder, SecPathBuilderExtendPaths); } else { --builder->partialIX; } return true; }
static void _serviceOrder_add(SCNetworkSetRef set, SCNetworkServiceRef service) { CFIndex i; CFIndex n; CFMutableArrayRef newOrder; CFArrayRef order; CFStringRef serviceID; CFIndex serviceOrder; SCNetworkSetPrivateRef setPrivate = (SCNetworkSetPrivateRef)set; CFIndex slot; order = SCNetworkSetGetServiceOrder(set); if (order != NULL) { newOrder = CFArrayCreateMutableCopy(NULL, 0, order); } else { newOrder = CFArrayCreateMutable(NULL, 0, &kCFTypeArrayCallBacks); } assert(newOrder != NULL); n = CFArrayGetCount(newOrder); serviceID = SCNetworkServiceGetServiceID(service); if (CFArrayContainsValue(newOrder, CFRangeMake(0, n), serviceID)) { // if serviceID already present goto done; } serviceOrder = _serviceOrder(service); slot = 0; for (i = 0; i < n; i++) { int slotOrder; SCNetworkServiceRef slotService; CFStringRef slotServiceID; slotServiceID = CFArrayGetValueAtIndex(newOrder, i); if (!isA_CFString(slotServiceID)) { // if bad prefs continue; } slotService = SCNetworkServiceCopy(setPrivate->prefs, slotServiceID); if (slotService == NULL) { // if serviceID not valid continue; } slotOrder = _serviceOrder(slotService); if (serviceOrder >= slotOrder) { // add the service *after* this one slot = i + 1; } CFRelease(slotService); } CFArrayInsertValueAtIndex(newOrder, slot, serviceID); (void) SCNetworkSetSetServiceOrder(set, newOrder); done : CFRelease(newOrder); return; }
static void get_osx_device_elements(JoystickImpl *device, int axis_map[8]) { IOHIDElementRef tIOHIDElementRef; CFArrayRef gElementCFArrayRef; DWORD axes = 0; DWORD sliders = 0; DWORD buttons = 0; DWORD povs = 0; device->elementCFArrayRef = NULL; if (!gCollections) return; tIOHIDElementRef = (IOHIDElementRef)CFArrayGetValueAtIndex(gCollections, device->id); if (!tIOHIDElementRef) return; gElementCFArrayRef = CFArrayCreateMutable(kCFAllocatorDefault, 0, &kCFTypeArrayCallBacks); get_element_children(tIOHIDElementRef, gElementCFArrayRef); if (gElementCFArrayRef) { CFIndex idx, cnt = CFArrayGetCount( gElementCFArrayRef ); /* build our element array in the order that dinput expects */ device->elementCFArrayRef = CFArrayCreateMutable(NULL,0,NULL); for ( idx = 0; idx < cnt; idx++ ) { IOHIDElementRef tIOHIDElementRef = ( IOHIDElementRef ) CFArrayGetValueAtIndex( gElementCFArrayRef, idx ); int eleType = IOHIDElementGetType( tIOHIDElementRef ); switch(eleType) { case kIOHIDElementTypeInput_Button: { int usagePage = IOHIDElementGetUsagePage( tIOHIDElementRef ); if (usagePage != kHIDPage_Button) { /* avoid strange elements found on the 360 controller */ continue; } if (buttons < 128) { CFArrayInsertValueAtIndex(device->elementCFArrayRef, (axes+povs+buttons), tIOHIDElementRef); buttons++; } break; } case kIOHIDElementTypeInput_Axis: { CFArrayInsertValueAtIndex(device->elementCFArrayRef, axes, tIOHIDElementRef); axes++; break; } case kIOHIDElementTypeInput_Misc: { uint32_t usage = IOHIDElementGetUsage( tIOHIDElementRef ); switch(usage) { case kHIDUsage_GD_Hatswitch: { CFArrayInsertValueAtIndex(device->elementCFArrayRef, (axes+povs), tIOHIDElementRef); povs++; break; } case kHIDUsage_GD_Slider: sliders ++; if (sliders > 2) break; /* fallthrough, sliders are axis */ case kHIDUsage_GD_X: case kHIDUsage_GD_Y: case kHIDUsage_GD_Z: case kHIDUsage_GD_Rx: case kHIDUsage_GD_Ry: case kHIDUsage_GD_Rz: { CFArrayInsertValueAtIndex(device->elementCFArrayRef, axes, tIOHIDElementRef); axis_map[axes]=usage; axes++; break; } default: FIXME("Unhandled usage %i\n",usage); } break; } default: FIXME("Unhandled type %i\n",eleType); } } } device->generic.devcaps.dwAxes = axes; device->generic.devcaps.dwButtons = buttons; device->generic.devcaps.dwPOVs = povs; /* Sort buttons into correct order */ for (buttons = 0; buttons < device->generic.devcaps.dwButtons; buttons++) { IOHIDElementRef tIOHIDElementRef = ( IOHIDElementRef ) CFArrayGetValueAtIndex( device->elementCFArrayRef, axes+povs+buttons); uint32_t usage = IOHIDElementGetUsage( tIOHIDElementRef ); usage --; /* usage is 1 indexed we need 0 indexed */ if (usage == buttons) continue; insert_sort_button(axes+povs, tIOHIDElementRef, device->elementCFArrayRef,buttons,usage); } }
__private_extern__ void set_service(int argc, char **argv) { Boolean ok; if (net_service == NULL) { SCPrint(TRUE, stdout, CFSTR("service not selected\n")); return; } if (argc < 1) { SCPrint(TRUE, stdout, CFSTR("set what?\n")); return; } while (argc > 0) { char *command; command = argv[0]; argv++; argc--; if (strcmp(command, "name") == 0) { CFStringRef serviceName; if (argc < 1) { SCPrint(TRUE, stdout, CFSTR("name not specified\n")); return; } serviceName = (strlen(argv[0]) > 0) ? CFStringCreateWithCString(NULL, argv[0], kCFStringEncodingUTF8) : NULL; argv++; argc--; ok = SCNetworkServiceSetName(net_service, serviceName); if (serviceName != NULL) CFRelease(serviceName); if (!ok) { SCPrint(TRUE, stdout, CFSTR("%s\n"), SCErrorString(SCError())); return; } _prefs_changed = TRUE; } else if (strcmp(command, "order") == 0) { char *end; long newIndex; CFIndex nServices; char *str; CFArrayRef services; services = SCNetworkSetCopyServices(net_set); nServices = CFArrayGetCount(services); CFRelease(services); if (argc < 1) { SCPrint(TRUE, stdout, CFSTR("order not specified\n")); return; } if (net_set == NULL) { SCPrint(TRUE, stdout, CFSTR("set not selected\n")); return; } str = argv[0]; argv++; argc--; errno = 0; newIndex = strtol(str, &end, 10); if ((*str != '\0') && (*end == '\0') && (errno == 0)) { if ((newIndex > 0) && (newIndex <= nServices)) { CFIndex curIndex; CFMutableArrayRef newOrder; CFArrayRef order; CFStringRef serviceID = SCNetworkServiceGetServiceID(net_service); order = SCNetworkSetGetServiceOrder(net_set); if (order == NULL) { newOrder = CFArrayCreateMutable(NULL, 0, &kCFTypeArrayCallBacks); } else { newOrder = CFArrayCreateMutableCopy(NULL, 0, order); } curIndex = CFArrayGetFirstIndexOfValue(newOrder, CFRangeMake(0, CFArrayGetCount(newOrder)), serviceID); if (curIndex != kCFNotFound) { CFArrayRemoveValueAtIndex(newOrder, curIndex); } if (newIndex <= CFArrayGetCount(newOrder)) { CFArrayInsertValueAtIndex(newOrder, newIndex - 1, serviceID); } else { CFArrayAppendValue(newOrder, serviceID); } ok = SCNetworkSetSetServiceOrder(net_set, newOrder); CFRelease(newOrder); if (!ok) { SCPrint(TRUE, stdout, CFSTR("%s\n"), SCErrorString(SCError())); return; } _prefs_changed = TRUE; } else { SCPrint(TRUE, stdout, CFSTR("set order to what?\n")); return; } } else { SCPrint(TRUE, stdout, CFSTR("set what?\n")); return; } } else if (strcmp(command, "rank") == 0) { SCNetworkServicePrimaryRank rank = kSCNetworkServicePrimaryRankDefault; SCNetworkServiceRef service = (argc < 2) ? net_service : NULL; if (argc < 1) { SCPrint(TRUE, stdout, CFSTR("rank not specified\n")); return; } if (strlen(argv[0]) > 0) { if (strcasecmp(argv[0], "Never") == 0) { rank = kSCNetworkServicePrimaryRankNever; } else if ((service != net_service) && (strcasecmp(argv[0], "First") == 0)) { rank = kSCNetworkServicePrimaryRankFirst; } else if ((service != net_service) && (strcasecmp(argv[0], "Last") == 0)) { rank = kSCNetworkServicePrimaryRankLast; } else if ((service != net_service) && (strcasecmp(argv[0], "Scoped") == 0)) { rank = kSCNetworkServicePrimaryRankScoped; } else { SCPrint(TRUE, stdout, CFSTR("rank not valid\n")); return; } } argv++; argc--; if (service == NULL) { CFStringRef serviceID; SCDynamicStoreRef store; store = SCDynamicStoreCreate(NULL, CFSTR("scutil (set primary rank)"), NULL, NULL); serviceID = SCNetworkServiceGetServiceID(net_service); service = _SCNetworkServiceCopyActive(store, serviceID); CFRelease(store); argv++; argc--; } ok = SCNetworkServiceSetPrimaryRank(service, rank); if (service != net_service) CFRelease(service); if (ok) { if (service == net_service) _prefs_changed = TRUE; } else { SCPrint(TRUE, stdout, CFSTR("%s\n"), SCErrorString(SCError())); return; } } else if (strcmp(command, "id") == 0) { CFStringRef serviceID; if ((argc < 1) || (strlen(argv[0]) == 0)) { SCPrint(TRUE, stdout, CFSTR("set id not specified\n")); return; } serviceID = CFStringCreateWithCString(NULL, argv[0], kCFStringEncodingUTF8); argv++; argc--; ok = _SCNetworkServiceSetServiceID(net_service, serviceID); CFRelease(serviceID); if (!ok) { SCPrint(TRUE, stdout, CFSTR("%s\n"), SCErrorString(SCError())); return; } _prefs_changed = TRUE; } else { SCPrint(TRUE, stdout, CFSTR("set what?\n")); } } return; }
bool CAuthAuthority::SetValueDisabledForTag( const char *inTagStr ) { bool theResult = false; CFMutableArrayRef dataArray = NULL; CFStringRef tagString = NULL; CFMutableDictionaryRef aaDict = this->GetValueForTagAsCFDict( inTagStr ); if ( aaDict != NULL ) { dataArray = (CFMutableArrayRef) CFDictionaryGetValue( aaDict, CFSTR("data") ); if ( dataArray == NULL ) { dataArray = CFArrayCreateMutable( kCFAllocatorDefault, 0, &kCFTypeArrayCallBacks ); if ( dataArray == NULL ) return false; CFDictionaryAddValue( aaDict, CFSTR("data"), dataArray ); CFRelease( dataArray ); } // Insert the current tag into the data array tagString = (CFStringRef) CFDictionaryGetValue( aaDict, CFSTR("tag") ); CFArrayInsertValueAtIndex( dataArray, 0, tagString ); CFArrayInsertValueAtIndex( dataArray, 0, CFSTR("") ); // replace the primary tag CFDictionarySetValue( aaDict, CFSTR("tag"), CFSTR(kDSTagAuthAuthorityDisabledUser) ); theResult = true; } else { aaDict = this->GetValueForTagAsCFDict( kDSTagAuthAuthorityDisabledUser ); if ( aaDict != NULL ) { // There's already a disabled Auth Authority, so check the first // data item to see if it's a match for the tag CFStringRef searchTagValueString = CFStringCreateWithCString( kCFAllocatorDefault, inTagStr, kCFStringEncodingUTF8 ); if ( searchTagValueString != NULL ) { dataArray = (CFMutableArrayRef) CFDictionaryGetValue( aaDict, CFSTR("data") ); if ( dataArray != NULL ) { tagString = (CFStringRef) CFArrayGetValueAtIndex( dataArray, 0 ); if ( tagString != NULL && CFStringCompare(searchTagValueString, tagString, kCFCompareCaseInsensitive) == kCFCompareEqualTo ) { // already disabled theResult = true; } } CFRelease( searchTagValueString ); } } // if not disabled yet, disable if ( theResult == false ) { char disabledAAStr[256] = {0}; snprintf( disabledAAStr, sizeof(disabledAAStr), "%s;%s;", kDSValueAuthAuthorityDisabledUser, inTagStr ); theResult = this->AddValue( disabledAAStr ); } } return theResult; }
void VectorCommand::SInsertCommandAtIndex( IOFireWireLibVectorCommandRef self, IOFireWireLibCommandRef command, UInt32 index ) { VectorCommand * me = IOFireWireIUnknown::InterfaceMap<VectorCommand>::GetThis(self); CFArrayInsertValueAtIndex( me->mCommandArray, index, command ); }
void configSet(CFMutableArrayRef config, CFStringRef key, CFStringRef value) { CFMutableStringRef pref; CFIndex configLen = CFArrayGetCount(config); CFIndex i; CFIndex n; CFMutableStringRef newValue; CFRange range; CFStringRef specialChars = CFSTR(" \"'$!|\\<>`{}[]"); boolean_t mustQuote = FALSE; /* create search prefix */ pref = CFStringCreateMutableCopy(NULL, 0, key); CFStringAppend(pref, CFSTR("=")); /* * create new / replacement value * * Note: Since the configuration file may be processed by a * shell script we need to ensure that, if needed, the * string is properly quoted. */ newValue = CFStringCreateMutableCopy(NULL, 0, value); n = CFStringGetLength(specialChars); for (i = 0; i < n; i++) { CFStringRef specialChar; specialChar = CFStringCreateWithSubstring(NULL, specialChars, CFRangeMake(i, 1)); range = CFStringFind(newValue, specialChar, 0); CFRelease(specialChar); if (range.location != kCFNotFound) { /* this string has at least one special character */ mustQuote = TRUE; break; } } if (mustQuote) { CFStringRef charsToQuote = CFSTR("\\\"$`"); /* * in addition to quoting the entire string we also need to escape the * space " " and backslash "\" characters */ n = CFStringGetLength(charsToQuote); for (i = 0; i < n; i++) { CFStringRef quoteChar; CFArrayRef matches; quoteChar = CFStringCreateWithSubstring(NULL, charsToQuote, CFRangeMake(i, 1)); range = CFRangeMake(0, CFStringGetLength(newValue)); matches = CFStringCreateArrayWithFindResults(NULL, newValue, quoteChar, range, 0); CFRelease(quoteChar); if (matches) { CFIndex j = CFArrayGetCount(matches); while (--j >= 0) { const CFRange *range; range = CFArrayGetValueAtIndex(matches, j); CFStringInsert(newValue, range->location, CFSTR("\\")); } CFRelease(matches); } } CFStringInsert(newValue, 0, CFSTR("\"")); CFStringAppend(newValue, CFSTR("\"")); } /* locate existing key */ for (i = 0; i < configLen; i++) { if (CFStringHasPrefix(CFArrayGetValueAtIndex(config, i), pref)) { break; } } CFStringAppend(pref, newValue); CFRelease(newValue); if (i < configLen) { /* if replacing an existing entry */ CFArraySetValueAtIndex(config, i, pref); } else { /* * if new entry, insert it just prior to the last (emtpy) * array element. */ CFArrayInsertValueAtIndex(config, configLen-1, pref); } CFRelease(pref); return; }
/** * Insert a new item at position n in a #PLIST_ARRAY node. * * @param node the node of type #PLIST_ARRAY * @param item the new item to insert * @param n The position at which the node will be stored. Range is [0, array_size[. Assert if n is not in range. */ void plist_array_insert_item(plist_t node, plist_t item, uint32_t n) { CFArrayInsertValueAtIndex((CFMutableArrayRef) node, n, item); CFRelease(item); }
// Resolve a path and append it to the CLI settings structure // The FSEvents API will, internally, resolve paths using a similar scheme. // Performing this ahead of time makes things less confusing, IMHO. static void append_path(const char* path) { #ifdef DEBUG fprintf(stderr, "\n"); fprintf(stderr, "append_path called for: %s\n", path); #endif #if MAC_OS_X_VERSION_MIN_REQUIRED >= 1060 #ifdef DEBUG fprintf(stderr, "compiled against 10.6+, using CFURLCreateFileReferenceURL\n"); #endif CFURLRef url = CFURLCreateFromFileSystemRepresentation(NULL, (const UInt8*)path, (CFIndex)strlen(path), false); CFURLRef placeholder = CFURLCopyAbsoluteURL(url); CFRelease(url); CFMutableArrayRef imaginary = NULL; // if we don't have an existing url, spin until we get to a parent that // does exist, saving any imaginary components for appending back later while(!CFURLResourceIsReachable(placeholder, NULL)) { #ifdef DEBUG fprintf(stderr, "path does not exist\n"); #endif CFStringRef child; if (imaginary == NULL) { imaginary = CFArrayCreateMutable(NULL, 0, &kCFTypeArrayCallBacks); } child = CFURLCopyLastPathComponent(placeholder); CFArrayInsertValueAtIndex(imaginary, 0, child); CFRelease(child); url = CFURLCreateCopyDeletingLastPathComponent(NULL, placeholder); CFRelease(placeholder); placeholder = url; #ifdef DEBUG fprintf(stderr, "parent: "); CFShow(placeholder); #endif } #ifdef DEBUG fprintf(stderr, "path exists\n"); #endif // realpath() doesn't always return the correct case for a path, so this // is a funky workaround that converts a path into a (volId/inodeId) pair // and asks what the path should be for that. since it looks at the actual // inode instead of returning the same case passed in like realpath() // appears to do for HFS+, it should always be correct. url = CFURLCreateFileReferenceURL(NULL, placeholder, NULL); CFRelease(placeholder); placeholder = CFURLCreateFilePathURL(NULL, url, NULL); CFRelease(url); #ifdef DEBUG fprintf(stderr, "path resolved to: "); CFShow(placeholder); #endif // if we stripped off any imaginary path components, append them back on if (imaginary != NULL) { CFIndex count = CFArrayGetCount(imaginary); for (CFIndex i = 0; i<count; i++) { CFStringRef component = CFArrayGetValueAtIndex(imaginary, i); #ifdef DEBUG fprintf(stderr, "appending component: "); CFShow(component); #endif url = CFURLCreateCopyAppendingPathComponent(NULL, placeholder, component, false); CFRelease(placeholder); placeholder = url; } CFRelease(imaginary); } #ifdef DEBUG fprintf(stderr, "result: "); CFShow(placeholder); #endif CFStringRef cfPath = CFURLCopyFileSystemPath(placeholder, kCFURLPOSIXPathStyle); CFArrayAppendValue(config.paths, cfPath); CFRelease(cfPath); CFRelease(placeholder); #else #ifdef DEBUG fprintf(stderr, "compiled against 10.5, using realpath()\n"); #endif char fullPath[PATH_MAX + 1]; if (realpath(path, fullPath) == NULL) { #ifdef DEBUG fprintf(stderr, " realpath not directly resolvable from path\n"); #endif if (path[0] != '/') { #ifdef DEBUG fprintf(stderr, " passed path is not absolute\n"); #endif size_t len; getcwd(fullPath, sizeof(fullPath)); #ifdef DEBUG fprintf(stderr, " result of getcwd: %s\n", fullPath); #endif len = strlen(fullPath); fullPath[len] = '/'; strlcpy(&fullPath[len + 1], path, sizeof(fullPath) - (len + 1)); } else { #ifdef DEBUG fprintf(stderr, " assuming path does not YET exist\n"); #endif strlcpy(fullPath, path, sizeof(fullPath)); } } #ifdef DEBUG fprintf(stderr, " resolved path to: %s\n", fullPath); fprintf(stderr, "\n"); #endif CFStringRef pathRef = CFStringCreateWithCString(kCFAllocatorDefault, fullPath, kCFStringEncodingUTF8); CFArrayAppendValue(config.paths, pathRef); CFRelease(pathRef); #endif }
kim_error kim_os_selection_hints_remember_identity (kim_selection_hints in_selection_hints, kim_identity in_identity) { kim_error err = KIM_NO_ERROR; CFArrayRef old_hints_array = NULL; CFMutableArrayRef new_hints_array = NULL; CFIndex count = 0; CFIndex i = 0; kim_boolean hint_already_exists = 0; kim_boolean hints_array_changed = 0; if (!err && !in_selection_hints) { err = check_error (KIM_NULL_PARAMETER_ERR); } if (!err && !in_identity ) { err = check_error (KIM_NULL_PARAMETER_ERR); } if (!err) { err = kim_os_selection_hints_get_selection_hints_array (&old_hints_array); } if (!err) { if (old_hints_array) { new_hints_array = CFArrayCreateMutableCopy (kCFAllocatorDefault, 0, old_hints_array); } else { new_hints_array = CFArrayCreateMutable (kCFAllocatorDefault, 0, &kCFTypeArrayCallBacks); } if (!new_hints_array) { err = KIM_OUT_OF_MEMORY_ERR; } } if (!err) { count = CFArrayGetCount (new_hints_array); } for (i = 0; !err && i < count; i++) { CFDictionaryRef dictionary = NULL; kim_identity identity = NULL; kim_boolean hints_equal = 0; dictionary = CFArrayGetValueAtIndex (new_hints_array, i); if (!dictionary) { err = KIM_OUT_OF_MEMORY_ERR; } if (!err && CFGetTypeID (dictionary) != CFDictionaryGetTypeID ()) { kim_debug_printf ("%s: Malformed entry in hints array.", __FUNCTION__); continue; /* skip entries which aren't dictionaries */ } if (!err) { err = kim_os_selection_hints_compare_to_dictionary (in_selection_hints, dictionary, &hints_equal); } if (!err && hints_equal) { kim_comparison comparison; err = kim_os_selection_hints_get_dictionary_identity (dictionary, &identity); if (!err) { err = kim_identity_compare (in_identity, identity, &comparison); } if (!err) { if (kim_comparison_is_equal_to (comparison) && !hint_already_exists) { hint_already_exists = 1; } else { CFArrayRemoveValueAtIndex (new_hints_array, i); i--; /* back up one index so we don't skip */ count = CFArrayGetCount (new_hints_array); /* count changed */ hints_array_changed = 1; } } kim_identity_free (&identity); } } if (!err && !hint_already_exists) { CFDictionaryRef new_hint_dictionary = NULL; err = kim_os_selection_hints_create_dictionary (in_selection_hints, in_identity, &new_hint_dictionary); if (!err) { CFArrayInsertValueAtIndex (new_hints_array, 0, new_hint_dictionary); hints_array_changed = 1; } if (new_hint_dictionary) { CFRelease (new_hint_dictionary); } } if (!err && hints_array_changed) { err = kim_os_selection_hints_set_selection_hints_array (new_hints_array); } if (new_hints_array ) { CFRelease (new_hints_array); } if (old_hints_array ) { CFRelease (old_hints_array); } return check_error (err); }
void _CFApplicationPreferencesAddSuitePreferences(_CFApplicationPreferences *appPrefs, CFStringRef suiteName) { CFPreferencesDomainRef domain; CFIndex idx; CFRange range; // Find where to insert the new suite __CFSpinLock(&__CFApplicationPreferencesLock); domain = _CFPreferencesStandardDomain(appPrefs->_appName, kCFPreferencesCurrentUser, kCFPreferencesAnyHost); range.location = 0; range.length = CFArrayGetCount(appPrefs->_search); idx = domain ? CFArrayGetFirstIndexOfValue(appPrefs->_search, range, domain) : kCFNotFound; __CFSpinUnlock(&__CFApplicationPreferencesLock); idx ++; // We want just below the app domain. Coincidentally, this gives us the top of the list if the app domain has been removed. domain = _CFPreferencesStandardDomain(suiteName, kCFPreferencesCurrentUser, kCFPreferencesAnyHost); if (domain) { __CFSpinLock(&__CFApplicationPreferencesLock); CFArrayInsertValueAtIndex(appPrefs->_search, idx, domain); __CFSpinUnlock(&__CFApplicationPreferencesLock); range.length ++; } domain = _CFPreferencesStandardDomain(suiteName, kCFPreferencesCurrentUser, kCFPreferencesCurrentHost); if (domain) { __CFSpinLock(&__CFApplicationPreferencesLock); CFArrayInsertValueAtIndex(appPrefs->_search, idx, domain); __CFSpinUnlock(&__CFApplicationPreferencesLock); range.length ++; } // Now the AnyUser domains domain = _CFPreferencesStandardDomain(appPrefs->_appName, kCFPreferencesAnyUser, kCFPreferencesAnyHost); idx = domain ? CFArrayGetFirstIndexOfValue(appPrefs->_search, range, domain) : kCFNotFound; if (idx == kCFNotFound) { // Someone blew away the app domain. For the any user case, we look for right below the global domain domain = _CFPreferencesStandardDomain(kCFPreferencesAnyApplication, kCFPreferencesCurrentUser, kCFPreferencesAnyHost); idx = domain ? CFArrayGetFirstIndexOfValue(appPrefs->_search, range, domain) : kCFNotFound; if (idx == kCFNotFound) { // Try the "any host" choice domain = _CFPreferencesStandardDomain(kCFPreferencesAnyApplication, kCFPreferencesCurrentUser, kCFPreferencesCurrentHost); idx = domain ? CFArrayGetFirstIndexOfValue(appPrefs->_search, range, domain) : kCFNotFound; if (idx == kCFNotFound) { // We give up; put the new domains at the bottom idx = CFArrayGetCount(appPrefs->_search) - 1; } } } idx ++; domain = _CFPreferencesStandardDomain(suiteName, kCFPreferencesAnyUser, kCFPreferencesAnyHost); if (domain) { __CFSpinLock(&__CFApplicationPreferencesLock); CFArrayInsertValueAtIndex(appPrefs->_search, idx, domain); __CFSpinUnlock(&__CFApplicationPreferencesLock); } domain = _CFPreferencesStandardDomain(suiteName, kCFPreferencesAnyUser, kCFPreferencesCurrentHost); if (domain) { __CFSpinLock(&__CFApplicationPreferencesLock); CFArrayInsertValueAtIndex(appPrefs->_search, idx, domain); __CFSpinUnlock(&__CFApplicationPreferencesLock); } __CFSpinLock(&__CFApplicationPreferencesLock); updateDictRep(appPrefs); __CFSpinUnlock(&__CFApplicationPreferencesLock); }
int main(int argc, const char * argv[]) { SInt32 errorCode; CFArrayRef pArraySrcVID; //array of Vendor ID's in the source plist (plist to copy from) CFArrayRef pArrayDestVID; //array of Vendor ID's in the destination plist (plist to copy to) CFMutableArrayRef pArrayNewVID;//new array of Vendor ID's containing the merge of source and destination CFArrayRef pArraySrcPID; //array of Product ID's in the source plist (plist to copy from) CFArrayRef pArrayDestPID; //array of Product ID's in the destination plist (plist to copy to) CFMutableArrayRef pArrayNewPID; //new array of Product ID's containing the merge of source and destination CFArrayRef pArraySrcFN; //array of Friendly names in the source plist (plist to copy from) CFArrayRef pArrayDestFN; //array of Friendly names in the destination plist (plist to copy to) CFMutableArrayRef pArrayNewFN; //new array of Friendly names containing the merge of source and destination //the new Dictionary has been added by the installer //the original one will be checked against the new one, to see if all old devices are still present in the list CFDictionaryRef pDictDestOrg = CreateDictionaryFromPlist(CFSTR("./Info_org.plist"), &errorCode); //CreateDictionaryFromPlist(CFSTR("/usr/libexec/SmartCardServices/drivers/ifd-ccid.bundle/Contents/Info.plist"), &errorCode); CFMutableDictionaryRef pDictDest = CFDictionaryCreateMutableCopy(kCFAllocatorDefault, 0, pDictDestOrg); CFDictionaryRef pDictSrc = CreateDictionaryFromPlist(CFSTR("./Info.plist"), &errorCode); if( (pDictSrc != NULL) && (pDictDest != NULL) ) { //get the 3 arrays per library that we need to search into //we create mutable copies for the destination arrays, as they might need to be expanded Boolean bArrayPresent = false; Boolean bAllArraysPresent = false; bArrayPresent = CFDictionaryGetValueIfPresent (pDictDest,CFSTR("ifdVendorID"),(const void **)&pArrayDestVID); if (bArrayPresent) { //create a mutable (changeable) copy pArrayNewVID = CFArrayCreateMutableCopy(kCFAllocatorDefault, 0, pArrayDestVID); bArrayPresent = CFDictionaryGetValueIfPresent (pDictSrc,CFSTR("ifdVendorID"),(const void **)&pArraySrcVID); if (bArrayPresent) { bArrayPresent = CFDictionaryGetValueIfPresent (pDictDest,CFSTR("ifdProductID"),(const void **)&pArrayDestPID); if (bArrayPresent) { pArrayNewPID = CFArrayCreateMutableCopy(kCFAllocatorDefault, 0, pArrayDestPID); bArrayPresent = CFDictionaryGetValueIfPresent (pDictSrc,CFSTR("ifdProductID"),(const void **)&pArraySrcPID); if (bArrayPresent) { bArrayPresent = CFDictionaryGetValueIfPresent (pDictDest,CFSTR("ifdFriendlyName"),(const void **)&pArrayDestFN); if (bArrayPresent) { pArrayNewFN = CFArrayCreateMutableCopy(kCFAllocatorDefault, 0, pArrayDestFN); bArrayPresent = CFDictionaryGetValueIfPresent (pDictSrc,CFSTR("ifdFriendlyName"),(const void **)&pArraySrcFN); if (bArrayPresent) { bAllArraysPresent = true; } } } } } } if (!bAllArraysPresent) { CFShow(CFSTR("Cannot merge\nNot all arrays are present in the plists\n")); return 0; } CFIndex indexSrcTotalCount = CFArrayGetCount (pArraySrcVID); CFIndex indexDestTotalCount = CFArrayGetCount (pArrayDestVID); //go through the array of the source plist, and add entries that are missing in the dest array CFIndex index = 0; Boolean bEntryFound; Boolean bStopSearch; CFRange range; CFStringRef pStringSrcVID; CFStringRef pStringSrcPID; CFStringRef pStringSrcFN; CFStringRef pStringTemp; for (index = 0; index < indexSrcTotalCount; index++) { pStringSrcVID = CFArrayGetValueAtIndex (pArraySrcVID, index); pStringSrcPID = CFArrayGetValueAtIndex (pArraySrcPID, index); pStringSrcFN = CFArrayGetValueAtIndex (pArraySrcFN, index); bStopSearch = false; bEntryFound = false; range.location = 0; range.length = indexDestTotalCount; pStringSrcVID = CFArrayGetValueAtIndex (pArraySrcVID, index); CFIndex found = CFArrayGetFirstIndexOfValue (pArrayDestVID,range,pStringSrcVID); while ((found != -1)&&(!bStopSearch)) { //We found a match for VID's at Destination index 'found' //Now check if at that index, the PID's also match pStringTemp = CFArrayGetValueAtIndex (pArrayDestPID,found); if (kCFCompareEqualTo == CFStringCompare(pStringTemp, pStringSrcPID, kCFCompareCaseInsensitive)) { //the PID's also match at Destination index 'found' //Now check if Friendly names also match pStringTemp = CFArrayGetValueAtIndex (pArrayDestFN,found); if (kCFCompareEqualTo == CFStringCompare(pStringTemp, pStringSrcFN, kCFCompareCaseInsensitive)) { bEntryFound = true; bStopSearch = true; } } if(bEntryFound == false) { //search if the VID is also present further down the array if ((found+1) < indexDestTotalCount) { range.length = indexDestTotalCount - (found+1); range.location = found+1; found = CFArrayGetFirstIndexOfValue (pArrayDestVID,range,pStringSrcVID); } else { bStopSearch = true; } } } //the destination plist has been searched for the entry at 'index' of the source plist if(bEntryFound == false) { range.location = 0; range.length = CFArrayGetCount (pArrayNewVID); CFIndex vIDFound = CFArrayGetFirstIndexOfValue (pArrayNewVID,range,pStringSrcVID); //if the entry was not found, we add it to the destination arrays now //add it up front in the subarray with the same vendorID's if the vendorid was already present //If its a new vendorid, add it to the back of the arrays if(vIDFound != -1) { CFArrayInsertValueAtIndex (pArrayNewVID, vIDFound,pStringSrcVID); CFArrayInsertValueAtIndex (pArrayNewPID, vIDFound,pStringSrcPID); CFArrayInsertValueAtIndex (pArrayNewFN, vIDFound,pStringSrcFN); } else { CFArrayAppendValue(pArrayNewVID, pStringSrcVID); CFArrayAppendValue(pArrayNewPID, pStringSrcPID); CFArrayAppendValue(pArrayNewFN, pStringSrcFN); } } }//end of for (entire plist searched) //now put the merged arrays into the destination dictionary CFDictionaryReplaceValue (pDictDest,CFSTR("ifdVendorID"),pArrayNewVID); CFDictionaryReplaceValue (pDictDest,CFSTR("ifdProductID"),pArrayNewPID); CFDictionaryReplaceValue (pDictDest,CFSTR("ifdFriendlyName"),pArrayNewFN); //write changes into the new plist StoreDictionaryInPlist(pDictDest, CFSTR("./Info_merged.plist"), &errorCode); //release all created variables CFRelease(pDictDest); } CFShow(CFSTR("Merge completed\n")); return 0; }
__private_extern__ kern_return_t _io_pm_hid_event_report_activity( mach_port_t server, audit_token_t token, int _action) { pid_t callerPID; CFNumberRef appPID = NULL; int _app_pid_; CFMutableDictionaryRef foundDictionary = NULL; CFMutableArrayRef bucketsArray = NULL; CFDataRef dataEvent = NULL; IOPMHIDPostEventActivityWindow *ev = NULL; CFAbsoluteTime timeNow = CFAbsoluteTimeGetCurrent(); int arrayCount = 0; int i = 0; // Unwrapping big data structure... if (!gHIDEventHistory) { gHIDEventHistory = CFArrayCreateMutable(0, 1, &kCFTypeArrayCallBacks); } if (!gHIDEventHistory) { goto exit; } audit_token_to_au32(token, NULL, NULL, NULL, NULL, NULL, &callerPID, NULL, NULL); if (0 !=(arrayCount = CFArrayGetCount(gHIDEventHistory))) { // Scan through the array to find an existing dictionary for the given pid for (i=0; i<arrayCount; i++) { CFMutableDictionaryRef dictionaryForApp = NULL; dictionaryForApp = (CFMutableDictionaryRef)CFArrayGetValueAtIndex(gHIDEventHistory, i); if (!dictionaryForApp) { break; } appPID = CFDictionaryGetValue(dictionaryForApp, kIOPMHIDAppPIDKey); if (appPID) { CFNumberGetValue(appPID, kCFNumberIntType, &_app_pid_); if (callerPID == _app_pid_) { foundDictionary = dictionaryForApp; break; } } } } // Unwrapping big data structure... if (!foundDictionary) { foundDictionary = CFDictionaryCreateMutable(0, 3, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); CFArrayAppendValue(gHIDEventHistory, foundDictionary); CFRelease(foundDictionary); /* Tag our pid */ appPID = CFNumberCreate(0, kCFNumberIntType, &callerPID); if (appPID) { CFDictionarySetValue(foundDictionary, kIOPMHIDAppPIDKey, appPID); CFRelease(appPID); } /* Tag the process name */ CFStringRef appName = NULL; char appBuf[MAXPATHLEN]; int len = proc_name(callerPID, appBuf, MAXPATHLEN); if (0 != len) { appName = CFStringCreateWithCString(0, appBuf, kCFStringEncodingMacRoman); if (appName) { CFDictionarySetValue(foundDictionary, kIOPMHIDAppPathKey, appName); CFRelease(appName); } } } if (!foundDictionary) goto exit; // Unwrapping big data structure... bucketsArray = (CFMutableArrayRef)CFDictionaryGetValue(foundDictionary, kIOPMHIDHistoryArrayKey); if (!bucketsArray) { bucketsArray = CFArrayCreateMutable(0, 1, &kCFTypeArrayCallBacks); CFDictionarySetValue(foundDictionary, kIOPMHIDHistoryArrayKey, bucketsArray); CFRelease(bucketsArray); } if (!bucketsArray) goto exit; // Check last HID event bucket timestamp - is it more than 5 minutes old? bool foundWindowForEvent = false; if (0 < CFArrayGetCount(bucketsArray)) { dataEvent = (CFDataRef)CFArrayGetValueAtIndex(bucketsArray, 0); } if (dataEvent) { ev = (IOPMHIDPostEventActivityWindow *)CFDataGetBytePtr(dataEvent); if (timeNow < (ev->eventWindowStart + kFiveMinutesInSeconds)) { // This HID event gets dropped into this existing 5 minute bucket. // We bump the count for HID activity! if (__NX_NULL_EVENT == _action) { ev->nullEventCount++; } else { ev->hidEventCount++; } foundWindowForEvent = true; } } if (!foundWindowForEvent) { IOPMHIDPostEventActivityWindow newv; // We align the starts of our windows with 5 minute intervals newv.eventWindowStart = ((int)timeNow / (int)kFiveMinutesInSeconds) * kFiveMinutesInSeconds; newv.nullEventCount = newv.hidEventCount = 0; if (__NX_NULL_EVENT == _action) { newv.nullEventCount++; } else { newv.hidEventCount++; } dataEvent = CFDataCreate(0, (const UInt8 *)&newv, sizeof(IOPMHIDPostEventActivityWindow)); if (dataEvent) { CFArrayInsertValueAtIndex(bucketsArray, 0, dataEvent); CFRelease(dataEvent); } // If we've recorded more than kMaxFiveMinutesWindowsCount activity windows for this process, delete the old ones. while (kMaxFiveMinutesWindowsCount < CFArrayGetCount(bucketsArray)) { CFArrayRemoveValueAtIndex(bucketsArray, CFArrayGetCount(bucketsArray) - 1); } } exit: return KERN_SUCCESS; }