// ____________________________________________________________________________ // Obtain the name of an endpoint without regard for whether it has connections. // The result should be released by the caller. static CFStringRef EndpointName(MIDIEndpointRef endpoint, bool isExternal) { CFMutableStringRef result = CFStringCreateMutable(NULL, 0); CFStringRef str; // begin with the endpoint's name str = NULL; MIDIObjectGetStringProperty(endpoint, kMIDIPropertyName, &str); if (str != NULL) { CFStringAppend(result, str); CFRelease(str); } MIDIEntityRef entity = NULL; MIDIEndpointGetEntity(endpoint, &entity); if (entity == NULL) // probably virtual return result; if (CFStringGetLength(result) == 0) { // endpoint name has zero length -- try the entity str = NULL; MIDIObjectGetStringProperty(entity, kMIDIPropertyName, &str); if (str != NULL) { CFStringAppend(result, str); CFRelease(str); } } // now consider the device's name MIDIDeviceRef device = NULL; MIDIEntityGetDevice(entity, &device); if (device == NULL) return result; str = NULL; MIDIObjectGetStringProperty(device, kMIDIPropertyName, &str); if (str != NULL) { // if an external device has only one entity, throw away the endpoint name and just use the device name if (isExternal && MIDIDeviceGetNumberOfEntities(device) < 2) { CFRelease(result); return str; } else { // does the entity name already start with the device name? (some drivers do this though they shouldn't) // if so, do not prepend if (CFStringCompareWithOptions(str /* device name */, result /* endpoint name */, CFRangeMake(0, CFStringGetLength(str)), 0) != kCFCompareEqualTo) { // prepend the device name to the entity name if (CFStringGetLength(result) > 0) CFStringInsert(result, 0, CFSTR(" ")); CFStringInsert(result, 0, str); } CFRelease(str); } } return result; }
static void _CFStringTransformCopy(UReplaceable *rep, int32_t start, int32_t limit, int32_t dest) { CFMutableStringRef string = (CFMutableStringRef)rep; UniChar stack_text[BUFFER_SIZE]; UniChar *text = &stack_text[0]; if (limit - start > BUFFER_SIZE) { text = malloc(limit - start); if (text == NULL) { // we cant throw a NSException here, but return before anything blows up... DEBUG_LOG("ICU Internal failure occurred, we are out of memory: time to go cry in a corner now..."); return; } } CFStringGetCharacters(string, CFRangeMake(start, limit - start), text); CFStringRef insert = CFStringCreateWithCharactersNoCopy(kCFAllocatorDefault, text, limit - start, kCFAllocatorNull); CFStringInsert(string, dest, insert); CFRelease(insert); if (text != &stack_text[0]) { free(text); } }
CFStringRef SecCreateRecoveryPassword(void) { CFStringRef result = NULL; CFErrorRef error = NULL; CFDataRef encodedData = NULL; CFDataRef randData = getRandomBytes(16); int i; // base32FDE is a "private" base32 encoding, it has no 0/O or L/l/1 in it (it uses 8 and 9). SecTransformRef encodeTrans = SecEncodeTransformCreate(CFSTR("base32FDE"), &error); if(error == NULL) { SecTransformSetAttribute(encodeTrans, kSecTransformInputAttributeName, randData, &error); if(error == NULL) encodedData = SecTransformExecute(encodeTrans, &error); CFRelease(encodeTrans); } CFRelease(randData); if(encodedData != NULL && error == NULL) { CFStringRef b32string = CFStringCreateFromExternalRepresentation(kCFAllocatorDefault, encodedData, kCFStringEncodingMacRoman); CFMutableStringRef encodedString = CFStringCreateMutableCopy(kCFAllocatorDefault, 64, b32string); // Add some hyphens to make the generated password easier to use for(i = 4; i < 34; i += 5) CFStringInsert(encodedString, i, CFSTR("-")); // Trim so the last section is 4 characters long CFStringDelete(encodedString, CFRangeMake(29,CFStringGetLength(encodedString)-29)); result = CFStringCreateCopy(kCFAllocatorDefault, encodedString); CFRelease(encodedString); CFRelease(b32string); CFRelease(encodedData); } else { secDebug(ASL_LEVEL_ERR, "Failed to base32 encode random data for recovery password\n", NULL); } return result; }
// performs a locale sensitive date formatting operation on the struct tm parameter nsresult nsDateTimeFormatMac::FormatTMTime(nsILocale* locale, const nsDateFormatSelector dateFormatSelector, const nsTimeFormatSelector timeFormatSelector, const struct tm* tmTime, nsAString& stringOut) { nsresult res = NS_OK; // set up locale data (void) Initialize(locale); // return, nothing to format if (dateFormatSelector == kDateFormatNone && timeFormatSelector == kTimeFormatNone) { stringOut.Truncate(); return NS_OK; } NS_ASSERTION(tmTime->tm_mon >= 0, "tm is not set correctly"); NS_ASSERTION(tmTime->tm_mday >= 1, "tm is not set correctly"); NS_ASSERTION(tmTime->tm_hour >= 0, "tm is not set correctly"); NS_ASSERTION(tmTime->tm_min >= 0, "tm is not set correctly"); NS_ASSERTION(tmTime->tm_sec >= 0, "tm is not set correctly"); NS_ASSERTION(tmTime->tm_wday >= 0, "tm is not set correctly"); // Got the locale for the formatter: CFLocaleRef formatterLocale; if (!locale) { formatterLocale = CFLocaleCopyCurrent(); } else { CFStringRef localeStr = CFStringCreateWithCharacters(nullptr, reinterpret_cast<const UniChar*>(mLocale.get()), mLocale.Length()); formatterLocale = CFLocaleCreate(nullptr, localeStr); CFRelease(localeStr); } // Get the date style for the formatter: CFDateFormatterStyle dateStyle; switch (dateFormatSelector) { case kDateFormatLong: dateStyle = kCFDateFormatterLongStyle; break; case kDateFormatShort: dateStyle = kCFDateFormatterShortStyle; break; case kDateFormatYearMonth: case kDateFormatWeekday: dateStyle = kCFDateFormatterNoStyle; // formats handled below break; case kDateFormatNone: dateStyle = kCFDateFormatterNoStyle; break; default: NS_ERROR("Unknown nsDateFormatSelector"); res = NS_ERROR_FAILURE; dateStyle = kCFDateFormatterNoStyle; } // Get the time style for the formatter: CFDateFormatterStyle timeStyle; switch (timeFormatSelector) { case kTimeFormatSeconds: case kTimeFormatSecondsForce24Hour: // 24 hour part fixed below timeStyle = kCFDateFormatterMediumStyle; break; case kTimeFormatNoSeconds: case kTimeFormatNoSecondsForce24Hour: // 24 hour part fixed below timeStyle = kCFDateFormatterShortStyle; break; case kTimeFormatNone: timeStyle = kCFDateFormatterNoStyle; break; default: NS_ERROR("Unknown nsTimeFormatSelector"); res = NS_ERROR_FAILURE; timeStyle = kCFDateFormatterNoStyle; } // Create the formatter and fix up its formatting as necessary: CFDateFormatterRef formatter = CFDateFormatterCreate(nullptr, formatterLocale, dateStyle, timeStyle); CFRelease(formatterLocale); if (dateFormatSelector == kDateFormatYearMonth || dateFormatSelector == kDateFormatWeekday) { CFStringRef dateFormat = dateFormatSelector == kDateFormatYearMonth ? CFSTR("yyyy/MM ") : CFSTR("EEE "); CFStringRef oldFormat = CFDateFormatterGetFormat(formatter); CFMutableStringRef newFormat = CFStringCreateMutableCopy(nullptr, 0, oldFormat); CFStringInsert(newFormat, 0, dateFormat); CFDateFormatterSetFormat(formatter, newFormat); CFRelease(newFormat); // note we don't own oldFormat } if (timeFormatSelector == kTimeFormatSecondsForce24Hour || timeFormatSelector == kTimeFormatNoSecondsForce24Hour) { // Replace "h" with "H", and remove "a": CFStringRef oldFormat = CFDateFormatterGetFormat(formatter); CFMutableStringRef newFormat = CFStringCreateMutableCopy(nullptr, 0, oldFormat); CFIndex replaceCount = CFStringFindAndReplace(newFormat, CFSTR("h"), CFSTR("H"), CFRangeMake(0, CFStringGetLength(newFormat)), 0); NS_ASSERTION(replaceCount <= 2, "Unexpected number of \"h\" occurrences"); replaceCount = CFStringFindAndReplace(newFormat, CFSTR("a"), CFSTR(""), CFRangeMake(0, CFStringGetLength(newFormat)), 0); NS_ASSERTION(replaceCount <= 1, "Unexpected number of \"a\" occurrences"); CFDateFormatterSetFormat(formatter, newFormat); CFRelease(newFormat); // note we don't own oldFormat } // Now get the formatted date: CFGregorianDate date; date.second = tmTime->tm_sec; date.minute = tmTime->tm_min; date.hour = tmTime->tm_hour; date.day = tmTime->tm_mday; // Mac is 1-based, tm is 1-based date.month = tmTime->tm_mon + 1; // Mac is 1-based, tm is 0-based date.year = tmTime->tm_year + 1900; CFTimeZoneRef timeZone = CFTimeZoneCopySystem(); // tmTime is in local time CFAbsoluteTime absTime = CFGregorianDateGetAbsoluteTime(date, timeZone); CFRelease(timeZone); CFStringRef formattedDate = CFDateFormatterCreateStringWithAbsoluteTime(nullptr, formatter, absTime); CFIndex stringLen = CFStringGetLength(formattedDate); AutoTArray<UniChar, 256> stringBuffer; stringBuffer.SetLength(stringLen + 1); CFStringGetCharacters(formattedDate, CFRangeMake(0, stringLen), stringBuffer.Elements()); stringOut.Assign(reinterpret_cast<char16_t*>(stringBuffer.Elements()), stringLen); CFRelease(formattedDate); CFRelease(formatter); return res; }
void DAMountWithArguments( DADiskRef disk, CFURLRef mountpoint, DAMountCallback callback, void * callbackContext, ... ) { /* * Mount the specified volume. A status of 0 indicates success. All arguments in * the argument list shall be of type CFStringRef. The argument list must be NULL * terminated. */ CFStringRef argument = NULL; va_list arguments; CFBooleanRef automatic = kCFBooleanTrue; CFBooleanRef check = NULL; __DAMountCallbackContext * context = NULL; CFIndex count = 0; DAFileSystemRef filesystem = DADiskGetFileSystem( disk ); Boolean force = FALSE; CFIndex index = 0; CFDictionaryRef map = NULL; CFMutableStringRef options = NULL; int status = 0; DALogDebugHeader( "%s -> %s", gDAProcessNameID, gDAProcessNameID ); /* * Initialize our minimal state. */ if ( mountpoint ) { CFRetain( mountpoint ); } /* * Prepare the mount context. */ context = malloc( sizeof( __DAMountCallbackContext ) ); if ( context == NULL ) { status = ENOMEM; goto DAMountWithArgumentsErr; } /* * Prepare the mount options. */ options = CFStringCreateMutable( kCFAllocatorDefault, 0 ); if ( options == NULL ) { status = ENOMEM; goto DAMountWithArgumentsErr; } va_start( arguments, callbackContext ); while ( ( argument = va_arg( arguments, CFStringRef ) ) ) { if ( CFEqual( argument, kDAFileSystemMountArgumentForce ) ) { force = TRUE; } else if ( CFEqual( argument, CFSTR( "automatic" ) ) ) { automatic = NULL; check = kCFBooleanTrue; } else { CFStringAppend( options, argument ); CFStringAppend( options, CFSTR( "," ) ); } } va_end( arguments ); CFStringTrim( options, CFSTR( "," ) ); ///w:start context->automatic = ( automatic == NULL ) ? TRUE : FALSE; ///w:stop /* * Determine whether the volume is to be updated. */ if ( DAMountContainsArgument( options, kDAFileSystemMountArgumentUpdate ) ) { if ( mountpoint ) { status = EINVAL; goto DAMountWithArgumentsErr; } mountpoint = DADiskGetDescription( disk, kDADiskDescriptionVolumePathKey ); if ( mountpoint == NULL ) { status = EINVAL; goto DAMountWithArgumentsErr; } CFRetain( mountpoint ); } /* * Scan the mount map list. */ count = CFArrayGetCount( gDAMountMapList1 ); for ( index = 0; index < count; index++ ) { map = CFArrayGetValueAtIndex( gDAMountMapList1, index ); if ( map ) { CFTypeRef id; CFStringRef kind; id = CFDictionaryGetValue( map, kDAMountMapProbeIDKey ); kind = CFDictionaryGetValue( map, kDAMountMapProbeKindKey ); if ( kind ) { /* * Determine whether the volume kind matches. */ if ( CFEqual( kind, DAFileSystemGetKind( filesystem ) ) == FALSE ) { continue; } } if ( CFGetTypeID( id ) == CFUUIDGetTypeID( ) ) { /* * Determine whether the volume UUID matches. */ if ( DADiskCompareDescription( disk, kDADiskDescriptionVolumeUUIDKey, id ) == kCFCompareEqualTo ) { break; } } else if ( CFGetTypeID( id ) == CFStringGetTypeID( ) ) { /* * Determine whether the volume name matches. */ if ( DADiskCompareDescription( disk, kDADiskDescriptionVolumeNameKey, id ) == kCFCompareEqualTo ) { break; } } else if ( CFGetTypeID( id ) == CFDictionaryGetTypeID( ) ) { boolean_t match = FALSE; /* * Determine whether the device description matches. */ IOServiceMatchPropertyTable( DADiskGetIOMedia( disk ), id, &match ); if ( match ) { break; } } } } /* * Process the map. */ if ( index < count ) { CFStringRef string; /* * Determine whether the volume is to be mounted. */ if ( automatic == NULL ) { automatic = CFDictionaryGetValue( map, kDAMountMapMountAutomaticKey ); if ( automatic == kCFBooleanTrue ) { DADiskSetState( disk, _kDADiskStateMountAutomatic, TRUE ); DADiskSetState( disk, _kDADiskStateMountAutomaticNoDefer, TRUE ); } } /* * Prepare the mount options. */ string = CFDictionaryGetValue( map, kDAMountMapMountOptionsKey ); if ( string ) { CFStringInsert( options, 0, CFSTR( "," ) ); CFStringInsert( options, 0, string ); } /* * Prepare the mount point. */ if ( mountpoint == NULL ) { mountpoint = CFDictionaryGetValue( map, kDAMountMapMountPathKey ); if ( mountpoint ) { CFRetain( mountpoint ); } } } /* * Scan the mount map list. */ count = CFArrayGetCount( gDAMountMapList2 ); for ( index = 0; index < count; index++ ) { map = CFArrayGetValueAtIndex( gDAMountMapList2, index ); if ( map ) { CFTypeRef id; id = CFDictionaryGetValue( map, kDAMountMapProbeIDKey ); /* * Determine whether the volume UUID matches. */ if ( DADiskCompareDescription( disk, kDADiskDescriptionVolumeUUIDKey, id ) == kCFCompareEqualTo ) { break; } } } /* * Process the map. */ if ( index < count ) { CFStringRef string; /* * Prepare the mount options. */ string = CFDictionaryGetValue( map, kDAMountMapMountOptionsKey ); if ( string ) { CFStringInsert( options, 0, CFSTR( "," ) ); CFStringInsert( options, 0, string ); } } /* * Determine whether the volume is to be mounted. */ if ( automatic == NULL ) { if ( DADiskGetState( disk, _kDADiskStateMountAutomatic ) ) { if ( DADiskGetState( disk, _kDADiskStateMountAutomaticNoDefer ) ) { automatic = kCFBooleanTrue; } } else { automatic = kCFBooleanFalse; } if ( automatic == NULL ) { if ( gDAConsoleUserList == NULL ) { if ( DAMountGetPreference( disk, kDAMountPreferenceDefer ) ) { automatic = kCFBooleanFalse; } } } } if ( automatic == kCFBooleanFalse ) { status = ECANCELED; goto DAMountWithArgumentsErr; } /* * Prepare the mount options. */ if ( DADiskGetDescription( disk, kDADiskDescriptionMediaWritableKey ) == kCFBooleanFalse ) { CFStringInsert( options, 0, CFSTR( "," ) ); CFStringInsert( options, 0, kDAFileSystemMountArgumentNoWrite ); } if ( DAMountGetPreference( disk, kDAMountPreferenceTrust ) == FALSE ) { CFStringInsert( options, 0, CFSTR( "," ) ); CFStringInsert( options, 0, kDAFileSystemMountArgumentNoSetUserID ); CFStringInsert( options, 0, CFSTR( "," ) ); CFStringInsert( options, 0, kDAFileSystemMountArgumentNoOwnership ); CFStringInsert( options, 0, CFSTR( "," ) ); CFStringInsert( options, 0, kDAFileSystemMountArgumentNoDevice ); } ///w:start if ( CFEqual( DAFileSystemGetKind( filesystem ), CFSTR( "hfs" ) ) ) { ___CFStringInsertFormat( options, 0, CFSTR( "-m=%o," ), 0755 ); if ( DADiskGetUserGID( disk ) ) { ___CFStringInsertFormat( options, 0, CFSTR( "-g=%d," ), DADiskGetUserGID( disk ) ); } else { ___CFStringInsertFormat( options, 0, CFSTR( "-g=%d," ), ___GID_UNKNOWN ); } if ( DADiskGetUserUID( disk ) ) { ___CFStringInsertFormat( options, 0, CFSTR( "-u=%d," ), DADiskGetUserUID( disk ) ); } else { ___CFStringInsertFormat( options, 0, CFSTR( "-u=%d," ), ___UID_UNKNOWN ); } } ///w:stop CFStringTrim( options, CFSTR( "," ) ); /* * Determine whether the volume is to be repaired. */ if ( check == NULL ) { if ( DAMountContainsArgument( options, kDAFileSystemMountArgumentNoWrite ) ) { check = kCFBooleanFalse; } else { check = kCFBooleanTrue; } } if ( check == kCFBooleanFalse ) { if ( DADiskGetState( disk, kDADiskStateRequireRepair ) ) { if ( force == FALSE ) { status = ___EDIRTY; goto DAMountWithArgumentsErr; } } } if ( check == kCFBooleanTrue ) { if ( DADiskGetState( disk, kDADiskStateRequireRepair ) == FALSE ) { check = kCFBooleanFalse; } } /* * Repair the volume. */ CFRetain( disk ); context->assertionID = kIOPMNullAssertionID; context->callback = callback; context->callbackContext = callbackContext; context->disk = disk; context->force = force; context->mountpoint = mountpoint; context->options = options; if ( check == kCFBooleanTrue ) { DALogDebug( " repaired disk, id = %@, ongoing.", disk ); IOPMAssertionCreateWithDescription( kIOPMAssertionTypePreventUserIdleSystemSleep, CFSTR( _kDADaemonName ), NULL, NULL, NULL, 0, NULL, &context->assertionID ); DAFileSystemRepair( DADiskGetFileSystem( disk ), DADiskGetDevice( disk ), __DAMountWithArgumentsCallbackStage1, context ); } else { __DAMountWithArgumentsCallbackStage1( ECANCELED, context ); } DAMountWithArgumentsErr: if ( status ) { if ( context ) { free( context ); } if ( mountpoint ) { CFRelease( mountpoint ); } if ( options ) { CFRelease( options ); } if ( callback ) { ( callback )( status, NULL, callbackContext ); } } }
static void encodeName(CFStringRef name, CFStringEncoding encoding, CFMutableDictionaryRef startup, CFMutableDictionaryRef globals) { CFDataRef bytes; CFMutableStringRef encodedName = NULL; CFIndex len; if (!isA_CFString(name)) { return; } if (encoding == kCFStringEncodingASCII) { encodedName = (CFMutableStringRef)CFStringCreateCopy(NULL, name); goto done; } /* * encode the potentially non-printable string */ bytes = CFStringCreateExternalRepresentation(NULL, name, encoding, 0); if (bytes) { unsigned char *byte; CFIndex i; /* * check if the MacRoman string can be represented as ASCII */ if (encoding == kCFStringEncodingMacRoman) { CFDataRef ascii; ascii = CFStringCreateExternalRepresentation(NULL, name, kCFStringEncodingASCII, 0); if (ascii) { CFRelease(ascii); CFRelease(bytes); encodedName = (CFMutableStringRef)CFStringCreateCopy(NULL, name); goto done; } } encodedName = CFStringCreateMutable(NULL, 0); len = CFDataGetLength(bytes); byte = (unsigned char *)CFDataGetBytePtr(bytes); for (i = 0; i < len; i++, byte++) { CFStringAppendFormat(encodedName, NULL, CFSTR("%02x"), *byte); } /* * add "encoded string" markers */ CFStringInsert(encodedName, 0, CFSTR("*")); CFStringAppend(encodedName, CFSTR("*")); CFRelease(bytes); } done : if (encodedName) { if (startup) { /* update "startup" dictionary */ CFDictionaryAddValue(startup, CFSTR("APPLETALK_HOSTNAME"), encodedName); } if (globals) { CFNumberRef num; /* update "global" dictionary */ num = CFNumberCreate(NULL, kCFNumberIntType, &encoding); CFDictionaryAddValue(globals, kSCPropNetAppleTalkComputerName, name); CFDictionaryAddValue(globals, kSCPropNetAppleTalkComputerNameEncoding, num); CFRelease(num); } CFRelease(encodedName); } return; }
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; }