Esempio n. 1
0
/*
	druProgressCallback
	
	DRNotificationCallback to handle burn or erase progress.
*/
void
druProgressCallback(DRNotificationCenterRef center,void *observer,CFStringRef name,DRTypeRef object,CFDictionaryRef taskStatus)
{
#pragma unused(center, name, object)
	druBurnStatus	*status = (druBurnStatus*)observer;
	CFStringRef		currentState = NULL;
	CFNumberRef		progressRef = NULL;
	CFNumberRef		currentTrackRef = NULL;
	float			progress = 0.0;
	int				currentTrack = 0;
	char			buffer[sizeof(status->stage)];
	
	/* Get information from the status dictionary. */
	currentState = CFDictionaryGetValue(taskStatus,kDRStatusStateKey);
	progressRef = CFDictionaryGetValue(taskStatus,kDRStatusPercentCompleteKey);
	currentTrackRef = CFDictionaryGetValue(taskStatus,kDRStatusCurrentTrackKey);
	
	/* Fetch values from CFNumbers. */
	if (progressRef != NULL)
		CFNumberGetValue(progressRef,kCFNumberFloatType,&progress);
	if (currentTrackRef != NULL)
		CFNumberGetValue(currentTrackRef,kCFNumberIntType,&currentTrack);
	
	/* Check to see if primary burn state has changed. (Preparing, Writing, Verifying, etc) */
	if (status->lastState == NULL ||
		!CFEqual(status->lastState,currentState) ||
		((currentTrackRef != NULL) && !CFEqual(status->lastTrack,currentTrackRef)))
	{
		/* Yes - did we have a previous state? */
		if (status->lastState != NULL)
		{
			/* Forget about the old state. */
			if (status->lastState) CFRelease(status->lastState);
			if (status->lastTrack) CFRelease(status->lastTrack);
		}
		
		/* If the burn was successful, stop the runloop. */
		if (CFEqual(currentState,kDRStatusStateDone))
		{
			status->completionStatus = (CFDictionaryRef)CFRetain(taskStatus);
			status->success = 1;
			CFRunLoopStop(CFRunLoopGetCurrent());
			return;
		}
		
		/* If the burn was unsuccessful, print a failure message (localized)
			and stop the runloop. */
		if (CFEqual(currentState,kDRStatusStateFailed))
		{
			status->completionStatus = (CFDictionaryRef)CFRetain(taskStatus);
			status->success = 0;
			CFRunLoopStop(CFRunLoopGetCurrent());
			return;
		}
		
		/* Remember the new state. */
		status->lastState = CFStringCreateCopy(NULL,currentState);
		if (currentTrackRef) status->lastTrack = CFRetain(currentTrackRef);
		
		/* Translate the stage into a user-visible string.
			
			We only display a few of the possible states - the others are
			brief and the user doesn't really care about them.
		*/
		buffer[0] = 0;
		if (CFEqual(currentState,kDRStatusStatePreparing))
		{
			if (currentTrack == 0)
				snprintf(buffer,sizeof(buffer),"Preparing...");
			else
				snprintf(buffer,sizeof(buffer),"Preparing track %d ...", currentTrack);
		}
		else if (CFEqual(currentState,kDRStatusStateTrackWrite))
		{
			if (currentTrack != 0)
				snprintf(buffer,sizeof(buffer),"Writing track %d ...", currentTrack);
		}
		else if (CFEqual(currentState,kDRStatusStateSessionClose) ||
				 CFEqual(currentState,kDRStatusStateTrackClose))
		{
			snprintf(buffer,sizeof(buffer),"Closing...");
		}
		else if (CFEqual(currentState,kDRStatusStateVerifying))
		{
			if (currentTrack != 0)
				snprintf(buffer,sizeof(buffer),"Verifying...");
		}
		else if (CFEqual(currentState,kDRStatusStateErasing))
		{
			snprintf(buffer,sizeof(buffer),"Erasing...");
		}
		
		/* Change the stage string - the progress bar will catch this. */
		if (buffer[0] != 0 && strcmp(status->stage,buffer))
			strncpy(status->stage, buffer, sizeof(status->stage));
	}
	
	/* Update the progress bar. */
	druProgressBarUpdate(status->progressBar,status->stage,progress);
}
Esempio n. 2
0
File: parse_url.c Progetto: aosm/smb
CFStringRef CreateURLCFString(CFStringRef Domain, CFStringRef Username,
                              CFStringRef Password, CFStringRef ServerName,
                              CFStringRef Path, CFStringRef PortNumber)
{
	CFMutableDictionaryRef mutableDict = NULL;
	int error;
	CFMutableStringRef urlString = NULL;
	
	mutableDict = CFDictionaryCreateMutable(kCFAllocatorDefault, 0, &kCFTypeDictionaryKeyCallBacks, 
											&kCFTypeDictionaryValueCallBacks);
	if (mutableDict == NULL) {
		smb_log_info("%s: CFDictionaryCreateMutable failed, syserr = %s", 
					 ASL_LEVEL_ERR, __FUNCTION__, strerror(errno));	
		return NULL;
	}
	
	if (Domain && Username) {
		CFMutableStringRef tempString = CFStringCreateMutableCopy(kCFAllocatorDefault, 0, Domain);
		
		if (tempString) {
			CFStringAppend(tempString, CFSTR("\\"));
			CFStringAppend(tempString, Username);
			Username = tempString;
		}
        else {
			CFRetain(Username);
		}
	} else if (Username) {
		CFRetain(Username);
	}
    
	if (Username) {
		CFDictionarySetValue(mutableDict, kNetFSUserNameKey, Username);
		CFRelease(Username);
	}
    
	if (Password) {
		CFDictionarySetValue(mutableDict, kNetFSPasswordKey, Password);
	}
    
	if (ServerName) {
		CFDictionarySetValue(mutableDict, kNetFSHostKey, ServerName);
	}
    
	if (Path) {
		CFDictionarySetValue (mutableDict, kNetFSPathKey, Path);
	}
    
	if (PortNumber) {
		CFDictionarySetValue (mutableDict, kNetFSAlternatePortKey, PortNumber);
	}
    
	error = smb_dictionary_to_urlstring(mutableDict, &urlString);
	CFRelease(mutableDict);
    
	if (error) {
		errno = error;
	}
    
	return urlString;
}
Esempio n. 3
0
/*
	druPromptForDevice
	
	Interactively asks the user to select a device from the devices which are
	currently attached.  If only one device is connected, the device is
	automatically chosen and nothing is printed.
	
	The optional filter function is called to filter devices.  If you wish to
	suppress a device, the filter function should return 0.
	
	The returned device is retained by this routine.
*/
DRDeviceRef
druPromptForDevice(char *promptString, druDeviceFilterProc filter)
{
	CFArrayRef	deviceList = DRCopyDeviceArray();
	CFIndex		deviceCount = CFArrayGetCount(deviceList);
	DRDeviceRef	device;
	CFIndex		selection;
	char		userInput[10];
	
	/* Can't proceed without at least one drive. */
	if (deviceCount == 0)
	{
		printf("Sorry, no CD/DVD drives were found.\n");
		exit(1);
	}
	
	/* Filter the list. */
	if (filter != NULL)
	{
		CFMutableArrayRef	filteredList = CFArrayCreateMutableCopy(NULL,0,deviceList);
		
		for (selection=deviceCount-1; selection>=0; --selection)
			if ((*filter)((DRDeviceRef)CFArrayGetValueAtIndex(filteredList,selection)) == 0)
				CFArrayRemoveValueAtIndex(filteredList,selection);
		
		CFRelease(deviceList);
		deviceList = filteredList;
		deviceCount = CFArrayGetCount(deviceList);
	}
	
	/* Can't proceed without at least one drive. */
	if (deviceCount == 0)
	{
		printf("Sorry, no eligible drives were found.\n");
		exit(1);
	}
	
	/* If there's only one device, which is actually true for many machines (those with
		an internal CD burner and no external burners attached) then the choice
		is obvious, and we don't need to display a menu. */
	if (deviceCount == 1)
	{
		device = (DRDeviceRef)CFArrayGetValueAtIndex(deviceList,0);
		CFRetain(device);
		CFRelease(deviceList);
		return device;
	}
	
	/* Display a menu of devices. */
	printf("Available devices:\n");
	druDisplayDeviceList(deviceList);
	
	/* Display the prompt. */
	if (promptString == NULL)
		promptString = "Please select a device:";
	printf("%s ", promptString);
	fflush(stdout);
	
	/* Get user input. */
	userInput[0] = 0;
	selection = atoi(fgets(userInput,sizeof(userInput),stdin)) - 1;
	if (selection < 0 || selection >= deviceCount)
	{
		printf("Aborted.\n");
		exit(1);
	}
	
	/* Return the selected device. */
	device = (DRDeviceRef)CFArrayGetValueAtIndex(deviceList,selection);
	CFRetain(device);
	CFRelease(deviceList);
	return device;
}
Esempio n. 4
0
//-----------------------------------------------------------------------------
// wxDockEventHandler
//
// This is the global Mac/Carbon event handler for the dock.
// We need this for two reasons:
// 1) To handle wxTaskBarIcon menu events (see below for why)
// 2) To handle events from the dock when it requests a menu
//-----------------------------------------------------------------------------
pascal OSStatus
wxDockEventHandler(EventHandlerCallRef WXUNUSED(inHandlerCallRef),
                   EventRef inEvent,
                   void *pData)
{
    // Get the parameters we want from the event
    wxDockTaskBarIcon* pTB = (wxDockTaskBarIcon*) pData;
    const UInt32 eventClass = GetEventClass(inEvent);
    const UInt32 eventKind = GetEventKind(inEvent);

    OSStatus err = eventNotHandledErr;

    // Handle wxTaskBar menu events (note that this is a global event handler
    // so it will actually get called by all commands/menus)
    if ((eventClass == kEventClassCommand) && (eventKind == kEventCommandProcess || eventKind == kEventCommandUpdateStatus ))
    {
        // if we have no taskbar menu quickly pass it back to wxApp
        if (pTB->m_pMenu != NULL)
        {
            // This is the real reason why we need this. Normally menus
            // get handled in wxMacAppEventHandler
            // However, in the case of a taskbar menu call
            // command.menu.menuRef IS NULL!
            // Which causes the wxApp handler just to skip it.

            // get the HICommand from the event
            HICommand command;
            if (GetEventParameter(inEvent, kEventParamDirectObject,
                typeHICommand, NULL,sizeof(HICommand), NULL, &command ) == noErr)
            {
                // Obtain the REAL menuRef and the menuItemIndex in the real menuRef
                //
                // NOTE: menuRef is generally used here for submenus, as
                // GetMenuItemRefCon could give an incorrect wxMenuItem if we pass
                // just the top level wxTaskBar menu
                MenuItemIndex menuItemIndex;
                MenuRef menuRef;
                MenuRef taskbarMenuRef = MAC_WXHMENU(pTB->m_pMenu->GetHMenu());

                // the next command is only successful if it was a command from the taskbar menu
                // otherwise we pass it on
                if (GetIndMenuItemWithCommandID(taskbarMenuRef,command.commandID,
                    1, &menuRef, &menuItemIndex ) == noErr)
                {
                    wxMenu* itemMenu = wxFindMenuFromMacMenu( menuRef ) ;
                    int id = wxMacCommandToId( command.commandID ) ;
                    wxMenuItem *item = NULL;

                    if (id != 0) // get the wxMenuItem reference from the MenuRef
                        GetMenuItemRefCon( menuRef, menuItemIndex, (URefCon*) &item );

                    if (item && itemMenu )
                    {
                        if ( eventKind == kEventCommandProcess )
                        {
                            if ( itemMenu->HandleCommandProcess( item ) )
                                err = noErr;
                        }
                        else if ( eventKind == kEventCommandUpdateStatus )
                        {
                            if ( itemMenu->HandleCommandUpdateStatus( item ) )
                                err = noErr;
                        }
                    }
                }
            }
        } //end if noErr on getting HICommand from event
    }
    else if ((eventClass == kEventClassApplication) && (eventKind == kEventAppGetDockTileMenu ))
    {
        // process the right click events
        // NB: This may result in double or even triple-creation of the menus
        // We need to do this for 2.4 compat, however
        wxTaskBarIconEvent downevt(wxEVT_TASKBAR_RIGHT_DOWN, NULL);
        pTB->m_parent->ProcessEvent(downevt);

        wxTaskBarIconEvent upevt(wxEVT_TASKBAR_RIGHT_UP, NULL);
        pTB->m_parent->ProcessEvent(upevt);

        // create popup menu
        wxMenu* menu = pTB->DoCreatePopupMenu();

        if (menu != NULL)
        {
            // note to self - a MenuRef *is* a MenuHandle
            MenuRef hMenu = MAC_WXHMENU(menu->GetHMenu());

            // When SetEventParameter is called it will decrement
            // the reference count of the menu - we need to make
            // sure it stays around in the wxMenu class here
            CFRetain(hMenu);

            // set the actual dock menu
            err = SetEventParameter(
                inEvent, kEventParamMenuRef,
                typeMenuRef, sizeof(MenuRef), &hMenu );
            verify_noerr( err );
        }
    }

    return err;
}
Esempio n. 5
0
static CFURLRef _CFCreateHomeDirectoryURLForUser(CFStringRef uName) {
#if defined(__MACH__) || defined(__svr4__) || defined(__hpux__) || defined(__LINUX__) || defined(__FREEBSD__)
    if (!uName) {
        if (geteuid() != __CFEUID || getuid() != __CFUID || !__CFHomeDirectory)
            _CFUpdateUserInfo();
        if (__CFHomeDirectory) CFRetain(__CFHomeDirectory);
        return __CFHomeDirectory;
    } else {
        struct passwd *upwd = NULL;
        char buf[128], *user;
        SInt32 len = CFStringGetLength(uName), size = CFStringGetMaximumSizeForEncoding(len, kCFPlatformInterfaceStringEncoding);
        CFIndex usedSize;
        if (size < 127) {
            user = buf;
        } else {
            user = CFAllocatorAllocate(kCFAllocatorDefault, size+1, 0);
            if (__CFOASafe) __CFSetLastAllocationEventName(user, "CFUtilities (temp)");
        }
        if (CFStringGetBytes(uName, CFRangeMake(0, len), kCFPlatformInterfaceStringEncoding, 0, true, user, size, &usedSize) == len) {
            user[usedSize] = '\0';
            upwd = getpwnam(user);
        }
        if (buf != user) {
            CFAllocatorDeallocate(kCFAllocatorDefault, user);
        }
        return _CFCopyHomeDirURLForUser(upwd);
    }
#elif defined(__WIN32__)
#warning CF: Windows home directory goop disabled
    return NULL;
#if 0
    CFString *user = !uName ? CFUserName() : uName;

    if (!uName || CFEqual(user, CFUserName())) {
        const char *cpath = getenv("HOMEPATH");
        const char *cdrive = getenv("HOMEDRIVE");
        if (cdrive && cpath) {
            char fullPath[CFMaxPathSize];
            CFStringRef str;
            strcpy(fullPath, cdrive);
            strncat(fullPath, cpath, CFMaxPathSize-strlen(cdrive)-1);
            str = CFStringCreateWithCString(NULL, fullPath, kCFPlatformInterfaceStringEncoding);
            home = CFURLCreateWithFileSystemPath(NULL, str, kCFURLWindowsPathStyle, true);
            CFRelease(str);
        }
    }
    if (!home) {
        struct _USER_INFO_2 *userInfo;
        HINSTANCE hinstDll = GetModuleHandleA("NETAPI32");
        if (!hinstDll)
            hinstDll = LoadLibraryEx("NETAPI32", NULL, 0);
        if (hinstDll) {
            FARPROC lpfn = GetProcAddress(hinstDll, "NetUserGetInfo");
            if (lpfn) {
                unsigned namelen = CFStringGetLength(user);
                UniChar *username;
                username = CFAllocatorAllocate(kCFAllocatorDefault, sizeof(UniChar) * (namelen + 1), 0);
                if (__CFOASafe) __CFSetLastAllocationEventName(username, "CFUtilities (temp)");
                CFStringGetCharacters(user, CFRangeMake(0, namelen), username);
                if (!(*lpfn)(NULL, (LPWSTR)username, 2, (LPBYTE *)&userInfo)) {
                    UInt32 len = 0;
                    CFMutableStringRef str;
                    while (userInfo->usri2_home_dir[len] != 0) len ++;
                    str = CFStringCreateMutable(NULL, len+1);
                    CFStringAppendCharacters(str, userInfo->usri2_home_dir, len);
                    home = CFURLCreateWithFileSystemPath(NULL, str, kCFURLWindowsPathStyle, true);
                    CFRelease(str);
                }
                CFAllocatorDeallocate(kCFAllocatorDefault, username);
            }
        } else {
        }
    }
    // We could do more here (as in KB Article Q101507). If that article is to
    // be believed, we should only run into this case on Win95, or through
    // user error.
    if (CFStringGetLength(CFURLGetPath(home)) == 0) {
        CFRelease(home);
        home=NULL;
    }
#endif

#else
#error Dont know how to compute users home directories on this platform
#endif
}
Esempio n. 6
0
void PopupMenu::createPlatformMenu()
{
   OSStatus err = CreateNewMenu( mData->tag, kMenuAttrAutoDisable,&(mData->mMenu));
   CFRetain(mData->mMenu);
   AssertFatal(err == noErr, "Could not create Carbon MenuRef");
}
Esempio n. 7
0
/*----------------------------------------------------------------------------------------------------------*/
pascal OSStatus ScrollingTextViewHandler(EventHandlerCallRef inCaller, EventRef inEvent, void* inRefcon)
	{
	OSStatus result = eventNotHandledErr;
	ScrollingTextBoxData* myData = (ScrollingTextBoxData*)inRefcon;

	switch (GetEventClass(inEvent))
		{

		case kEventClassHIObject:
			switch (GetEventKind(inEvent))
				{
				case kEventHIObjectConstruct:
					{
					// allocate some instance data
					myData = (ScrollingTextBoxData*) calloc(1, sizeof(ScrollingTextBoxData));

					// get our superclass instance
					HIViewRef epView;
					GetEventParameter(inEvent, kEventParamHIObjectInstance, typeHIObjectRef, NULL, sizeof(epView), NULL, &epView);

					// remember our superclass in our instance data and initialize other fields
					myData->view = epView;

					// set the control ID so that we can find it later with HIViewFindByID
					result = SetControlID(myData->view, &kScrollingTextBoxViewID);

					// store our instance data into the event
					result = SetEventParameter(inEvent, kEventParamHIObjectInstance, typeVoidPtr, sizeof(myData), &myData);

					break;
					}

				case kEventHIObjectDestruct:
					{
					if (myData->theTimer != NULL) RemoveEventLoopTimer(myData->theTimer);
					CFRelease(myData->theText);
					free(myData);
					result = noErr;
					break;
					}

				case kEventHIObjectInitialize:
					{
					// always begin kEventHIObjectInitialize by calling through to the previous handler
					result = CallNextEventHandler(inCaller, inEvent);

					// if that succeeded, do our own initialization
					if (result == noErr)
						{
						GetEventParameter(inEvent, kEventParamScrollingText, typeCFStringRef, NULL, sizeof(myData->theText), NULL, &myData->theText);
						CFRetain(myData->theText);
						GetEventParameter(inEvent, kEventParamAutoScroll, typeBoolean, NULL, sizeof(myData->autoScroll), NULL, &myData->autoScroll);
						GetEventParameter(inEvent, kEventParamDelayBeforeAutoScroll, typeUInt32, NULL, sizeof(myData->delayBeforeAutoScroll), NULL, &myData->delayBeforeAutoScroll);
						GetEventParameter(inEvent, kEventParamDelayBetweenAutoScroll, typeUInt32, NULL, sizeof(myData->delayBetweenAutoScroll), NULL, &myData->delayBetweenAutoScroll);
						GetEventParameter(inEvent, kEventParamAutoScrollAmount, typeSInt16, NULL, sizeof(myData->autoScrollAmount), NULL, &myData->autoScrollAmount);
						myData->theTimer = NULL;
						}
					break;
					}

				default:
					break;
				}
			break;

		case kEventClassScrollable:
			switch (GetEventKind(inEvent))
				{
				case kEventScrollableGetInfo:
					{
					// we're being asked to return information about the scrolled view that we set as Event Parameters
					HISize imageSize = {50.0, myData->height};
					SetEventParameter(inEvent, kEventParamImageSize, typeHISize, sizeof(imageSize), &imageSize);
					HISize lineSize = {50.0, 20.0};
					SetEventParameter(inEvent, kEventParamLineSize, typeHISize, sizeof(lineSize), &lineSize);

					HIRect bounds;
					HIViewGetBounds(myData->view, &bounds);
					SetEventParameter(inEvent, kEventParamViewSize, typeHISize, sizeof(bounds.size), &bounds.size);
					SetEventParameter(inEvent, kEventParamOrigin, typeHIPoint, sizeof(myData->originPoint), &myData->originPoint);
					result = noErr;
					break;
					}

				case kEventScrollableScrollTo:
					{
					// we're being asked to scroll, we just do a sanity check and ask for a redraw
					HIPoint where;
					GetEventParameter(inEvent, kEventParamOrigin, typeHIPoint, NULL, sizeof(where), NULL, &where);

					HIViewSetNeedsDisplay(myData->view, true);

					myData->originPoint.y = (where.y < 0.0)?0.0:where.y;
					HIViewSetBoundsOrigin(myData->view, 0, myData->originPoint.y);

					break;
					}

				default:
					break;
				}
			break;

		case kEventClassControl:
			switch (GetEventKind(inEvent))
				{

				//	sets the feature of the view.

				case kEventControlInitialize:
					{
					result = CallNextEventHandler(inCaller, inEvent);
					if (result != noErr) break;

					UInt32 features = 0;
					result = GetEventParameter(inEvent, kEventParamControlFeatures, typeUInt32, NULL, sizeof(features), NULL, &features);
					if (result == noErr)
						features |= kControlSupportsEmbedding;
					else
						features = kControlSupportsEmbedding;

					result = SetEventParameter(inEvent, kEventParamControlFeatures, typeUInt32, sizeof features, &features);

					break;
					}

				//	Our parent view just changed dimensions, so we determined our new height.

				case kEventControlSetData:
					CFRelease(myData->theText);
					CFStringRef *p;
					GetEventParameter(inEvent, kEventParamControlDataBuffer, typePtr, NULL, sizeof(p), NULL, &p);
					myData->theText = *p;
					CFRetain(myData->theText);
					// fallthrough

				case kEventControlBoundsChanged:
					{
					HIRect bounds;
					HIViewGetBounds(myData->view, &bounds);

//
// If we're building on Panther (or later) then HIThemeGetTextDimensions is available, else we use GetThemeTextDimensions
//
#if PANTHER_BUILD
//
// Furthermore, if we're running on Panther then we can call HIThemeGetTextDimensions else we call GetThemeTextDimensions
//
					if (GetHIToolboxVersion() >= Panther_HIToolbox_Version)
						{
						HIThemeTextInfo textInfo = {0, kThemeStateActive, kScrollingTextBoxFontID, kHIThemeTextHorizontalFlushLeft, kHIThemeTextVerticalFlushTop, kHIThemeTextBoxOptionStronglyVertical, kHIThemeTextTruncationNone, 0, false};
						HIThemeGetTextDimensions(myData->theText, bounds.size.width - kMargin - kMargin, &textInfo, NULL, &myData->height, NULL);
						}
					else
#endif
						{
						Point pointBounds;
						pointBounds.h = (int)(bounds.size.width - kMargin - kMargin);
						GetThemeTextDimensions(myData->theText, kScrollingTextBoxFontID, kThemeStateActive, true, &pointBounds, NULL);
						myData->height = pointBounds.v;
						}

					myData->height += 2.0 * kMargin;

					HIViewSetNeedsDisplay(myData->view, true);

					result = eventNotHandledErr;
					break;
					}

				//	Draw the view.

				case kEventControlDraw:
					{
					CGContextRef context;
					result = GetEventParameter(inEvent, kEventParamCGContextRef, typeCGContextRef, NULL, sizeof(context), NULL, &context);

					HIRect bounds;
					HIViewGetBounds(myData->view, &bounds);

					CGContextSaveGState(context);
					CGAffineTransform transform = CGAffineTransformIdentity;
					// adjust the transform so the text doesn't draw upside down
					transform = CGAffineTransformScale(transform, 1, -1);
					CGContextSetTextMatrix(context, transform);

					// now that the proper parameters and configurations have been dealt with, let's draw
					result = ScrollingTextBoxDraw(context, &bounds, myData);

					CGContextRestoreGState(context);

					if (myData->autoScroll)
						CGContextStrokeRect(context, bounds);

					// we postpone starting the autoscroll timer until after we do our first drawing
					if ( (myData->autoScroll) && (myData->theTimer == NULL) )
						InstallEventLoopTimer(GetCurrentEventLoop(), TicksToEventTime(myData->delayBeforeAutoScroll), TicksToEventTime(myData->delayBetweenAutoScroll), myScrollingTextTimeProc, myData, &myData->theTimer);

					result = noErr;
					break;
					}

				default:
					break;
				}
			break;

		default:
			break;
		}

	return result;
	}
Esempio n. 8
0
static CAImageQueueRef WKCAImageQueueRetain(CAImageQueueRef iq) 
{
    if (iq)
        return (CAImageQueueRef)CFRetain(iq);
    return 0;
}
/*
  Create matching dictionaries for the devices we want to get notifications for,
  and add them to the current run loop.  Invoke the callbacks that will be responding
  to these notifications once to arm them, and discover any devices that
  are currently connected at the time notifications are setup.
*/
bool QextSerialEnumeratorPrivate::setUpNotifications_sys(bool /*setup*/)
{
    kern_return_t kernResult;
    mach_port_t masterPort;
    CFRunLoopSourceRef notificationRunLoopSource;
    CFMutableDictionaryRef classesToMatch;
    CFMutableDictionaryRef cdcClassesToMatch;
    io_iterator_t portIterator;

    kernResult = IOMasterPort(MACH_PORT_NULL, &masterPort);
    if (KERN_SUCCESS != kernResult) {
        qDebug() << "IOMasterPort returned:" << kernResult;
        return false;
    }

    classesToMatch = IOServiceMatching(kIOSerialBSDServiceValue);
    if (classesToMatch == nullptr)
        qDebug("IOServiceMatching returned a nullptr dictionary.");
    else
        CFDictionarySetValue(classesToMatch, CFSTR(kIOSerialBSDTypeKey), CFSTR(kIOSerialBSDAllTypes));

    if (!(cdcClassesToMatch = IOServiceNameMatching("AppleUSBCDC"))) {
        QESP_WARNING("couldn't create cdc matching dict");
        return false;
    }

    // Retain an additional reference since each call to IOServiceAddMatchingNotification consumes one.
    classesToMatch = (CFMutableDictionaryRef) CFRetain(classesToMatch);
    cdcClassesToMatch = (CFMutableDictionaryRef) CFRetain(cdcClassesToMatch);

    notificationPortRef = IONotificationPortCreate(masterPort);
    if (notificationPortRef == nullptr) {
        qDebug("IONotificationPortCreate return a nullptr IONotificationPortRef.");
        return false;
    }

    notificationRunLoopSource = IONotificationPortGetRunLoopSource(notificationPortRef);
    if (notificationRunLoopSource == nullptr) {
        qDebug("IONotificationPortGetRunLoopSource returned nullptr CFRunLoopSourceRef.");
        return false;
    }

    CFRunLoopAddSource(CFRunLoopGetCurrent(), notificationRunLoopSource, kCFRunLoopDefaultMode);

    kernResult = IOServiceAddMatchingNotification(notificationPortRef, kIOMatchedNotification, classesToMatch,
                                                  deviceDiscoveredCallbackOSX, this, &portIterator);
    if (kernResult != KERN_SUCCESS) {
        qDebug() << "IOServiceAddMatchingNotification return:" << kernResult;
        return false;
    }

    // arm the callback, and grab any devices that are already connected
    deviceDiscoveredCallbackOSX(this, portIterator);

    kernResult = IOServiceAddMatchingNotification(notificationPortRef, kIOMatchedNotification, cdcClassesToMatch,
                                                  deviceDiscoveredCallbackOSX, this, &portIterator);
    if (kernResult != KERN_SUCCESS) {
        qDebug() << "IOServiceAddMatchingNotification return:" << kernResult;
        return false;
    }

    // arm the callback, and grab any devices that are already connected
    deviceDiscoveredCallbackOSX(this, portIterator);

    kernResult = IOServiceAddMatchingNotification(notificationPortRef, kIOTerminatedNotification, classesToMatch,
                                                  deviceTerminatedCallbackOSX, this, &portIterator);
    if (kernResult != KERN_SUCCESS) {
        qDebug() << "IOServiceAddMatchingNotification return:" << kernResult;
        return false;
    }

    // arm the callback, and clear any devices that are terminated
    deviceTerminatedCallbackOSX(this, portIterator);

    kernResult = IOServiceAddMatchingNotification(notificationPortRef, kIOTerminatedNotification, cdcClassesToMatch,
                                                  deviceTerminatedCallbackOSX, this, &portIterator);
    if (kernResult != KERN_SUCCESS) {
        qDebug() << "IOServiceAddMatchingNotification return:" << kernResult;
        return false;
    }

    // arm the callback, and clear any devices that are terminated
    deviceTerminatedCallbackOSX(this, portIterator);
    return true;
}
Esempio n. 10
0
static CFDictionaryRef __DAMountMapCreate1( CFAllocatorRef allocator, struct fstab * fs )
{
    CFMutableDictionaryRef map = NULL;

    if ( strcmp( fs->fs_type, FSTAB_SW ) )
    {
        char * idAsCString = fs->fs_spec;

        strsep( &idAsCString, "=" );

        if ( idAsCString )
        {
            CFStringRef idAsString;

            idAsString = CFStringCreateWithCString( kCFAllocatorDefault, idAsCString, kCFStringEncodingUTF8 );

            if ( idAsString )
            {
                CFTypeRef id = NULL;

                if ( strcmp( fs->fs_spec, "UUID" ) == 0 )
                {
                    id = ___CFUUIDCreateFromString( kCFAllocatorDefault, idAsString );
                }
                else if ( strcmp( fs->fs_spec, "LABEL" ) == 0 )
                {
                    id = CFRetain( idAsString );
                }
                else if ( strcmp( fs->fs_spec, "DEVICE" ) == 0 )
                {
                    id = ___CFDictionaryCreateFromXMLString( kCFAllocatorDefault, idAsString );
                }

                if ( id )
                {
                    map = CFDictionaryCreateMutable( kCFAllocatorDefault, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks );

                    if ( map )
                    {
                        CFMutableStringRef options;

                        options = CFStringCreateMutable( kCFAllocatorDefault, 0 );

                        if ( options )
                        {
                            char *       argument  = NULL;
                            char *       arguments = fs->fs_mntops;
                            CFBooleanRef automatic = NULL;

                            while ( ( argument = strsep( &arguments, "," ) ) )
                            {
                                if ( strcmp( argument, "auto" ) == 0 )
                                {
                                    automatic = kCFBooleanTrue;
                                }
                                else if ( strcmp( argument, "noauto" ) == 0 )
                                {
                                    automatic = kCFBooleanFalse;
                                }
                                else
                                {
                                    CFStringAppendCString( options, argument, kCFStringEncodingUTF8 );    
                                    CFStringAppendCString( options, ",", kCFStringEncodingUTF8 );
                                }
                            }

                            if ( automatic )
                            {
                                CFDictionarySetValue( map, kDAMountMapMountAutomaticKey, automatic );
                            }

                            if ( CFStringGetLength( options ) )
                            {
                                CFStringTrim( options, CFSTR( "," ) );

                                CFDictionarySetValue( map, kDAMountMapMountOptionsKey, options );
                            }

                            CFRelease( options );
                        }

                        if ( strcmp( fs->fs_file, "none" ) )
                        {
                            CFURLRef path;

                            path = CFURLCreateFromFileSystemRepresentation( kCFAllocatorDefault, ( void * ) fs->fs_file, strlen( fs->fs_file ), TRUE );

                            if ( path )
                            {
                                CFDictionarySetValue( map, kDAMountMapMountPathKey, path );

                                CFRelease( path );
                            }
                        }

                        if ( strcmp( fs->fs_vfstype, "auto" ) )
                        {
                            CFStringRef kind;

                            kind = CFStringCreateWithCString( kCFAllocatorDefault, fs->fs_vfstype, kCFStringEncodingUTF8 );

                            if ( kind )
                            {
                                CFDictionarySetValue( map, kDAMountMapProbeKindKey, kind );

                                CFRelease( kind );
                            }
                        }

                        CFDictionarySetValue( map, kDAMountMapProbeIDKey, id );
                    }

                    CFRelease( id );
                }

                CFRelease( idAsString );
            }
        }
    }

    return map;
}
Esempio n. 11
0
__private_extern__ CFStringRef _CFCopyExtensionForAbstractType(CFStringRef abstractType) {
    return (abstractType ? CFRetain(abstractType) : NULL);
}
Esempio n. 12
0
TStringIRep* TSICTStringCreateWithNumberAndFormat(CFNumberRef number, TSITStringFormat format)
{
    CFRetain(number);
    TSITStringTag tag = kTSITStringTagNumber;
    CFDataRef data;
    CFNumberType numType = CFNumberGetType(number);

    switch(numType) {
        case kCFNumberCharType:
        {
            int value;
            if (CFNumberGetValue(number, kCFNumberIntType, &value)) {
                if (value == 0 || value == 1) {
                    tag = kTSITStringTagBool;
                } else {
                    tag = kTSITStringTagString;
                }
            }
            break;
        }
        case kCFNumberFloat32Type:
        case kCFNumberFloat64Type:
        case kCFNumberFloatType:
        case kCFNumberDoubleType:
        {
            tag = kTSITStringTagFloat;
            break;
        }
    }

    if (tag == kTSITStringTagBool) {
        bool value;
        CFNumberGetValue(number, kCFNumberIntType, &value);
        if (value) {
            data = CFDataCreate(kCFAllocatorDefault, (UInt8*)"true", 4);
        } else {
            data = CFDataCreate(kCFAllocatorDefault, (UInt8*)"false", 5);
        }
    } else if (tag == kTSITStringTagFloat) {
        char buf[32];
        char *p, *e;
        double value;

        CFNumberGetValue(number, numType, &value);
        sprintf(buf, "%#.15g", value);

        e = buf + strlen(buf);
        p = e;
        while (p[-1]=='0' && ('0' <= p[-2] && p[-2] <= '9')) {
            p--;
        }
        memmove(p, e, strlen(e)+1);

        data = CFDataCreate(kCFAllocatorDefault, (UInt8*)buf, (CFIndex)strlen(buf));
    } else {
        char buf[32];
        SInt64 value;
        CFNumberGetValue(number, numType, &value);
        sprintf(buf, "%lli", value);
        data = CFDataCreate(kCFAllocatorDefault, (UInt8*)buf, (CFIndex)strlen(buf));
    }

    TStringIRep* rep = TSICTStringCreateWithDataOfTypeAndFormat(data, tag, format);
    CFRelease(data);
    CFRelease(number);
    return rep;
}
Esempio n. 13
0
static void __DAStagePeek( DADiskRef disk )
{
    /*
     * We commence the "peek" stage if the conditions are right.
     */

    CFMutableArrayRef candidates;

    candidates = CFArrayCreateMutable( kCFAllocatorDefault, 0, &kCFTypeArrayCallBacks );

    if ( candidates )
    {
        DASessionRef session;
        CFArrayRef   sessionList;
        CFIndex      sessionListCount;
        CFIndex      sessionListIndex;

        sessionList      = gDASessionList;
        sessionListCount = CFArrayGetCount( sessionList );

        for ( sessionListIndex = 0; sessionListIndex < sessionListCount; sessionListIndex++ )
        {
            DACallbackRef callback;
            CFArrayRef    callbackList;
            CFIndex       callbackListCount;
            CFIndex       callbackListIndex;
            
            session = ( void * ) CFArrayGetValueAtIndex( sessionList, sessionListIndex );

            callbackList      = DASessionGetCallbackRegister( session );
            callbackListCount = CFArrayGetCount( callbackList );

            for ( callbackListIndex = 0; callbackListIndex < callbackListCount; callbackListIndex++ )
            {
                callback = ( void * ) CFArrayGetValueAtIndex( callbackList, callbackListIndex );

                if ( DACallbackGetKind( callback ) == _kDADiskPeekCallback )
                {
                    CFArrayAppendValue( candidates, callback );
                }
            }
        }

        CFArraySortValues( candidates, CFRangeMake( 0, CFArrayGetCount( candidates ) ), __DAStagePeekCompare, NULL );

        /*
         * Commence the peek.
         */

        CFRetain( disk );

        DADiskSetContext( disk, candidates );

        DADiskSetState( disk, kDADiskStateStagedPeek, TRUE );

        DADiskSetState( disk, kDADiskStateCommandActive, TRUE );

        __DAStagePeekCallback( NULL, disk );

        CFRelease( candidates );
    }
}
//_____________________________________________________________________________
//
void	AUElement::SetName (CFStringRef inName) 
{ 
	if (mElementName) CFRelease (mElementName);
	mElementName = inName; 
	if (mElementName) CFRetain (mElementName);
}
Esempio n. 15
0
SCPreferencesRef
SCPreferencesCreateWithOptions(CFAllocatorRef	allocator,
			       CFStringRef	name,
			       CFStringRef	prefsID,
			       AuthorizationRef	authorization,
			       CFDictionaryRef	options)
{
	CFDataRef			authorizationData	= NULL;
	SCPreferencesPrivateRef		prefsPrivate;

	if (options != NULL) {
		if (!isA_CFDictionary(options)) {
			_SCErrorSet(kSCStatusInvalidArgument);
			return NULL;
		}
	}

	if (authorization != NULL) {
		CFMutableDictionaryRef	authorizationDict;
		CFBundleRef		bundle;
		CFStringRef		bundleID	= NULL;

		authorizationDict =  CFDictionaryCreateMutable(NULL,
							       0,
							       &kCFTypeDictionaryKeyCallBacks,
							       &kCFTypeDictionaryValueCallBacks);
#if	!TARGET_OS_IPHONE
		if (authorization != kSCPreferencesUseEntitlementAuthorization) {
			CFDataRef			data;
			AuthorizationExternalForm	extForm;
			OSStatus			os_status;

			os_status = AuthorizationMakeExternalForm(authorization, &extForm);
			if (os_status != errAuthorizationSuccess) {
				SCLog(TRUE, LOG_INFO, CFSTR("_SCHelperOpen AuthorizationMakeExternalForm() failed"));
				_SCErrorSet(kSCStatusInvalidArgument);
				CFRelease(authorizationDict);
				return NULL;
			}

			data = CFDataCreate(NULL, (const UInt8 *)extForm.bytes, sizeof(extForm.bytes));
			CFDictionaryAddValue(authorizationDict,
					     kSCHelperAuthAuthorization,
					     data);
			CFRelease(data);
		}
#endif

		/* get the application/executable/bundle name */
		bundle = CFBundleGetMainBundle();
		if (bundle != NULL) {
			bundleID = CFBundleGetIdentifier(bundle);
			if (bundleID != NULL) {
				CFRetain(bundleID);
			} else {
				CFURLRef	url;

				url = CFBundleCopyExecutableURL(bundle);
				if (url != NULL) {
					bundleID = CFURLCopyPath(url);
					CFRelease(url);
				}
			}

			if (bundleID != NULL) {
				if (CFEqual(bundleID, CFSTR("/"))) {
					CFRelease(bundleID);
					bundleID = NULL;
				}
			}
		}
		if (bundleID == NULL) {
			bundleID = CFStringCreateWithFormat(NULL, NULL, CFSTR("Unknown(%d)"), getpid());
		}
		CFDictionaryAddValue(authorizationDict,
				     kSCHelperAuthCallerInfo,
				     bundleID);
		CFRelease(bundleID);

		if (authorizationDict != NULL) {
			_SCSerialize((CFPropertyListRef)authorizationDict,
				     &authorizationData,
				     NULL,
				     NULL);
			CFRelease(authorizationDict);
		}
	}

	prefsPrivate = __SCPreferencesCreate(allocator, name, prefsID, authorizationData, options);
	if (authorizationData != NULL) CFRelease(authorizationData);

	return (SCPreferencesRef)prefsPrivate;
}
Esempio n. 16
0
//
// Query NDAS info by Slot number.
//
// Return :	-1 if Bad parameters, No memory or bad Infos.
//			0 if Not exist
//			1 if success.
//
SInt32 NDASPreferencesQueryBySlotNumber(PNDASPreferencesParameter parameter)
{
	CFStringRef				strEntryKey = NULL;	
	CFStringRef				strIDKey[4] = { NULL };
	CFStringRef				strWriteKeyKey = NULL;
	CFStringRef				strConfigurationKey = NULL;
	CFStringRef				strNameKey = NULL;
	
	CFStringRef				strIDValue[4] = { NULL };
	CFStringRef				strWriteKeyValue = NULL;
	CFNumberRef				numberConfigurationValue = NULL;
	CFStringRef				strNameValue = NULL;
	
	CFDictionaryRef			dictEntry = NULL;
	
	int						count;
	bool					present;
	SInt32					result = -1;
	CFArrayRef				cfaKeys = NULL;
	
	if(parameter == NULL || parameter->slotNumber == 0) {
		return -1;
	}

	// Read Last Value.
	CFPreferencesSynchronize( 
							 NDAS_PREFERENCES_FILE_REGISTER,
							 kCFPreferencesAnyUser, 
							 kCFPreferencesCurrentHost
							 );
	
	// Slot Number is the Key.
	strEntryKey = CFStringCreateWithFormat(NULL, NULL, CFSTR(KEY_SLOT_NUMBER_STRING), parameter->slotNumber);
	if(NULL == strEntryKey) {
		return -1;
	}
	
	dictEntry = CFPreferencesCopyValue (
										strEntryKey,
										NDAS_PREFERENCES_FILE_REGISTER,
										kCFPreferencesAnyUser,
										kCFPreferencesCurrentHost
										);
	
	if(dictEntry == NULL) {
		result = 0;
		goto cleanup;
	}
	
	//
	// Check and Copy Values.
	//
	
	// Create Keys.
	for(count = 0; count < 4; count++) {		
		strIDKey[count] = CFStringCreateWithFormat(NULL, NULL, CFSTR(KEY_ID_STRING), count);
		if(NULL == strIDKey[count]) {
			goto cleanup;
		}
	}
	strWriteKeyKey = CFStringCreateWithFormat(NULL, NULL, CFSTR(KEY_WRITEKEY_STRING));
	strConfigurationKey = CFStringCreateWithFormat(NULL, NULL, CFSTR(KEY_CONFIGURATION_STRING));
	if(NULL == strWriteKeyKey || NULL == strConfigurationKey) {
		goto cleanup;
	}
	
	// ID
	for(count = 0; count < 4; count++) {
		
		strIDValue[count] = NDASPreferencesGetIDorWriteKey(dictEntry, strIDKey[count]);
		if (NULL == strIDValue[count]) {
			result = -1;
			goto cleanup;			
		}
		
		if(!CFStringGetCString(strIDValue[count], parameter->chID[count], 6, CFStringGetSystemEncoding())) {
			goto cleanup;
		}
	}
	
	// Write Key.
	strWriteKeyValue = NDASPreferencesGetIDorWriteKey(dictEntry, strWriteKeyKey);
	if (NULL == strWriteKeyValue) {
		// Write Key is Optional.
		memset(parameter->chWriteKey, 0, 6);
	}
	CFStringGetCString(strWriteKeyValue, parameter->chWriteKey, 6, CFStringGetSystemEncoding());
	
	// Copy Name.
	strNameKey = CFStringCreateWithFormat(NULL, NULL, CFSTR(KEY_NAME_STRING), KEY_NAME_STRING);
	if(NULL == strNameKey) {
		goto cleanup;
	}
	
	present = CFDictionaryGetValueIfPresent(
											dictEntry,
											strNameKey,
											(const void**)&strNameValue
											);
	if(!present || !strNameValue) {
		// Name is Optional.
		parameter->cfsName = NULL;
	} else {
		
		CFRetain(strNameValue);
		
		if(CFStringGetTypeID() == CFGetTypeID(strNameValue)) {
			parameter->cfsName = CFStringCreateCopy(kCFAllocatorDefault, strNameValue);
		}
	}
	
	// Configuration.
	present = CFDictionaryGetValueIfPresent(
											dictEntry,
											strConfigurationKey,
											(const void**)&numberConfigurationValue
											);
	if(!present || !numberConfigurationValue) {
		// configuraton is Optional.
		parameter->configuration = kNDASUnitConfigurationUnmount;
	} else {
		
		CFRetain(numberConfigurationValue);
		
		// Convert CF Number to int
		CFNumberGetValue (numberConfigurationValue, kCFNumberSInt32Type, &parameter->configuration);
		
		if(parameter->configuration > kNDASNumberOfUnitConfiguration) {
			parameter->configuration = kNDASUnitConfigurationUnmount;
		}
	}
	
	result = 1;
	
cleanup:
	
	// clean up.	
	if(strEntryKey)					CFRelease(strEntryKey);
	if(dictEntry)					CFRelease(dictEntry);
	
	if(strWriteKeyKey)				CFRelease(strWriteKeyKey);
	if(strWriteKeyValue)			CFRelease(strWriteKeyValue);
	if(strNameKey)					CFRelease(strNameKey);
	if(strNameValue)				CFRelease(strNameValue);
	
	if(strConfigurationKey)			CFRelease(strConfigurationKey);
	if(numberConfigurationValue)	CFRelease(numberConfigurationValue);
	
	for(count = 0; count < 4; count++) {
		if(strIDKey[count])			CFRelease(strIDKey[count]);
		if(strIDValue[count])		CFRelease(strIDValue[count]);
	}
	
	return result;
}
Esempio n. 17
0
static Boolean
__SCPreferencesScheduleWithRunLoop(SCPreferencesRef	prefs,
				   CFRunLoopRef		runLoop,
				   CFStringRef		runLoopMode,
				   dispatch_queue_t	queue)
{
	Boolean			ok		= FALSE;
	SCPreferencesPrivateRef	prefsPrivate	= (SCPreferencesPrivateRef)prefs;

	pthread_mutex_lock(&prefsPrivate->lock);

	if ((prefsPrivate->dispatchQueue != NULL) ||		// if we are already scheduled on a dispatch queue
	    ((queue != NULL) && prefsPrivate->scheduled)) {	// if we are already scheduled on a CFRunLoop
		_SCErrorSet(kSCStatusInvalidArgument);
		goto done;
	}

	if (!prefsPrivate->scheduled) {
		CFMutableArrayRef       keys;

		if (prefsPrivate->session == NULL) {
			ok = __SCPreferencesAddSession(prefs);
			if (!ok) {
				goto done;
			}
		}

		CFRetain(prefs);	// hold a reference to the prefs

		keys = CFArrayCreateMutable(NULL, 0, &kCFTypeArrayCallBacks);
		CFArrayAppendValue(keys, prefsPrivate->sessionKeyCommit);
		CFArrayAppendValue(keys, prefsPrivate->sessionKeyApply);
		(void) SCDynamicStoreSetNotificationKeys(prefsPrivate->session, keys, NULL);
		CFRelease(keys);

		if (runLoop != NULL) {
			prefsPrivate->rls = SCDynamicStoreCreateRunLoopSource(NULL, prefsPrivate->session, 0);
			prefsPrivate->rlList = CFArrayCreateMutable(NULL, 0, &kCFTypeArrayCallBacks);
		}

		prefsPrivate->scheduled = TRUE;
	}

	if (queue != NULL) {
		ok = SCDynamicStoreSetDispatchQueue(prefsPrivate->session, queue);
		if (!ok) {
			prefsPrivate->scheduled = FALSE;
			(void) SCDynamicStoreSetNotificationKeys(prefsPrivate->session, NULL, NULL);
			CFRelease(prefs);
			goto done;
		}

		prefsPrivate->dispatchQueue = queue;
		dispatch_retain(prefsPrivate->dispatchQueue);
	} else {
		if (!_SC_isScheduled(NULL, runLoop, runLoopMode, prefsPrivate->rlList)) {
			/*
			 * if we do not already have notifications scheduled with
			 * this runLoop / runLoopMode
			 */
			CFRunLoopAddSource(runLoop, prefsPrivate->rls, runLoopMode);
		}

		_SC_schedule(prefs, runLoop, runLoopMode, prefsPrivate->rlList);
	}

	ok = TRUE;

    done :

	pthread_mutex_unlock(&prefsPrivate->lock);
	return ok;
}
Esempio n. 18
0
SCNetworkServiceRef
SCNetworkSetCopySelectedVPNService(SCNetworkSetRef set)
{
	CFIndex			i;
	CFIndex			n;
	SCNetworkServiceRef	selected	= NULL;
	CFArrayRef		services;
	CFMutableArrayRef	services_vpn	= NULL;

	if (!isA_SCNetworkSet(set)) {
		_SCErrorSet(kSCStatusInvalidArgument);
		return NULL;
	}

	services = SCNetworkSetCopyServices(set);
	if (services != NULL) {
		n = CFArrayGetCount(services);
		for (i = 0; i < n; i++) {
			SCNetworkServiceRef	service;

			service = CFArrayGetValueAtIndex(services, i);
			if (!SCNetworkServiceGetEnabled(service)) {
				// if not enabled
				continue;
			}

			if (!_SCNetworkServiceIsVPN(service)) {
				// if not VPN service
				continue;
			}

			if (services_vpn == NULL) {
				services_vpn = CFArrayCreateMutable(NULL, 0, &kCFTypeArrayCallBacks);
			}
			CFArrayAppendValue(services_vpn, service);
		}

		CFRelease(services);
	}

	if (services_vpn == NULL) {
		// if no VPN services
		return NULL;
	}

	n = CFArrayGetCount(services_vpn);
	if (n > 1) {
		CFArrayRef		order;
		CFMutableArrayRef	sorted;

		order = SCNetworkSetGetServiceOrder(set);
		sorted = CFArrayCreateMutableCopy(NULL, 0, services_vpn);
		CFArraySortValues(sorted,
				  CFRangeMake(0, CFArrayGetCount(sorted)),
				  _SCNetworkServiceCompare,
				  (void *)order);
		CFRelease(services_vpn);
		services_vpn = sorted;
	}

#if	TARGET_OS_IPHONE
	if (n > 1) {
		CFStringRef	serviceID_prefs;

#define VPN_PREFERENCES	CFSTR("com.apple.mobilevpn")
#define VPN_SERVICE_ID	CFSTR("activeVPNID")

		CFPreferencesAppSynchronize(VPN_PREFERENCES);
		serviceID_prefs = CFPreferencesCopyAppValue(VPN_SERVICE_ID, VPN_PREFERENCES);
		if (serviceID_prefs != NULL) {
			for (i = 0; i < n; i++) {
				SCNetworkServiceRef	service;
				CFStringRef		serviceID;

				service = CFArrayGetValueAtIndex(services_vpn, i);
				serviceID = SCNetworkServiceGetServiceID(service);
				if (CFEqual(serviceID, serviceID_prefs)) {
					selected = service;
					CFRetain(selected);
					break;
				}

			}

			CFRelease(serviceID_prefs);
		}
	}
#endif	// TARGET_OS_IPHONE

	if (selected == NULL) {
		selected = CFArrayGetValueAtIndex(services_vpn, 0);
		CFRetain(selected);
	}

	CFRelease(services_vpn);
	return selected;
}
Esempio n. 19
0
/* This accessor never returns NULL. For usage inside this file, consider __CFErrorGetUserInfo().
*/
CFDictionaryRef CFErrorCopyUserInfo(CFErrorRef err) {
    CFDictionaryRef userInfo = _CFErrorGetUserInfo(err);
    return userInfo ? (CFDictionaryRef)CFRetain(userInfo) : _CFErrorCreateEmptyDictionary(CFGetAllocator(err));
}
Esempio n. 20
0
Boolean
_SCNetworkSetSetSetID(SCNetworkSetRef set, CFStringRef newSetID)
{
	SCNetworkSetRef		currentSet		= NULL;
	SCNetworkSetPrivateRef	currentSetPrivate	= NULL;
	CFDictionaryRef		entity;
	CFStringRef		newPath;
	Boolean			ok			= FALSE;
	CFStringRef		oldPath			= NULL;
	SCNetworkSetPrivateRef	setPrivate		= (SCNetworkSetPrivateRef)set;
	Boolean			updateCurrentSet	= FALSE;

	if (!isA_SCNetworkSet(set)) {
		_SCErrorSet(kSCStatusInvalidArgument);
		return FALSE;
	}

	if (!isA_CFString(newSetID)) {
		_SCErrorSet(kSCStatusInvalidArgument);
		return FALSE;
	}

	// If newSetID is equal to current setID, our work is done
	if (CFEqual(newSetID, setPrivate->setID)) {
		return TRUE;
	}

	newPath = SCPreferencesPathKeyCreateSet(NULL, newSetID);
	entity = SCPreferencesPathGetValue(setPrivate->prefs, newPath);
	if (isA_CFDictionary(entity)) {
		// if the new set already exists
		_SCErrorSet(kSCStatusKeyExists);
		goto done;
	}

	oldPath = SCPreferencesPathKeyCreateSet(NULL, setPrivate->setID);
	entity = SCPreferencesPathGetValue(setPrivate->prefs, oldPath);
	if (!isA_CFDictionary(entity)) {
		// if the set has already been removed
		_SCErrorSet(kSCStatusNoKey);
		goto done;
	}

	ok = SCPreferencesPathSetValue(setPrivate->prefs, newPath, entity);
	if (!ok) {
		goto done;
	}

	ok = SCPreferencesPathRemoveValue(setPrivate->prefs, oldPath);
	if (!ok) {
		goto done;
	}

	// update current set (if needed)
	currentSet = SCNetworkSetCopyCurrent(setPrivate->prefs);
	if (currentSet != NULL) {
		currentSetPrivate = (SCNetworkSetPrivateRef)currentSet;
		if (CFEqual(currentSetPrivate->setID, setPrivate->setID)) {
			updateCurrentSet = TRUE;
		}
		CFRelease(currentSet);
	}

	CFRetain(newSetID);
	CFRelease(setPrivate->setID);

	setPrivate->setID = newSetID;

	if (updateCurrentSet) {
		SCNetworkSetSetCurrent(set);
	}

    done:

	if (oldPath != NULL) {
		CFRelease(oldPath);
	}
	if (newPath != NULL) {
		CFRelease(newPath);
	}

	return ok;
}
Esempio n. 21
0
CFTimeZoneRef CFCalendarCopyTimeZone(CFCalendarRef calendar) {
    CF_OBJC_FUNCDISPATCHV(CFCalendarGetTypeID(), CFTimeZoneRef, calendar_copyTimeZone);
    __CFGenericValidateType(calendar, CFCalendarGetTypeID());
    return (CFTimeZoneRef)CFRetain(calendar->_tz);
}
Esempio n. 22
0
CFStringRef
SCNetworkSetGetName(SCNetworkSetRef set)
{
	CFBundleRef		bundle;
	CFDictionaryRef		entity;
	CFStringRef		path;
	SCNetworkSetPrivateRef	setPrivate	= (SCNetworkSetPrivateRef)set;

	if (!isA_SCNetworkSet(set)) {
		_SCErrorSet(kSCStatusInvalidArgument);
		return NULL;
	}

	if (setPrivate->name != NULL) {
		return setPrivate->name;
	}

	path = SCPreferencesPathKeyCreateSet(NULL, setPrivate->setID);
	entity = SCPreferencesPathGetValue(setPrivate->prefs, path);
	CFRelease(path);

	if (isA_CFDictionary(entity)) {
		CFStringRef	name;

		name = CFDictionaryGetValue(entity, kSCPropUserDefinedName);
		if (isA_CFString(name)) {
			setPrivate->name = CFRetain(name);
		}
	}

	bundle = _SC_CFBundleGet();
	if (bundle != NULL) {
		if (setPrivate->name != NULL) {
			CFStringRef	non_localized;

			non_localized = _SC_CFBundleCopyNonLocalizedString(bundle,
									   CFSTR("DEFAULT_SET_NAME"),
									   CFSTR("Automatic"),
									   NULL);
			if (non_localized != NULL) {
				if (CFEqual(setPrivate->name, non_localized)) {
					CFStringRef	localized;

					// if "Automatic", return localized name
					localized = CFBundleCopyLocalizedString(bundle,
										CFSTR("DEFAULT_SET_NAME"),
										CFSTR("Automatic"),
										NULL);
					if (localized != NULL) {
						CFRelease(setPrivate->name);
						setPrivate->name = localized;
					}
				}

				CFRelease(non_localized);
			}
		}
	}

	return setPrivate->name;
}
Esempio n. 23
0
const char *_CFProcessPath(void) {
#if !defined(__LINUX__)
    CFAllocatorRef alloc = NULL;
    char *thePath = NULL;
    int execIndex = 0;
    
    if (__CFProcessPath) return __CFProcessPath;
    if (!__CFProcessPath) {
        thePath = getenv("CFProcessPath");
        
        alloc = CFRetain(__CFGetDefaultAllocator());
        
	if (thePath) {
	    int len = strlen(thePath);
	    __CFProcessPath = CFAllocatorAllocate(alloc, len+1, 0);
            if (__CFOASafe) __CFSetLastAllocationEventName((void *)__CFProcessPath, "CFUtilities (process-path)");
	    memmove((char *)__CFProcessPath, thePath, len + 1);
	}
    }

#if defined(__MACH__)
    {
	struct stat exec, lcfm;
        unsigned long size = CFMaxPathSize;
        char buffer[CFMaxPathSize];
        if (0 == _NSGetExecutablePath(buffer, &size) &&
            strcasestr(buffer, "LaunchCFMApp") != NULL &&
                0 == stat("/System/Library/Frameworks/Carbon.framework/Versions/Current/Support/LaunchCFMApp", &lcfm) &&
                0 == stat(buffer, &exec) &&
                (lcfm.st_dev == exec.st_dev) &&
                (lcfm.st_ino == exec.st_ino)) {
            // Executable is LaunchCFMApp, take special action
            execIndex = 1;
            __CFIsCFM = true;
        }
    }
#endif
    
    if (!__CFProcessPath && NULL != (*_NSGetArgv())[execIndex]) {
	char buf[CFMaxPathSize] = {0};
#if defined(__WIN32__)
	HINSTANCE hinst = GetModuleHandle(NULL);
	DWORD rlen = hinst ? GetModuleFileName(hinst, buf, 1028) : 0;
	thePath = rlen ? buf : NULL;
#else
	struct stat statbuf;
        const char *arg0 = (*_NSGetArgv())[execIndex];
        if (arg0[0] == '/') {
            // We've got an absolute path; look no further;
            thePath = (char *)arg0;
        } else {
            char *theList = getenv("PATH");
            if (NULL != theList && NULL == strrchr(arg0, '/')) {
                thePath = _CFSearchForNameInPath(alloc, arg0, theList);
                if (thePath) {
                    // User could have "." or "../bin" or other relative path in $PATH
                    if (('/' != thePath[0]) && _CFGetCurrentDirectory(buf, CFMaxPathSize)) {
                        strlcat(buf, "/", CFMaxPathSize);
                        strlcat(buf, thePath, CFMaxPathSize);
                        if (0 == stat(buf, &statbuf)) {
                            CFAllocatorDeallocate(alloc, (void *)thePath);
                            thePath = buf;
                        }
                    }
                    if (thePath != buf) {
                        strlcpy(buf, thePath, CFMaxPathSize);
                        CFAllocatorDeallocate(alloc, (void *)thePath);
                        thePath = buf;
                    }
                }
            }
        }
        
	// After attempting a search through $PATH, if existant,
	// try prepending the current directory to argv[0].
        if (!thePath && _CFGetCurrentDirectory(buf, CFMaxPathSize)) {
            if (buf[strlen(buf)-1] != '/') {
                strlcat(buf, "/", CFMaxPathSize);
            }
	    strlcat(buf, arg0, CFMaxPathSize);
            if (0 == stat(buf, &statbuf)) {
		thePath = buf;
            }
	}

        if (thePath) {
            // We are going to process the buffer replacing all "/./" with "/"
            CFIndex srcIndex = 0, dstIndex = 0;
            CFIndex len = strlen(thePath);
            for (srcIndex=0; srcIndex<len; srcIndex++) {
                thePath[dstIndex] = thePath[srcIndex];
                dstIndex++;
                if ((srcIndex < len-2) && (thePath[srcIndex] == '/') && (thePath[srcIndex+1] == '.') && (thePath[srcIndex+2] == '/')) {
                    // We are at the first slash of a "/./"  Skip the "./"
                    srcIndex+=2;
                }
            }
            thePath[dstIndex] = 0;
        }
#endif
        if (!thePath) {
	    thePath = (*_NSGetArgv())[execIndex];
        }
	if (thePath) {
	    int len = strlen(thePath);
	    __CFProcessPath = CFAllocatorAllocate(alloc, len + 1, 0);
            if (__CFOASafe) __CFSetLastAllocationEventName((void *)__CFProcessPath, "CFUtilities (process-path)");
            memmove((char *)__CFProcessPath, thePath, len + 1);
	}
	if (__CFProcessPath) {
	    const char *p = 0;
	    int i;
	    for (i = 0; __CFProcessPath[i] != 0; i++){
		if (__CFProcessPath[i] == '/')
		    p = __CFProcessPath + i; 
	    }
	    if (p != 0)
		__CFprogname = p + 1;
	    else
		__CFprogname = __CFProcessPath;
	}
    }
#endif
    if (!__CFProcessPath) {
	__CFProcessPath = "";
    }
    return __CFProcessPath;
}
Esempio n. 24
0
void handle_device(AMDeviceRef device) {
    if (found_device) return; // handle one device only

    CFStringRef found_device_id = AMDeviceCopyDeviceIdentifier(device);

    if (device_id != NULL) {
        if(strcmp(device_id, CFStringGetCStringPtr(found_device_id, CFStringGetSystemEncoding())) == 0) {
            found_device = true;
        } else {
            return;
        }
    } else {
        found_device = true;
    }

    CFRetain(device); // don't know if this is necessary?

    printf("[  0%%] Found device (%s), beginning install\n", CFStringGetCStringPtr(found_device_id, CFStringGetSystemEncoding()));

    AMDeviceConnect(device);
    assert(AMDeviceIsPaired(device));
    assert(AMDeviceValidatePairing(device) == 0);
    assert(AMDeviceStartSession(device) == 0);

    CFStringRef path = CFStringCreateWithCString(NULL, app_path, kCFStringEncodingASCII);
    CFURLRef relative_url = CFURLCreateWithFileSystemPath(NULL, path, kCFURLPOSIXPathStyle, false);
    CFURLRef url = CFURLCopyAbsoluteURL(relative_url);

    CFRelease(relative_url);

    int afcFd;
    assert(AMDeviceStartService(device, CFSTR("com.apple.afc"), &afcFd, NULL) == 0);
    assert(AMDeviceStopSession(device) == 0);
    assert(AMDeviceDisconnect(device) == 0);
    assert(AMDeviceTransferApplication(afcFd, path, NULL, transfer_callback, NULL) == 0);

    close(afcFd);

    CFStringRef keys[] = { CFSTR("PackageType") };
    CFStringRef values[] = { CFSTR("Developer") };
    CFDictionaryRef options = CFDictionaryCreate(NULL, (const void **)&keys, (const void **)&values, 1, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);

    AMDeviceConnect(device);
    assert(AMDeviceIsPaired(device));
    assert(AMDeviceValidatePairing(device) == 0);
    assert(AMDeviceStartSession(device) == 0);

    int installFd;
    assert(AMDeviceStartService(device, CFSTR("com.apple.mobile.installation_proxy"), &installFd, NULL) == 0);

    assert(AMDeviceStopSession(device) == 0);
    assert(AMDeviceDisconnect(device) == 0);

    mach_error_t result = AMDeviceInstallApplication(installFd, path, options, install_callback, NULL);
    if (result != 0)
    {
       printf("AMDeviceInstallApplication failed: %d\n", result);
        exit(1);
    }

    close(installFd);

    CFRelease(path);
    CFRelease(options);

    printf("[100%%] Installed package %s\n", app_path);

    if (!debug) exit(0); // no debug phase

    AMDeviceConnect(device);
    assert(AMDeviceIsPaired(device));
    assert(AMDeviceValidatePairing(device) == 0);
    assert(AMDeviceStartSession(device) == 0);

    printf("------ Debug phase ------\n");

    mount_developer_image(device);      // put debugserver on the device
    start_remote_debug_server(device);  // start debugserver
    write_gdb_prep_cmds(device, url);   // dump the necessary gdb commands into a file

    CFRelease(url);

    printf("[100%%] Connecting to remote debug server\n");
    printf("-------------------------\n");

    signal(SIGHUP, gdb_ready_handler);

    pid_t parent = getpid();
    int pid = fork();
    if (pid == 0) {
        system(GDB_SHELL);      // launch gdb
        kill(parent, SIGHUP);  // "No. I am your father."
        _exit(0);
    }
}
Esempio n. 25
0
nsresult
AppleVDADecoder::SubmitFrame(MediaRawData* aSample)
{
  MOZ_ASSERT(mTaskQueue->IsCurrentThreadIn());

  mInputIncoming--;

  AutoCFRelease<CFDataRef> block =
    CFDataCreate(kCFAllocatorDefault, aSample->Data(), aSample->Size());
  if (!block) {
    NS_ERROR("Couldn't create CFData");
    return NS_ERROR_FAILURE;
  }

  AutoCFRelease<CFNumberRef> pts =
    CFNumberCreate(kCFAllocatorDefault,
                   kCFNumberSInt64Type,
                   &aSample->mTime);
  AutoCFRelease<CFNumberRef> dts =
    CFNumberCreate(kCFAllocatorDefault,
                   kCFNumberSInt64Type,
                   &aSample->mTimecode);
  AutoCFRelease<CFNumberRef> duration =
    CFNumberCreate(kCFAllocatorDefault,
                   kCFNumberSInt64Type,
                   &aSample->mDuration);
  AutoCFRelease<CFNumberRef> byte_offset =
    CFNumberCreate(kCFAllocatorDefault,
                   kCFNumberSInt64Type,
                   &aSample->mOffset);
  char keyframe = aSample->mKeyframe ? 1 : 0;
  AutoCFRelease<CFNumberRef> cfkeyframe =
    CFNumberCreate(kCFAllocatorDefault,
                   kCFNumberSInt8Type,
                   &keyframe);

  const void* keys[] = { CFSTR("FRAME_PTS"),
                         CFSTR("FRAME_DTS"),
                         CFSTR("FRAME_DURATION"),
                         CFSTR("FRAME_OFFSET"),
                         CFSTR("FRAME_KEYFRAME") };
  const void* values[] = { pts,
                           dts,
                           duration,
                           byte_offset,
                           cfkeyframe };
  static_assert(ArrayLength(keys) == ArrayLength(values),
                "Non matching keys/values array size");

  AutoCFRelease<CFDictionaryRef> frameInfo =
    CFDictionaryCreate(kCFAllocatorDefault,
                       keys,
                       values,
                       ArrayLength(keys),
                       &kCFTypeDictionaryKeyCallBacks,
                       &kCFTypeDictionaryValueCallBacks);

  mQueuedSamples++;

  OSStatus rv = VDADecoderDecode(mDecoder,
                                 0,
                                 block,
                                 frameInfo);

  if (rv != noErr) {
    NS_WARNING("AppleVDADecoder: Couldn't pass frame to decoder");
    mCallback->Error();
    return NS_ERROR_FAILURE;
  }

  if (mIs106) {
    // TN2267:
    // frameInfo: A CFDictionaryRef containing information to be returned in
    // the output callback for this frame.
    // This dictionary can contain client provided information associated with
    // the frame being decoded, for example presentation time.
    // The CFDictionaryRef will be retained by the framework.
    // In 10.6, it is released one too many. So retain it.
    CFRetain(frameInfo);
  }

  // Ask for more data.
  if (!mInputIncoming && mQueuedSamples <= mMaxRefFrames) {
    LOG("AppleVDADecoder task queue empty; requesting more data");
    mCallback->InputExhausted();
  }

  return NS_OK;
}
Esempio n. 26
0
static Boolean
__SCPreferencesAccess_helper(SCPreferencesRef prefs)
{
	Boolean			ok;
	SCPreferencesPrivateRef	prefsPrivate	= (SCPreferencesPrivateRef)prefs;
	CFDictionaryRef		serverDict	= NULL;
	CFDictionaryRef		serverPrefs	= NULL;
	CFDictionaryRef		serverSignature	= NULL;
	uint32_t		status		= kSCStatusOK;
	CFDataRef		reply		= NULL;

	if (prefsPrivate->helper_port == MACH_PORT_NULL) {
		ok = __SCPreferencesCreate_helper(prefs);
		if (!ok) {
			return FALSE;
		}
	}

	// have the helper "access" the prefs
	ok = _SCHelperExec(prefsPrivate->helper_port,
			   SCHELPER_MSG_PREFS_ACCESS,
			   NULL,
			   &status,
			   &reply);
	if (!ok) {
		goto fail;
	}

	if (status != kSCStatusOK) {
		goto error;
	}

	if (reply == NULL) {
		goto fail;
	}

	ok = _SCUnserialize((CFPropertyListRef *)&serverDict, reply, NULL, 0);
	CFRelease(reply);
	if (!ok) {
		goto fail;
	}

	if (isA_CFDictionary(serverDict)) {
		serverPrefs = CFDictionaryGetValue(serverDict, CFSTR("preferences"));
		serverPrefs = isA_CFDictionary(serverPrefs);

		serverSignature = CFDictionaryGetValue(serverDict, CFSTR("signature"));
		serverSignature = isA_CFData(serverSignature);
	}

	if ((serverPrefs == NULL) || (serverSignature == NULL)) {
		if (serverDict != NULL) CFRelease(serverDict);
		goto fail;
	}

	prefsPrivate->prefs     = CFDictionaryCreateMutableCopy(NULL, 0, serverPrefs);
	prefsPrivate->signature = CFRetain(serverSignature);
	prefsPrivate->accessed  = TRUE;
	CFRelease(serverDict);

	return TRUE;

    fail :

	// close helper
	if (prefsPrivate->helper_port != MACH_PORT_NULL) {
		_SCHelperClose(&prefsPrivate->helper_port);
	}

	status = kSCStatusAccessError;

    error :

	// return error
	_SCErrorSet(status);
	return FALSE;
}
Esempio n. 27
0
int
Tcl_MacOSXOpenVersionedBundleResources(
    Tcl_Interp *interp,
    const char *bundleName,
    const char *bundleVersion,
    int hasResourceFile,
    int maxPathLen,
    char *libraryPath)
{
#ifdef HAVE_COREFOUNDATION
    CFBundleRef bundleRef, versionedBundleRef = NULL;
    CFStringRef bundleNameRef;
    CFURLRef libURL;

    libraryPath[0] = '\0';

    bundleNameRef = CFStringCreateWithCString(NULL, bundleName,
	    kCFStringEncodingUTF8);

    bundleRef = CFBundleGetBundleWithIdentifier(bundleNameRef);
    CFRelease(bundleNameRef);

    if (bundleVersion && bundleRef) {
	/*
	 * Create bundle from bundleVersion subdirectory of 'Versions'.
	 */

	CFURLRef bundleURL = CFBundleCopyBundleURL(bundleRef);

	if (bundleURL) {
	    CFStringRef bundleVersionRef = CFStringCreateWithCString(NULL,
		    bundleVersion, kCFStringEncodingUTF8);

	    if (bundleVersionRef) {
		CFStringRef bundleTailRef = CFURLCopyLastPathComponent(
			bundleURL);

		if (bundleTailRef) {
		    if (CFStringCompare(bundleTailRef, bundleVersionRef, 0) ==
			    kCFCompareEqualTo) {
			versionedBundleRef = (CFBundleRef) CFRetain(bundleRef);
		    }
		    CFRelease(bundleTailRef);
		}
		if (!versionedBundleRef) {
		    CFURLRef versURL = CFURLCreateCopyAppendingPathComponent(
			    NULL, bundleURL, CFSTR("Versions"), TRUE);

		    if (versURL) {
			CFURLRef versionedBundleURL =
				CFURLCreateCopyAppendingPathComponent(
				NULL, versURL, bundleVersionRef, TRUE);
			if (versionedBundleURL) {
			    versionedBundleRef = CFBundleCreate(NULL,
				    versionedBundleURL);
			    CFRelease(versionedBundleURL);
			}
			CFRelease(versURL);
		    }
		}
		CFRelease(bundleVersionRef);
	    }
	    CFRelease(bundleURL);
	}
	if (versionedBundleRef) {
	    bundleRef = versionedBundleRef;
	}
    }

    if (bundleRef) {
	if (hasResourceFile) {
	    /*
	     * Dynamically acquire address for CFBundleOpenBundleResourceMap
	     * symbol, since it is only present in full CoreFoundation on Mac
	     * OS X and not in CFLite on pure Darwin.
	     */

	    static int initialized = FALSE;
	    static short (*openresourcemap)(CFBundleRef) = NULL;

	    if (!initialized) {
#if TCL_DYLD_USE_DLFCN
#if MAC_OS_X_VERSION_MIN_REQUIRED < 1040
		if (tclMacOSXDarwinRelease >= 8)
#endif
		{
		    const char *errMsg = nil;
		    openresourcemap = dlsym(RTLD_NEXT,
			    "CFBundleOpenBundleResourceMap");
		    if (!openresourcemap) {
			errMsg = dlerror();
			TclLoadDbgMsg("dlsym() failed: %s", errMsg);
		    }
		}
		if (!openresourcemap)
#endif
		{
#if TCL_DYLD_USE_NSMODULE
		    NSSymbol nsSymbol = NULL;
		    if (NSIsSymbolNameDefinedWithHint(
			    "_CFBundleOpenBundleResourceMap",
			    "CoreFoundation")) {
			nsSymbol = NSLookupAndBindSymbolWithHint(
				"_CFBundleOpenBundleResourceMap",
				"CoreFoundation");
			if (nsSymbol) {
			    openresourcemap = NSAddressOfSymbol(nsSymbol);
			}
		    }
#endif
		}
		initialized = TRUE;
	    }

	    if (openresourcemap) {
		short refNum;

		refNum = openresourcemap(bundleRef);
	    }
	}

	libURL = CFBundleCopyResourceURL(bundleRef, CFSTR("Scripts"),
		NULL, NULL);

	if (libURL) {
	    /*
	     * FIXME: This is a quick fix, it is probably not right for
	     * internationalization.
	     */

	    CFURLGetFileSystemRepresentation(libURL, TRUE,
		    (unsigned char*) libraryPath, maxPathLen);
	    CFRelease(libURL);
	}
	if (versionedBundleRef) {
	    CFRelease(versionedBundleRef);
	}
    }

    if (libraryPath[0]) {
	return TCL_OK;
    } else {
	return TCL_ERROR;
    }
#else  /* HAVE_COREFOUNDATION */
    return TCL_ERROR;
#endif /* HAVE_COREFOUNDATION */
}
Esempio n. 28
0
static SCPreferencesPrivateRef
__SCPreferencesCreate(CFAllocatorRef	allocator,
		      CFStringRef	name,
		      CFStringRef	prefsID,
		      CFDataRef		authorizationData,
		      CFDictionaryRef	options)
{
	SCPreferencesPrivateRef		prefsPrivate;
	int				sc_status	= kSCStatusOK;

	/*
	 * allocate and initialize a new prefs session
	 */
	prefsPrivate = __SCPreferencesCreatePrivate(allocator);
	if (prefsPrivate == NULL) {
		return NULL;
	}

	prefsPrivate->name = CFStringCreateCopy(allocator, name);
	if (prefsID != NULL) {
		prefsPrivate->prefsID = CFStringCreateCopy(allocator, prefsID);
	}
	if (authorizationData != NULL) {
		prefsPrivate->authorizationData = CFRetain(authorizationData);
	}
	if (options != NULL) {
		prefsPrivate->options = CFDictionaryCreateCopy(allocator, options);
	}

    retry :

	/*
	 * convert prefsID to path
	 */
	prefsPrivate->path = __SCPreferencesPath(allocator,
						 prefsID,
						 (prefsPrivate->newPath == NULL));
	if (prefsPrivate->path == NULL) {
		sc_status = kSCStatusFailed;
		goto error;
	}

	if (access(prefsPrivate->path, R_OK) == 0) {
		goto done;
	}

	switch (errno) {
		case ENOENT :
			/* no prefs file */
			if ((prefsID == NULL) || !CFStringHasPrefix(prefsID, CFSTR("/"))) {
				/* if default preference ID or relative path */
				if (prefsPrivate->newPath == NULL) {
					/*
					 * we've looked in the "new" prefs directory
					 * without success.  Save the "new" path and
					 * look in the "old" prefs directory.
					 */
					prefsPrivate->newPath = prefsPrivate->path;
					goto retry;
				} else {
					/*
					 * we've looked in both the "new" and "old"
					 * prefs directories without success.  Use
					 * the "new" path.
					 */
					CFAllocatorDeallocate(NULL, prefsPrivate->path);
					prefsPrivate->path = prefsPrivate->newPath;
					prefsPrivate->newPath = NULL;
				}
			}

			/* no preference data, start fresh */
			sc_status = kSCStatusNoConfigFile;
			goto done;
		case EPERM  :
		case EACCES :
			if (prefsPrivate->authorizationData != NULL) {
				/* no problem, we'll be using the helper */
				goto done;
			}

			SCLog(_sc_verbose, LOG_DEBUG, CFSTR("__SCPreferencesCreate open() failed: %s"), strerror(errno));
			sc_status = kSCStatusAccessError;
			break;
		default :
			SCLog(TRUE, LOG_ERR, CFSTR("__SCPreferencesCreate open() failed: %s"), strerror(errno));
			sc_status = kSCStatusFailed;
			break;
	}

    error:

	CFRelease(prefsPrivate);
	_SCErrorSet(sc_status);
	return NULL;

    done :

	/* all OK */
	_SCErrorSet(sc_status);
	return prefsPrivate;
}
Esempio n. 29
0
hid_device * HID_API_EXPORT hid_open_path(const char *path)
{
	int i;
	hid_device *dev = NULL;
	CFIndex num_devices;

	dev = new_hid_device();

	/* Set up the HID Manager if it hasn't been done */
	if (hid_init() < 0)
		return NULL;

	/* give the IOHIDManager a chance to update itself */
	process_pending_events();
    IOHIDManagerRef hid_mgr = hidManager();
	CFSetRef device_set = IOHIDManagerCopyDevices(hid_mgr);
    if (device_set==NULL) {
        return NULL;
    }
    
	num_devices = CFSetGetCount(device_set);
	IOHIDDeviceRef *device_array = calloc(num_devices, sizeof(IOHIDDeviceRef));
	CFSetGetValues(device_set, (const void **) device_array);
	for (i = 0; i < num_devices; i++) {
		char cbuf[BUF_LEN];
		size_t len;
		IOHIDDeviceRef os_dev = device_array[i];

		len = make_path(os_dev, cbuf, sizeof(cbuf));
		if (!strcmp(cbuf, path)) {
			/* Matched Paths. Open this Device. */
			IOReturn ret = IOHIDDeviceOpen(os_dev, kIOHIDOptionsTypeSeizeDevice);
			if (ret == kIOReturnSuccess) {
				char str[32];

				free(device_array);
				CFRetain(os_dev);
				CFRelease(device_set);
				dev->device_handle = os_dev;

				/* Create the buffers for receiving data */
				dev->max_input_report_len = (CFIndex) get_max_report_length(os_dev);
				dev->input_report_buf = calloc(dev->max_input_report_len, sizeof(uint8_t));

				/* Create the Run Loop Mode for this device.
				   printing the reference seems to work. */
				sprintf(str, "HIDAPI_%p", os_dev);
				dev->run_loop_mode =
					CFStringCreateWithCString(NULL, str, kCFStringEncodingASCII);

				/* Attach the device to a Run Loop */
				IOHIDDeviceRegisterInputReportCallback(
					os_dev, dev->input_report_buf, dev->max_input_report_len,
					&hid_report_callback, dev);
				IOHIDDeviceRegisterRemovalCallback(dev->device_handle, hid_device_removal_callback, dev);

				/* Start the read thread */
				pthread_create(&dev->thread, NULL, read_thread, dev);

				/* Wait here for the read thread to be initialized. */
				pthread_barrier_wait(&dev->barrier);

				return dev;
			}
			else {
				goto return_error;
			}
		}
	}

return_error:
	free(device_array);
	CFRelease(device_set);
	free_hid_device(dev);
	return NULL;
}
/*
 * Obtain the status of a CMS message's signature. A CMS message can
 * be signed my multiple signers; this function returns the status
 * associated with signer 'n' as indicated by the signerIndex parameter.
 */
OSStatus CMSDecoderCopySignerStatus(
                                    CMSDecoderRef		cmsDecoder,
                                    size_t				signerIndex,
                                    CFTypeRef			policyOrArray,
                                    Boolean				evaluateSecTrust,
                                    CMSSignerStatus		*signerStatus,			/* optional; RETURNED */
                                    SecTrustRef			*secTrust,				/* optional; RETURNED */
                                    OSStatus			*certVerifyResultCode)	/* optional; RETURNED */
{
	if((cmsDecoder == NULL) || (cmsDecoder->decState != DS_Final)) {
		return errSecParam;
	}
	
	/* initialize return values */
	if(signerStatus) {
		*signerStatus = kCMSSignerUnsigned;
	}
	if(secTrust) {
		*secTrust = NULL;
	}
	if(certVerifyResultCode) {
		*certVerifyResultCode = 0;
	}
	
	if(cmsDecoder->signedData == NULL) {
		*signerStatus = kCMSSignerUnsigned;	/* redundant, I know, but explicit */
		return errSecSuccess;
	}
	ASSERT(cmsDecoder->numSigners > 0);
	if(signerIndex >= cmsDecoder->numSigners) {
		*signerStatus = kCMSSignerInvalidIndex;
		return errSecSuccess;
	}
	if(!SecCmsSignedDataHasDigests(cmsDecoder->signedData)) {
		*signerStatus = kCMSSignerNeedsDetachedContent;
		return errSecSuccess;
	}
	
	/*
	 * OK, we should be able to verify this signerInfo.
	 * I think we have to do the SecCmsSignedDataVerifySignerInfo first
	 * in order get all the cert pieces into place before returning them
	 * to the caller.
	 */
	SecTrustRef theTrust = NULL;
	OSStatus vfyRtn = SecCmsSignedDataVerifySignerInfo(cmsDecoder->signedData,
                                                       (int)signerIndex,
                                                       /*
                                                        * FIXME this cast should not be necessary, but libsecurity_smime
                                                        * declares this argument as a SecKeychainRef
                                                        */
                                                       (SecKeychainRef)cmsDecoder->keychainOrArray,
                                                       policyOrArray,
                                                       &theTrust);
    /* Subsequent errors to errOut: */
    
	/*
	 * NOTE the smime lib did NOT evaluate that SecTrust - it only does
	 * SecTrustEvaluate() if we don't ask for a copy.
	 *
	 * FIXME deal with multitudes of status returns here...for now, proceed with
	 * obtaining components the caller wants and assume that a nonzero vfyRtn
	 * means "bad signature".
	 */
	OSStatus ortn = errSecSuccess;
	SecTrustResultType secTrustResult;
	CSSM_RETURN tpVfyStatus = CSSM_OK;
	OSStatus evalRtn;
	
	if(secTrust != NULL) {
		*secTrust = theTrust;
		/* we'll release our reference at the end */
		if (theTrust)
			CFRetain(theTrust);
	}
	SecCmsSignerInfoRef signerInfo =
    SecCmsSignedDataGetSignerInfo(cmsDecoder->signedData, (int)signerIndex);
	if(signerInfo == NULL) {
		/* should never happen */
		ASSERT(0);
		dprintf("CMSDecoderCopySignerStatus: no signerInfo\n");
		ortn = errSecInternalComponent;
		goto errOut;
	}
    
	/* now do the actual cert verify */
	if(evaluateSecTrust) {
		evalRtn = SecTrustEvaluate(theTrust, &secTrustResult);
		if(evalRtn) {
			/* should never happen */
			CSSM_PERROR("SecTrustEvaluate", evalRtn);
			dprintf("CMSDecoderCopySignerStatus: SecTrustEvaluate error\n");
			ortn = errSecInternalComponent;
			goto errOut;
		}
		switch(secTrustResult) {
			case kSecTrustResultUnspecified:
				/* cert chain valid, no special UserTrust assignments */
			case kSecTrustResultProceed:
				/* cert chain valid AND user explicitly trusts this */
				break;
			case kSecTrustResultDeny:
				tpVfyStatus = CSSMERR_APPLETP_TRUST_SETTING_DENY;
				break;
			case kSecTrustResultConfirm:
				dprintf("SecTrustEvaluate reported confirm\n");
				tpVfyStatus = CSSMERR_TP_NOT_TRUSTED;
				break;
			default:
			{
				/* get low-level TP error */
				OSStatus tpStatus;
				ortn = SecTrustGetCssmResultCode(theTrust, &tpStatus);
				if(ortn) {
					CSSM_PERROR("SecTrustGetCssmResultCode", ortn);
				}
				else {
					tpVfyStatus = tpStatus;
				}
				CSSM_PERROR("TP status after SecTrustEvaluate", tpVfyStatus);
				break;
			}
		} 	/* switch(secTrustResult) */
	}		/* evaluateSecTrust true */
	if(certVerifyResultCode != NULL) {
		*certVerifyResultCode = tpVfyStatus;
	}
	
	/* cook up global status based on vfyRtn and tpVfyStatus */
	if(signerStatus != NULL) {
		if((vfyRtn == errSecSuccess) && (tpVfyStatus == CSSM_OK))  {
			*signerStatus = kCMSSignerValid;
		}
		else if(vfyRtn != errSecSuccess) {
			/* this could mean other things, but for now... */
			*signerStatus = kCMSSignerInvalidSignature;
		}
		else {
			*signerStatus = kCMSSignerInvalidCert;
		}
	}
errOut:
	CFRELEASE(theTrust);
	return ortn;
}