/* Test basic add delete update copy matching stuff. */ static void tests(void) { SecTrustRef trust; SecCertificateRef cert0, cert1; isnt(cert0 = SecCertificateCreateWithBytes(NULL, _c0, sizeof(_c0)), NULL, "create cert0"); isnt(cert1 = SecCertificateCreateWithBytes(NULL, _c1, sizeof(_c1)), NULL, "create cert1"); const void *v_certs[] = { cert0, cert1 }; SecPolicyRef policy = SecPolicyCreateSSL(false, CFSTR("store.apple.com")); CFArrayRef certs = CFArrayCreate(NULL, v_certs, array_size(v_certs), NULL); ok_status(SecTrustCreateWithCertificates(certs, policy, &trust), "create trust"); /* Jan 1st 2006. */ CFDateRef date = CFDateCreate(NULL, 157680000.0); ok_status(SecTrustSetVerifyDate(trust, date), "set date"); SecTrustResultType trustResult; ok_status(SecTrustEvaluate(trust, &trustResult), "evaluate trust"); is_status(trustResult, kSecTrustResultUnspecified, "trust is kSecTrustResultUnspecified"); CFDataRef exceptions; ok(exceptions = SecTrustCopyExceptions(trust), "create an exceptions"); ok(SecTrustSetExceptions(trust, exceptions), "set exceptions"); ok_status(SecTrustEvaluate(trust, &trustResult), "evaluate trust"); is_status(trustResult, kSecTrustResultProceed, "trust is kSecTrustResultProceed"); CFReleaseSafe(trust); CFReleaseSafe(policy); policy = SecPolicyCreateSSL(false, CFSTR("badstore.apple.com")); ok_status(SecTrustCreateWithCertificates(certs, policy, &trust), "create trust with hostname mismatch"); ok_status(SecTrustSetVerifyDate(trust, date), "set date"); ok(SecTrustSetExceptions(trust, exceptions), "set old exceptions"); ok_status(SecTrustEvaluate(trust, &trustResult), "evaluate trust"); is_status(trustResult, kSecTrustResultRecoverableTrustFailure, "trust is kSecTrustResultRecoverableTrustFailure"); CFReleaseSafe(exceptions); ok(exceptions = SecTrustCopyExceptions(trust), "create a new exceptions"); ok(SecTrustSetExceptions(trust, exceptions), "set exceptions"); ok_status(SecTrustEvaluate(trust, &trustResult), "evaluate trust"); is_status(trustResult, kSecTrustResultProceed, "trust is kSecTrustResultProceed"); CFReleaseSafe(trust); ok_status(SecTrustCreateWithCertificates(certs, policy, &trust), "create trust"); ok_status(SecTrustSetVerifyDate(trust, date), "set date"); ok(SecTrustSetExceptions(trust, exceptions), "set exceptions"); ok_status(SecTrustEvaluate(trust, &trustResult), "evaluate trust"); is_status(trustResult, kSecTrustResultProceed, "trust is kSecTrustResultProceed"); CFArrayRef anchors = CFArrayCreate(kCFAllocatorDefault, NULL, 0, &kCFTypeArrayCallBacks); ok_status(SecTrustSetAnchorCertificates(trust, anchors), "set empty anchor list"); ok_status(SecTrustEvaluate(trust, &trustResult), "evaluate trust"); is_status(trustResult, kSecTrustResultRecoverableTrustFailure, "trust is kSecTrustResultRecoverableTrustFailure"); ok_status(SecTrustSetAnchorCertificatesOnly(trust, false), "trust passed in anchors and system anchors"); ok_status(SecTrustEvaluate(trust, &trustResult), "evaluate trust"); is_status(trustResult, kSecTrustResultProceed, "trust is now kSecTrustResultProceed"); ok_status(SecTrustSetAnchorCertificatesOnly(trust, true), "only trust passed in anchors (default)"); ok_status(SecTrustEvaluate(trust, &trustResult), "evaluate trust"); is_status(trustResult, kSecTrustResultRecoverableTrustFailure, "trust is kSecTrustResultRecoverableTrustFailure again"); CFReleaseSafe(exceptions); ok(exceptions = SecTrustCopyExceptions(trust), "create a new exceptions"); ok(SecTrustSetExceptions(trust, exceptions), "set exceptions"); ok_status(SecTrustEvaluate(trust, &trustResult), "evaluate trust"); is_status(trustResult, kSecTrustResultProceed, "trust is kSecTrustResultProceed"); CFReleaseSafe(date); date = CFDateCreate(NULL, 667680000.0); ok_status(SecTrustSetVerifyDate(trust, date), "set date to far future so certs are expired"); ok_status(SecTrustEvaluate(trust, &trustResult), "evaluate trust"); is_status(trustResult, kSecTrustResultRecoverableTrustFailure, "trust is kSecTrustResultRecoverableTrustFailure"); CFReleaseSafe(anchors); CFReleaseSafe(exceptions); CFReleaseSafe(trust); CFReleaseSafe(policy); CFReleaseSafe(certs); CFReleaseSafe(cert0); CFReleaseSafe(cert1); CFReleaseSafe(date); }
bool check_date_comparison () { CFDateRef date1, date2; // Standard Core Foundation comparison result. CFComparisonResult result; CFShow(CFSTR("Checking date comparison functions:")); // Create two CFDates from absolute time. date1 = CFDateCreate(kCFAllocatorDefault, CFAbsoluteTimeGetCurrent()); date2 = CFDateCreate(kCFAllocatorDefault, CFAbsoluteTimeGetCurrent()); // Pass NULL for the context param. result = CFDateCompare(date1, date2, NULL); switch (result) { case kCFCompareLessThan: CFShow(CFSTR("date1 is before date2!\n")); break; case kCFCompareEqualTo: CFShow(CFSTR("date1 is the same as date2!\n")); break; case kCFCompareGreaterThan: CFShow(CFSTR("date1 is after date2!\n")); break; } printf("\n"); return true; }
static bool SecPathBuilderReportResult(SecPathBuilderRef builder) { SecPVCRef pvc = &builder->path; if (pvc->info && pvc->is_ev && pvc->result) { CFDictionarySetValue(pvc->info, kSecTrustInfoExtendedValidationKey, kCFBooleanTrue); SecCertificateRef leaf = SecPVCGetCertificateAtIndex(pvc, 0); CFStringRef leafCompanyName = SecCertificateCopyCompanyName(leaf); if (leafCompanyName) { CFDictionarySetValue(pvc->info, kSecTrustInfoCompanyNameKey, leafCompanyName); CFRelease(leafCompanyName); } if (pvc->rvcs) { CFAbsoluteTime nextUpdate = SecPVCGetEarliestNextUpdate(pvc); if (nextUpdate == 0) { CFDictionarySetValue(pvc->info, kSecTrustInfoRevocationKey, kCFBooleanFalse); } else { CFDateRef validUntil = CFDateCreate(kCFAllocatorDefault, nextUpdate); CFDictionarySetValue(pvc->info, kSecTrustInfoRevocationValidUntilKey, validUntil); CFRelease(validUntil); CFDictionarySetValue(pvc->info, kSecTrustInfoRevocationKey, kCFBooleanTrue); } } } /* This will trigger the outer step function to call the completion function. */ builder->state = NULL; return false; }
STATIC void remove_old_linklocal_modifiers(CFMutableDictionaryRef modifiers) { CFIndex count; count = CFDictionaryGetCount(modifiers); if (count > 0) { int i; const void * keys[count]; CFDateRef now; const void * values[count]; now = CFDateCreate(NULL, CFAbsoluteTimeGetCurrent()); CFDictionaryGetKeysAndValues(modifiers, keys, values); for (i = 0; i < count; i++) { CFDictionaryRef dict = (CFDictionaryRef)values[i]; if (linklocal_modifier_has_expired(dict, now)) { CFStringRef key = (CFStringRef)keys[i]; CFDictionaryRemoveValue(modifiers, key); } } CFRelease(now); } return; }
inline CFDateRef SQLite3StatementCreateDateWithColumn(SQLite3StatementRef statement, CFIndex index) { CFDateRef date = NULL; CFStringRef string = NULL; switch (SQLite3StatementGetColumnType(statement, index)) { // For integer and float, we're interpreting as unix timestamp case kSQLite3TypeInteger: case kSQLite3TypeFloat: date = CFDateCreate(statement->allocator, SQLite3StatementGetInt64WithColumn(statement, index) - kCFAbsoluteTimeIntervalSince1970); break; // For string we're using default format case kSQLite3TypeString: string = SQLite3StatementCreateStringWithColumn(statement, index); date = CFDateFormatterCreateDateFromString(statement->allocator, statement->connection->defaultDateFormatter, string, NULL); CFRelease(string); break; // For blobs, nulls (or unknown column type?) we're leaving it as NULL case kSQLite3TypeData: case kSQLite3TypeNULL: default: break; } return date; }
CFDateRef GetDateFieldFromCertificate(SecCertificateRef certificate, CFTypeRef oid) { const void *keys[] = { oid }; CFDictionaryRef dict = NULL; CFErrorRef error; CFDateRef date = NULL; CFArrayRef keySelection = CFArrayCreate(NULL, keys , sizeof(keys)/sizeof(keys[0]), &kCFTypeArrayCallBacks); dict = SecCertificateCopyValues(certificate, keySelection, &error); if (dict == NULL) { printErrorMsg("GetDateFieldFromCertificate: SecCertificateCopyValues", error); goto release_ks; } CFDictionaryRef vals = dict ? CFDictionaryGetValue(dict, oid) : NULL; CFNumberRef vals2 = vals ? CFDictionaryGetValue(vals, kSecPropertyKeyValue) : NULL; if (vals2 == NULL) goto release_dict; CFAbsoluteTime validityNotBefore; if (CFNumberGetValue(vals2, kCFNumberDoubleType, &validityNotBefore)) date = CFDateCreate(kCFAllocatorDefault,validityNotBefore); release_dict: CFRelease(dict); release_ks: CFRelease(keySelection); return date; }
static CFDictionaryRef DHCPLeaseCopyDictionary(DHCPLeaseRef lease_p) { CFDataRef data; CFDateRef date; CFMutableDictionaryRef dict; CFNumberRef num; CFStringRef str; dict = CFDictionaryCreateMutable(NULL, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); /* set the IP address */ str = CFStringCreateWithFormat(NULL, NULL, CFSTR(IP_FORMAT), IP_LIST(&lease_p->our_ip)); CFDictionarySetValue(dict, kIPAddress, str); CFRelease(str); /* set the lease start date */ date = CFDateCreate(NULL, lease_p->lease_start); CFDictionarySetValue(dict, kLeaseStartDate, date); CFRelease(date); /* set the lease length */ num = CFNumberCreate(NULL, kCFNumberSInt32Type, &lease_p->lease_length); CFDictionarySetValue(dict, kLeaseLength, num); CFRelease(num); /* set the SSID */ if (lease_p->ssid != NULL) { CFDictionarySetValue(dict, kSSID, lease_p->ssid); } /* set the packet data */ data = CFDataCreateWithBytesNoCopy(NULL, lease_p->pkt, lease_p->pkt_length, kCFAllocatorNull); CFDictionarySetValue(dict, kPacketData, data); CFRelease(data); if (lease_p->router_ip.s_addr != 0) { /* set the router IP address */ str = CFStringCreateWithFormat(NULL, NULL, CFSTR(IP_FORMAT), IP_LIST(&lease_p->router_ip)); CFDictionarySetValue(dict, kRouterIPAddress, str); CFRelease(str); if (lease_p->router_hwaddr_length > 0) { /* set the router hardware address */ data = CFDataCreateWithBytesNoCopy(NULL, lease_p->router_hwaddr, lease_p->router_hwaddr_length, kCFAllocatorNull); CFDictionarySetValue(dict, kRouterHardwareAddress, data); CFRelease(data); } } return (dict); }
bool decode(ArgumentDecoder* decoder, RetainPtr<CFDateRef>& result) { double absoluteTime; if (!decoder->decodeDouble(absoluteTime)) return false; result.adoptCF(CFDateCreate(0, absoluteTime)); return true; }
static CFStringRef utilCopyDefaultKeyLabel(void) { // generate a default label from the current date CFDateRef dateNow = CFDateCreate(kCFAllocatorDefault, CFAbsoluteTimeGetCurrent()); CFStringRef defaultLabel = CFCopyDescription(dateNow); CFRelease(dateNow); return defaultLabel; }
/* * Set a CSSM_DATE to "today plus delta days". Delta can be positive * or negative. */ static void setDate( CSSM_DATE &cdate, int deltaDays) { CFAbsoluteTime cfTime = CFAbsoluteTimeGetCurrent(); float fdelta = 60.0 * 60.0 * 24.0 * deltaDays; cfTime += fdelta; CFDateRef cfDate = CFDateCreate(NULL, cfTime); CssmUniformDate cud(cfDate); CFRelease(cfDate); cdate = cud; }
CFDateRef CFCalendarCopyGregorianStartDate(CFCalendarRef calendar) { CF_OBJC_FUNCDISPATCHV(CFCalendarGetTypeID(), CFDateRef, calendar, _gregorianStartDate); __CFGenericValidateType(calendar, CFCalendarGetTypeID()); if (!calendar->_cal) __CFCalendarSetupCal(calendar); UErrorCode status = U_ZERO_ERROR; UDate udate = calendar->_cal ? ucal_getGregorianChange(calendar->_cal, &status) : 0; if (calendar->_cal && U_SUCCESS(status)) { CFAbsoluteTime at = (double)udate / 1000.0 - kCFAbsoluteTimeIntervalSince1970; return CFDateCreate(CFGetAllocator(calendar), at); } return NULL; }
/** * Create a new plist_t type #PLIST_DATE * * @param sec the number of seconds since 01/01/2001 * @param usec the number of microseconds * @return the created item * @sa #plist_type */ plist_t plist_new_date(int32_t sec, int32_t usec) { // typedef double CFTimeInterval; // typedef CFTimeInterval CFAbsoluteTime; // /* absolute time is the time interval since the reference date */ // /* the reference date (epoch) is 00:00:00 1 January 2001. */ CFAbsoluteTime abstime = (CFAbsoluteTime) sec + (CFAbsoluteTime) usec / 100000.0; abstime -= 978307200.0; return CFDateCreate(kCFAllocatorDefault, abstime); }
STATIC CFDictionaryRef CGAModifierDictCreate(CFDataRef modifier, uint8_t sec_level) { CFDictionaryRef dict; CFDateRef now; CFNumberRef sec_level_cf; now = CFDateCreate(NULL, CFAbsoluteTimeGetCurrent()); sec_level_cf = CFNumberCreate(NULL, kCFNumberSInt8Type, &sec_level); dict = modifier_dict_create(modifier, sec_level_cf, now); CFRelease(now); CFRelease(sec_level_cf); return (dict); }
void CssmDateToCFDate(const char *cssmDate, CFDateRef *outCFDate) { CFTimeZoneRef timeZone = CFTimeZoneCreateWithTimeIntervalFromGMT(NULL, 0); CFGregorianDate gd; unsigned int year, month, day, hour, minute, second; sscanf(cssmDate, "%4d%2d%2d%2d%2d%2d", &year, &month, &day, &hour, &minute, &second); gd.year = year; gd.month = month; gd.day = day; gd.hour = hour; gd.minute = minute; gd.second = second; *outCFDate = CFDateCreate(NULL, CFGregorianDateGetAbsoluteTime(gd, timeZone)); CFRelease(timeZone); }
/* * Function: AFPUser_set_random_password * Purpose: * Set a random password for the user and returns it in passwd. * Do not change the password again until AFPUSER_PASSWORD_CHANGE_INTERVAL * has elapsed. This overcomes the problem where every client * request packet is duplicated. In that case, the client tries to use * a password that subsequently gets changed when the duplicate arrives. */ Boolean AFPUser_set_random_password(AFPUserRef user, char * passwd, size_t passwd_len) { CFDateRef last_set; Boolean ok = TRUE; CFDateRef now; CFStringRef pw; ODRecordRef record; now = CFDateCreate(NULL, CFAbsoluteTimeGetCurrent()); pw = CFDictionaryGetValue(user, kAFPUserPassword); last_set = CFDictionaryGetValue(user, kAFPUserDatePasswordLastSet); if (pw != NULL && last_set != NULL && (CFDateGetTimeIntervalSinceDate(now, last_set) < AFPUSER_PASSWORD_CHANGE_INTERVAL)) { /* return what we have */ #ifdef TEST_AFPUSERS printf("No need to change the password %d < %d\n", (int)CFDateGetTimeIntervalSinceDate(now, last_set), AFPUSER_PASSWORD_CHANGE_INTERVAL); #endif /* TEST_AFPUSERS */ (void)_SC_cfstring_to_cstring(pw, passwd, passwd_len, kCFStringEncodingASCII); CFDictionarySetValue(user, kAFPUserDatePasswordLastSet, now); } else { generate_random_password(passwd, passwd_len); record = (ODRecordRef)CFDictionaryGetValue(user, kAFPUserODRecord); pw = CFStringCreateWithCString(NULL, passwd, kCFStringEncodingASCII); ok = ODRecordChangePassword(record, NULL, pw, NULL); if (ok) { CFDictionarySetValue(user, kAFPUserPassword, pw); CFDictionarySetValue(user, kAFPUserDatePasswordLastSet, now); } else { my_log(LOG_NOTICE, "AFPUser_set_random_password:"******" ODRecordChangePassword() failed"); CFDictionaryRemoveValue(user, kAFPUserPassword); CFDictionaryRemoveValue(user, kAFPUserDatePasswordLastSet); } CFRelease(pw); } CFRelease(now); return ok; }
static void tests(void) { SecTrustRef trust; SecCertificateRef leaf, wwdr_intermediate; SecPolicyRef policy; isnt(wwdr_intermediate = SecCertificateCreateWithBytes(kCFAllocatorDefault, wwdr_intermediate_cert, sizeof(wwdr_intermediate_cert)), NULL, "create WWDR intermediate"); isnt(leaf = SecCertificateCreateWithBytes(kCFAllocatorDefault, codesigning_certificate, sizeof(codesigning_certificate)), NULL, "create leaf"); const void *vcerts[] = { leaf, wwdr_intermediate }; CFArrayRef certs = CFArrayCreate(kCFAllocatorDefault, vcerts, 2, NULL); isnt(policy = SecPolicyCreateiPhoneProfileApplicationSigning(), NULL, "create iPhoneProfileApplicationSigning policy instance"); ok_status(SecTrustCreateWithCertificates(certs, policy, &trust), "create trust for leaf"); CFDateRef verifyDate = CFDateCreate(kCFAllocatorDefault, 228244066); ok_status(SecTrustSetVerifyDate(trust, verifyDate), "set verify date"); CFReleaseNull(verifyDate); SecTrustResultType trustResult; CFArrayRef properties = NULL; properties = SecTrustCopyProperties(trust); is(properties, NULL, "no properties returned before eval"); CFReleaseNull(properties); ok_status(SecTrustEvaluate(trust, &trustResult), "evaluate trust"); is_status(trustResult, kSecTrustResultUnspecified, "trust is kSecTrustResultUnspecified"); properties = SecTrustCopyProperties(trust); if (properties) { print_plist(properties); print_cert(leaf, true); print_cert(wwdr_intermediate, false); } CFReleaseNull(properties); CFReleaseNull(trust); CFReleaseNull(wwdr_intermediate); CFReleaseNull(leaf); CFReleaseNull(certs); CFReleaseNull(policy); CFReleaseNull(trust); }
const uint8_t* der_decode_date(CFAllocatorRef allocator, CFOptionFlags mutability, CFDateRef* date, CFErrorRef *error, const uint8_t* der, const uint8_t *der_end) { if (NULL == der) return NULL; der = ccder_decode_constructed_tl(CCDER_GENERALIZED_TIME, &der_end, der, der_end); CFAbsoluteTime at = 0; der = der_decode_generalizedtime_body(&at, error, der, der_end); if (der) { *date = CFDateCreate(allocator, at); if (NULL == *date) { SecCFDERCreateError(kSecDERErrorAllocationFailure, CFSTR("Failed to create date"), NULL, error); return NULL; } } return der; }
bool check_date_constructors () { CFAbsoluteTime absTime; CFDateRef aCFDate; CFShow(CFSTR("Checking date constructors:")); absTime = CFAbsoluteTimeGetCurrent(); aCFDate = CFDateCreate(kCFAllocatorDefault, absTime); CFShow(CFSTR("Absolute Time is")); printf("The current absolute time is %f\n", absTime); CFShow(CFSTR("Equivalent CFDate object is")); CFShow(aCFDate); printf("\n"); return true; }
/* * * Purge past wakeup times * Does not care whether its operating on wakeup or poweron array. * Just purges all entries with a time < now * returns true on success, false on any failure * */ static bool purgePastEvents(PowerEventBehavior *behave) { CFDateRef date_now; CFDictionaryRef event; bool ret; if( !behave || !behave->title || !behave->array || (0 == CFArrayGetCount(behave->array))) { return true; } date_now = CFDateCreate(0, CFAbsoluteTimeGetCurrent()); // Loop over the array and remove any values that are in the past. // Since array is sorted by date already, we stop once we reach an event // scheduled in the future. // Do not try to optimize the CFArrayGetCount out of the while loop; this value may // change during loop execution. while(0 < CFArrayGetCount(behave->array)) { event = CFArrayGetValueAtIndex(behave->array, 0); if (isEntryValidAndFuturistic(event, date_now) ) break; // Remove entry from the array - its time has past // The rest of the array will shift down to fill index 0 CFArrayRemoveValueAtIndex(behave->array, 0); activeEventCnt--; } CFRelease(date_now); ret = true; return ret; }
static void rb_add_value_to_cf_dictionary(CFMutableDictionaryRef dict, CFStringRef key, VALUE value){ switch(TYPE(value)){ case T_STRING: { if(!CFStringCompare(key, kSecValueData,0) || !CFStringCompare(key, kSecAttrGeneric,0)){ CFDataRef dataValue = rb_create_cf_data(value); CFDictionarySetValue(dict,key,dataValue); CFRelease(dataValue); } else{ CFStringRef stringValue = rb_create_cf_string(value); CFDictionarySetValue(dict,key,stringValue); CFRelease(stringValue); } } break; case T_BIGNUM: case T_FIXNUM: { long long longLongValue = NUM2LL(value); CFNumberRef numberValue = CFNumberCreate(NULL,kCFNumberLongLongType,&longLongValue); CFDictionarySetValue(dict,key,numberValue); CFRelease(numberValue); break; } case T_DATA: { if(rb_obj_is_kind_of(value, rb_cTime)){ VALUE floatTime = rb_funcall(value, rb_intern("to_f"),0); CFAbsoluteTime abstime = RFLOAT_VALUE(floatTime) - kCFAbsoluteTimeIntervalSince1970; CFDateRef cfdate = CFDateCreate(NULL, abstime); CFDictionarySetValue(dict, key, cfdate); CFRelease(cfdate); break; } } default: rb_raise(rb_eTypeError, "Can't convert value to cftype: %s", rb_obj_classname(value)); } }
__private_extern__ void interface_update_link_issues(const char *if_name, uint64_t timestamp, uint8_t *modid, size_t modid_size, uint8_t *info, size_t info_size) { CFDataRef infoData; CFStringRef key; CFDataRef modidData; CFMutableDictionaryRef newDict; CFDateRef timeStamp; key = create_link_issues_key(if_name); newDict = copy_entity(key); modidData = CFDataCreate(NULL, modid, modid_size); CFDictionarySetValue(newDict, kSCPropNetLinkIssuesModuleID, modidData); CFRelease(modidData); if (info_size != 0) { infoData = CFDataCreate(NULL, info, info_size); CFDictionarySetValue(newDict, kSCPropNetLinkIssuesInfo, infoData); CFRelease(infoData); } else { CFDictionaryRemoveValue(newDict, kSCPropNetLinkIssuesInfo); } timeStamp = CFDateCreate(NULL, timestamp); CFDictionarySetValue(newDict, kSCPropNetLinkIssuesTimeStamp, timeStamp); CFRelease(timeStamp); cache_SCDynamicStoreSetValue(store, key, newDict); CFRelease(newDict); CFRelease(key); return; }
void logger::addLog(CFStringRef _log, bool _addTimeStamp){ if (_addTimeStamp){ CFAbsoluteTime timeNow = CFAbsoluteTimeGetCurrent(); CFDateRef d = CFDateCreate(kCFAllocatorDefault, timeNow); CFLocaleRef currentLocale = CFLocaleCopyCurrent(); CFDateFormatterRef dateFormatter = CFDateFormatterCreate(NULL, currentLocale, kCFDateFormatterShortStyle, kCFDateFormatterMediumStyle); CFStringRef t = CFDateFormatterCreateStringWithDate(kCFAllocatorDefault, dateFormatter, d); CFMutableStringRef tmpString = CFStringCreateMutableCopy(kCFAllocatorDefault, 0, t); CFStringAppend(tmpString, CFSTR("\t")); CFStringAppend(tmpString, _log); CFArrayAppendValue(logArray, tmpString); CFRelease(d); CFRelease(currentLocale); CFRelease(dateFormatter); CFRelease(t); } else { CFArrayAppendValue(logArray, _log); } needUpdate = true; if (CFArrayGetCount(logArray)>MAX_LOG) CFArrayRemoveValueAtIndex(logArray, 0); }
CssmUniformDate::operator CFDateRef() const { return CFDateCreate(NULL, mTime); }
__private_extern__ SInt32 _CFGetPathProperties(CFAllocatorRef alloc, char *path, Boolean *exists, SInt32 *posixMode, int64_t *size, CFDateRef *modTime, SInt32 *ownerID, CFArrayRef *dirContents) { Boolean fileExists; Boolean isDirectory = false; if ((exists == NULL) && (posixMode == NULL) && (size == NULL) && (modTime == NULL) && (ownerID == NULL) && (dirContents == NULL)) { // Nothing to do. return 0; } struct statinfo statBuf; if (stat(path, &statBuf) != 0) { // stat failed, but why? if (thread_errno() == ENOENT) { fileExists = false; } else { return thread_errno(); } } else { fileExists = true; isDirectory = ((statBuf.st_mode & S_IFMT) == S_IFDIR); } if (exists != NULL) { *exists = fileExists; } if (posixMode != NULL) { if (fileExists) { *posixMode = statBuf.st_mode; } else { *posixMode = 0; } } if (size != NULL) { if (fileExists) { *size = statBuf.st_size; } else { *size = 0; } } if (modTime != NULL) { if (fileExists) { #if DEPLOYMENT_TARGET_WINDOWS || DEPLOYMENT_TARGET_LINUX struct timespec ts = {statBuf.st_mtime, 0}; #else struct timespec ts = statBuf.st_mtimespec; #endif *modTime = CFDateCreate(alloc, _CFAbsoluteTimeFromFileTimeSpec(ts)); } else { *modTime = NULL; } } if (ownerID != NULL) { if (fileExists) { *ownerID = statBuf.st_uid; } else { *ownerID = -1; } } if (dirContents != NULL) { if (fileExists && isDirectory) { CFMutableArrayRef contents = _CFContentsOfDirectory(alloc, (char *)path, NULL, NULL, NULL); if (contents) { *dirContents = contents; } else { *dirContents = NULL; } } else { *dirContents = NULL; } } return 0; }
static CFDictionaryRef _IOFileURLCreatePropertiesFromResource(CFAllocatorRef alloc, CFURLRef url, CFArrayRef desiredProperties, SInt32 *errorCode) { static CFArrayRef _allProps = NULL; char cPath[CFMaxPathSize]; SInt32 index, count, statResult = 0; CFMutableDictionaryRef propertyDict = NULL; struct stat statBuf; Boolean statCompleted = FALSE; if (!CFURLGetFileSystemRepresentation(url, TRUE, cPath, CFMaxPathSize)) { if (errorCode) *errorCode = kIOURLImproperArgumentsError; return NULL; } if (errorCode) *errorCode = 0; if (!desiredProperties) { // Cheap and dirty hack to make this work for the moment; ultimately we need to do something more sophisticated. This will result in an error return whenever a property key is defined which isn't applicable to all file URLs. REW, 3/2/99 if (!_allProps) { const void *values[9]; values[0] = kIOURLFileExists; values[1] = kIOURLFilePOSIXMode; values[2] = kIOURLFileDirectoryContents; values[3] = kIOURLFileLength; values[4] = kIOURLFileLastModificationTime; values[5] = kIOURLFileOwnerID; values[6] = kIOFileURLExists; values[7] = kIOFileURLPOSIXMode; values[8] = kIOFileURLSize; _allProps = CFArrayCreate(NULL, values, 8, &kCFTypeArrayCallBacks); } desiredProperties = _allProps; } count = CFArrayGetCount(desiredProperties); propertyDict = CFDictionaryCreateMutable(alloc, 0, & kCFTypeDictionaryKeyCallBacks, & kCFTypeDictionaryValueCallBacks); if (count == 0) return propertyDict; for (index = 0; index < count; index ++) { CFStringRef key = (CFMutableStringRef )CFArrayGetValueAtIndex(desiredProperties, index); if (!statCompleted && (CFEqual(key, kIOURLFilePOSIXMode) || CFEqual(key, kIOURLFileDirectoryContents) || CFEqual(key, kIOURLFileLength) || CFEqual(key, kIOURLFileLastModificationTime) || CFEqual(key, kIOURLFileExists) || CFEqual(key, kIOFileURLExists) || CFEqual(key, kIOFileURLPOSIXMode) || CFEqual(key, kIOFileURLSize) || CFEqual(key, kIOURLFileOwnerID))) { statResult = stat(cPath, &statBuf); if (statResult != 0) statResult = thread_errno(); statCompleted = TRUE; } else if (errorCode) { *errorCode = kIOURLUnknownError; } if (CFEqual(key, kIOFileURLPOSIXMode)) { if (statResult == 0) { CFDataRef modeData = CFDataCreate(alloc, (void *)(&(statBuf.st_mode)), sizeof(statBuf.st_mode)); CFDictionarySetValue(propertyDict, kIOFileURLPOSIXMode, modeData); CFRelease(modeData); } else if (errorCode) { *errorCode = kIOURLUnknownError; } } else if (CFEqual(key, kIOURLFilePOSIXMode)) { if (statResult == 0) { SInt32 value = statBuf.st_mode; CFNumberRef num = CFNumberCreate(alloc, kCFNumberSInt32Type, &value); CFDictionarySetValue(propertyDict, kIOURLFilePOSIXMode, num); CFRelease(num); } else if (errorCode) { *errorCode = kIOURLUnknownError; } } else if (CFEqual(key, kIOURLFileDirectoryContents)) { if (statResult == 0 && (statBuf.st_mode & S_IFMT) == S_IFDIR) { CFMutableArrayRef contents = _IOContentsOfDirectory(alloc, cPath, url, NULL); if (contents) { CFDictionarySetValue(propertyDict, kIOURLFileDirectoryContents, contents); CFRelease(contents); } else if (errorCode) { *errorCode = kIOURLUnknownError; } } else if (errorCode) { *errorCode = kIOURLUnknownError; } } else if (CFEqual(key, kIOFileURLSize)) { if (statResult == 0) { UInt64 length = statBuf.st_size; CFDataRef tmpData = CFDataCreate(alloc, (void *)(&length), sizeof(UInt64)); CFDictionarySetValue(propertyDict, kIOFileURLSize, tmpData); CFRelease(tmpData); } else if (errorCode) { *errorCode = kIOURLUnknownError; } } else if (CFEqual(key, kIOURLFileLength)) { if (statResult == 0) { SInt64 length = statBuf.st_size; CFNumberRef num = CFNumberCreate(alloc, kCFNumberSInt64Type, &length); CFDictionarySetValue(propertyDict, kIOURLFileLength, num); CFRelease(num); } else if (errorCode) { *errorCode = kIOURLUnknownError; } } else if (CFEqual(key, kIOURLFileLastModificationTime)) { if (statResult == 0) { CFDateRef date = CFDateCreate(alloc, statBuf.st_mtime - kCFAbsoluteTimeIntervalSince1970); CFDictionarySetValue(propertyDict, kIOURLFileLastModificationTime, date); CFRelease(date); } else if (errorCode) { *errorCode = kIOURLUnknownError; } } else if (CFEqual(key, kIOURLFileExists)) { if (statResult == 0) { CFDictionarySetValue(propertyDict, kIOURLFileExists, kCFBooleanTrue); } else if (statResult == ENOENT) { CFDictionarySetValue(propertyDict, kIOURLFileExists, kCFBooleanFalse); } else if (errorCode) { *errorCode = kIOURLUnknownError; } } else if (CFEqual(key, kIOFileURLExists)) { if (statResult == 0) { CFDictionarySetValue(propertyDict, kIOFileURLExists, kIOFileURLExists); } else if (statResult == ENOENT) { CFDictionarySetValue(propertyDict, kIOFileURLExists, kCFBooleanFalse); // Choose any value other than kIOFileURLExists to designate non-existance. Note that we cannot use NULL, since the dictionary has value callbacks kCFTypeDictionaryValueCallBacks, which is not tolerant of NULL values. } else if (errorCode) { *errorCode = kIOURLUnknownError; } } else if (CFEqual(key, kIOURLFileOwnerID)) { if (statResult == 0) { SInt32 uid = statBuf.st_uid; CFNumberRef num = CFNumberCreate(alloc, kCFNumberSInt32Type, &uid); CFDictionarySetValue(propertyDict, kIOURLFileOwnerID, num); CFRelease(num); } else if (errorCode) { *errorCode = kIOURLUnknownError; } // Add more properties here } else if (errorCode) { *errorCode = kIOURLUnknownPropertyKeyError; } } return propertyDict; }
static QCFType<CFPropertyListRef> macValue(const QVariant &value) { CFPropertyListRef result = 0; switch (value.type()) { case QVariant::ByteArray: { QByteArray ba = value.toByteArray(); result = CFDataCreate(kCFAllocatorDefault, reinterpret_cast<const UInt8 *>(ba.data()), CFIndex(ba.size())); } break; // should be same as below (look for LIST) case QVariant::List: case QVariant::StringList: case QVariant::Polygon: result = macList(value.toList()); break; case QVariant::Map: { /* QMap<QString, QVariant> is potentially a multimap, whereas CFDictionary is a single-valued map. To allow for multiple values with the same key, we store multiple values in a CFArray. To avoid ambiguities, we also wrap lists in a CFArray singleton. */ QMap<QString, QVariant> map = value.toMap(); QMap<QString, QVariant>::const_iterator i = map.constBegin(); int maxUniqueKeys = map.size(); int numUniqueKeys = 0; QVarLengthArray<QCFType<CFPropertyListRef> > cfkeys(maxUniqueKeys); QVarLengthArray<QCFType<CFPropertyListRef> > cfvalues(maxUniqueKeys); while (i != map.constEnd()) { const QString &key = i.key(); QList<QVariant> values; do { values << i.value(); ++i; } while (i != map.constEnd() && i.key() == key); bool singleton = (values.count() == 1); if (singleton) { switch (values.first().type()) { // should be same as above (look for LIST) case QVariant::List: case QVariant::StringList: case QVariant::Polygon: singleton = false; default: ; } } cfkeys[numUniqueKeys] = QCFString::toCFStringRef(key); cfvalues[numUniqueKeys] = singleton ? macValue(values.first()) : macList(values); ++numUniqueKeys; } result = CFDictionaryCreate(kCFAllocatorDefault, reinterpret_cast<const void **>(cfkeys.data()), reinterpret_cast<const void **>(cfvalues.data()), CFIndex(numUniqueKeys), &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); } break; case QVariant::DateTime: { /* CFDate, unlike QDateTime, doesn't store timezone information. */ QDateTime dt = value.toDateTime(); if (dt.timeSpec() == Qt::LocalTime) { QDateTime reference; reference.setTime_t((uint)kCFAbsoluteTimeIntervalSince1970); result = CFDateCreate(kCFAllocatorDefault, CFAbsoluteTime(reference.secsTo(dt))); } else { goto string_case; } } break; case QVariant::Bool: result = value.toBool() ? kCFBooleanTrue : kCFBooleanFalse; break; case QVariant::Int: case QVariant::UInt: { int n = value.toInt(); result = CFNumberCreate(kCFAllocatorDefault, kCFNumberIntType, &n); } break; case QVariant::Double: { double n = value.toDouble(); result = CFNumberCreate(kCFAllocatorDefault, kCFNumberDoubleType, &n); } break; case QVariant::LongLong: case QVariant::ULongLong: { qint64 n = value.toLongLong(); result = CFNumberCreate(0, kCFNumberLongLongType, &n); } break; case QVariant::String: string_case: default: result = QCFString::toCFStringRef(QSettingsPrivate::variantToString(value)); } return result; }
__private_extern__ SInt32 _CFGetFileProperties(CFAllocatorRef alloc, CFURLRef pathURL, Boolean *exists, SInt32 *posixMode, int64_t *size, CFDateRef *modTime, SInt32 *ownerID, CFArrayRef *dirContents) { Boolean fileExists; Boolean isDirectory = false; struct stat statBuf; char path[CFMaxPathLength]; if ((exists == NULL) && (posixMode == NULL) && (size == NULL) && (modTime == NULL) && (ownerID == NULL) && (dirContents == NULL)) { // Nothing to do. return 0; } if (!CFURLGetFileSystemRepresentation(pathURL, true, path, CFMaxPathLength)) { return -1; } if (stat(path, &statBuf) != 0) { // stat failed, but why? if (thread_errno() == ENOENT) { fileExists = false; } else { return thread_errno(); } } else { fileExists = true; isDirectory = ((statBuf.st_mode & S_IFMT) == S_IFDIR); } if (exists != NULL) { *exists = fileExists; } if (posixMode != NULL) { if (fileExists) { *posixMode = statBuf.st_mode; } else { *posixMode = 0; } } if (size != NULL) { if (fileExists) { *size = statBuf.st_size; } else { *size = 0; } } if (modTime != NULL) { if (fileExists) { CFTimeInterval theTime; theTime = kCFAbsoluteTimeIntervalSince1970 + statBuf.st_mtime; *modTime = CFDateCreate(alloc, theTime); } else { *modTime = NULL; } } if (ownerID != NULL) { if (fileExists) { *ownerID = statBuf.st_uid; } else { *ownerID = -1; } } if (dirContents != NULL) { if (fileExists && isDirectory) { CFMutableArrayRef contents = _CFContentsOfDirectory(alloc, path, NULL, pathURL, NULL); if (contents) { *dirContents = contents; } else { *dirContents = NULL; } } else { *dirContents = NULL; } } return 0; }
__private_extern__ SInt32 _CFGetFileProperties(CFAllocatorRef alloc, CFURLRef pathURL, Boolean *exists, SInt32 *posixMode, int64_t *size, CFDateRef *modTime, SInt32 *ownerID, CFArrayRef *dirContents) { Boolean fileExists; Boolean isDirectory = false; #if DEPLOYMENT_TARGET_WINDOWS struct _stati64 statBuf; int fd = -1; #else struct stat64 statBuf; #endif char path[CFMaxPathSize]; if ((exists == NULL) && (posixMode == NULL) && (size == NULL) && (modTime == NULL) && (ownerID == NULL) && (dirContents == NULL)) { // Nothing to do. return 0; } if (!CFURLGetFileSystemRepresentation(pathURL, true, (uint8_t *)path, CFMaxPathLength)) { return -1; } #if DEPLOYMENT_TARGET_WINDOWS SECURITY_ATTRIBUTES sa; sa.nLength = sizeof(sa); sa.bInheritHandle = TRUE; sa.lpSecurityDescriptor = NULL; HANDLE hFile = CreateFileA(path, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, &sa, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL); if (INVALID_HANDLE_VALUE == hFile) { DWORD error = GetLastError (); return -1; } fd = _open_osfhandle((intptr_t)hFile, _O_RDONLY|CF_OPENFLGS); if (fd < 0) { if (thread_errno() == ENOENT) { fileExists = false; } else { CloseHandle (hFile); return thread_errno(); } } else { if (_fstati64(fd, &statBuf) != 0) { close(fd); // stat failed, but why? if (thread_errno() == ENOENT) { fileExists = false; } else { return thread_errno(); } } else { fileExists = true; // Hack to work around Windows strange stat behavior: DWORD attributes = GetFileAttributesA (path); close(fd); if (attributes & FILE_ATTRIBUTE_DIRECTORY) { statBuf.st_mode &= ~S_IFREG; // Don't claim it's a regular file. statBuf.st_mode |= S_IFDIR; // Properly mark it as a directory } isDirectory = ((statBuf.st_mode & S_IFMT) == S_IFDIR); } } #else if (stat64(path, &statBuf) != 0) { // stat failed, but why? if (thread_errno() == ENOENT) { fileExists = false; } else { return thread_errno(); } } else { fileExists = true; isDirectory = ((statBuf.st_mode & S_IFMT) == S_IFDIR); } #endif if (exists != NULL) { *exists = fileExists; } if (posixMode != NULL) { if (fileExists) { *posixMode = statBuf.st_mode; } else { *posixMode = 0; } } if (size != NULL) { if (fileExists) { *size = statBuf.st_size; } else { *size = 0; } } if (modTime != NULL) { if (fileExists) { #if DEPLOYMENT_TARGET_WINDOWS CFAbsoluteTime theTime = (CFAbsoluteTime)statBuf.st_mtime; #elif DEPLOYMENT_TARGET_LINUX #if defined _BSD_SOURCE || defined _SVID_SOURCE CFAbsoluteTime theTime = (CFAbsoluteTime)statBuf.st_mtim.tv_sec - kCFAbsoluteTimeIntervalSince1970; theTime += (CFAbsoluteTime)statBuf.st_mtim.tv_nsec / 1000000000.0; #else CFAbsoluteTime theTime = (CFAbsoluteTime)statBuf.st_mtime - kCFAbsoluteTimeIntervalSince1970; theTime += (CFAbsoluteTime)statBuf.st_mtimensec / 1000000000.0; #endif /* defined _BSD_SOURCE || defined _SVID_SOURCE */ #else CFAbsoluteTime theTime = (CFAbsoluteTime)statBuf.st_mtimespec.tv_sec - kCFAbsoluteTimeIntervalSince1970; theTime += (CFAbsoluteTime)statBuf.st_mtimespec.tv_nsec / 1000000000.0; #endif *modTime = CFDateCreate(alloc, theTime); } else { *modTime = NULL; } } if (ownerID != NULL) { if (fileExists) { *ownerID = statBuf.st_uid; } else { *ownerID = -1; } } if (dirContents != NULL) { if (fileExists && isDirectory) { CFMutableArrayRef contents = _CFContentsOfDirectory(alloc, path, NULL, pathURL, NULL); if (contents) { *dirContents = contents; } else { *dirContents = NULL; } } else { *dirContents = NULL; } } return 0; }
static CFTypeRef decode_cfvalue_sb(stream_buffer_t *sb) { trait_t trait; long number_long_long; double number_double; CFAbsoluteTime absolute_time; CFTypeRef *keys, *values; CFIndex count, i; CFTypeRef cfvalue; stream_buffer_read(sb, &trait, sizeof(trait)); if (trait == trait_string) { return decode_simple_cfstring(sb); } else if (trait == trait_data) { stream_buffer_read(sb, &count, sizeof(count)); cfvalue = stream_buffer_read_cfdata(sb, count); if (cfvalue == NULL) { return CFRetain(kCFNull); } return cfvalue; } else if (trait == trait_number_long_long || trait == trait_number_double) { if (trait == trait_number_long_long) { stream_buffer_read(sb, &number_long_long, sizeof(number_long_long)); return CFNumberCreate(kCFAllocatorDefault, kCFNumberLongLongType, &number_long_long); } else { stream_buffer_read(sb, &number_double, sizeof(number_double)); return CFNumberCreate(kCFAllocatorDefault, kCFNumberDoubleType, &number_double); } } else if (trait == trait_boolean_true || trait == trait_boolean_false) { return CFRetain((trait == trait_boolean_true) ? kCFBooleanTrue : kCFBooleanFalse); } else if (trait == trait_date) { stream_buffer_read(sb, &absolute_time, sizeof(absolute_time)); return CFDateCreate(kCFAllocatorDefault, absolute_time); } else if (trait == trait_dictionary) { stream_buffer_read(sb, &count, sizeof(count)); keys = (CFTypeRef *)malloc(sizeof(CFTypeRef) * count); values = (CFTypeRef *)malloc(sizeof(CFTypeRef) * count); for (i = 0; i < count; i++) { stream_buffer_move_cursor(sb, sizeof(trait)); keys[i] = decode_simple_cfstring(sb); values[i] = decode_cfvalue_sb(sb); } cfvalue = CFDictionaryCreate(kCFAllocatorDefault, keys, values, count, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); free(keys); free(values); return cfvalue; } else if (trait == trait_array || trait == trait_set) { stream_buffer_read(sb, &count, sizeof(count)); values = (CFTypeRef *)malloc(sizeof(CFTypeRef) * count); for (i = 0; i < count; i++) { values[i] = decode_cfvalue_sb(sb); } if (trait == trait_array) { cfvalue = CFArrayCreate(kCFAllocatorDefault, values, count, &kCFTypeArrayCallBacks); } else { cfvalue = CFSetCreate(kCFAllocatorDefault, values, count, &kCFTypeSetCallBacks); } free(values); return cfvalue; } else { return CFRetain(kCFNull); } }
/* ** OLD OBSOLETE FUNCTIONS with enum SECCertUsage - DO NOT USE FOR NEW CODE ** verify a certificate by checking validity times against a certain time, ** that we trust the issuer, and that the signature on the certificate is ** valid. ** "cert" the certificate to verify ** "checkSig" only check signatures if true */ SECStatus CERT_VerifyCert(SecKeychainRef keychainOrArray, SecCertificateRef cert, const CSSM_DATA_PTR *otherCerts, /* intermediates */ CFTypeRef policies, CFAbsoluteTime stime, SecTrustRef *trustRef) { CFMutableArrayRef certificates = NULL; SecTrustRef trust = NULL; OSStatus rv; int numOtherCerts = SecCmsArrayCount((void **)otherCerts); int dex; /* * Certs to evaluate: first the leaf - our cert - then all the rest we know * about. It's OK for otherCerts to contain a copy of the leaf. */ certificates = CFArrayCreateMutable(NULL, numOtherCerts + 1, &kCFTypeArrayCallBacks); CFArrayAppendValue(certificates, cert); for(dex=0; dex<numOtherCerts; dex++) { SecCertificateRef intCert; rv = SecCertificateCreateFromData(otherCerts[dex], CSSM_CERT_X_509v3, CSSM_CERT_ENCODING_DER, &intCert); if(rv) { goto loser; } CFArrayAppendValue(certificates, intCert); CFRelease(intCert); } rv = SecTrustCreateWithCertificates(certificates, policies, &trust); CFRelease(certificates); certificates = NULL; if (rv) goto loser; rv = SecTrustSetKeychains(trust, keychainOrArray); if (rv) goto loser; CFDateRef verifyDate = CFDateCreate(NULL, stime); rv = SecTrustSetVerifyDate(trust, verifyDate); CFRelease(verifyDate); if (rv) goto loser; if (trustRef) { *trustRef = trust; } else { SecTrustResultType result; /* The caller doesn't want a SecTrust object, so let's evaluate it for them. */ rv = SecTrustEvaluate(trust, &result); if (rv) goto loser; switch (result) { case kSecTrustResultProceed: case kSecTrustResultUnspecified: /* TP Verification succeeded and there was either a UserTurst entry telling us to procceed, or no user trust setting was specified. */ CFRelease(trust); break; default: PORT_SetError(SEC_ERROR_UNTRUSTED_CERT); rv = SECFailure; goto loser; break; } } return SECSuccess; loser: if (trust) CFRelease(trust); if(certificates) CFRelease(certificates); return rv; }