/**
 * Given two strings, compute a score representing whether the internal
 * boundary falls on logical boundaries.
 * Scores range from 5 (best) to 0 (worst).
 * @param one First CFStringRef.
 * @param two Second CFStringRef.
 * @return The score.
 */
CFIndex diff_cleanupSemanticScore(CFStringRef one, CFStringRef two) {
  static Boolean firstRun = true;
  static CFCharacterSetRef alphaNumericSet = NULL;
  static CFCharacterSetRef whiteSpaceSet = NULL;
  static CFCharacterSetRef controlSet = NULL;
  static regex_t blankLineEndRegEx;
  static regex_t blankLineStartRegEx;

  if (firstRun) {
    alphaNumericSet = CFCharacterSetGetPredefined(kCFCharacterSetAlphaNumeric);
    whiteSpaceSet = CFCharacterSetGetPredefined(kCFCharacterSetWhitespaceAndNewline);
    controlSet = CFCharacterSetGetPredefined(kCFCharacterSetControl);

    int status;
    status = regcomp(&blankLineEndRegEx, "\n\r?\n$", REG_EXTENDED | REG_NOSUB);
    check(status == 0);
    status = regcomp(&blankLineStartRegEx, "^\r?\n\r?\n", REG_EXTENDED | REG_NOSUB);
    check(status == 0);

    firstRun = false;
  }


  if (CFStringGetLength(one) == 0 || CFStringGetLength(two) == 0) {
    // Edges are the best.
    return 5;
  }

  // Each port of this function behaves slightly differently due to
  // subtle differences in each language's definition of things like
  // 'whitespace'.  Since this function's purpose is largely cosmetic,
  // the choice has been made to use each language's native features
  // rather than force total conformity.
  CFIndex score = 0;
  UniChar lastCharOfStringOne = CFStringGetCharacterAtIndex(one, (CFStringGetLength(one) - 1));
  UniChar firstCharOfStringTwo = CFStringGetCharacterAtIndex(two, 0);
  // One point for non-alphanumeric.
  if (!CFCharacterSetIsCharacterMember(alphaNumericSet, lastCharOfStringOne)
      || !CFCharacterSetIsCharacterMember(alphaNumericSet, firstCharOfStringTwo)) {
    score++;
    // Two points for whitespace.
    if (CFCharacterSetIsCharacterMember(whiteSpaceSet, lastCharOfStringOne)
        || CFCharacterSetIsCharacterMember(whiteSpaceSet, firstCharOfStringTwo)) {
      score++;
      // Three points for line breaks.
      if (CFCharacterSetIsCharacterMember(controlSet, lastCharOfStringOne)
          || CFCharacterSetIsCharacterMember(controlSet, firstCharOfStringTwo)) {
        score++;
        // Four points for blank lines.
        if (diff_regExMatch(one, &blankLineEndRegEx)
            || diff_regExMatch(two, &blankLineStartRegEx)) {
          score++;
        }
      }
    }
  }
  return score;
}
Пример #2
0
void SendString(CFStringRef str, unsigned delayMS)
{
  //virtual keycodes copied from 10.6 SDK.  Could not find them in 10.4 SDK
  enum { VK_RETURN = 0x24 /*KVK_Return*/, VK_TAB = 0x30 /*kVK_Tab*/, VK_SPACE = 0x31/*kVK_Space*/};
  
  //A list of chars for which we must specify the virtual keycode
  static const CFStringRef specialChars = CFSTR("\n\t ");
  
  static const UniChar verticalTab = CFStringGetCharacterAtIndex(CFSTR("\v"), 0);

  //each keycode must correspond to the correct char in 'specialChars'
  CGKeyCode specialKeyCodes[] = {VK_RETURN, VK_TAB, VK_SPACE };
  
  assert(CFStringGetLength(specialChars) == NumberOf(specialKeyCodes));

  for (unsigned i = 0, len = CFStringGetLength(str); i < len; ++i) {
    //The next char to send
    UniChar c = CFStringGetCharacterAtIndex(str, i);
    
    //throw away 'vertical tab' chars which are only used on Windows to send a shift+tab
    //as a workaround for some issues with IE 
    if (verticalTab == c)
      continue;
    
    //see if we need to specify the virtual keycode for this char
    CGKeyCode vKey = 0; //0 = kVK_ANSI_A, but I don't know of a more appropriate default value
    for (size_t j = 0; j < NumberOf(specialKeyCodes); ++j) {
      if ( CFStringGetCharacterAtIndex(specialChars, j) == c) {
        vKey = specialKeyCodes[j];
        break;
      }
    }
    
    CGEventRef keyDown = CGEventCreateKeyboardEvent(NULL, vKey, true);
    CGEventRef keyUp   = CGEventCreateKeyboardEvent(NULL, vKey, false);
    
    if (keyDown && keyUp) {
      //may be we should not do this if we found the virtual keycode?
      CGEventKeyboardSetUnicodeString(keyDown, 1, &c);
      CGEventKeyboardSetUnicodeString(keyUp, 1, &c);
      
      CGEventPost(kCGSessionEventTap, keyDown);
      CGEventPost(kCGSessionEventTap, keyUp);
      
      pws_os::sleep_ms(delayMS);
      
      CFRelease(keyDown);
      CFRelease(keyUp);
    }
    else {
      if (keyDown) CFRelease(keyDown);
      if (keyUp) CFRelease(keyUp);
      pws_os::IssueError(_T("Out of memory trying to allocate CGEventRef"));
      return;
    }
  }
}
static Boolean _hasNet(CFStringRef path) {
    if (CFStringGetLength(path) >= 2) {
        UniChar firstCharacters[2];
        firstCharacters[0] = CFStringGetCharacterAtIndex(path, 0);
        firstCharacters[1] = CFStringGetCharacterAtIndex(path, 1);
        if (firstCharacters[0] == '\\' && firstCharacters[1] == '\\') return true;
    }
    return false;
}
Пример #4
0
static int16_t handleEventCocoa(NPP instance, PluginObject* obj, NPCocoaEvent* event)
{
    switch (event->type) {
        case NPCocoaEventWindowFocusChanged:
            
        case NPCocoaEventFocusChanged:
            if (event->data.focus.hasFocus)
                pluginLog(instance, "getFocusEvent");
            else
                pluginLog(instance, "loseFocusEvent");
            return 1;

        case NPCocoaEventDrawRect:
            return 1;

        case NPCocoaEventKeyDown:
            if (event->data.key.characters)
                pluginLog(instance, "keyDown '%c'", CFStringGetCharacterAtIndex(reinterpret_cast<CFStringRef>(event->data.key.characters), 0));
            return 1;

        case NPCocoaEventKeyUp:
            if (event->data.key.characters) {
                pluginLog(instance, "keyUp '%c'", CFStringGetCharacterAtIndex(reinterpret_cast<CFStringRef>(event->data.key.characters), 0));
                if (obj->testKeyboardFocusForPlugins) {
                    obj->eventLogging = false;
                    obj->testKeyboardFocusForPlugins = FALSE;
                    executeScript(obj, "layoutTestController.notifyDone();");
                }
            }
            return 1;

        case NPCocoaEventFlagsChanged:
            return 1;

        case NPCocoaEventMouseDown:
            pluginLog(instance, "mouseDown at (%d, %d)", 
                   (int)event->data.mouse.pluginX,
                   (int)event->data.mouse.pluginY);
            return 1;
        case NPCocoaEventMouseUp:
            pluginLog(instance, "mouseUp at (%d, %d)", 
                   (int)event->data.mouse.pluginX,
                   (int)event->data.mouse.pluginY);
            return 1;
            
        case NPCocoaEventMouseMoved:
        case NPCocoaEventMouseEntered:
        case NPCocoaEventMouseExited:
        case NPCocoaEventMouseDragged:
        case NPCocoaEventScrollWheel:
        case NPCocoaEventTextInput:
            return 1;
    }
    
    return 0;
}
Пример #5
0
static UChar32 _CFStringTransformChar32At(const UReplaceable *rep, int32_t offset) {
    CFMutableStringRef string = (CFMutableStringRef)rep;
    UniChar ch = CFStringGetCharacterAtIndex(string, offset);
    if (CFStringIsSurrogateHighCharacter(ch)) {
        UniChar low = CFStringGetCharacterAtIndex(string, offset + 1);
        return CFStringGetLongCharacterForSurrogatePair(ch, low);
    } else {
        return (UChar32)ch;
    }
}
CF_PRIVATE Boolean _CFAppendPathExtension2(CFMutableStringRef path, CFStringRef extension) {
    if (!path) {
        return false;
    }
    
    if (0 < CFStringGetLength(extension) && IS_SLASH(CFStringGetCharacterAtIndex(extension, 0))) {
        return false;
    }
    if (1 < CFStringGetLength(extension)) {
        if (_hasDrive(extension)) return false;
    }
    
    Boolean destHasDrive = (1 < CFStringGetLength(path)) && _hasDrive(path);
    while (((destHasDrive && 3 < CFStringGetLength(path)) || (!destHasDrive && 1 < CFStringGetLength(path))) && IS_SLASH(CFStringGetCharacterAtIndex(path, CFStringGetLength(path) - 1))) {
        CFStringDelete(path, CFRangeMake(CFStringGetLength(path) - 1, 1));
    }

    if (CFStringGetLength(path) == 0) {
        return false;
    }
    
    UniChar firstChar = CFStringGetCharacterAtIndex(path, 0);
    CFIndex newLength = CFStringGetLength(path);
    switch (newLength) {
        case 0:
            return false;
        case 1:
            if (IS_SLASH(firstChar) || firstChar == '~') {
                return false;
            }
            break;
        case 2:
            if (_hasDrive(path) || _hasNet(path)) {
                return false;
            }
            break;
        case 3:
            if (IS_SLASH(CFStringGetCharacterAtIndex(path, 2)) && _hasDrive(path)) {
                return false;
            }
            break;
    }
    if (0 < newLength && firstChar == '~') {
        // Make sure we have a slash in the string
        if (!CFStringFindWithOptions(path, CFPreferredSlashStr, CFRangeMake(1, newLength - 1), 0, NULL)) {
            return false;
        }
    }
    static const UniChar dotChar = '.';
    CFStringAppendCharacters(path, &dotChar, 1);
    CFStringAppend(path, extension);
    return true;
}
static Boolean _hasDrive(CFStringRef path) {
    if (CFStringGetLength(path) >= 2) {
        UniChar firstCharacters[2];
        firstCharacters[0] = CFStringGetCharacterAtIndex(path, 0);
        firstCharacters[1] = CFStringGetCharacterAtIndex(path, 1);
        if (firstCharacters[1] == ':' &&
            (('A' <= (firstCharacters)[0] && (firstCharacters)[0] <= 'Z') ||
             ('a' <= (firstCharacters)[0] && (firstCharacters)[0] <= 'z'))
            ) {
            return true;
        }
    }
    return false;
}
Пример #8
0
CString TextCodecMac::encode(const UChar* characters, size_t length, UnencodableHandling handling)
{
    // FIXME: We should really use TEC here instead of CFString for consistency with the other direction.

    // FIXME: Since there's no "force ASCII range" mode in CFString, we change the backslash into a yen sign.
    // Encoding will change the yen sign back into a backslash.
    String copy(characters, length);
    copy.replace('\\', m_backslashAsCurrencySymbol);
    CFStringRef cfs = copy.createCFString();

    CFIndex startPos = 0;
    CFIndex charactersLeft = CFStringGetLength(cfs);
    Vector<char> result;
    size_t size = 0;
    UInt8 lossByte = handling == QuestionMarksForUnencodables ? '?' : 0;
    while (charactersLeft > 0) {
        CFRange range = CFRangeMake(startPos, charactersLeft);
        CFIndex bufferLength;
        CFStringGetBytes(cfs, range, m_encoding, lossByte, false, NULL, 0x7FFFFFFF, &bufferLength);

        result.grow(size + bufferLength);
        unsigned char* buffer = reinterpret_cast<unsigned char*>(result.data() + size);
        CFIndex charactersConverted = CFStringGetBytes(cfs, range, m_encoding, lossByte, false, buffer, bufferLength, &bufferLength);
        size += bufferLength;

        if (charactersConverted != charactersLeft) {
            unsigned badChar = CFStringGetCharacterAtIndex(cfs, startPos + charactersConverted);
            ++charactersConverted;
            if ((badChar & 0xFC00) == 0xD800 && charactersConverted != charactersLeft) { // is high surrogate
                UniChar low = CFStringGetCharacterAtIndex(cfs, startPos + charactersConverted);
                if ((low & 0xFC00) == 0xDC00) { // is low surrogate
                    badChar <<= 10;
                    badChar += low;
                    badChar += 0x10000 - (0xD800 << 10) - 0xDC00;
                    ++charactersConverted;
                }
            }
            UnencodableReplacementArray entity;
            int entityLength = getUnencodableReplacement(badChar, handling, entity);
            result.grow(size + entityLength);
            memcpy(result.data() + size, entity, entityLength);
            size += entityLength;
        }

        startPos += charactersConverted;
        charactersLeft -= charactersConverted;
    }
    CFRelease(cfs);
    return CString(result.data(), size);
}
Пример #9
0
UString MultiByteToUnicodeString(const AString &srcString, UINT codePage)
{
  if (!srcString.IsEmpty())
  {
    UString resultString;
    const char * path = &srcString[0];

    CFStringRef cfpath = CFStringCreateWithCString(NULL,path,kCFStringEncodingUTF8);

    if (cfpath)
    {

       CFMutableStringRef cfpath2 = CFStringCreateMutableCopy(NULL,0,cfpath);
       CFRelease(cfpath);
       CFStringNormalize(cfpath2,kCFStringNormalizationFormC);
    
       size_t n = CFStringGetLength(cfpath2);
       for(size_t i =   0 ; i< n ;i++) {
         UniChar uc = CFStringGetCharacterAtIndex(cfpath2,i);
         resultString += (wchar_t)uc; // FIXME
       }

       CFRelease(cfpath2);  

       return resultString;
    }
  }

  UString resultString;
  for (int i = 0; i < srcString.Len(); i++)
    resultString += wchar_t(srcString[i] & 255);

  return resultString;
}
CF_PRIVATE CFStringRef _CFCreateLastPathComponent(CFAllocatorRef alloc, CFStringRef path, CFIndex *slashIndex) {
    CFIndex len = CFStringGetLength(path);
    if (len < 2) {
        // Can't be any path components in a string this short
        if (slashIndex) *slashIndex = -1;
        return (CFStringRef)CFRetain(path);
    }
    
    // Find the last slash
    for (CFIndex i = len - 1; i >= 0; i--) {
        if (IS_SLASH(CFStringGetCharacterAtIndex(path, i))) {
            if (slashIndex) *slashIndex = i;
            return CFStringCreateWithSubstring(alloc, path, CFRangeMake(i + 1, len - i - 1));
        }
    }
    
    // Strip any drive if we have one
    if (len > 2 && _hasDrive(path)) {
        if (slashIndex) *slashIndex = -1;
        return CFStringCreateWithSubstring(alloc, path, CFRangeMake(2, len - 2));
    }
    
    // No slash, so just return the same string
    if (slashIndex) *slashIndex = -1;
    return (CFStringRef)CFRetain(path);
}
Пример #11
0
CFStringRef find_path(CFStringRef rootPath, CFStringRef namePattern, CFStringRef expression) {
    FILE *fpipe = NULL;
    CFStringRef quotedRootPath = rootPath;
    if (CFStringGetCharacterAtIndex(rootPath, 0) != '`') {
        quotedRootPath = CFStringCreateWithFormat(NULL, NULL, CFSTR("'%@'"), rootPath);
    }
    CFStringRef cf_command = CFStringCreateWithFormat(NULL, NULL, CFSTR("find %@ -name '%@' %@ 2>/dev/null | sort | tail -n 1"), quotedRootPath, namePattern, expression);
    if (quotedRootPath != rootPath) {
        CFRelease(quotedRootPath);
    }

    char command[1024] = { '\0' };
    CFStringGetCString(cf_command, command, sizeof(command), kCFStringEncodingUTF8);
    CFRelease(cf_command);

    if (!(fpipe = (FILE *)popen(command, "r")))
    {
        perror("Error encountered while opening pipe");
        exit(EXIT_FAILURE);
    }

    char buffer[256] = { '\0' };

    fgets(buffer, sizeof(buffer), fpipe);
    pclose(fpipe);

    strtok(buffer, "\n");
    return CFStringCreateWithCString(NULL, buffer, kCFStringEncodingUTF8);
}
CF_PRIVATE void _CFAppendConditionalTrailingPathSlash2(CFMutableStringRef path) {
    static const UniChar slash[1] = { CFPreferredSlash };
    UniChar character = CFStringGetCharacterAtIndex((CFStringRef)path, CFStringGetLength(path) - 1);
    if (!IS_SLASH(character)) {
        CFStringAppendCharacters(path, slash, 1);
    }
}
Пример #13
0
/* There seems to be a bug with MacFUSE such that the CFString that
 * it returns for kFUSEMountPath in the dictionary accompanying the
 * com.google.filesystems.fusefs.unotifications.mounted notification
 * is represented as UTF-8 within the internal representation.
 * Probably UTF-8 encoded text represented as UTF-16 values. This
 * function transforms it to a true null terminated UTF-8 string.
 * This function assumes that the target buffer out is at least
 * CFStringGetLength(in) bytes long. */
static void GetCorruptedMacFUSEStringAsUTF8(CFStringRef in, char* out, int outsize) {
  int inLength = CFStringGetLength(in);
  int bytesToWrite = MIN(inLength, outsize-1);
  int i;
  for(i = 0; i < bytesToWrite; ++i)
    out[i] = (char)CFStringGetCharacterAtIndex(in, i);
  out[i] = '\0';
}
JNIEXPORT jchar JNICALL WebKit_win32_NATIVE(CFStringGetCharacterAtIndex)
	(JNIEnv *env, jclass that, jintLong arg0, jint arg1)
{
	jchar rc = 0;
	WebKit_win32_NATIVE_ENTER(env, that, CFStringGetCharacterAtIndex_FUNC);
	rc = (jchar)CFStringGetCharacterAtIndex((CFStringRef)arg0, (CFIndex)arg1);
	WebKit_win32_NATIVE_EXIT(env, that, CFStringGetCharacterAtIndex_FUNC);
	return rc;
}
Пример #15
0
static void
CFStringTruncateToUTF8Length(CFMutableStringRef str, ssize_t utf8LengthLimit)
    // Truncates a CFString such that it's UTF-8 representation will have 
    // utf8LengthLimit or less characters (not including the terminating 
    // null character).  Handles UTF-16 surrogates and trims whitespace 
    // from the end of the resulting string.
{
    CFIndex             shortLen;
    CFIndex             convertedLen;
    CFIndex             originalLen;
    CFIndex             utf8Length;
    CFCharacterSetRef   whiteCharSet;
    UniChar             thisChar;
    CFIndex             trailingCharsToDelete;
    
    // Keep converting successively smaller strings until the UTF-8 string is suitably 
    // short.  Note that utf8LengthLimit must be non-negative, so this loop will 
    // always terminate before we run off the front of the string.
    
    originalLen = CFStringGetLength(str);
    shortLen = originalLen;
    do {
        // Because the buffer parameter is NULL, CFStringGetBytes returns the size of 
        // buffer required for the range of characters.  This doesn't include the 
        // trailing null byte traditionally associated with UTF-8 C strings, which 
        // is cool because that's what our caller is expecting.
        
        convertedLen = CFStringGetBytes(str, CFRangeMake(0, shortLen), kCFStringEncodingUTF8, 0, false, NULL, 0, &utf8Length);
        assert( (convertedLen == shortLen) || (convertedLen == (shortLen - 1)) );
        shortLen = convertedLen;
        
        if (utf8Length <= utf8LengthLimit) {
            break;
        }
        shortLen -= 1;
    } while (true);
    
    whiteCharSet = CFCharacterSetGetPredefined(kCFCharacterSetWhitespaceAndNewline);
    assert(whiteCharSet != NULL);
    
    do {
        if ( shortLen == 0 ) {
            break;
        }
        thisChar = CFStringGetCharacterAtIndex(str, shortLen - 1);
        if ( ! CFCharacterSetIsCharacterMember(whiteCharSet, thisChar) ) {
            break;
        }
        shortLen -= 1;
    } while (true);    
    
    trailingCharsToDelete = originalLen - shortLen;
    CFStringDelete(str, CFRangeMake(originalLen - trailingCharsToDelete, trailingCharsToDelete));
}
Пример #16
0
Tcl_UniChar Tcl_UniCharToTitle(Tcl_UniChar c)
{
    if (c < 0x7f)
	return toupper(c);
    CFMutableStringRef str = CFStringCreateMutableWithExternalCharactersNoCopy(kCFAllocatorDefault,&c, 1,0, kCFAllocatorNull);
    CFStringCapitalize(str,NULL);
    Tcl_UniChar retval = c;
    if (CFStringGetLength(str)) { // make sure one exists
	retval = CFStringGetCharacterAtIndex(str, 0);
    }
    CFRelease(str);
    return retval;
}
Пример #17
0
/*++
Function:
  PAL_towupper

See MSDN

--*/
wchar_16
__cdecl
PAL_towupper( wchar_16 c )
{
#if HAVE_COREFOUNDATION
    PERF_ENTRY(towupper);
    ENTRY("towupper (c=%d)\n", c);
    if (!PAL_iswupper(c))
    {
        CFMutableStringRef cfString = CFStringCreateMutable(
                                            kCFAllocatorDefault, 1);
        if (cfString != NULL)
        {
            CFStringAppendCharacters(cfString, (const UniChar*)&c, 1);
            CFStringUppercase(cfString, NULL);
            c = CFStringGetCharacterAtIndex(cfString, 0);
            CFRelease(cfString);
        }
    }
    LOGEXIT("towupper returns int %d\n", c );
    PERF_EXIT(towupper);
    return c;
#else   /* HAVE_COREFOUNDATION */
    UnicodeDataRec dataRec;

    PERF_ENTRY(towupper);
    ENTRY("towupper (c=%d)\n", c);

    if (!GetUnicodeData(c, &dataRec))
    {
        TRACE( "Unable to retrieve unicode data for the character %c.\n", c );
        LOGEXIT("towupper returns int %d\n", c );
        PERF_EXIT(towupper);
        return c;
    }
    
    if ( (dataRec.C1_TYPE_FLAGS & C1_UPPER) || (dataRec.nOpposingCase ==  0 ))
    {
        LOGEXIT("towupper returns int %d\n", c );
        PERF_EXIT(towupper);
        return c;
    }
    else
    {
        LOGEXIT("towupper returns int %d\n", dataRec.nOpposingCase );
        PERF_EXIT(towupper);
        return dataRec.nOpposingCase;
    }
#endif  /* HAVE_COREFOUNDATION */
}
Пример #18
0
/* HasDirectoryPath returns true if pathString ends with a '/' character */
static Boolean HasDirectoryPath(
    CFStringRef pathString,					// input: the path string
    CFURLPathStyle pathStyle)				// input: the path style
{
    Boolean result;

    switch ( pathStyle )
    {
    case kCFURLPOSIXPathStyle:
        result = CFStringGetCharacterAtIndex(pathString, CFStringGetLength(pathString)) == (UniChar)'/';
        break;
    case kCFURLHFSPathStyle:
        result = CFStringGetCharacterAtIndex(pathString, CFStringGetLength(pathString)) == (UniChar)':';
        break;
    case kCFURLWindowsPathStyle:
        result = CFStringGetCharacterAtIndex(pathString, CFStringGetLength(pathString)) == (UniChar)'\\';
        break;
    default:
        result = FALSE;
        break;
    }
    return ( result );
}
Пример #19
0
wchar_t* convert_CFString_to_wchar(const CFStringRef str)
{
  wchar_t *prov = malloc(sizeof(wchar_t) * (CFStringGetLength(str)+1));
  CFIndex i;
  
  if(prov)
    {
      for(i = 0 ; i<CFStringGetLength(str) ; i++)
        prov[i] = CFStringGetCharacterAtIndex(str, i);
      prov[i] = L'\0';
    }

  return prov;
}
Пример #20
0
wchar_t
towlower (wchar_t wc)
{
    CFMutableStringRef strRef = CFStringCreateMutable (NULL, 0);
    UniChar c = (UniChar) wc;
    wchar_t wcs;

    CFStringAppendCharacters (strRef, &c, 1);
    CFStringLowercase (strRef, NULL);
    wcs = CFStringGetCharacterAtIndex (strRef, 0);
    CFRelease (strRef);

    return wcs;
}
CF_PRIVATE CFIndex _CFStartOfLastPathComponent2(CFStringRef path) {
    CFIndex length = CFStringGetLength(path);
    if (length < 2) {
        return 0;
    }
    for (CFIndex idx = length - 1; idx; idx--) {
        if (IS_SLASH(CFStringGetCharacterAtIndex(path, idx - 1))) {
            return idx;
        }
    }
    if ((2 < length && _hasDrive(path))) {
        return 2;
    }
    return 0;
}
CF_PRIVATE void _CFAppendTrailingPathSlash2(CFMutableStringRef path) {
    static const UniChar slash[1] = { CFPreferredSlash };
    CFIndex len = CFStringGetLength(path);
    if (len == 0) {
        // Do nothing for this case
    } else if (len == 1) {
        UniChar character = CFStringGetCharacterAtIndex((CFStringRef)path, 0);
        if (!IS_SLASH(character)) {
            CFStringAppendCharacters(path, slash, 1);
        }
    } else if (len == 2) {
        if (!_hasDrive(path) && !_hasNet(path)) {
            CFStringAppendCharacters(path, slash, 1);
        }
    } else {
        CFStringAppendCharacters(path, slash, 1);
    }
}
/*
 * Convert CFString to little-endian unicode. 
 */
void ntlmStringToLE(
	CFStringRef		pwd,
	unsigned char   **ucode,		// mallocd and RETURNED
	unsigned		*ucodeLen)		// RETURNED
{
	CFIndex len = CFStringGetLength(pwd);
	unsigned char *data = (unsigned char *)malloc(len * 2);
	unsigned char *cp = data;

	CFIndex dex;
	for(dex=0; dex<len; dex++) {
		UniChar uc = CFStringGetCharacterAtIndex(pwd, dex);
		*cp++ = uc & 0xff;
		*cp++ = uc >> 8;
	}
	*ucode = data;
	*ucodeLen = (unsigned)(len * 2);
}
Пример #24
0
/*++
Function:
  PAL_towlower

See MSDN

--*/
wchar_16
__cdecl
PAL_towlower( wchar_16 c )
{
#if HAVE_CFSTRING
    ENTRY("towlower (c=%d)\n", c);
    if (!PAL_iswlower(c))
    {
        CFMutableStringRef cfString = CFStringCreateMutable(
                                            kCFAllocatorDefault, 1);
        if (cfString != NULL)
        {
            CFStringAppendCharacters(cfString, &c, 1);
            CFStringLowercase(cfString, NULL);
            c = CFStringGetCharacterAtIndex(cfString, 0);
            CFRelease(cfString);
        }
    }
    ENTRY("towlower returns int %d\n", c );
    return c;
#else   /* HAVE_CFSTRING */
    UnicodeDataRec dataRec;
    
    ENTRY("towlower (c=%d)\n", c);
    
    if (!GetUnicodeData(c, &dataRec))
    {
        TRACE( "Unable to retrive unicode data for the character %c.\n", c );
        LOGEXIT("towlower returns int %d\n", c );
        return c;
    }

    if ( (dataRec.C1_TYPE_FLAGS & C1_LOWER) || (dataRec.nOpposingCase ==  0 ))
    {
        LOGEXIT("towlower returns int %d\n", c );
        return c;
    }
    else
    {
        LOGEXIT("towlower returns int %d\n", dataRec.nOpposingCase );
        return dataRec.nOpposingCase;
    }
#endif  /* HAVE_CFSTRING */
}
void P12ParseInfo::pwdToUcode(
	CFStringRef str,
	CSSM_DATA &pwd)
{
	if(str == NULL) {
		pwd.Data = NULL;
		pwd.Length = 0;
		return;
	}
	CFIndex len = CFStringGetLength(str);
	mCoder.allocItem(pwd, (len * sizeof(UniChar)) + 2);
	uint8 *cp = pwd.Data;
	for(CFIndex dex=0; dex<len; dex++) {
		UniChar uc = CFStringGetCharacterAtIndex(str, dex);
		*cp++ = uc >> 8;
		*cp++ = uc & 0xff;
	}
	*cp++ = 0;
	*cp++ = 0;
}
CF_PRIVATE CFIndex _CFStartOfPathExtension2(CFStringRef path) {
    if (CFStringGetLength(path) < 2) {
        return 0;
    }
    Boolean hasDrive = _hasDrive(path);
    for (CFIndex idx = CFStringGetLength(path) - 1; idx; idx--) {
        UniChar thisCharacter = CFStringGetCharacterAtIndex(path, idx);
        if (IS_SLASH(thisCharacter)) {
            return 0;
        }
        if (thisCharacter != '.') {
            continue;
        }
        if (idx == 2 && hasDrive) {
            return 0;
        }
        return idx;
    }
    return 0;
}
void	HP_IOCycleTelemetry::Initialize(CFStringRef /*inName*/)
{
    //	get the device's UID
    CACFString theUID(mDevice->CopyDeviceUID());

    //	get the CFHash of the UID
    UInt32 theHashCode = ToUInt32(CFHash(theUID.GetCFString()));

    //	sum all the characters in the UID
    UInt64 theSum = 0;
    UInt32 theNumberCharacters = ToUInt32(CFStringGetLength(theUID.GetCFString()));
    for(UInt32 theCharacterIndex = 0; theCharacterIndex < theNumberCharacters; ++theCharacterIndex)
    {
        UniChar theCharacter = CFStringGetCharacterAtIndex(theUID.GetCFString(), theCharacterIndex);
        theSum += theCharacter;
    }

    //	build a string out of the hash code and character sum
    CFStringRef thePortName = CFStringCreateWithFormat(NULL, NULL, CFSTR(kHALIOCycleTelemetryServerPortNameFormat), CAProcess::GetPID(), theHashCode, theSum);

    //	initialize the super class (who releases the port name too)
    HP_TelemetryServer::Initialize(thePortName);
}
Пример #28
0
/* There has got to be an easier way to do this.  For now we based this code
   on CFNetwork/Connection/URLResponse.cpp. */
static CFStringRef copyParseMaxAge(CFStringRef cacheControlHeader) {
    /* The format of the cache control header is a comma-separated list, but
       each list element could be a key-value pair, with the value quoted and
       possibly containing a comma. */
    CFStringInlineBuffer inlineBuf;
    CFRange componentRange;
    CFIndex length = CFStringGetLength(cacheControlHeader);
    bool done = false;
    CFCharacterSetRef whitespaceSet = CFCharacterSetGetPredefined(kCFCharacterSetWhitespace);
    CFStringRef maxAgeValue = NULL;

    CFStringInitInlineBuffer(cacheControlHeader, &inlineBuf, CFRangeMake(0, length));
    componentRange.location = 0;

    while (!done) {
        bool inQuotes = false;
        bool foundComponentStart = false;
        CFIndex charIndex = componentRange.location;
        CFIndex componentEnd = -1;
        CFRange maxAgeRg;
        componentRange.length = 0;

        while (charIndex < length) {
            UniChar ch = CFStringGetCharacterFromInlineBuffer(&inlineBuf, charIndex);
            if (!inQuotes && ch == ',') {
                componentRange.length = charIndex - componentRange.location;
                break;
            }
            if (!CFCharacterSetIsCharacterMember(whitespaceSet, ch)) {
                if (!foundComponentStart) {
                    foundComponentStart = true;
                    componentRange.location = charIndex;
                } else {
                    componentEnd = charIndex;
                }
                if (ch == '\"') {
                    inQuotes = (inQuotes == false);
                }
            }
            charIndex ++;
        }

        if (componentEnd == -1) {
            componentRange.length = charIndex - componentRange.location;
        } else {
            componentRange.length = componentEnd - componentRange.location + 1;
        }

        if (charIndex == length) {
            /* Fell off the end; this is the last component. */
            done = true;
        }

        /* componentRange should now contain the range of the current
           component; trimmed of any whitespace. */

        /* We want to look for a max-age value. */
        if (!maxAgeValue && CFStringFindWithOptions(cacheControlHeader, CFSTR("max-age"), componentRange, kCFCompareCaseInsensitive | kCFCompareAnchored, &maxAgeRg)) {
            CFIndex equalIdx;
            CFIndex maxCompRg = componentRange.location + componentRange.length;
            for (equalIdx = maxAgeRg.location + maxAgeRg.length; equalIdx < maxCompRg; equalIdx ++) {
                UniChar equalCh = CFStringGetCharacterFromInlineBuffer(&inlineBuf, equalIdx);
                if (equalCh == '=') {
                    // Parse out max-age value
                    equalIdx ++;
                    while (equalIdx < maxCompRg && CFCharacterSetIsCharacterMember(whitespaceSet, CFStringGetCharacterAtIndex(cacheControlHeader, equalIdx))) {
                        equalIdx ++;
                    }
                    if (equalIdx < maxCompRg) {
                        maxAgeValue = CFStringCreateWithSubstring(kCFAllocatorDefault, cacheControlHeader, CFRangeMake(equalIdx, maxCompRg-equalIdx));
                    }
                } else if (!CFCharacterSetIsCharacterMember(whitespaceSet, equalCh)) {
                    // Not a valid max-age header; break out doing nothing
                    break;
                }
            }
        }

        if (!done && maxAgeValue) {
            done = true;
        }
        if (!done) {
            /* Advance to the next component; + 1 to get past the comma. */
            componentRange.location = charIndex + 1;
        }
    }

    return maxAgeValue;
}
Пример #29
0
static void cb(am_device_notification_callback_info * info, void *foo)
{
	struct am_device *dev;

	if (info->msg == ADNCI_MSG_CONNECTED) {
		dev = info->dev;

		AMDeviceConnect(dev);
		assert(AMDeviceIsPaired(dev));
		assert(!AMDeviceValidatePairing(dev));
		assert(!AMDeviceStartSession(dev));

		CFStringRef product =
		    AMDeviceCopyValue(dev, 0, CFSTR("ProductVersion"));
		assert(product);
		UniChar first = CFStringGetCharacterAtIndex(product, 0);
		int epoch = first - '0';
Retry:	{}
		printf("Attempting to mount image...\n");

		service_conn_t afc_socket = 0;
		struct afc_connection *afc = NULL;
		assert(!AMDeviceStartService(dev, CFSTR("com.apple.afc"), &afc_socket, NULL));
		assert(!AFCConnectionOpen(afc_socket, 0, &afc));
		assert(!AFCDirectoryCreate(afc, "PublicStaging"));

		AFCRemovePath(afc, "PublicStaging/staging.dimage");
		qwrite(afc, real_dmg, "PublicStaging/staging.dimage");
		qwrite(afc, ddi_dmg, "PublicStaging/ddi.dimage");

		service_conn_t mim_socket1 = 0;
		service_conn_t mim_socket2 = 0;
		assert(!AMDeviceStartService(dev, CFSTR("com.apple.mobile.mobile_image_mounter"), &mim_socket1, NULL));
		assert(mim_socket1);

		CFPropertyListRef result = NULL;
		CFMutableDictionaryRef dict = CFDictionaryCreateMutable(NULL, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
		CFDictionarySetValue(dict, CFSTR("Command"), CFSTR("MountImage"));
		CFDictionarySetValue(dict, CFSTR("ImageType"), CFSTR("Developer"));

		CFDictionarySetValue(dict, CFSTR("ImagePath"), CFSTR("/var/mobile/Media/PublicStaging/staging.dimage"));

		int fd = open(real_dmg_signature, O_RDONLY);
		assert(fd != -1);
		uint8_t sig[128];
		assert(read(fd, sig, sizeof(sig)) == sizeof(sig));
		close(fd);

		CFDictionarySetValue(dict, CFSTR("ImageSignature"), CFDataCreateWithBytesNoCopy(NULL, sig, sizeof(sig), kCFAllocatorNull));
		send_message(mim_socket1, dict);

		usleep(timesl);
		assert(!AFCRenamePath(afc, "PublicStaging/ddi.dimage", "PublicStaging/staging.dimage"));

		result = receive_message(mim_socket1);

		int len = CFDataGetLength(CFPropertyListCreateXMLData(NULL, result));
		char* bytes = CFDataGetBytePtr(CFPropertyListCreateXMLData(NULL, result));

		if(strstr(bytes, "Complete")) {
			char* the_service = "CopyIt";
			service_conn_t socket = 0;
			sleep(2);
			printf("Image mounted, running helper...\n");
			assert(!AMDeviceStartService(dev, CFStringCreateWithCStringNoCopy(NULL, the_service, kCFStringEncodingUTF8, kCFAllocatorNull),
				&socket, NULL));
			assert(!fcntl(socket, F_SETFL, O_NONBLOCK));
			assert(!fcntl(0, F_SETFL, O_NONBLOCK));
		} else {
			printf("Failed to inject image, trying again... (if it fails, try a different time), delay ... %dus\n", timesl);
			timesl += 1000;
			goto Retry;
		}

		exit(0);
	}
}
Пример #30
0
/*
 * See if this is a BTMM address
 */
int isBTMMAddress(CFStringRef serverNameRef)
{
    boolean_t	foundBTMM;
    CFStringRef btmmRef;
    CFStringRef serverNameQual;
    CFIndex serverNameLen, btmmCount, serverCount, btmmIndex, srvIndex;
    CFArrayRef btmmArrRef, serverArrRef;
    CFStringRef btmmTmpRef, serverTmpRef;
    CFComparisonResult res;
    
    foundBTMM = TRUE;
    btmmRef = NULL;
    serverNameQual = NULL;
    btmmArrRef = NULL;
    serverArrRef = NULL;
	
	if (serverNameRef == NULL) {
		smb_log_info("%s: serverNameRef is NULL!", ASL_LEVEL_DEBUG, __FUNCTION__);
		foundBTMM = FALSE;
        goto out;
	}
	
    serverNameLen = CFStringGetLength(serverNameRef);
	if (serverNameLen == 0) {
		smb_log_info("%s: serverNameRef len is 0!", ASL_LEVEL_DEBUG, __FUNCTION__);
		foundBTMM = FALSE;
        goto out;
	}
    
    /*  Create a copy of the server name, add a trailing '.' */
    /*  if it doesn't already have one. */
    if (CFStringGetCharacterAtIndex(serverNameRef, serverNameLen - 1) == (UniChar)'.') {
        serverNameQual = CFStringCreateCopy(kCFAllocatorDefault, serverNameRef);
    } else {
        serverNameQual = CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR("%@."), serverNameRef);
    }
    
    if (serverNameQual == NULL) {
		foundBTMM = FALSE;
        goto out;
    }
    
    /* Fetch BTMM domain from DynamicStore */
    btmmRef = _CSBackToMyMacCopyDomain();
    if (btmmRef == NULL) {
		foundBTMM = FALSE;
        goto out;
    }
    
    /* Split them into component string arrays */
    btmmArrRef = CFStringCreateArrayBySeparatingStrings(kCFAllocatorDefault, btmmRef, CFSTR("."));
    btmmCount = CFArrayGetCount(btmmArrRef);
    
    serverArrRef = CFStringCreateArrayBySeparatingStrings(kCFAllocatorDefault, serverNameQual, CFSTR("."));
    serverCount = CFArrayGetCount(serverArrRef);
    
    if (btmmCount == 0 || serverCount == 0) {
		foundBTMM = FALSE;
        goto out;
    }
    
    if (btmmCount > serverCount) {
        /* Not a BTMM domain */
		foundBTMM = FALSE;
        goto out;
    }
    
    for (btmmIndex = btmmCount - 1, srvIndex = serverCount - 1; btmmIndex >= 0; btmmIndex--, srvIndex--) {
        btmmTmpRef = CFArrayGetValueAtIndex(btmmArrRef, btmmIndex);
        serverTmpRef = CFArrayGetValueAtIndex(serverArrRef, srvIndex);
        
        res = CFStringCompare(btmmTmpRef, serverTmpRef, kCFCompareCaseInsensitive);
        if (res != kCFCompareEqualTo) {
            /* Not a BTMM domain */
            foundBTMM = FALSE;
            break;
        }
    }
        
	if (foundBTMM == TRUE) {
        smb_log_info("%s: found a btmm address", ASL_LEVEL_DEBUG, __FUNCTION__);
	}

out:
    
    // Clean up mem
    if (btmmArrRef != NULL) {
        CFRelease(btmmArrRef);
    }
    if (serverArrRef != NULL) {
        CFRelease(serverArrRef);
    }
    if (btmmRef != NULL) {
        CFRelease(btmmRef);
    }
    if (serverNameQual !=NULL) {
        CFRelease(serverNameQual);
    }
    
	return (foundBTMM);
}