Esempio n. 1
0
void ResourceHandle::createCFURLConnection(bool shouldUseCredentialStorage, bool shouldRelaxThirdPartyCookiePolicy, bool shouldContentSniff)
{
    if ((!d->m_user.isEmpty() || !d->m_pass.isEmpty()) && !firstRequest().url().protocolIsInHTTPFamily()) {
        // Credentials for ftp can only be passed in URL, the didReceiveAuthenticationChallenge delegate call won't be made.
        KURL urlWithCredentials(firstRequest().url());
        urlWithCredentials.setUser(d->m_user);
        urlWithCredentials.setPass(d->m_pass);
        firstRequest().setURL(urlWithCredentials);
    }

    if (shouldRelaxThirdPartyCookiePolicy)
        firstRequest().setFirstPartyForCookies(firstRequest().url());

    // <rdar://problem/7174050> - For URLs that match the paths of those previously challenged for HTTP Basic authentication, 
    // try and reuse the credential preemptively, as allowed by RFC 2617.
    if (shouldUseCredentialStorage && firstRequest().url().protocolIsInHTTPFamily()) {
        if (d->m_user.isEmpty() && d->m_pass.isEmpty()) {
            // <rdar://problem/7174050> - For URLs that match the paths of those previously challenged for HTTP Basic authentication, 
            // try and reuse the credential preemptively, as allowed by RFC 2617.
            d->m_initialCredential = CredentialStorage::get(firstRequest().url());
        } else {
            // If there is already a protection space known for the URL, update stored credentials before sending a request.
            // This makes it possible to implement logout by sending an XMLHttpRequest with known incorrect credentials, and aborting it immediately
            // (so that an authentication dialog doesn't pop up).
            CredentialStorage::set(Credential(d->m_user, d->m_pass, CredentialPersistenceNone), firstRequest().url());
        }
    }
        
    if (!d->m_initialCredential.isEmpty()) {
        // FIXME: Support Digest authentication, and Proxy-Authorization.
        applyBasicAuthorizationHeader(firstRequest(), d->m_initialCredential);
    }

    RetainPtr<CFMutableURLRequestRef> request = adoptCF(CFURLRequestCreateMutableCopy(kCFAllocatorDefault, firstRequest().cfURLRequest()));
    wkSetRequestStorageSession(d->m_storageSession.get(), request.get());
    
    if (!shouldContentSniff)
        wkSetCFURLRequestShouldContentSniff(request.get(), false);

    RetainPtr<CFMutableDictionaryRef> sslProps;

    if (allowsAnyHTTPSCertificateHosts().contains(firstRequest().url().host().lower())) {
        sslProps.adoptCF(CFDictionaryCreateMutable(kCFAllocatorDefault, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks));
        CFDictionaryAddValue(sslProps.get(), kCFStreamSSLAllowsAnyRoot, kCFBooleanTrue);
        CFDictionaryAddValue(sslProps.get(), kCFStreamSSLAllowsExpiredRoots, kCFBooleanTrue);
        CFDictionaryAddValue(sslProps.get(), kCFStreamSSLAllowsExpiredCertificates, kCFBooleanTrue);
        CFDictionaryAddValue(sslProps.get(), kCFStreamSSLValidatesCertificateChain, kCFBooleanFalse);
    }

    HashMap<String, RetainPtr<CFDataRef> >::iterator clientCert = clientCerts().find(firstRequest().url().host().lower());
    if (clientCert != clientCerts().end()) {
        if (!sslProps)
            sslProps.adoptCF(CFDictionaryCreateMutable(kCFAllocatorDefault, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks));
#if PLATFORM(WIN)
        wkSetClientCertificateInSSLProperties(sslProps.get(), (clientCert->value).get());
#endif
    }

    if (sslProps)
        CFURLRequestSetSSLProperties(request.get(), sslProps.get());

#if PLATFORM(WIN)
    if (CFHTTPCookieStorageRef cookieStorage = overridenCookieStorage()) {
        // Overridden cookie storage doesn't come from a session, so the request does not have it yet.
        CFURLRequestSetHTTPCookieStorage(request.get(), cookieStorage);
    }
#endif

    CFURLConnectionClient_V6 client = { 6, this, 0, 0, 0, WebCore::willSendRequest, didReceiveResponse, didReceiveData, 0, didFinishLoading, didFail, willCacheResponse, didReceiveChallenge, didSendBodyData, shouldUseCredentialStorageCallback, 0,
#if USE(PROTECTION_SPACE_AUTH_CALLBACK)
        canRespondToProtectionSpace,
#else
        0,
#endif
        0,
#if USE(NETWORK_CFDATA_ARRAY_CALLBACK)
        didReceiveDataArray
#else 
        0
#endif
    };
    RetainPtr<CFDictionaryRef> connectionProperties(AdoptCF, createConnectionProperties(shouldUseCredentialStorage));

    d->m_connection.adoptCF(CFURLConnectionCreateWithProperties(0, request.get(), reinterpret_cast<CFURLConnectionClient*>(&client), connectionProperties.get()));
}
Esempio n. 2
0
// The primary problem we need to resolve for OSX portability is that Apple
// only permit you to define static MIME types in the property list for
// plugins bundles, because we need to generate these dynamically.
//
// Luckily, Apple also want to generate MIME types dynamically for QuickTime,
// so they provide a (bizarre) API to do so.
//
// The solution is to set WebPluginMIMETypesFilename to an invalid filename,
// and then implement the dynamic symbol BP_CreatePluginMIMETypesPreferences.
// When the path is found to be invalid by the loader, our callback will be
// invoked and we can generate a new plist.
//
// Once our callback returns, the loader then attempts to load the missing
// filename again, and then parses it for the MIME types.
//
// In order to keep this file fresh, we should unlink() it on NP_Initialize().
//
// This is an example of the data we need:
//
//    <key>WebPluginMIMETypes</key>
//    <dict>
//        <key>application/pdf</key>
//        <dict>
//            <key>WebPluginExtensions</key>
//            <array>
//                <string>pdf</string>
//            </array>
//            <key>WebPluginTypeDescription</key>
//            <string>PDF Image</string>
//            <key>WebPluginTypeEnabled</key>
//            <false/>
//        </dict>
//    </dict>
//
// This is the dynamic symbol used by the loader to resolve the missing MIME list.
void __export BP_CreatePluginMIMETypesPreferences(void)
{
    CFMutableDictionaryRef  cf_root;
    CFMutableDictionaryRef  cf_mimetypes;
    CFDictionaryRef         cf_pluginmimetypes;
    struct plugin          *current;

    // We need to create a new preferences dictionary, so this will be the root
    // of the new property list.
    cf_root = CFDictionaryCreateMutable(kCFAllocatorDefault,
                                        0,
                                        &kCFTypeDictionaryKeyCallBacks,
                                        &kCFTypeDictionaryValueCallBacks);
    // A WebPluginMIMETypes Dictionary.
    cf_mimetypes = CFDictionaryCreateMutable(kCFAllocatorDefault,
                                             0,
                                             &kCFTypeDictionaryKeyCallBacks,
                                             &kCFTypeDictionaryValueCallBacks);

    // Every plugin should have a handle should have a CFBundle handle open,
    // which we can query for it's WebPluginMIMETypes CFDictionary, which we
    // simply merge with ours.
    for (current = registry.plugins; current; current = current->next) {
        // Verify this handle exists, it can be NULL when LoadPlugin fails.
        if (current->handle) {
            // This should be a CFDictionary of all the MIME types supported by the plugin.
            cf_pluginmimetypes = CFBundleGetValueForInfoDictionaryKey(current->handle,
                                                                      CFSTR("WebPluginMIMETypes"));

            // Check that key exists in the Proerty Info.
            if (cf_pluginmimetypes) {
                // Merge this dictionary with ours.
                CFDictionaryApplyFunction(cf_pluginmimetypes,
                                          merge_dictionary_applier,
                                          cf_mimetypes);
            } else {
                // FIXME: If a plugin does not have a WebPluginMIMETypes key,
                //        it is either invalid, or uses dynamic MIME type
                //        generation. QuickTime is the only major plugin that
                //        does this.
                //
                //        I can implement it on request, but see no reason to
                //        implement now.
                l_warning("unable to handle plugin %s, from %s",
                          current->section,
                          current->plugin);
            }
        }
    }

    // Add the types to my plist root.
    CFDictionarySetValue(cf_root, CFSTR("WebPluginMIMETypes"), cf_mimetypes);

    // Create the missing plist file.
    CFPreferencesSetMultiple(cf_root,
                             NULL,
                             CFSTR("com.google.netscapesecurity"),
                             kCFPreferencesCurrentUser,
                             kCFPreferencesAnyHost);

    // Save changes to disk.
    CFPreferencesAppSynchronize(CFSTR("com.google.netscapesecurity"));

    // Clean up.
    CFRelease(cf_mimetypes);
    CFRelease(cf_root);
    return;
}
Esempio n. 3
0
/* Volatile domains - context is ignored; domain is a CFDictionary (mutable) */
static void *createVolatileDomain(CFAllocatorRef allocator, CFTypeRef  context) {
    return CFDictionaryCreateMutable(allocator, 0, & kCFTypeDictionaryKeyCallBacks, & kCFTypeDictionaryValueCallBacks);
}
Esempio n. 4
0
File: main.c Progetto: TARRANUM/ppp
/* ----------------------------------------------------------------------------- 
    l2tpvpn_get_pppd_args
----------------------------------------------------------------------------- */
int l2tpvpn_get_pppd_args(struct vpn_params *params, int reload)
{

    CFStringRef	string;
    int		noipsec = 0;
    CFMutableDictionaryRef	dict = NULL;
	
    if (reload) {
        noipsec = opt_noipsec;
    }
    
    if (params->serverRef) {			
        /* arguments from the preferences file */
        addstrparam(params->exec_args, &params->next_arg_index, "l2tpmode", "answer");

        string = get_cfstr_option(params->serverRef, kRASEntL2TP, kRASPropL2TPTransport);
        if (string && CFEqual(string, kRASValL2TPTransportIP)) {
            addparam(params->exec_args, &params->next_arg_index, "l2tpnoipsec");
            opt_noipsec = 1;
        }
			
		dict = (CFMutableDictionaryRef)CFDictionaryGetValue(params->serverRef, kRASEntIPSec);
		if (isDictionary(dict)) {
			/* get the parameters from the IPSec dictionary */
			dict = CFDictionaryCreateMutableCopy(0, 0, dict);
		}
		else {
			/* get the parameters from the L2TP dictionary */
			dict = CFDictionaryCreateMutable(0, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
			
			string = get_cfstr_option(params->serverRef, kRASEntL2TP, kRASPropL2TPIPSecSharedSecretEncryption);
			if (isString(string))
				CFDictionarySetValue(dict, kRASPropIPSecSharedSecretEncryption, string);

			string = get_cfstr_option(params->serverRef, kRASEntL2TP, kRASPropL2TPIPSecSharedSecret);
			if (isString(string))
				CFDictionarySetValue(dict, kRASPropIPSecSharedSecret, string);
		}

    } else {
        /* arguments from command line */
        if (opt_noipsec)
            addparam(params->exec_args, &params->next_arg_index, "l2tpnoipsec");
    }
    
    if (reload) {
        if (noipsec != opt_noipsec ||
            !CFEqual(dict, ipsec_settings)) {
				vpnlog(LOG_ERR, "reload prefs - IPSec shared secret cannot be changed\n");
				if (dict)
					CFRelease(dict);
				return -1;
		}
    }

	if (ipsec_settings) 
		CFRelease(ipsec_settings);
	ipsec_settings = dict;
	
    return 0;
}
Esempio n. 5
0
bool CDVDVideoCodecVDA::Open(CDVDStreamInfo &hints, CDVDCodecOptions &options)
{
  if (CSettings::Get().GetBool("videoplayer.usevda") && !hints.software)
  {
    CCocoaAutoPool pool;

    //
    int width  = hints.width;
    int height = hints.height;
    int level  = hints.level;
    int profile = hints.profile;
    
    switch(profile)
    {
      case FF_PROFILE_H264_HIGH_10:
      case FF_PROFILE_H264_HIGH_10_INTRA:
      case FF_PROFILE_H264_HIGH_422:
      case FF_PROFILE_H264_HIGH_422_INTRA:
      case FF_PROFILE_H264_HIGH_444_PREDICTIVE:
      case FF_PROFILE_H264_HIGH_444_INTRA:
      case FF_PROFILE_H264_CAVLC_444:
        CLog::Log(LOGNOTICE, "%s - unsupported h264 profile(%d)", __FUNCTION__, hints.profile);
        return false;
        break;
    }

    if (width <= 0 || height <= 0)
    {
      CLog::Log(LOGNOTICE, "%s - bailing with bogus hints, width(%d), height(%d)",
        __FUNCTION__, width, height);
      return false;
    }
    
    if (Cocoa_GPUForDisplayIsNvidiaPureVideo3() && !CDVDCodecUtils::IsVP3CompatibleWidth(width))
    {
      CLog::Log(LOGNOTICE, "%s - Nvidia 9400 GPU hardware limitation, cannot decode a width of %d", __FUNCTION__, width);
      return false;
    }

    CFDataRef avcCData;
    switch (hints.codec)
    {
      case CODEC_ID_H264:
        m_bitstream = new CBitstreamConverter;
        if (!m_bitstream->Open(hints.codec, (uint8_t*)hints.extradata, hints.extrasize, false))
          return false;

        avcCData = CFDataCreate(kCFAllocatorDefault,
          (const uint8_t*)m_bitstream->GetExtraData(), m_bitstream->GetExtraSize());

        m_format = 'avc1';
        m_pFormatName = "vda-h264";
      break;
      default:
        return false;
      break;
    }

    // check the avcC atom's sps for number of reference frames and
    // bail if interlaced, VDA does not handle interlaced h264.
    uint32_t avcc_len = CFDataGetLength(avcCData);
    if (avcc_len < 8)
    {
      // avcc atoms with length less than 8 are borked.
      CFRelease(avcCData);
      delete m_bitstream, m_bitstream = NULL;
      return false;
    }
    else
    {
      bool interlaced = true;
      uint8_t *spc = (uint8_t*)CFDataGetBytePtr(avcCData) + 6;
      uint32_t sps_size = BS_RB16(spc);
      if (sps_size)
        m_bitstream->parseh264_sps(spc+3, sps_size-1, &interlaced, &m_max_ref_frames);
      if (interlaced)
      {
        CLog::Log(LOGNOTICE, "%s - possible interlaced content.", __FUNCTION__);
        CFRelease(avcCData);
        return false;
      }
    }

    if (profile == FF_PROFILE_H264_MAIN && level == 32 && m_max_ref_frames > 4)
    {
      // [email protected], VDA cannot handle greater than 4 reference frames
      CLog::Log(LOGNOTICE, "%s - [email protected] detected, VDA cannot decode.", __FUNCTION__);
      CFRelease(avcCData);
      return false;
    }

    CStdString rendervendor = g_Windowing.GetRenderVendor();
    rendervendor.MakeLower();
    if (rendervendor.find("nvidia") != std::string::npos)
    {
      // Nvidia gpu's are all powerful and work the way god intended
      m_decode_async = true;
      m_use_cvBufferRef = true;
    }
    else if (rendervendor.find("intel") != std::string::npos)
    {
      // Intel gpu are borked when using cvBufferRef
      m_decode_async = true;
      m_use_cvBufferRef = false;
    }
    else
    {
      // ATI gpu's are borked when using async decode
      m_decode_async = false;
      m_use_cvBufferRef = true;
    }

    if (!m_use_cvBufferRef)
    {
      m_dllSwScale = new DllSwScale;
      if (!m_dllSwScale->Load())
      {
        CFRelease(avcCData);
        return false;
      }

      // allocate a YV12 DVDVideoPicture buffer.
      // first make sure all properties are reset.
      memset(&m_videobuffer, 0, sizeof(DVDVideoPicture));
      unsigned int iPixels = width * height;
      unsigned int iChromaPixels = iPixels/4;

      m_videobuffer.dts = DVD_NOPTS_VALUE;
      m_videobuffer.pts = DVD_NOPTS_VALUE;
      m_videobuffer.iFlags = DVP_FLAG_ALLOCATED;
      m_videobuffer.format = RENDER_FMT_YUV420P;
      m_videobuffer.color_range  = 0;
      m_videobuffer.color_matrix = 4;
      m_videobuffer.iWidth  = width;
      m_videobuffer.iHeight = height;
      m_videobuffer.iDisplayWidth  = width;
      m_videobuffer.iDisplayHeight = height;

      m_videobuffer.iLineSize[0] = width;   //Y
      m_videobuffer.iLineSize[1] = width/2; //U
      m_videobuffer.iLineSize[2] = width/2; //V
      m_videobuffer.iLineSize[3] = 0;

      m_videobuffer.data[0] = (uint8_t*)malloc(16 + iPixels);
      m_videobuffer.data[1] = (uint8_t*)malloc(16 + iChromaPixels);
      m_videobuffer.data[2] = (uint8_t*)malloc(16 + iChromaPixels);
      m_videobuffer.data[3] = NULL;

      // set all data to 0 for less artifacts.. hmm.. what is black in YUV??
      memset(m_videobuffer.data[0], 0, iPixels);
      memset(m_videobuffer.data[1], 0, iChromaPixels);
      memset(m_videobuffer.data[2], 0, iChromaPixels);
    }

    // setup the decoder configuration dict
    CFMutableDictionaryRef decoderConfiguration = CFDictionaryCreateMutable(
      kCFAllocatorDefault, 4, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);

    CFNumberRef avcWidth  = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &width);
    CFNumberRef avcHeight = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &height);
    CFNumberRef avcFormat = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &m_format);

    CFDictionarySetValue(decoderConfiguration, kVDADecoderConfiguration_Height, avcHeight);
    CFDictionarySetValue(decoderConfiguration, kVDADecoderConfiguration_Width,  avcWidth);
    CFDictionarySetValue(decoderConfiguration, kVDADecoderConfiguration_SourceFormat, avcFormat);
    CFDictionarySetValue(decoderConfiguration, kVDADecoderConfiguration_avcCData, avcCData);

    // release the retained object refs, decoderConfiguration owns them now
    CFRelease(avcWidth);
    CFRelease(avcHeight);
    CFRelease(avcFormat);
    CFRelease(avcCData);

    // setup the destination image buffer dict, vda will output this pict format
    CFMutableDictionaryRef destinationImageBufferAttributes = CFDictionaryCreateMutable(
      kCFAllocatorDefault, 2, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
    OSType cvPixelFormatType = kCVPixelFormatType_422YpCbCr8;
    CFNumberRef pixelFormat  = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &cvPixelFormatType);

    // an IOSurface properties dictionary
    CFDictionaryRef iosurfaceDictionary = CFDictionaryCreate(kCFAllocatorDefault,
      NULL, NULL, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);

    CFDictionarySetValue(destinationImageBufferAttributes,
      kCVPixelBufferPixelFormatTypeKey, pixelFormat);
    CFDictionarySetValue(destinationImageBufferAttributes,
      kCVPixelBufferIOSurfacePropertiesKey, iosurfaceDictionary);
    // release the retained object refs, destinationImageBufferAttributes owns them now
    CFRelease(pixelFormat);
    CFRelease(iosurfaceDictionary);

    // create the VDADecoder object
    OSStatus status;
    try
    {
      status = VDADecoderCreate(decoderConfiguration, destinationImageBufferAttributes,
        (VDADecoderOutputCallback*)VDADecoderCallback, this, (VDADecoder*)&m_vda_decoder);
    }
    catch (...)
    {
      CLog::Log(LOGERROR, "%s - exception",__FUNCTION__);
      status = kVDADecoderDecoderFailedErr;
    }
    CFRelease(decoderConfiguration);
    CFRelease(destinationImageBufferAttributes);
    if (status != kVDADecoderNoErr)
    {
      if (status == kVDADecoderDecoderFailedErr)
          CLog::Log(LOGNOTICE, "%s - VDADecoder Codec failed to open, currently in use by another process",
            __FUNCTION__);
      else
          CLog::Log(LOGNOTICE, "%s - VDADecoder Codec failed to open, status(%d), profile(%d), level(%d)",
            __FUNCTION__, (int)status, profile, level);
      return false;
    }

    m_DropPictures = false;
    m_max_ref_frames = std::max(m_max_ref_frames + 1, 5);
    m_sort_time = 0;
    return true;
  }

  return false;
}
Esempio n. 6
0
static bool
switchPartition(char * diskName, char * partitionType)
{
    char wholeDevicePath[256];
    sprintf(wholeDevicePath, "/dev/%s", diskName);

    unsigned int partitionNumber = 0;
    char * c = wholeDevicePath + 5 + 4;		        // skip over "/dev/disk"
    while (*c != 's' && *c++);				// look for 's'
    if (*c == 's') {
	*c = 0;						// clip off remainder
	sscanf(c+1, "%u", &partitionNumber);		// get partition number
    }
    if (!partitionNumber) return true;			// just assume it is a raid disk

#define LIVERAID
#ifdef LIVERAID
    char * optionString = "<dict> <key>Writable</key> <true/> <key>Shared Writer</key> <true/></dict>";
#else
    char * optionString = "<dict> <key>Writable</key> <true/> </dict>";
#endif    
    CFDictionaryRef options = IOCFUnserialize(optionString, kCFAllocatorDefault, 0, NULL);
    if (!options) exit(1);

    int32_t err;
    MKMediaRef device = MKMediaCreateWithPath(nil, wholeDevicePath, options, &err);
    CFRelease(options);
    if (!device || err) return false;
    
    options = NULL;
    MKStatus err2;
    CFMutableDictionaryRef media = MKCFReadMedia(options, device, &err2);
    if (!media || err2) goto Failure;

    // find and extract the 'Schemes' array 
    CFMutableArrayRef Schemes = (CFMutableArrayRef) CFDictionaryGetValue(media, CFSTR("Schemes"));
    if (!Schemes) goto Failure;

    // DMTool just grabs the first "default" scheme, so do the same
    CFMutableDictionaryRef Scheme = (CFMutableDictionaryRef) CFArrayGetValueAtIndex(Schemes, 0);
    if (!Scheme) goto Failure;

    // Then find and extract the 'Sections' array of that scheme:
    CFMutableArrayRef Sections = (CFMutableArrayRef) CFDictionaryGetValue(Scheme, CFSTR("Sections"));
    if (!Sections) goto Failure;

    // Every scheme can have multiple sections to it, we need to find the 'MAP' section:
    CFMutableDictionaryRef Section = (CFMutableDictionaryRef) CFArrayDictionarySearch(Sections, CFSTR("ID"), CFSTR("MAP"));
    if (!Section) goto Failure;

    // Then find and extract the 'Partitions' array of that section:
    CFMutableArrayRef Partitions = (CFMutableArrayRef) CFDictionaryGetValue(Section, CFSTR("Partitions"));
    if (!Partitions) goto Failure;

    CFNumberRef partitionIndex = CFNumberCreate(nil, kCFNumberSInt32Type, &partitionNumber);
    if (!partitionIndex) goto Failure;
    CFMutableDictionaryRef Partition = (CFMutableDictionaryRef) CFArrayDictionarySearch(Partitions, CFSTR("Partition ID"), partitionIndex);
    if (!Partition) goto Failure;

    // change the partition type (finally!)
    CFStringRef Type = CFStringCreateWithCString(nil, partitionType, kCFStringEncodingUTF8);
    if (!Type) goto Failure;
    CFDictionarySetValue(Partition, CFSTR("Type"), Type);

    CFMutableDictionaryRef woptions = CFDictionaryCreateMutable(kCFAllocatorDefault,
								2,
								&kCFTypeDictionaryKeyCallBacks,
								&kCFTypeDictionaryValueCallBacks);
    if (!woptions) goto Failure;
    CFDictionarySetValue(woptions, CFSTR("Retain existing content"), kCFBooleanTrue);
    CFDictionarySetValue(woptions, CFSTR("Direct Mode"), kCFBooleanTrue);

    err2 = MKCFWriteMedia(media, nil, nil, woptions, device);

    MKCFDisposeMedia(media);
    CFRelease(woptions);
    CFRelease(device);
    return !err2;

Failure:
    if (media) MKCFDisposeMedia(media);
    if (device) CFRelease(device);

    return false;
}
Esempio n. 7
0
static OSStatus
acquireticket_ui(KLPrincipal inPrincipal,
		 KLLoginOptions inLoginOptions,
		 KLPrincipal *outPrincipal,
		 char **outCredCacheName)
{
    AuthorizationRef auth;
    OSStatus ret;
    char *princ = NULL;
    CFDataRef d = NULL;
    
    LOG_ENTRY();

    if (outPrincipal)
	*outPrincipal = NULL;
    if (outCredCacheName)
	*outCredCacheName = NULL;

    if (inPrincipal) {
	ret = heim_krb5_unparse_name(milcontext, inPrincipal, &princ);
	if (ret)
	    return ret;
    }
    

    ret = AuthorizationCreate(NULL, NULL, kAuthorizationFlagDefaults, &auth);
    if (ret) {
	free(princ);
	return ret;
    }
    
    AuthorizationItem rightItems[1] = { kCoreAuthPanelKerberosRight, 0, NULL, 0 };
    AuthorizationRights rights = { sizeof(rightItems[0])/sizeof(rightItems) , rightItems };
    AuthorizationItem envItems[3];
    AuthorizationEnvironment env = { 0 , envItems };
    AuthorizationFlags authFlags = kAuthorizationFlagInteractionAllowed | kAuthorizationFlagExtendRights;

    if (princ) {
	envItems[env.count].name = kCoreAuthPanelKerberosPrincipal;
	envItems[env.count].valueLength = strlen(princ);
	envItems[env.count].value = princ;
	envItems[env.count].flags = 0;
	env.count++;
    }

    if (inLoginOptions && inLoginOptions->opt) {
	CFMutableDictionaryRef dict;

	dict = CFDictionaryCreateMutable(NULL, 1,
					 &kCFTypeDictionaryKeyCallBacks,
					 &kCFTypeDictionaryValueCallBacks);
	if (dict == NULL)
	    goto out;
	
	if (inLoginOptions->opt->renew_life) {
	    CFStringRef t;
	    t = CFStringCreateWithFormat(NULL, 0, CFSTR("%ld"),(long)inLoginOptions->opt->renew_life);
	    CFDictionarySetValue(dict, CFSTR("renewTime"), t);
	    CFRelease(t);
	}

	d = CFPropertyListCreateData(NULL, dict, kCFPropertyListBinaryFormat_v1_0,
				     0, NULL);
	CFRelease(dict);

	envItems[env.count].name = kCoreAuthPanelKerberosOptions;
	envItems[env.count].valueLength = CFDataGetLength(d);
	envItems[env.count].value = (void *)CFDataGetBytePtr(d);
	envItems[env.count].flags = 0;
	env.count++;
    }
    
    ret = AuthorizationCopyRights(auth, &rights, &env, authFlags, NULL);

    if (ret == 0 && outPrincipal) {
	AuthorizationItemSet *info;
	UInt32 i;
	ret = AuthorizationCopyInfo(auth, NULL, &info);
	if (ret)
	    goto out;
	for(i = 0; i < info->count; i++) {
	    if (strcmp(info->items[i].name, "out-principal") == 0) {
		char *str;
		asprintf(&str, "%.*s", (int)info->items[i].valueLength, (char *)info->items[i].value);
		heim_krb5_parse_name(milcontext, str, outPrincipal);
	    } else if (strcmp(info->items[i].name, "out-cache-name") == 0) {
		asprintf(outCredCacheName, "%.*s", (int)info->items[i].valueLength, (char *)info->items[i].value);
	    }
	}
	AuthorizationFreeItemSet(info);
	if (*outPrincipal == NULL)
	    ret = EINVAL;
    }
out:
    if (d)
	CFRelease(d);
    AuthorizationFree(auth, kAuthorizationFlagDestroyRights);
    free(princ);
    return ret;
}
Esempio n. 8
0
__private_extern__ kern_return_t _io_pm_hid_event_report_activity(
    mach_port_t server,
    audit_token_t token,                                                        
    int         _action)
{
    pid_t                               callerPID;
    CFNumberRef                         appPID = NULL;
    int                                 _app_pid_;
    CFMutableDictionaryRef              foundDictionary = NULL;
    CFMutableArrayRef                   bucketsArray = NULL;
    CFDataRef                           dataEvent = NULL;
    IOPMHIDPostEventActivityWindow      *ev = NULL;
    CFAbsoluteTime                      timeNow = CFAbsoluteTimeGetCurrent();
    int                                 arrayCount = 0;
    int                                 i = 0;
    
    // Unwrapping big data structure...
    if (!gHIDEventHistory) {
        gHIDEventHistory = CFArrayCreateMutable(0, 1, &kCFTypeArrayCallBacks);
    }
    if (!gHIDEventHistory) {
        goto exit;
    }
    
    audit_token_to_au32(token, NULL, NULL, NULL, NULL, NULL, &callerPID, NULL, NULL);

    if (0 !=(arrayCount = CFArrayGetCount(gHIDEventHistory)))
    {
        // Scan through the array to find an existing dictionary for the given pid
        for (i=0; i<arrayCount; i++)
        {
            CFMutableDictionaryRef dictionaryForApp = NULL;
            dictionaryForApp = (CFMutableDictionaryRef)CFArrayGetValueAtIndex(gHIDEventHistory, i);
            if (!dictionaryForApp) {
                break;
            }
            appPID = CFDictionaryGetValue(dictionaryForApp, kIOPMHIDAppPIDKey);
            if (appPID) {
                CFNumberGetValue(appPID, kCFNumberIntType, &_app_pid_);
                if (callerPID == _app_pid_) {
                    foundDictionary = dictionaryForApp;
                    break;
                }
            }
        }
    }
    
    // Unwrapping big data structure...
    if (!foundDictionary) {
        foundDictionary = CFDictionaryCreateMutable(0, 3, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
        CFArrayAppendValue(gHIDEventHistory, foundDictionary);
        CFRelease(foundDictionary);
        
        /* Tag our pid */
        appPID = CFNumberCreate(0, kCFNumberIntType, &callerPID);
        if (appPID) {
            CFDictionarySetValue(foundDictionary, kIOPMHIDAppPIDKey, appPID);
            CFRelease(appPID);
        }

        /* Tag the process name */
        CFStringRef appName = NULL;
        char    appBuf[MAXPATHLEN];
        int     len = proc_name(callerPID, appBuf, MAXPATHLEN);
        if (0 != len) {
            appName = CFStringCreateWithCString(0, appBuf, kCFStringEncodingMacRoman);
            if (appName) {
                CFDictionarySetValue(foundDictionary, kIOPMHIDAppPathKey, appName);
                CFRelease(appName);
            }
        }
    }

    if (!foundDictionary)
        goto exit;

    // Unwrapping big data structure...
    bucketsArray = (CFMutableArrayRef)CFDictionaryGetValue(foundDictionary, kIOPMHIDHistoryArrayKey);
    if (!bucketsArray) {
        bucketsArray = CFArrayCreateMutable(0, 1, &kCFTypeArrayCallBacks);
        CFDictionarySetValue(foundDictionary, kIOPMHIDHistoryArrayKey, bucketsArray);
        CFRelease(bucketsArray);
    }
    if (!bucketsArray) 
        goto exit;

    // Check last HID event bucket timestamp - is it more than 5 minutes old?
    bool foundWindowForEvent = false;
    if (0 < CFArrayGetCount(bucketsArray)) {
        dataEvent = (CFDataRef)CFArrayGetValueAtIndex(bucketsArray, 0);
    }
    if (dataEvent) {
        ev = (IOPMHIDPostEventActivityWindow *)CFDataGetBytePtr(dataEvent);
        if (timeNow < (ev->eventWindowStart + kFiveMinutesInSeconds))
        {
            // This HID event gets dropped into this existing 5 minute bucket.
            // We bump the count for HID activity!
            if (__NX_NULL_EVENT == _action) {
                ev->nullEventCount++;
            } else {
                ev->hidEventCount++;
            }
            foundWindowForEvent = true;
        }
    }

    if (!foundWindowForEvent) {
        IOPMHIDPostEventActivityWindow  newv;

        // We align the starts of our windows with 5 minute intervals
        newv.eventWindowStart = ((int)timeNow / (int)kFiveMinutesInSeconds) * kFiveMinutesInSeconds;
        newv.nullEventCount = newv.hidEventCount = 0;
        if (__NX_NULL_EVENT == _action) {
            newv.nullEventCount++;
        } else {
            newv.hidEventCount++;
        }
    
        dataEvent = CFDataCreate(0, (const UInt8 *)&newv, sizeof(IOPMHIDPostEventActivityWindow));
        if (dataEvent) {
            CFArrayInsertValueAtIndex(bucketsArray, 0, dataEvent);
            CFRelease(dataEvent);
        }
        
        // If we've recorded more than kMaxFiveMinutesWindowsCount activity windows for this process, delete the old ones.
        while (kMaxFiveMinutesWindowsCount < CFArrayGetCount(bucketsArray)) {
            CFArrayRemoveValueAtIndex(bucketsArray, CFArrayGetCount(bucketsArray) - 1);
        }
        
    }

exit:
    return KERN_SUCCESS;
}
CFTypeRef GTMCFTypeCreateFromLaunchData(launch_data_t ldata,
                                        bool convert_non_standard_objects,
                                        CFErrorRef *error) {
  CFTypeRef cf_type_ref = NULL;
  CFErrorRef local_error = NULL;
  if (ldata == NULL) {
    local_error = GTMCFLaunchCreateUnlocalizedError(EINVAL,
                                                    CFSTR("NULL ldata"));
    goto exit;
  }

  launch_data_type_t ldata_type = launch_data_get_type(ldata);
  switch (ldata_type) {
    case LAUNCH_DATA_STRING:
      cf_type_ref
        = CFStringCreateWithCString(kCFAllocatorDefault,
                                    launch_data_get_string(ldata),
                                    kCFStringEncodingUTF8);
      break;

    case LAUNCH_DATA_INTEGER: {
      long long value = launch_data_get_integer(ldata);
      cf_type_ref = CFNumberCreate(kCFAllocatorDefault,
                                   kCFNumberLongLongType,
                                   &value);
      break;
    }

    case LAUNCH_DATA_REAL: {
      double value = launch_data_get_real(ldata);
      cf_type_ref = CFNumberCreate(kCFAllocatorDefault,
                                   kCFNumberDoubleType,
                                   &value);
      break;
    }

    case LAUNCH_DATA_BOOL: {
      bool value = launch_data_get_bool(ldata);
      cf_type_ref = value ? kCFBooleanTrue : kCFBooleanFalse;
      CFRetain(cf_type_ref);
      break;
    }

    case LAUNCH_DATA_OPAQUE: {
      // Must get the data before we get the size.
      // Otherwise the size will come back faulty on macOS 10.11.6.
      // Radar: 28509492 launch_data_get_opaque_size gives wrong size
      void *data = launch_data_get_opaque(ldata);
      size_t size = launch_data_get_opaque_size(ldata);
      cf_type_ref = CFDataCreate(kCFAllocatorDefault, data, size);
      break;
    }

    case LAUNCH_DATA_ARRAY: {
      size_t count = launch_data_array_get_count(ldata);
      cf_type_ref = CFArrayCreateMutable(kCFAllocatorDefault,
                                         count,
                                         &kCFTypeArrayCallBacks);
      if (cf_type_ref) {
        for (size_t i = 0; !local_error && i < count; i++) {
          launch_data_t l_sub_data = launch_data_array_get_index(ldata, i);
          CFTypeRef cf_sub_type
            = GTMCFTypeCreateFromLaunchData(l_sub_data,
                                            convert_non_standard_objects,
                                            &local_error);
          if (cf_sub_type) {
            CFArrayAppendValue((CFMutableArrayRef)cf_type_ref, cf_sub_type);
            CFRelease(cf_sub_type);
          }
        }
      }
      break;
    }

    case LAUNCH_DATA_DICTIONARY:
      cf_type_ref = CFDictionaryCreateMutable(kCFAllocatorDefault,
                                              0,
                                              &kCFTypeDictionaryKeyCallBacks,
                                              &kCFTypeDictionaryValueCallBacks);
      if (cf_type_ref) {
        GTMLToCFDictContext context = {
          (CFMutableDictionaryRef)cf_type_ref,
          convert_non_standard_objects,
          &local_error
        };
        launch_data_dict_iterate(ldata,
                                 GTMConvertLaunchDataDictEntryToCFDictEntry,
                                 &context);
      }
      break;

    case LAUNCH_DATA_FD:
      if (convert_non_standard_objects) {
        int file_descriptor = launch_data_get_fd(ldata);
        cf_type_ref = CFNumberCreate(kCFAllocatorDefault,
                                     kCFNumberIntType,
                                     &file_descriptor);
      }
      break;

    case LAUNCH_DATA_MACHPORT:
      if (convert_non_standard_objects) {
        mach_port_t port = launch_data_get_machport(ldata);
        cf_type_ref = CFNumberCreate(kCFAllocatorDefault,
                                     kCFNumberIntType,
                                     &port);
      }
      break;

    default:
      local_error =
        GTMCFLaunchCreateUnlocalizedError(EINVAL,
                                          CFSTR("Unknown launchd type %d"),
                                          ldata_type);
      break;
  }
exit:
  if (error) {
    *error = local_error;
  } else if (local_error) {
#ifdef DEBUG
    CFShow(local_error);
#endif //  DEBUG
    CFRelease(local_error);
  }
  return cf_type_ref;
}
void propertyListExample (void) {
    CFMutableDictionaryRef dict;
    CFNumberRef num;
    CFArrayRef array;
    CFDataRef data;
    #define NumKids 2
    CFStringRef kidsNames[] = { CFSTR ("John"), CFSTR ("Kyra") };
    #define NumPets 0
    int yearOfBirth = 1965;
    #define NumBytesInPic 10
    const unsigned char pic[ NumBytesInPic ] = { 0x3c, 0x42, 0x81, 0xa5, 0x81, 0xa5, 0x99, 0x81, 0x42, 0x3c };
    CFDataRef xmlPropertyListData;
    CFStringRef xmlAsString;

    // Create and populate a pretty standard mutable dictionary: CFString keys, CF type values.
    // To be written out as a "propertyList", the tree of CF types can contain only:
    //   CFDictionary, CFArray, CFString, CFData, CFNumber, and CFDate.
    // In addition, the keys of the dictionaries should be CFStrings.

    dict = CFDictionaryCreateMutable (NULL, 0, &kCFCopyStringDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks );

    CFDictionarySetValue (dict, CFSTR ("Name"), CFSTR ("John Doe"));

    CFDictionarySetValue (dict, CFSTR ("City of Birth"), CFSTR ("Springfield"));

    num = CFNumberCreate (NULL, kCFNumberIntType, &yearOfBirth);
    CFDictionarySetValue (dict, CFSTR ("Year Of Birth"), num);
    CFRelease (num);

    array = CFArrayCreate (NULL, (const void **)kidsNames, NumKids, &kCFTypeArrayCallBacks); 
    CFDictionarySetValue (dict, CFSTR ("Kids Names"), array);
    CFRelease (array);

    array = CFArrayCreate (NULL, NULL, 0, &kCFTypeArrayCallBacks);
    CFDictionarySetValue (dict, CFSTR ("Pets Names"), array );
    CFRelease (array);

    data = CFDataCreate (NULL, pic, NumBytesInPic);
    CFDictionarySetValue (dict, CFSTR ("Picture"), data);
    CFRelease (data);

    // We now have a dictionary which contains everything we want to know about
    // John Doe; let's show it first:
    show (CFSTR ("John Doe info dictionary:\n%@"), dict);

    // Now create a "property list", which is a flattened, XML version of the
    // dictionary:
    xmlPropertyListData = CFPropertyListCreateXMLData (NULL, dict);

   // The return value is a CFData containing the XML file; show the data

    show (CFSTR ("Shown as XML property list (bytes):\n%@"), xmlPropertyListData);

    // Given CFDatas are shown as ASCII versions of their hex contents, we can also
    // attempt to show the contents of the XML, assuming it was encoded in UTF8
    // (This is the case for XML property lists generated by CoreFoundation currently)

    xmlAsString = CFStringCreateFromExternalRepresentation (NULL, xmlPropertyListData, kCFStringEncodingUTF8);

    show (CFSTR ("The XML property list contents:\n%@"), xmlAsString);

    writePropertyListToFile (xmlPropertyListData);

    CFRelease (dict);
    CFRelease (xmlAsString);
    CFRelease (xmlPropertyListData);

    CFStringRef name = CFSTR("Brent");
    if (CFBundleRef bundle = CFBundleGetMainBundle ())
       if (CFTypeRef bundleExecutable = CFBundleGetValueForInfoDictionaryKey(bundle, kCFBundleExecutableKey))
          if (CFGetTypeID(bundleExecutable) == CFStringGetTypeID())
             name = reinterpret_cast<CFStringRef>(bundleExecutable);

    int value = 1;
    CFNumberRef numRef = CFNumberCreate(0, kCFNumberSInt8Type, &value);
    show (CFSTR ("The number was: %@"), numRef);
    CFRelease (numRef);
}
Esempio n. 11
0
void	CASettingsStorage::RefreshSettings()
{
	//	if this storage is only supporting a single file, there is no need to hit the disk unless
	//	required to by it being the first time or if the refresh is specifically forced for some reason
	if(!mIsSingleProcessOnly || (mSettingsCache == NULL) || ((mSettingsCacheTime.tv_sec == 0) && (mSettingsCacheTime.tv_nsec == 0)) || mSettingsCacheForceRefresh)
	{
		//	first, we need to stat the file to check the mod date, this has the side effect of also
		//	telling us if the file exisits
		struct stat theFileInfo;
		int theStatError = stat(mSettingsFilePath, &theFileInfo);
		
		//	we use this boolean to make error recovery easier since we need a case for when there's no file anyway
		bool theSettingsWereCached = false;
		bool theSettingsNeedSaving = true;
		
		if(theStatError == 0)
		{
			//	stat says there is something there, only have to do work if we either don't have a cache or the cache is out of date
			if((mSettingsCache == NULL) || (mSettingsCacheTime < theFileInfo.st_mtimespec) || mSettingsCacheForceRefresh)
			{
				//	open the file
				FILE* theFile = fopen(mSettingsFilePath, "r");
				if(theFile != NULL)
				{
					//	lock the file (this call blocks until the lock is taken)
					int theError = flock(fileno(theFile), LOCK_EX);
					if(theError == 0)
					{
						//	get the length of the file
						fseek(theFile, 0, SEEK_END);
						size_t theFileLength = ftell(theFile);
						fseek(theFile, 0, SEEK_SET);
						
						if(theFileLength > 0)
						{
							//	allocate a block of memory to hold the data in the file
							CAAutoFree<Byte> theRawFileData(theFileLength);
							
							//	read all the data in
							fread(static_cast<Byte*>(theRawFileData), theFileLength, 1, theFile);
							
							//	release the lock
							flock(fileno(theFile), LOCK_UN);
							
							//	put it into a CFData object
							CACFData theRawFileDataCFData(static_cast<Byte*>(theRawFileData), static_cast<UInt32>(theFileLength));
							
							//	get rid of the existing cache
							if(mSettingsCache != NULL)
							{
								CFRelease(mSettingsCache);
								mSettingsCache = NULL;
							}
							
							//	parse the data as a property list
							mSettingsCache = (CFMutableDictionaryRef)CFPropertyListCreateWithData(NULL, theRawFileDataCFData.GetCFData(), kCFPropertyListMutableContainersAndLeaves, NULL, NULL);
							
							//	check to be sure we parsed a plist out of the file
							if(mSettingsCache != NULL)
							{
								//	save the date of the cache
								mSettingsCacheTime = theFileInfo.st_mtimespec;
								
								//	mark that we're done
								theSettingsWereCached = true;
								theSettingsNeedSaving = false;
							}
						}
					}
					
					//	close the file
					fclose(theFile);
					mSettingsCacheForceRefresh = false;
				}
			}
			else
			{
				//	nothing to do since the file was older than the cached data
				theSettingsNeedSaving = false;
				theSettingsWereCached = true;
			}
		}
		
		//	if there was a failure, we need to clean up 
		if((theStatError != 0) || theSettingsNeedSaving || !theSettingsWereCached)
		{
			//	we get here if either there isn't a file or something wacky happenned while parsing it
			//	all we do here is make sure that the member variables are set to their initial values
			if(mSettingsCache != NULL)
			{
				CFRelease(mSettingsCache);
				mSettingsCache = NULL;
			}
			mSettingsCache = CFDictionaryCreateMutable(NULL, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
			
			mSettingsCacheTime.tv_sec = 0;
			mSettingsCacheTime.tv_nsec = 0;
			
			if((theStatError != 0) || theSettingsNeedSaving)
			{
				SaveSettings();
			}
		}
	}
}
Esempio n. 12
0
int ff_vda_default_init(AVCodecContext *avctx)
{
    AVVDAContext *vda_ctx = avctx->hwaccel_context;
    OSStatus status = kVDADecoderNoErr;
    CFNumberRef height;
    CFNumberRef width;
    CFNumberRef format;
    CFDataRef avc_data;
    CFMutableDictionaryRef config_info;
    CFMutableDictionaryRef buffer_attributes;
    CFMutableDictionaryRef io_surface_properties;
    CFNumberRef cv_pix_fmt;
    int32_t fmt = 'avc1', pix_fmt = kCVPixelFormatType_422YpCbCr8;

    // kCVPixelFormatType_420YpCbCr8Planar;

    /* Each VCL NAL in the bistream sent to the decoder
     * is preceded by a 4 bytes length header.
     * Change the avcC atom header if needed, to signal headers of 4 bytes. */
    if (avctx->extradata_size >= 4 && (avctx->extradata[4] & 0x03) != 0x03) {
        uint8_t *rw_extradata;

        if (!(rw_extradata = av_malloc(avctx->extradata_size)))
            return AVERROR(ENOMEM);

        memcpy(rw_extradata, avctx->extradata, avctx->extradata_size);

        rw_extradata[4] |= 0x03;

        avc_data = CFDataCreate(kCFAllocatorDefault, rw_extradata, avctx->extradata_size);

        av_freep(&rw_extradata);
    } else {
        avc_data = CFDataCreate(kCFAllocatorDefault,
                                avctx->extradata, avctx->extradata_size);
    }

    config_info = CFDictionaryCreateMutable(kCFAllocatorDefault,
                                            4,
                                            &kCFTypeDictionaryKeyCallBacks,
                                            &kCFTypeDictionaryValueCallBacks);

    height = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &avctx->height);
    width  = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &avctx->width);
    format = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &fmt);
    CFDictionarySetValue(config_info, kVDADecoderConfiguration_Height, height);
    CFDictionarySetValue(config_info, kVDADecoderConfiguration_Width, width);
    CFDictionarySetValue(config_info, kVDADecoderConfiguration_avcCData, avc_data);
    CFDictionarySetValue(config_info, kVDADecoderConfiguration_SourceFormat, format);

    buffer_attributes = CFDictionaryCreateMutable(kCFAllocatorDefault,
                                                  2,
                                                  &kCFTypeDictionaryKeyCallBacks,
                                                  &kCFTypeDictionaryValueCallBacks);
    io_surface_properties = CFDictionaryCreateMutable(kCFAllocatorDefault,
                                                      0,
                                                      &kCFTypeDictionaryKeyCallBacks,
                                                      &kCFTypeDictionaryValueCallBacks);
    cv_pix_fmt      = CFNumberCreate(kCFAllocatorDefault,
                                     kCFNumberSInt32Type,
                                     &pix_fmt);

    CFDictionarySetValue(buffer_attributes,
                         kCVPixelBufferPixelFormatTypeKey,
                         cv_pix_fmt);
    CFDictionarySetValue(buffer_attributes,
                         kCVPixelBufferIOSurfacePropertiesKey,
                         io_surface_properties);

    status = VDADecoderCreate(config_info,
                              buffer_attributes,
                              (VDADecoderOutputCallback *)ff_vda_output_callback,
                              avctx,
                              &vda_ctx->decoder);

    CFRelease(format);
    CFRelease(height);
    CFRelease(width);
    CFRelease(avc_data);
    CFRelease(config_info);
    CFRelease(cv_pix_fmt);
    CFRelease(io_surface_properties);
    CFRelease(buffer_attributes);

    if (status != kVDADecoderNoErr) {
        av_log(avctx, AV_LOG_ERROR, "Cannot initialize VDA %d\n", status);
    }

    switch (status) {
    case kVDADecoderHardwareNotSupportedErr:
    case kVDADecoderFormatNotSupportedErr:
        return AVERROR(ENOSYS);
    case kVDADecoderConfigurationError:
        return AVERROR(EINVAL);
    case kVDADecoderDecoderFailedErr:
        return AVERROR_INVALIDDATA;
    case kVDADecoderNoErr:
        return 0;
    default:
        return AVERROR_UNKNOWN;
    }
}
Esempio n. 13
0
int ff_vda_create_decoder(struct vda_context *vda_ctx,
                          uint8_t *extradata,
                          int extradata_size)
{
    OSStatus status = kVDADecoderNoErr;
    CFNumberRef height;
    CFNumberRef width;
    CFNumberRef format;
    CFDataRef avc_data;
    CFMutableDictionaryRef config_info;
    CFMutableDictionaryRef buffer_attributes;
    CFMutableDictionaryRef io_surface_properties;
    CFNumberRef cv_pix_fmt;

    /* Each VCL NAL in the bistream sent to the decoder
     * is preceded by a 4 bytes length header.
     * Change the avcC atom header if needed, to signal headers of 4 bytes. */
    if (extradata_size >= 4 && (extradata[4] & 0x03) != 0x03) {
        uint8_t *rw_extradata;

        if (!(rw_extradata = av_malloc(extradata_size)))
            return AVERROR(ENOMEM);

        memcpy(rw_extradata, extradata, extradata_size);

        rw_extradata[4] |= 0x03;

        avc_data = CFDataCreate(kCFAllocatorDefault, rw_extradata, extradata_size);

        av_freep(&rw_extradata);
    } else {
        avc_data = CFDataCreate(kCFAllocatorDefault, extradata, extradata_size);
    }

    config_info = CFDictionaryCreateMutable(kCFAllocatorDefault,
                                            4,
                                            &kCFTypeDictionaryKeyCallBacks,
                                            &kCFTypeDictionaryValueCallBacks);

    height   = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &vda_ctx->height);
    width    = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &vda_ctx->width);
    format   = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &vda_ctx->format);

    CFDictionarySetValue(config_info, kVDADecoderConfiguration_Height, height);
    CFDictionarySetValue(config_info, kVDADecoderConfiguration_Width, width);
    CFDictionarySetValue(config_info, kVDADecoderConfiguration_SourceFormat, format);
    CFDictionarySetValue(config_info, kVDADecoderConfiguration_avcCData, avc_data);

    buffer_attributes = CFDictionaryCreateMutable(kCFAllocatorDefault,
                                                  2,
                                                  &kCFTypeDictionaryKeyCallBacks,
                                                  &kCFTypeDictionaryValueCallBacks);
    io_surface_properties = CFDictionaryCreateMutable(kCFAllocatorDefault,
                                                      0,
                                                      &kCFTypeDictionaryKeyCallBacks,
                                                      &kCFTypeDictionaryValueCallBacks);
    cv_pix_fmt      = CFNumberCreate(kCFAllocatorDefault,
                                     kCFNumberSInt32Type,
                                     &vda_ctx->cv_pix_fmt_type);
    CFDictionarySetValue(buffer_attributes,
                         kCVPixelBufferPixelFormatTypeKey,
                         cv_pix_fmt);
    CFDictionarySetValue(buffer_attributes,
                         kCVPixelBufferIOSurfacePropertiesKey,
                         io_surface_properties);

    status = VDADecoderCreate(config_info,
                              buffer_attributes,
                              (VDADecoderOutputCallback *)vda_decoder_callback,
                              vda_ctx,
                              &vda_ctx->decoder);

    CFRelease(height);
    CFRelease(width);
    CFRelease(format);
    CFRelease(avc_data);
    CFRelease(config_info);
    CFRelease(io_surface_properties);
    CFRelease(cv_pix_fmt);
    CFRelease(buffer_attributes);

    return status;
}
Esempio n. 14
0
int mailstream_cfstream_set_ssl_enabled(mailstream * s, int ssl_enabled)
{
#if HAVE_CFNETWORK
  struct mailstream_cfstream_data * cfstream_data;
  int r;
  
  cfstream_data = (struct mailstream_cfstream_data *) s->low->data;
  cfstream_data->ssl_enabled = ssl_enabled;
  if (ssl_enabled) {
    CFMutableDictionaryRef settings;
    
    settings = CFDictionaryCreateMutable(NULL, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
    switch (cfstream_data->ssl_level) {
      case MAILSTREAM_CFSTREAM_SSL_LEVEL_NONE:
        CFDictionarySetValue(settings, kCFStreamSSLLevel, kCFStreamSocketSecurityLevelNone);
        break;
      case MAILSTREAM_CFSTREAM_SSL_LEVEL_SSLv2:
        CFDictionarySetValue(settings, kCFStreamSSLLevel, kCFStreamSocketSecurityLevelSSLv2);
        break;
      case MAILSTREAM_CFSTREAM_SSL_LEVEL_SSLv3:
        CFDictionarySetValue(settings, kCFStreamSSLLevel, kCFStreamSocketSecurityLevelSSLv3);
        break;
      case MAILSTREAM_CFSTREAM_SSL_LEVEL_TLSv1:
        CFDictionarySetValue(settings, kCFStreamSSLLevel, kCFStreamSocketSecurityLevelTLSv1);
        break;
      case MAILSTREAM_CFSTREAM_SSL_LEVEL_NEGOCIATED_SSL:
        CFDictionarySetValue(settings, kCFStreamSSLLevel, kCFStreamSocketSecurityLevelNegotiatedSSL);
        break;
    }
    
    if ((cfstream_data->ssl_certificate_verification_mask & MAILSTREAM_CFSTREAM_SSL_ALLOWS_EXPIRED_CERTIFICATES) != 0) {
      CFDictionarySetValue(settings, kCFStreamSSLAllowsExpiredCertificates, kCFBooleanTrue);
    }
    if ((cfstream_data->ssl_certificate_verification_mask & MAILSTREAM_CFSTREAM_SSL_ALLOWS_EXPIRED_ROOTS) != 0) {
      CFDictionarySetValue(settings, kCFStreamSSLAllowsExpiredRoots, kCFBooleanTrue);
    }
    if ((cfstream_data->ssl_certificate_verification_mask & MAILSTREAM_CFSTREAM_SSL_ALLOWS_ANY_ROOT) != 0) {
      CFDictionarySetValue(settings, kCFStreamSSLAllowsAnyRoot, kCFBooleanTrue);
    }
    if ((cfstream_data->ssl_certificate_verification_mask & MAILSTREAM_CFSTREAM_SSL_DISABLE_VALIDATES_CERTIFICATE_CHAIN) != 0) {
      CFDictionarySetValue(settings, kCFStreamSSLValidatesCertificateChain, kCFBooleanFalse);
    }
    
    CFReadStreamSetProperty(cfstream_data->readStream, kCFStreamPropertySSLSettings, settings);
    CFWriteStreamSetProperty(cfstream_data->writeStream, kCFStreamPropertySSLSettings, settings);
    CFRelease(settings);
  }
  else {
    CFMutableDictionaryRef settings;
    
    settings = CFDictionaryCreateMutable(NULL, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
    CFDictionarySetValue(settings, kCFStreamSSLLevel, kCFStreamSocketSecurityLevelNone);
		CFReadStreamSetProperty(cfstream_data->readStream, kCFStreamPropertySSLSettings, settings);
		CFWriteStreamSetProperty(cfstream_data->writeStream, kCFStreamPropertySSLSettings, settings);
    CFRelease(settings);
    
    //fprintf(stderr, "is not ssl\n");
  }
  
  r = wait_runloop(s->low, STATE_WAIT_SSL);
  if (r != WAIT_RUNLOOP_EXIT_NO_ERROR) {
    return -1;
  }
  
  if (cfstream_data->writeSSLResult < 0)
    return -1;
  if (cfstream_data->readSSLResult < 0)
    return -1;
  
  return 0;
#else
  return -1;
#endif
}
/**
 * Get the MAC address of the first logical IP-enabled network interface
 *
 * @param out the output character array
 * @return CPL_OK on success or an error code
 */
cpl_return_t
cpl_platform_get_mac_address(cpl_mac_address_t* out)
{

#ifdef __unix__

	// From: http://stackoverflow.com/questions/1779715/how-to-get-mac-address-of-your-machine-using-a-c-program

	ifreq ifr;
	ifconf ifc;
	char buf[1024];
	int success = 0;

	int sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_IP);
	if (sock == -1) return CPL_E_PLATFORM_ERROR;

	ifc.ifc_len = sizeof(buf);
	ifc.ifc_buf = buf;
	if (ioctl(sock, SIOCGIFCONF, &ifc) == -1) return CPL_E_PLATFORM_ERROR;

	ifreq* it = ifc.ifc_req;
	const ifreq* const end = it + (ifc.ifc_len / sizeof(ifreq));

	for (; it != end; ++it) {
		strcpy(ifr.ifr_name, it->ifr_name);
		if (ioctl(sock, SIOCGIFFLAGS, &ifr) == 0) {
			if (! (ifr.ifr_flags & IFF_LOOPBACK)) { // don't count loopback
				if (ioctl(sock, SIOCGIFHWADDR, &ifr) == 0) {
					success = 1;
					break;
				}
			}
		}
		else { /* ignore error */ }
	}

	if (success && out) {
		memcpy(out, ifr.ifr_hwaddr.sa_data, 6);
	}

	if (!success) return CPL_E_NOT_FOUND;

#elif defined(__APPLE__)

	/*
	 * Adapted from GetMACAddress.c:
	 *   http://opensource.apple.com/source/DirectoryService
	 *            /DirectoryService-621/CoreFramework/Private/GetMACAddress.c
	 *
	 * Copyright (c) 2003 Apple Computer, Inc. All rights reserved.
	 * 
	 * This file contains Original Code and/or Modifications of Original Code
	 * as defined in and that are subject to the Apple Public Source License
	 * Version 2.0 (the 'License'). You may not use this file except in
	 * compliance with the License. Please obtain a copy of the License at
	 * http://www.opensource.apple.com/apsl/ and read it before using this
	 * file.
	 * 
	 * The Original Code and all software distributed under the License are
	 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
	 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
	 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
	 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
	 * Please see the License for the specific language governing rights and
	 * limitations under the License.
	 */

	kern_return_t kernResult = KERN_FAILURE; 
	mach_port_t masterPort = MACH_PORT_NULL;
	CFMutableDictionaryRef classesToMatch = NULL;
	io_object_t intfService = MACH_PORT_NULL;
	io_object_t controllerService = MACH_PORT_NULL;
	io_iterator_t intfIterator = MACH_PORT_NULL;
	unsigned char macAddress[kIOEthernetAddressSize];
	io_iterator_t *matchingServices = &intfIterator;
	UInt8 *MACAddress = macAddress;

	// Create an iterator with Primary Ethernet interface
	kernResult = IOMasterPort(MACH_PORT_NULL, &masterPort);
	if (kernResult != KERN_SUCCESS) return CPL_E_PLATFORM_ERROR;

	// Ethernet interfaces are instances of class kIOEthernetInterfaceClass
	classesToMatch = IOServiceMatching(kIOEthernetInterfaceClass);
	if (classesToMatch != NULL) {

		CFMutableDictionaryRef propertyMatch;
		propertyMatch = CFDictionaryCreateMutable(kCFAllocatorDefault, 0,
				&kCFTypeDictionaryKeyCallBacks,
				&kCFTypeDictionaryValueCallBacks);

		CFDictionarySetValue(propertyMatch,
				CFSTR(kIOPrimaryInterface), kCFBooleanTrue);
		CFDictionarySetValue(classesToMatch,
				CFSTR(kIOPropertyMatchKey), propertyMatch);

		CFRelease(propertyMatch);

		kernResult = IOServiceGetMatchingServices(masterPort,
				classesToMatch, matchingServices);    
	}


	// Given an iterator across a set of Ethernet interfaces, return the
	// MAC address of the first one.

	intfService = IOIteratorNext(intfIterator);
	if (intfService == MACH_PORT_NULL) {
			IOObjectRelease(intfIterator);
			return CPL_E_PLATFORM_ERROR;
	}

	CFDataRef MACAddressAsCFData = NULL;        
	kernResult = IORegistryEntryGetParentEntry(intfService,
			kIOServicePlane,
			&controllerService);

	if (kernResult != KERN_SUCCESS || controllerService == MACH_PORT_NULL) {
		IOObjectRelease(intfService);
		IOObjectRelease(intfIterator);
		return CPL_E_PLATFORM_ERROR;
	}

	MACAddressAsCFData = (CFDataRef) IORegistryEntryCreateCFProperty(
			controllerService,
			CFSTR(kIOMACAddress),
			kCFAllocatorDefault,
			0);

	if (MACAddressAsCFData != NULL) {
		CFDataGetBytes(MACAddressAsCFData,
				CFRangeMake(0, kIOEthernetAddressSize), MACAddress);
		CFRelease(MACAddressAsCFData);
	}
	else {
		IOObjectRelease(controllerService);
		IOObjectRelease(intfService);
		IOObjectRelease(intfIterator);
		return CPL_E_NOT_FOUND;
	}

	IOObjectRelease(controllerService);
	IOObjectRelease(intfService);
	IOObjectRelease(intfIterator);

	if (out) memcpy(out, macAddress, 6);
	

#elif defined(_WINDOWS)

	PIP_ADAPTER_ADDRESSES AdapterAddresses;
	ULONG family = AF_UNSPEC;
	ULONG flags = 0;
	ULONG outBufLen = 0;
	bool success = false;

	DWORD dwRetVal = GetAdaptersAddresses(family, flags, NULL, NULL, &outBufLen);
	if (dwRetVal == ERROR_NO_DATA) return CPL_E_NOT_FOUND;
	if (dwRetVal == 0 && outBufLen == 0) return CPL_E_NOT_FOUND;
	if (dwRetVal != ERROR_BUFFER_OVERFLOW) return CPL_E_PLATFORM_ERROR;

	AdapterAddresses = (IP_ADAPTER_ADDRESSES*)
		malloc(sizeof(IP_ADAPTER_ADDRESSES) * outBufLen);
	if (AdapterAddresses == NULL) return CPL_E_INSUFFICIENT_RESOURCES;

	dwRetVal = GetAdaptersAddresses(family, flags, NULL, AdapterAddresses,
		&outBufLen);
	if (dwRetVal != 0) { free(AdapterAddresses); return CPL_E_PLATFORM_ERROR; }

	for (PIP_ADAPTER_ADDRESSES p = AdapterAddresses; p != NULL; p = p->Next) {
		if (p->IfType == IF_TYPE_SOFTWARE_LOOPBACK) continue;
		if (p->PhysicalAddressLength != 6 /* Ethernet */) continue;

		success = true;
		if (out) memcpy(out, p->PhysicalAddress, 6);
		break;
	}

	free(AdapterAddresses);

	if (!success) return CPL_E_NOT_FOUND;

#else
#error "Not implemented for this platform"
#endif

	return CPL_OK;
}