static void
add_supplemental_proxies(CFMutableArrayRef proxies, CFDictionaryRef services, CFArrayRef service_order)
{
	const void *		keys_q[N_QUICK];
	const void **		keys	= keys_q;
	CFIndex			i;
	CFIndex			n_order;
	CFIndex			n_services;
	const void *		vals_q[N_QUICK];
	const void **		vals	= vals_q;

	n_services = isA_CFDictionary(services) ? CFDictionaryGetCount(services) : 0;
	if (n_services == 0) {
		return;		// if no services
	}

	if (n_services > (CFIndex)(sizeof(keys_q) / sizeof(CFTypeRef))) {
		keys = CFAllocatorAllocate(NULL, n_services * sizeof(CFTypeRef), 0);
		vals = CFAllocatorAllocate(NULL, n_services * sizeof(CFTypeRef), 0);
	}

	n_order = isA_CFArray(service_order) ? CFArrayGetCount(service_order) : 0;

	CFDictionaryGetKeysAndValues(services, keys, vals);
	for (i = 0; i < n_services; i++) {
		uint32_t		defaultOrder;
		CFDictionaryRef		proxy;
		CFMutableDictionaryRef	proxyWithDNS	= NULL;
		CFDictionaryRef		service		= (CFDictionaryRef)vals[i];

		if (!isA_CFDictionary(service)) {
			continue;
		}

		proxy = CFDictionaryGetValue(service, kSCEntNetProxies);
		if (!isA_CFDictionary(proxy)) {
			continue;
		}

		if ((G_supplemental_proxies_follow_dns != NULL) && CFBooleanGetValue(G_supplemental_proxies_follow_dns)) {
			CFDictionaryRef	dns;
			CFArrayRef	matchDomains;
			CFArrayRef	matchOrders;

			if (!CFDictionaryContainsKey(proxy, kSCPropNetProxiesSupplementalMatchDomains) &&
			    CFDictionaryGetValueIfPresent(service, kSCEntNetDNS, (const void **)&dns) &&
			    isA_CFDictionary(dns) &&
			    CFDictionaryGetValueIfPresent(dns, kSCPropNetDNSSupplementalMatchDomains, (const void **)&matchDomains) &&
			    isA_CFArray(matchDomains)) {
				proxyWithDNS = CFDictionaryCreateMutableCopy(NULL, 0, proxy);
				CFDictionarySetValue(proxyWithDNS, kSCPropNetProxiesSupplementalMatchDomains, matchDomains);
				if (CFDictionaryGetValueIfPresent(dns, kSCPropNetDNSSupplementalMatchOrders, (const void **)&matchOrders) &&
				    isA_CFArray(matchOrders)) {
					CFDictionarySetValue(proxyWithDNS, kSCPropNetProxiesSupplementalMatchOrders, matchOrders);
				} else {
					CFDictionaryRemoveValue(proxyWithDNS, kSCPropNetProxiesSupplementalMatchOrders);
				}
				proxy = proxyWithDNS;
			}
		}

		defaultOrder = DEFAULT_MATCH_ORDER
			       - (DEFAULT_MATCH_ORDER / 2)
			       + ((DEFAULT_MATCH_ORDER / 1000) * i);
		if ((n_order > 0) &&
		    !CFArrayContainsValue(service_order, CFRangeMake(0, n_order), keys[i])) {
			// push out services not specified in service order
			defaultOrder += (DEFAULT_MATCH_ORDER / 1000) * n_services;
		}

		add_supplemental(proxies, proxy, defaultOrder);
		if (proxyWithDNS != NULL) CFRelease(proxyWithDNS);
	}

	if (keys != keys_q) {
		CFAllocatorDeallocate(NULL, keys);
		CFAllocatorDeallocate(NULL, vals);
	}

	return;
}
Ejemplo n.º 2
0
/* Main program */
int main (int argc, const char * argv[])
{
	enum                   suspend_type {soft, dump, hard};
	int                    vmmib[2] = {CTL_VM, VM_SWAPUSAGE};
	int					   osmib[2] = {CTL_KERN, KERN_OSRELEASE};
	int                    original_mode;
	int                    target_mode;
	int                    default_mode;
	int                    original_profile;
	int                    target_profile = -1;
	void                   *refCon;
	struct xsw_usage       swap;
	size_t                 swlen = sizeof(swap);
	size_t				   oslen;
	char                   *kernel_version;
	int                    major_version = 0;
	int                    minor_version = 0;
	struct stat            sleepimage;
	                                                                                                                               /* By default, */
	int                    do_sleep = 1;                                                                                           /* send the sleep call, */
	int                    repair = 0;                                                                                             /* do not check the validity of the original hibernation mode, */
	int                    check_hibernation = 1;                                                                                  /* check if the hibernation file is present, */
	int                    check_os = 1;                                                                                           /* check if the operating system is supported, */
	enum suspend_type      target_suspend = soft;                                                                                  /* send computer to software suspend mode, */
	int                    restore = 1;                                                                                            /* restore the original mode, */

	if (argc >= 2) {
		if (!strcmp(argv[1], "-v")) {                                                                                              /* Display version number if invoked with -v */
			printf("deepsleep build %s\n", VERSION);
			return 0;
		} else if (!strcmp(argv[1], "-h")) {
			printf("deepsleep usage: deepsleep [-bdhrvsu] [hard|dump|soft]\n");
			printf("                 -b : bypass the hibernation file check\n");
			printf("                 -d : debug mode - be verbose\n");
			printf("                 -h : display this help screen\n");
			printf("                 -m : mute - be silent\n");
			printf("                 -o : do not restore the original hibernation mode\n");
			printf("                 -r : repair the default hibernation mode if needed\n");
			printf("                 -s : simulation - do not send the computer to sleep\n");
			printf("                 -v : display version number\n");
			printf("                 -u : perform operations even on unsupported OS revisions\n");
			printf("                 hard : send computer to hardware suspend mode\n");
			printf("                 dump : send computer to safe hardware suspend mode\n");
			printf("                 soft : send computer to software suspend mode (by default)\n");
			return 0;
		} else {
			if (argc >= 3) {
				if (strstr(argv[1], "b"))                                                                                             /* Do not check the existence of the hibernation file if invoked with -b */
					check_hibernation = 0;	
				if (strstr(argv[1], "d"))                                                                                             /* Print debug information if invoked with -d */
					debug = 1;
				if (strstr(argv[1], "o"))                                                                                             /* Do not restore the original hibernation mode if invoked with -o */
					restore = 0;
				if (strstr(argv[1], "r"))                                                                                             /* Check for the validity of the original hibernation mode if invoked with -r*/ 
					repair = 1;
				if (strstr(argv[1], "s"))                                                                                             /* Do not send the sleep call if invoked with -s */
					do_sleep = 0;
				if (strstr(argv[1], "u"))                                                                                             /* Do not care about OS revision if invoked with -u */
					check_os = 0;
				if (strstr(argv[1], "m"))
					mute = 1;
			} 	
			if (strstr(argv[argc-1], "hard"))                                                                                         /* Send computer to hardware suspend mode instead of software suspend mode if the hard argument is present */
				target_suspend = hard;
			else if (strstr(argv[argc-1], "dump"))                                                                                    /* Send computer to safe hardware suspend mode instead of software suspend mode if the safe argument is present */
				target_suspend = dump;	
		}
	}
	
	if (sysctl(osmib, 2, NULL, &oslen, NULL, 0) == -1) {                                                                          /* Get the operating system revision length */
		printf("Failed to get the operating system revision\n");                                                                     /* On failure: quit */
		return 1;
	} else {
		kernel_version = malloc(oslen * sizeof(char));                                        
		sysctl(osmib, 2, kernel_version, &oslen, NULL, 0);                                                                       /* Get the operating system revision length */
		sscanf(kernel_version, "%d.%d", &major_version, &minor_version);
		free(kernel_version);
	}
	if (debug) {
		printf("OS revision: %d.%d", major_version, minor_version);
		if (!check_os) printf(" (ignored)");
		printf("\n");
	}
	if (check_os && (major_version != 8 || minor_version < 3) && (major_version <= 8)) {                                         /* If needed, check if major version is 8 (Mac OS X 10.4) and minor version is greater or equal than 3. Mac OS X 10.5 is also supported.*/
		printf("This operating system is not supported\n");                                                                           /* On failure: quit */
		return 1;
	}
	
	if (check_hibernation && stat("/private/var/vm/sleepimage", &sleepimage)) {                                                  /* If needed, check if the hibernation file (/private/var/vm/sleepimage) exists */
		printf("Hibernation file is missing\n");                                                                                     /* On failure: quit */   
		return 1;
	}
	
	if (sysctl(vmmib, 2, &swap, &swlen, NULL, 0) == -1) {                                                                       /* Get the current virtual memory parameters */
		printf("Failed to get the virtual memory information\n");                                                                  /* On failure: quit */
		return 1;
	} else {
        default_mode = 3;
        if (target_suspend == dump) {
            target_mode = default_mode;                                                                                               /* we will use the regular mode 3 for safe hardware suspsend */
        } else /*if (target_suspend == soft)*/ {
            target_mode = 25;                                                                                                          /* or the regular mode 25 for software suspsend */
        }        
		if (target_suspend == hard)                                                                                                 /* If we only want to perform basic hardware suspend */
			target_mode = 0;                                                                                                            /* we will sleep with hibernate mode 0 */
		if (debug) printf("target mode: %d\n", target_mode);
	}
	
	ps_info = IOPSCopyPowerSourcesInfo();                                                                                       /* Get the power source information */
	if (ps_info) {
		current_ps = IOPSGetProvidingPowerSourceType(ps_info);                                                                     /* On success, store the active power source */
	} else {
		printf("Failed to get the power source information\n");                                                                    /* On failure: quit */
		return 1;
	}
	if (debug) printf("target power source: %s\n", CFStringGetCStringPtr(current_ps, kCFStringEncodingMacRoman));	
	
	active_prof = IOPMCopyActivePowerProfiles();                                                                                /* Get the power profiles */
    if (!active_prof) {
        printf("Failed to get the active profile\n");
		CFCleanup();
		return 1;
    }
	if (CFDictionaryContainsKey(active_prof, current_ps)) {                                                                     /* Get the active profile corresponding to the current power source */
		profile_ref = (CFNumberRef) CFDictionaryGetValue(active_prof, current_ps);
		profile_type = CFNumberGetType(profile_ref);
		CFNumberGetValue(profile_ref, profile_type, &original_profile);                                                            /* On succes, store its value */
		if (debug) printf("original profile: %d\n", original_profile);
	} else {
		printf("Failed to get the power management settings\n");                                                                   /* On failure: quit */
		CFCleanup();
		return 1;
	}	
		
	ds = SCDynamicStoreCreate(NULL, CFSTR("deepsleep"), NULL, NULL);                                                            /* Create a new dynamic store */
	live_settings = SCDynamicStoreCopyValue(ds, CFSTR(kIOPMDynamicStoreSettingsKey));                                           /* Read current settings */
	if(!isA_CFDictionary(live_settings)) {                                                                                         /* We did not get the settings: quit */
		printf("Failed to get the power management settings\n");
		CFCleanup();
		return 1;                                               
	}
	
	if (CFDictionaryContainsKey(live_settings, CFSTR("Hibernate Mode"))) {                                                      /* Check if the hibernate mode key exists */
		hm_ref = (CFNumberRef) CFDictionaryGetValue(live_settings, CFSTR("Hibernate Mode"));                                       /* On success, get its value */
		hm_type = CFNumberGetType(hm_ref);
		CFNumberGetValue(hm_ref, hm_type, &original_mode);
		if (debug) printf("original mode: %d\n", original_mode);
	}
	else {                                                                                                                         /* On failure, cleanup and quit */ 
		printf("Failed to get the hibernation mode\n");
		CFCleanup();                                                                                                  
		return 1;
	}
	
	if (repair && original_mode == target_mode) {                                                                              /* If the original mode is the same as the target mode */
		original_mode = default_mode;                                                                                              /* A crash has probably happened during hibernation: we will set back the hibernation mode to its default value after wakeup */ 
		if (debug) printf("repair mode to: %d\n", default_mode);
	}
	
	root_power_port = IORegisterForSystemPower(refCon, &notifyPortRef, PowerCallBack, &notifierObject);                         /* Register to the Root Power Domain IOService: notifications will be handled by the PowerCallBack functions */
	if (!root_power_port) {                                                                                                        /* Registering failed: quit */
		printf("Failed to register to the Root Power Domain IOService\n");		
		CFCleanup();
		return 1;
	}
	
	CFRunLoopAddSource(CFRunLoopGetCurrent(), IONotificationPortGetRunLoopSource(notifyPortRef), kCFRunLoopCommonModes);        /* Add the notification port to the run loop */
	
	if (SetActiveProfile(target_profile, current_ps, active_prof)) {                                                            /* Set the active power profile to custom (-1) */
		printf("Failed to set the active profile\n");
		PortsCleanup();
		CFCleanup();
		return 1;
	}
	if (SetHibernateMode(target_mode, current_ps))	{                                                                           /* Set the hibernate mode to target mode */
		printf("Failed to set the hibernation mode\n");
		SetActiveProfile(original_profile, current_ps, active_prof);
		PortsCleanup();
		CFCleanup();
		return 1;
	}
	
	if (do_sleep) {                                                                                                             /* If we are not in simulation mode */
		sleep(3);                                                                                                                   /* Wait for 3s to allow settings to settle down */
		if (IOPMSleepSystem(root_power_port) == kIOReturnSuccess)                                                                   /* Request the system to sleep */
			CFRunLoopRun();                                                                                                            /* On success, start the run loop */
		else 
			perror("Failed to send the sleep request\n");                                                                              /* On failure, do not start it */
	}																															/* The run loop has stopped: system has woken up */
	
	if (restore) {                                                                                                              /* If we are asked to restore the original hibernate mode */
		if (SetHibernateMode(original_mode, current_ps)) {                                                                          /* Restore the original hibernate mode */
			printf("Failed to set the hibernation mode\n");
			SetActiveProfile(original_profile, current_ps, active_prof);
			PortsCleanup();
			CFCleanup();
			return 1;
		}
		if (SetActiveProfile(original_profile, current_ps, active_prof)) {                                                          /* Restore the original power profile */
			printf("Failed to set the active profile\n");
			PortsCleanup();
			CFCleanup();
			return 1;
		}
	}
																																   
	PortsCleanup();				                                                                                                /* Cleanup */																																																											
	CFCleanup();
    return 0;
}
Ejemplo n.º 3
0
static void
booterExit(pid_t pid, int status, struct rusage *rusage, void *context)
{
	Boolean		again	= FALSE;
	CFStringRef	name;
	Boolean		ok	= TRUE;
	kickeeRef	target	= (kickeeRef)context;

	name = CFDictionaryGetValue(target->dict, CFSTR("name"));

	if (WIFEXITED(status)) {
		SCLog(TRUE, LOG_DEBUG,
		      CFSTR("  target=%@: exit status = %d"),
		      name,
		      WEXITSTATUS(status));
		if (WEXITSTATUS(status) != 0) {
			ok = FALSE;
		}
	} else if (WIFSIGNALED(status)) {
		SCLog(TRUE, LOG_DEBUG,
		      CFSTR("  target=%@: terminated w/signal = %d"),
		      name,
		      WTERMSIG(status));
		ok = FALSE;
	} else {
		SCLog(TRUE, LOG_DEBUG,
		      CFSTR("  target=%@: exit status = %d"),
		      name,
		      status);
		ok = FALSE;
	}

	if (ok) {
		if (target->needsKick) {
			again = TRUE;		/* one more time */
		} else {
			target->active = FALSE;	/* normal exit, no more requests */
		}
	}

	if (!ok) {
		if (CFDictionaryContainsKey(target->dict, CFSTR("postName"))) {
			CFDictionaryRef		oldDict	= target->dict;
			CFMutableDictionaryRef	newDict	= CFDictionaryCreateMutableCopy(NULL, 0, oldDict);

			/*
			 * if this target specifies both a BSD notification and
			 * a script to be executed then we want to continue to
			 * post the BSD notifications (and not execute the
			 * script).  As such, remove the script reference from
			 * the dictionary.
			 */
			CFDictionaryRemoveValue(newDict, CFSTR("execCommand"));
			CFDictionaryRemoveValue(newDict, CFSTR("execGID"));
			CFDictionaryRemoveValue(newDict, CFSTR("execUID"));
			CFDictionaryRemoveValue(newDict, CFSTR("changedKeysAsArguments"));
			target->dict = newDict;
			CFRelease(oldDict);

			/* ... and allow BSD notifications */
			target->active = FALSE;
		} else {
			/*
			 * If the target action can't be performed this time then
			 * there's not much point in trying again. As such, I close
			 * the session and the kickee target released.
			 */
			cleanupKicker(target);
		}
	} else if (again) {
		booter(target);
	}

	return;
}
Ejemplo n.º 4
0
static GstFlowReturn
gst_vtenc_encode_frame (GstVTEnc * self, GstBuffer * buf)
{
  GstVTApi *vt = self->ctx->vt;
  CMTime ts, duration;
  GstCoreMediaMeta *meta;
  CVPixelBufferRef pbuf = NULL;
  VTStatus vt_status;
  GstFlowReturn ret = GST_FLOW_OK;
  guint i;

  self->cur_inbuf = buf;

  ts = CMTimeMake (GST_TIME_AS_MSECONDS (GST_BUFFER_TIMESTAMP (buf)), 1000);
  duration = CMTimeMake
      (GST_TIME_AS_MSECONDS (GST_BUFFER_DURATION (buf)), 1000);

  meta = gst_buffer_get_core_media_meta (buf);
  if (meta != NULL) {
    pbuf = gst_core_media_buffer_get_pixel_buffer (buf);
  }

  if (pbuf == NULL) {
    GstVTEncFrame *frame;
    CVReturn cv_ret;

    frame = gst_vtenc_frame_new (buf, &self->video_info);
    if (!frame)
      goto cv_error;

    {
      const size_t num_planes = GST_VIDEO_FRAME_N_PLANES (&frame->videoframe);
      void *plane_base_addresses[GST_VIDEO_MAX_PLANES];
      size_t plane_widths[GST_VIDEO_MAX_PLANES];
      size_t plane_heights[GST_VIDEO_MAX_PLANES];
      size_t plane_bytes_per_row[GST_VIDEO_MAX_PLANES];
      OSType pixel_format_type;
      size_t i;

      for (i = 0; i < num_planes; i++) {
        plane_base_addresses[i] =
            GST_VIDEO_FRAME_PLANE_DATA (&frame->videoframe, i);
        plane_widths[i] = GST_VIDEO_FRAME_COMP_WIDTH (&frame->videoframe, i);
        plane_heights[i] = GST_VIDEO_FRAME_COMP_HEIGHT (&frame->videoframe, i);
        plane_bytes_per_row[i] =
            GST_VIDEO_FRAME_COMP_STRIDE (&frame->videoframe, i);
        plane_bytes_per_row[i] =
            GST_VIDEO_FRAME_COMP_STRIDE (&frame->videoframe, i);
      }

      switch (GST_VIDEO_INFO_FORMAT (&self->video_info)) {
        case GST_VIDEO_FORMAT_I420:
          pixel_format_type = kCVPixelFormatType_420YpCbCr8Planar;
          break;
        case GST_VIDEO_FORMAT_NV12:
          pixel_format_type = kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange;
          break;
        default:
          goto cv_error;
      }

      cv_ret = CVPixelBufferCreateWithPlanarBytes (NULL,
          self->negotiated_width, self->negotiated_height,
          pixel_format_type,
          frame,
          GST_VIDEO_FRAME_SIZE (&frame->videoframe),
          num_planes,
          plane_base_addresses,
          plane_widths,
          plane_heights,
          plane_bytes_per_row, gst_pixel_buffer_release_cb, frame, NULL, &pbuf);
      if (cv_ret != kCVReturnSuccess) {
        gst_vtenc_frame_free (frame);
        goto cv_error;
      }
    }
  }

  GST_OBJECT_LOCK (self);

  self->expect_keyframe = CFDictionaryContainsKey (self->options,
      *(vt->kVTEncodeFrameOptionKey_ForceKeyFrame));
  if (self->expect_keyframe)
    gst_vtenc_clear_cached_caps_downstream (self);

  vt_status = self->ctx->vt->VTCompressionSessionEncodeFrame (self->session,
      pbuf, ts, duration, self->options, NULL, NULL);

  if (vt_status != 0) {
    GST_WARNING_OBJECT (self, "VTCompressionSessionEncodeFrame returned %d",
        vt_status);
  }

  self->ctx->vt->VTCompressionSessionCompleteFrames (self->session,
      kCMTimeInvalid);

  GST_OBJECT_UNLOCK (self);

  CVPixelBufferRelease (pbuf);
  self->cur_inbuf = NULL;
  gst_buffer_unref (buf);

  if (self->cur_outbufs->len > 0) {
    meta =
        gst_buffer_get_core_media_meta (g_ptr_array_index (self->cur_outbufs,
            0));
    if (!gst_vtenc_negotiate_downstream (self, meta->sample_buf))
      ret = GST_FLOW_NOT_NEGOTIATED;
  }

  for (i = 0; i != self->cur_outbufs->len; i++) {
    GstBuffer *buf = g_ptr_array_index (self->cur_outbufs, i);

    if (ret == GST_FLOW_OK) {
      ret = gst_pad_push (self->srcpad, buf);
    } else {
      gst_buffer_unref (buf);
    }
  }
  g_ptr_array_set_size (self->cur_outbufs, 0);

  return ret;

cv_error:
  {
    self->cur_inbuf = NULL;
    gst_buffer_unref (buf);

    return GST_FLOW_ERROR;
  }
}
Ejemplo n.º 5
0
static GstFlowReturn
gst_vtenc_encode_frame (GstVTEnc * self, GstBuffer * buf)
{
  GstCVApi *cv = self->ctx->cv;
  GstVTApi *vt = self->ctx->vt;
  CMTime ts, duration;
  CVPixelBufferRef pbuf = NULL;
  VTStatus vt_status;
  GstFlowReturn ret = GST_FLOW_OK;
  guint i;

  self->cur_inbuf = buf;

  ts = self->ctx->cm->CMTimeMake
      (GST_TIME_AS_MSECONDS (GST_BUFFER_TIMESTAMP (buf)), 1000);
  duration = self->ctx->cm->CMTimeMake
      (GST_TIME_AS_MSECONDS (GST_BUFFER_DURATION (buf)), 1000);

  if (GST_IS_CORE_MEDIA_BUFFER (buf)) {
    GstCoreMediaBuffer *cmbuf = GST_CORE_MEDIA_BUFFER_CAST (buf);
    pbuf = gst_core_media_buffer_get_pixel_buffer (cmbuf);
  }

  if (pbuf == NULL) {
    CVReturn cv_ret;

    cv_ret = cv->CVPixelBufferCreateWithBytes (NULL,
        self->negotiated_width, self->negotiated_height,
        kCVPixelFormatType_422YpCbCr8Deprecated, GST_BUFFER_DATA (buf),
        self->negotiated_width * 2,
        (CVPixelBufferReleaseBytesCallback) gst_buffer_unref, buf, NULL, &pbuf);
    if (cv_ret != kCVReturnSuccess)
      goto cv_error;
    gst_buffer_ref (buf);
  }

  GST_OBJECT_LOCK (self);

  self->expect_keyframe = CFDictionaryContainsKey (self->options,
      *(vt->kVTEncodeFrameOptionKey_ForceKeyFrame));
  if (self->expect_keyframe)
    gst_vtenc_clear_cached_caps_downstream (self);

  vt_status = self->ctx->vt->VTCompressionSessionEncodeFrame (self->session,
      pbuf, ts, duration, self->options, NULL, NULL);

  if (vt_status != 0) {
    GST_WARNING_OBJECT (self, "VTCompressionSessionEncodeFrame returned %d",
        vt_status);
  }

  self->ctx->vt->VTCompressionSessionCompleteFrames (self->session,
      *(self->ctx->cm->kCMTimeInvalid));

  GST_OBJECT_UNLOCK (self);

  cv->CVPixelBufferRelease (pbuf);
  self->cur_inbuf = NULL;
  gst_buffer_unref (buf);

  if (self->cur_outbufs->len > 0) {
    GstCoreMediaBuffer *cmbuf =
        GST_CORE_MEDIA_BUFFER_CAST (g_ptr_array_index (self->cur_outbufs, 0));
    if (!gst_vtenc_negotiate_downstream (self, cmbuf->sample_buf))
      ret = GST_FLOW_NOT_NEGOTIATED;
  }

  for (i = 0; i != self->cur_outbufs->len; i++) {
    GstBuffer *buf = g_ptr_array_index (self->cur_outbufs, i);

    if (ret == GST_FLOW_OK) {
      gst_buffer_set_caps (buf, GST_PAD_CAPS (self->srcpad));
      ret = gst_pad_push (self->srcpad, buf);
    } else {
      gst_buffer_unref (buf);
    }
  }
  g_ptr_array_set_size (self->cur_outbufs, 0);

  return ret;

cv_error:
  {
    self->cur_inbuf = NULL;
    gst_buffer_unref (buf);

    return GST_FLOW_ERROR;
  }
}
__private_extern__
CF_RETURNS_RETAINED CFDictionaryRef
proxy_configuration_update(CFDictionaryRef	defaultProxy,
			   CFDictionaryRef	services,
			   CFArrayRef		serviceOrder,
			   CFDictionaryRef	servicesInfo)
{
	CFIndex			i;
	CFMutableDictionaryRef	myDefault;
	Boolean			myOrderAdded	= FALSE;
	CFMutableDictionaryRef	newProxy	= NULL;
	CFIndex			n_proxies;
	CFDictionaryRef		proxy;
	CFMutableArrayRef	proxies;

	// establish full list of proxies

	proxies = CFArrayCreateMutable(NULL, 0, &kCFTypeArrayCallBacks);

	// collect (and add) any "supplemental" proxy configurations

	add_supplemental_proxies(proxies, services, serviceOrder);

	// add the "default" proxy

	add_default_proxy(proxies, defaultProxy, &myOrderAdded);

	// sort proxies, cleanup

	n_proxies = CFArrayGetCount(proxies);
	if (n_proxies > 1) {
		CFArraySortValues(proxies, CFRangeMake(0, n_proxies), compareDomain, NULL);
	}

	// cleanup

	for (i = n_proxies - 1; i >= 0; i--) {
		proxy = CFArrayGetValueAtIndex(proxies, i);

		if ((i > 0) &&
		    !CFDictionaryContainsKey(proxy, kSCPropNetProxiesSupplementalMatchDomain)) {
			// remove non-supplemental proxy
			CFArrayRemoveValueAtIndex(proxies, i);
			n_proxies--;
			continue;
		}

		newProxy = CFDictionaryCreateMutableCopy(NULL, 0, proxy);
		CFDictionaryRemoveValue(newProxy, PROXY_MATCH_ORDER_KEY);
		CFDictionaryRemoveValue(newProxy, ORDER_KEY);
		CFArraySetValueAtIndex(proxies, i, newProxy);
		CFRelease(newProxy);
	}

	// update the default proxy

	myDefault = CFDictionaryCreateMutableCopy(NULL,
						  0,
						  CFArrayGetValueAtIndex(proxies, 0));
	if (myOrderAdded && (n_proxies > 1)) {
		CFDictionaryRef	proxy;

		proxy = CFArrayGetValueAtIndex(proxies, 1);
		if (CFDictionaryContainsKey(proxy, kSCPropNetProxiesSupplementalMatchDomain)) {
			// if not a supplemental "default" proxy (a match domain name is
			// present)
			CFDictionaryRemoveValue(myDefault, PROXY_MATCH_ORDER_KEY);
		}
	}
	CFArraySetValueAtIndex(proxies, 0, myDefault);
	CFRelease(myDefault);

	// establish proxy configuration

	if (n_proxies > 0) {
		CFDictionaryRef		app_layer;
		CFDictionaryRef		scoped;
		CFArrayRef		serviceOrderAll;
		Boolean			skip		= FALSE;
		CFArrayRef		supplemental;

		proxy = CFArrayGetValueAtIndex(proxies, 0);
		if (!CFDictionaryContainsKey(proxy, kSCPropNetProxiesSupplementalMatchDomain)) {
			// if we have "a" default (non-supplemental) proxy
			newProxy = CFDictionaryCreateMutableCopy(NULL, 0, proxy);
			CFDictionaryRemoveValue(newProxy, kSCPropNetProxiesSupplementalMatchDomains);
			CFDictionaryRemoveValue(newProxy, kSCPropNetProxiesSupplementalMatchOrders);
			skip = TRUE;
		} else {
			newProxy = CFDictionaryCreateMutable(NULL,
							     0,
							     &kCFTypeDictionaryKeyCallBacks,
							     &kCFTypeDictionaryValueCallBacks);
		}

		serviceOrderAll = service_order_copy_all(services, serviceOrder);

		// collect (and add) any "supplemental" proxy configurations

		supplemental = copy_supplemental_proxies(proxies, skip);
		if (supplemental != NULL) {
			CFDictionarySetValue(newProxy, kSCPropNetProxiesSupplemental, supplemental);
			CFRelease(supplemental);
		}

		// collect (and add) any "scoped" proxy configurations

		scoped = copy_scoped_proxies(services, serviceOrderAll);
		if (scoped != NULL) {
			CFDictionarySetValue(newProxy, kSCPropNetProxiesScoped, scoped);
			CFRelease(scoped);
		}

		// collect (and add) any "services" based proxy configurations

		app_layer = copy_app_layer_vpn_proxies(services, serviceOrderAll, servicesInfo);
		if (app_layer != NULL) {
			CFDictionarySetValue(newProxy, kSCPropNetProxiesServices, app_layer);
			CFRelease(app_layer);
		}

		if (serviceOrderAll != NULL) {
			CFRelease(serviceOrderAll);
		}
	} else {
		newProxy = NULL;
	}

	CFRelease(proxies);
	return newProxy;
}
Ejemplo n.º 7
0
//-----------------------------------------------------------------------------
void C700::RestorePGDataDic(CFPropertyListRef data, int pgnum)
{
    int editProg = mEfx->GetPropertyValue(kAudioUnitCustomProperty_EditingProgram);
    mEfx->SetPropertyValue(kAudioUnitCustomProperty_EditingProgram, pgnum);

    CFDictionaryRef dict = static_cast<CFDictionaryRef>(data);
    CFNumberRef cfnum;

    CFDataRef cfdata = reinterpret_cast<CFDataRef>(CFDictionaryGetValue(dict, kSaveKey_brrdata));
    int	size = CFDataGetLength(cfdata);
    const UInt8	*dataptr = CFDataGetBytePtr(cfdata);
    BRRData		brr;
    brr.data = const_cast<unsigned char*>(dataptr);
    brr.size = size;
    mEfx->SetBRRData(&brr);
    mEfx->SetPropertyValue(kAudioUnitCustomProperty_Loop,
                           brr.data[brr.size-9]&2?true:false);

    int	value;
    if (CFDictionaryContainsKey(dict, kSaveKey_looppoint)) {
        cfnum = reinterpret_cast<CFNumberRef>(CFDictionaryGetValue(dict, kSaveKey_looppoint));
        CFNumberGetValue(cfnum, kCFNumberIntType, &value);
        mEfx->SetPropertyValue(kAudioUnitCustomProperty_LoopPoint, value);
    }

    double	dvalue;
    if (CFDictionaryContainsKey(dict, kSaveKey_samplerate)) {
        cfnum = reinterpret_cast<CFNumberRef>(CFDictionaryGetValue(dict, kSaveKey_samplerate));
        CFNumberGetValue(cfnum, kCFNumberDoubleType, &dvalue);
        mEfx->SetPropertyValue(kAudioUnitCustomProperty_Rate, dvalue);
    }

    if (CFDictionaryContainsKey(dict, kSaveKey_basekey)) {
        cfnum = reinterpret_cast<CFNumberRef>(CFDictionaryGetValue(dict, kSaveKey_basekey));
        CFNumberGetValue(cfnum, kCFNumberIntType, &value);
        mEfx->SetPropertyValue(kAudioUnitCustomProperty_BaseKey, value);
    }
    else {
        mEfx->SetPropertyValue(kAudioUnitCustomProperty_BaseKey, 60);
    }
    if (CFDictionaryContainsKey(dict, kSaveKey_lowkey)) {
        cfnum = reinterpret_cast<CFNumberRef>(CFDictionaryGetValue(dict, kSaveKey_lowkey));
        CFNumberGetValue(cfnum, kCFNumberIntType, &value);
        mEfx->SetPropertyValue(kAudioUnitCustomProperty_LowKey, value);
    }
    else {
        mEfx->SetPropertyValue(kAudioUnitCustomProperty_LowKey, 0);
    }
    if (CFDictionaryContainsKey(dict, kSaveKey_highkey)) {
        cfnum = reinterpret_cast<CFNumberRef>(CFDictionaryGetValue(dict, kSaveKey_highkey));
        CFNumberGetValue(cfnum, kCFNumberIntType, &value);
        mEfx->SetPropertyValue(kAudioUnitCustomProperty_HighKey,value );
    }
    else {
        mEfx->SetPropertyValue(kAudioUnitCustomProperty_HighKey,127 );
    }

    if (CFDictionaryContainsKey(dict, kSaveKey_ar)) {
        cfnum = reinterpret_cast<CFNumberRef>(CFDictionaryGetValue(dict, kSaveKey_ar));
        CFNumberGetValue(cfnum, kCFNumberIntType, &value);
        mEfx->SetPropertyValue(kAudioUnitCustomProperty_AR, value);
    }

    if (CFDictionaryContainsKey(dict, kSaveKey_dr)) {
        cfnum = reinterpret_cast<CFNumberRef>(CFDictionaryGetValue(dict, kSaveKey_dr));
        CFNumberGetValue(cfnum, kCFNumberIntType, &value);
        mEfx->SetPropertyValue(kAudioUnitCustomProperty_DR, value);
    }

    if (CFDictionaryContainsKey(dict, kSaveKey_sl)) {
        cfnum = reinterpret_cast<CFNumberRef>(CFDictionaryGetValue(dict, kSaveKey_sl));
        CFNumberGetValue(cfnum, kCFNumberIntType, &value);
        mEfx->SetPropertyValue(kAudioUnitCustomProperty_SL, value);
    }

    if (CFDictionaryContainsKey(dict, kSaveKey_sr)) {
        cfnum = reinterpret_cast<CFNumberRef>(CFDictionaryGetValue(dict, kSaveKey_sr));
        CFNumberGetValue(cfnum, kCFNumberIntType, &value);
        mEfx->SetPropertyValue(kAudioUnitCustomProperty_SR, value);
    }

    if (CFDictionaryContainsKey(dict, kSaveKey_SustainMode)) {
        CFBooleanRef cfbool = reinterpret_cast<CFBooleanRef>(CFDictionaryGetValue(dict, kSaveKey_SustainMode));
        mEfx->SetPropertyValue(kAudioUnitCustomProperty_SustainMode,CFBooleanGetValue(cfbool) ? 1.0f:.0f);
    }
    else {
        mEfx->SetPropertyValue(kAudioUnitCustomProperty_SustainMode, 1.0f);
    }

    if (CFDictionaryContainsKey(dict, kSaveKey_volL)) {
        cfnum = reinterpret_cast<CFNumberRef>(CFDictionaryGetValue(dict, kSaveKey_volL));
        CFNumberGetValue(cfnum, kCFNumberIntType, &value);
        mEfx->SetPropertyValue(kAudioUnitCustomProperty_VolL, value);
    }
    else {
        mEfx->SetPropertyValue(kAudioUnitCustomProperty_VolL, 100);
    }

    if (CFDictionaryContainsKey(dict, kSaveKey_volR)) {
        cfnum = reinterpret_cast<CFNumberRef>(CFDictionaryGetValue(dict, kSaveKey_volR));
        CFNumberGetValue(cfnum, kCFNumberIntType, &value);
        mEfx->SetPropertyValue(kAudioUnitCustomProperty_VolR, value);
    }
    else {
        mEfx->SetPropertyValue(kAudioUnitCustomProperty_VolR, 100);
    }

    if (CFDictionaryContainsKey(dict, kSaveKey_echo)) {
        CFBooleanRef cfbool = reinterpret_cast<CFBooleanRef>(CFDictionaryGetValue(dict, kSaveKey_echo));
        mEfx->SetPropertyValue(kAudioUnitCustomProperty_Echo,CFBooleanGetValue(cfbool) ? 1.0f:.0f);
    }
    else {
        mEfx->SetPropertyValue(kAudioUnitCustomProperty_Echo, .0f);
    }

    if (CFDictionaryContainsKey(dict, kSaveKey_bank)) {
        cfnum = reinterpret_cast<CFNumberRef>(CFDictionaryGetValue(dict, kSaveKey_bank));
        CFNumberGetValue(cfnum, kCFNumberIntType, &value);
        mEfx->SetPropertyValue(kAudioUnitCustomProperty_Bank, value );
    }
    else {
        mEfx->SetPropertyValue(kAudioUnitCustomProperty_Bank, 0 );
    }

    if (CFDictionaryContainsKey(dict, kSaveKey_MonoMode)) {
        CFBooleanRef cfbool = reinterpret_cast<CFBooleanRef>(CFDictionaryGetValue(dict, kSaveKey_MonoMode));
        mEfx->SetPropertyValue(kAudioUnitCustomProperty_MonoMode,CFBooleanGetValue(cfbool) ? 1.0f:.0f);
    }
    else {
        mEfx->SetPropertyValue(kAudioUnitCustomProperty_MonoMode, .0f);
    }

    if (CFDictionaryContainsKey(dict, kSaveKey_PortamentoOn)) {
        CFBooleanRef cfbool = reinterpret_cast<CFBooleanRef>(CFDictionaryGetValue(dict, kSaveKey_PortamentoOn));
        mEfx->SetPropertyValue(kAudioUnitCustomProperty_PortamentoOn,CFBooleanGetValue(cfbool) ? 1.0f:.0f);
    }
    else {
        mEfx->SetPropertyValue(kAudioUnitCustomProperty_PortamentoOn, .0f);
    }

    if (CFDictionaryContainsKey(dict, kSaveKey_PortamentoRate)) {
        cfnum = reinterpret_cast<CFNumberRef>(CFDictionaryGetValue(dict, kSaveKey_PortamentoRate));
        CFNumberGetValue(cfnum, kCFNumberIntType, &value);
        mEfx->SetPropertyValue(kAudioUnitCustomProperty_PortamentoRate, value );
    }
    else {
        mEfx->SetPropertyValue(kAudioUnitCustomProperty_PortamentoRate, 0 );
    }

    if (CFDictionaryContainsKey(dict, kSaveKey_NoteOnPriority)) {
        cfnum = reinterpret_cast<CFNumberRef>(CFDictionaryGetValue(dict, kSaveKey_NoteOnPriority));
        CFNumberGetValue(cfnum, kCFNumberIntType, &value);
        mEfx->SetPropertyValue(kAudioUnitCustomProperty_NoteOnPriority, value );
    }
    else {
        mEfx->SetPropertyValue(kAudioUnitCustomProperty_NoteOnPriority, 64 );
    }

    if (CFDictionaryContainsKey(dict, kSaveKey_ReleasePriority)) {
        cfnum = reinterpret_cast<CFNumberRef>(CFDictionaryGetValue(dict, kSaveKey_ReleasePriority));
        CFNumberGetValue(cfnum, kCFNumberIntType, &value);
        mEfx->SetPropertyValue(kAudioUnitCustomProperty_ReleasePriority, value );
    }
    else {
        mEfx->SetPropertyValue(kAudioUnitCustomProperty_ReleasePriority, 0 );
    }

    if (CFDictionaryContainsKey(dict, kSaveKey_ProgName)) {
        char	pgname[PROGRAMNAME_MAX_LEN];
        CFStringGetCString(reinterpret_cast<CFStringRef>(CFDictionaryGetValue(dict, kSaveKey_ProgName)),
                           pgname, PROGRAMNAME_MAX_LEN, kCFStringEncodingUTF8);
        mEfx->SetProgramName(pgname);
    }
    else {
        mEfx->SetProgramName("");
    }

    //元波形ファイル情報を復元
    if (CFDictionaryContainsKey(dict, kSaveKey_SourceFile)) {
        CFDataRef	urlData = reinterpret_cast<CFDataRef>(CFDictionaryGetValue(dict, kSaveKey_SourceFile));
        CFURLRef	url = CFURLCreateWithBytes( NULL, CFDataGetBytePtr(urlData),
                                                CFDataGetLength(urlData), kCFStringEncodingUTF8, NULL );
        CFStringRef pathStr = CFURLCopyFileSystemPath(url, kCFURLPOSIXPathStyle);
        char	path[PATH_LEN_MAX];
        CFStringGetCString(pathStr, path, PATH_LEN_MAX-1, kCFStringEncodingUTF8);
        mEfx->SetSourceFilePath(path);
        CFRelease(pathStr);
        CFRelease(url);

        CFBooleanRef cfbool = reinterpret_cast<CFBooleanRef>(CFDictionaryGetValue(dict, kSaveKey_IsEmphasized));
        mEfx->SetPropertyValue(kAudioUnitCustomProperty_IsEmaphasized, CFBooleanGetValue(cfbool) ? 1.0f:.0f);
    }
    else {
        mEfx->SetSourceFilePath("");
        mEfx->SetPropertyValue(kAudioUnitCustomProperty_IsEmaphasized, .0f);
    }

    //UIに変更を反映
    if (pgnum == editProg) {
        mEfx->SetPropertyValue(kAudioUnitCustomProperty_EditingProgram, editProg);
    }

    mEfx->GetGenerator()->RefreshKeyMap();
}
Ejemplo n.º 8
0
/*************************************************************************
 *
 * hu_AddVendorProductToCFDict( inCFMutableDictionaryRef, inVendorID, inVendorCFStringRef, inProductID, inProductCFStringRef )
 *
 * Purpose: add a vendor & product to a dictionary
 *
 * Inputs: inCFMutableDictionaryRef - the dictionary
 *			inVendorID				- the elements vendor ID
 *			inProductID				- the elements product ID
 *			inProductCFStringRef	- the string to be added
 *
 * Returns: Boolean		- if successful
 */
static Boolean hu_AddVendorProductToCFDict(CFMutableDictionaryRef inCFMutableDictionaryRef,
                                           long                   inVendorID,
                                           CFStringRef            inVendorCFStringRef,
                                           long                   inProductID,
                                           CFStringRef            inProductCFStringRef) {
	Boolean results = FALSE;
	if ( inCFMutableDictionaryRef && ( CFDictionaryGetTypeID() == CFGetTypeID(inCFMutableDictionaryRef) ) ) {
		CFMutableDictionaryRef vendorCFMutableDictionaryRef;
		CFStringRef vendorKeyCFStringRef;
		
		CFMutableDictionaryRef productCFMutableDictionaryRef;
		CFStringRef productKeyCFStringRef;
		
		// if the vendor dictionary doesn't exist
		vendorKeyCFStringRef = CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR("%ld"), inVendorID);
		if ( CFDictionaryGetValueIfPresent(inCFMutableDictionaryRef, vendorKeyCFStringRef,
		                                   (const void **) &vendorCFMutableDictionaryRef) )
		{
			// copy it.
			vendorCFMutableDictionaryRef = CFDictionaryCreateMutableCopy(kCFAllocatorDefault, 0, vendorCFMutableDictionaryRef);
		} else {    // ...otherwise...
			// create it.
			vendorCFMutableDictionaryRef = CFDictionaryCreateMutable(kCFAllocatorDefault,
			                                                         0,
			                                                         &kCFTypeDictionaryKeyCallBacks,
			                                                         &kCFTypeDictionaryValueCallBacks);
			results = TRUE;
		}
		// if the vendor name key doesn't exist
		if ( !CFDictionaryContainsKey(vendorCFMutableDictionaryRef, kNameKeyCFStringRef) ) {
			// create it.
			CFDictionaryAddValue(vendorCFMutableDictionaryRef, kNameKeyCFStringRef, inVendorCFStringRef);
			results = TRUE;
		}
		
		// if the product key exists in the vendor dictionary
		productKeyCFStringRef = CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR("%ld"), inProductID);
		if ( CFDictionaryGetValueIfPresent(vendorCFMutableDictionaryRef, productKeyCFStringRef,
		                                   (const void **) &productCFMutableDictionaryRef) )
		{
			// copy it.
			productCFMutableDictionaryRef = CFDictionaryCreateMutableCopy(kCFAllocatorDefault, 0, productCFMutableDictionaryRef);
		} else {    // ...otherwise...
			// create it.
			productCFMutableDictionaryRef = CFDictionaryCreateMutable(kCFAllocatorDefault,
			                                                          0,
			                                                          &kCFTypeDictionaryKeyCallBacks,
			                                                          &kCFTypeDictionaryValueCallBacks);
			results = TRUE;
		}
		// if the product name key doesn't exist
		if ( !CFDictionaryContainsKey(productCFMutableDictionaryRef, kNameKeyCFStringRef) ) {
			// create it.
			CFDictionaryAddValue(productCFMutableDictionaryRef, kNameKeyCFStringRef, inProductCFStringRef);
			results = TRUE;
		}
		if ( vendorCFMutableDictionaryRef ) {
			if ( productCFMutableDictionaryRef ) {
				if ( results ) {
					CFDictionarySetValue(vendorCFMutableDictionaryRef, productKeyCFStringRef, productCFMutableDictionaryRef);
				}
				
				CFRelease(productCFMutableDictionaryRef);
			}
			if ( results ) {
				CFDictionarySetValue(inCFMutableDictionaryRef, vendorKeyCFStringRef, vendorCFMutableDictionaryRef);
			}
			
			CFRelease(vendorCFMutableDictionaryRef);
		}
		if ( productKeyCFStringRef ) {
			CFRelease(productKeyCFStringRef);
		}
		if ( vendorKeyCFStringRef ) {
			CFRelease(vendorKeyCFStringRef);
		}
	}
	
	return (results);
}   // hu_AddVendorProductToCFDict
Ejemplo n.º 9
0
static void
filter_exception(const void *key, const void *value, void *context)
{
	SecExceptionFilterContext *ctx = (SecExceptionFilterContext *)context;
	if (!ctx) { return; }

	SecTrustOptionFlags options = ctx->flags;
	CFMutableDictionaryRef filteredException = ctx->filteredException;
	CFStringRef keystr = (CFStringRef)key;

	if (ctx->oldException && CFDictionaryContainsKey(ctx->oldException, key)) {
		// Keep existing exception in filtered dictionary, regardless of options
		CFDictionaryAddValue(filteredException, key, CFDictionaryGetValue(ctx->oldException, key));
		return;
	}

	bool allowed = false;

	if (CFEqual(keystr, CFSTR("SHA1Digest"))) {
		allowed = true; // this key is informational and always permitted
	}
	else if (CFEqual(keystr, CFSTR("NotValidBefore"))) {
		allowed = ((options & kSecTrustOptionAllowExpired) != 0);
	}
	else if (CFEqual(keystr, CFSTR("ValidLeaf"))) {
		allowed = ((options & kSecTrustOptionAllowExpired) != 0);
	}
	else if (CFEqual(keystr, CFSTR("ValidIntermediates"))) {
		allowed = ((options & kSecTrustOptionAllowExpired) != 0);
	}
	else if (CFEqual(keystr, CFSTR("ValidRoot"))) {
        if (((options & kSecTrustOptionAllowExpired) != 0) ||
            ((options & kSecTrustOptionAllowExpiredRoot) != 0)) {
            allowed = true;
        }
	}
	else if (CFEqual(keystr, CFSTR("AnchorTrusted"))) {
		bool implicitAnchors = ((options & kSecTrustOptionImplicitAnchors) != 0);
		// Implicit anchors option only filters exceptions for self-signed certs
		if (implicitAnchors && ctx->trustRef &&
		    (ctx->certIX < SecTrustGetCertificateCount(ctx->trustRef))) {
			Boolean isSelfSigned = false;
			SecCertificateRef cert = SecTrustGetCertificateAtIndex(ctx->trustRef, ctx->certIX);
			if (cert && (errSecSuccess == SecCertificateIsSelfSigned(cert, &isSelfSigned)) &&
			    isSelfSigned) {
				allowed = true;
			}
		}
	}
	else if (CFEqual(keystr, CFSTR("KeyUsage")) ||
	         CFEqual(keystr, CFSTR("ExtendedKeyUsage")) ||
	         CFEqual(keystr, CFSTR("BasicConstraints")) ||
	         CFEqual(keystr, CFSTR("NonEmptySubject")) ||
	         CFEqual(keystr, CFSTR("IdLinkage"))) {
		// Cannot override these exceptions
		allowed = false;
	}
	else {
		// Unhandled exceptions should not be overridden,
		// but we want to know which ones we're missing
		char *cstr = CFStringToCString(keystr);
		syslog(LOG_ERR, "Unfiltered exception: %s", (cstr) ? cstr : "<NULL>");
		if (cstr) { free(cstr); }
		allowed = false;
	}

	if (allowed) {
		CFDictionaryAddValue(filteredException, key, value);
	}
}
Ejemplo n.º 10
0
__private_extern__
int
__SCDynamicStoreRemoveValue(SCDynamicStoreRef store, CFStringRef key, Boolean internal)
{
	CFDictionaryRef			dict;
	CFMutableDictionaryRef		newDict;
	SCDynamicStorePrivateRef	storePrivate	= (SCDynamicStorePrivateRef)store;
	int				sc_status	= kSCStatusOK;
	CFStringRef			sessionKey;

	SC_trace(_configd_trace, "%s : %5d : %@\n",
		 internal ? "*remove" : "remove ",
		 storePrivate->server,
		 key);

	/*
	 * Ensure that this key exists.
	 */
	dict = CFDictionaryGetValue(storeData, key);
	if ((dict == NULL) || (CFDictionaryContainsKey(dict, kSCDData) == FALSE)) {
		/* key doesn't exist (or data never defined) */
		sc_status = kSCStatusNoKey;
		goto done;
	}
	newDict = CFDictionaryCreateMutableCopy(NULL, 0, dict);

	/*
	 * Mark this key as "changed". Any "watchers" will be
	 * notified as soon as the lock is released.
	 */
	CFSetAddValue(changedKeys, key);

	/*
	 * Add this key to a deferred cleanup list so that, after
	 * the change notifications are posted, any associated
	 * regex keys can be removed.
	 */
	CFSetAddValue(deferredRemovals, key);

	/*
	 * Check if this is a session key and, if so, add it
	 * to the (session) removal list
	 */
	sessionKey = CFDictionaryGetValue(newDict, kSCDSession);
	if (sessionKey) {
		CFStringRef	removedKey;

		/* We are no longer a session key! */
		CFDictionaryRemoveValue(newDict, kSCDSession);

		/* add this session key to the (session) removal list */
		removedKey = CFStringCreateWithFormat(NULL, 0, CFSTR("%@:%@"), sessionKey, key);
		CFSetAddValue(removedSessionKeys, removedKey);
		CFRelease(removedKey);
	}

	/*
	 * Remove data and update/remove the dictionary store entry.
	 */
	CFDictionaryRemoveValue(newDict, kSCDData);
	if (CFDictionaryGetCount(newDict) > 0) {
		/* this key is still being "watched" */
		CFDictionarySetValue(storeData, key, newDict);
	} else {
		/* no information left, remove the empty dictionary */
		CFDictionaryRemoveValue(storeData, key);
	}
	CFRelease(newDict);

	if (!internal) {
		/* push changes */
		__SCDynamicStorePush();
	}

    done:

	return sc_status;
}
Ejemplo n.º 11
0
/*************************************************************************
 *
 * hu_AddDeviceElementToUsageXML( inDevice, inElement )
 *
 * Purpose: add a device and it's elements to our usage( XML ) file
 *
 * Inputs: inDevice		- the device
 *			inElement	- the element
 *
 * Returns: Boolean		- if successful
 */
static Boolean hu_AddDeviceElementToUsageXML(IOHIDDeviceRef inIOHIDDeviceRef, IOHIDElementRef inIOHIDElementRef) {
	Boolean results = FALSE;
	if ( gUsageCFPropertyListRef ) {
		CFRelease(gUsageCFPropertyListRef);
	}
	
	gUsageCFPropertyListRef =
	hu_XMLLoad(                                 CFSTR(
													  "HID_device_usage_strings"), CFSTR("plist") );
	if ( gUsageCFPropertyListRef ) {
		CFMutableDictionaryRef tCFMutableDictionaryRef =
		CFDictionaryCreateMutableCopy(
									  kCFAllocatorDefault,
									  0,
									  gUsageCFPropertyListRef);
		if ( tCFMutableDictionaryRef ) {
			CFMutableDictionaryRef vendorCFMutableDictionaryRef;
			
			CFMutableDictionaryRef productCFMutableDictionaryRef;
			CFStringRef productKeyCFStringRef;
			
			CFStringRef usageKeyCFStringRef;
			
			// if the vendor dictionary exists...
			long vendorID = IOHIDDevice_GetVendorID(inIOHIDDeviceRef);
			CFStringRef vendorKeyCFStringRef = CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR("%ld"), vendorID);
			if ( vendorKeyCFStringRef ) {
				if ( CFDictionaryGetValueIfPresent(tCFMutableDictionaryRef, vendorKeyCFStringRef,
				                                   (const void **) &vendorCFMutableDictionaryRef) )
				{
					// ...copy it...
					vendorCFMutableDictionaryRef = CFDictionaryCreateMutableCopy(kCFAllocatorDefault,
					                                                             0,
					                                                             vendorCFMutableDictionaryRef);
				} else {        // ...otherwise...
					// ...create it.
					vendorCFMutableDictionaryRef = CFDictionaryCreateMutable(kCFAllocatorDefault,
					                                                         0,
					                                                         &kCFTypeDictionaryKeyCallBacks,
					                                                         &kCFTypeDictionaryValueCallBacks);
					results = TRUE;
				}
				// if the vendor name key doesn't exist...
				if ( !CFDictionaryContainsKey(vendorCFMutableDictionaryRef, kNameKeyCFStringRef) ) {
					CFStringRef manCFStringRef = IOHIDDevice_GetManufacturer(inIOHIDDeviceRef);
					// ...create it.
					CFDictionaryAddValue(vendorCFMutableDictionaryRef, kNameKeyCFStringRef, manCFStringRef);
					results = TRUE;
				}
				
				// if the product key exists in the vendor dictionary...
				long productID = IOHIDDevice_GetProductID(inIOHIDDeviceRef);
				productKeyCFStringRef = CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR("%ld"), productID);
				if ( CFDictionaryGetValueIfPresent(vendorCFMutableDictionaryRef, productKeyCFStringRef,
				                                   (const void **) &productCFMutableDictionaryRef) )
				{
					// ...copy it...
					productCFMutableDictionaryRef = CFDictionaryCreateMutableCopy(kCFAllocatorDefault,
					                                                              0,
					                                                              productCFMutableDictionaryRef);
				} else {        // ...otherwise...
					// ...create it.
					productCFMutableDictionaryRef = CFDictionaryCreateMutable(kCFAllocatorDefault,
					                                                          0,
					                                                          &kCFTypeDictionaryKeyCallBacks,
					                                                          &kCFTypeDictionaryValueCallBacks);
					results = TRUE;
				}
				// if the product name key doesn't exist...
				if ( !CFDictionaryContainsKey(productCFMutableDictionaryRef, kNameKeyCFStringRef) ) {
					CFStringRef productCFStringRef = IOHIDDevice_GetProduct(inIOHIDDeviceRef);
					// ...create it.
					CFDictionaryAddValue(productCFMutableDictionaryRef, kNameKeyCFStringRef, productCFStringRef);
					results = TRUE;
				}
				
				// if the usage key doesn't exist in the product dictionary...
				uint32_t usagePage =  IOHIDElementGetUsagePage(inIOHIDElementRef);
				uint32_t usage =      IOHIDElementGetUsagePage(inIOHIDElementRef);
				usageKeyCFStringRef = CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR("%ld:%ld"), usagePage, usage);
				if ( usageKeyCFStringRef ) {
					if ( !CFDictionaryContainsKey(productCFMutableDictionaryRef, usageKeyCFStringRef) ) {
						// find it's generic name
						CFStringRef usageCFStringRef = HIDCopyUsageName(usagePage, usage);
						if ( usageCFStringRef ) {
							// and add that.
							CFDictionaryAddValue(productCFMutableDictionaryRef, usageKeyCFStringRef, usageCFStringRef);
							results = TRUE;
							CFRelease(usageCFStringRef);
						}
					}
					
					CFRelease(usageKeyCFStringRef);
				}
				if ( vendorCFMutableDictionaryRef ) {
					if ( productCFMutableDictionaryRef ) {
						if ( results ) {
							CFDictionarySetValue(vendorCFMutableDictionaryRef, productKeyCFStringRef, productCFMutableDictionaryRef);
						}
						
						CFRelease(productCFMutableDictionaryRef);
					}
					if ( results ) {
						CFDictionarySetValue(tCFMutableDictionaryRef, vendorKeyCFStringRef, vendorCFMutableDictionaryRef);
					}
					
					CFRelease(vendorCFMutableDictionaryRef);
				}
				
				CFRelease(vendorKeyCFStringRef);
			}
			if ( productKeyCFStringRef ) {
				CFRelease(productKeyCFStringRef);
			}
			if ( results ) {
				hu_XMLSave( tCFMutableDictionaryRef,
						   CFSTR(
								 "HID_device_usage_strings"), CFSTR("plist") );
			}
			
			CFRelease(
					  tCFMutableDictionaryRef);
		}
	}
	
	return (results);
}   // hu_AddDeviceElementToUsageXML
Ejemplo n.º 12
0
void RunAppOnDeviceWithIdentifier(char *udid, char *identifier, bool waitForDebugger)
{
	SDMMD_AMDeviceRef device = FindDeviceFromUDID(udid);
	if (device) {
		sdmmd_return_t result = SDMMD_AMDeviceConnect(device);
		if (SDM_MD_CallSuccessful(result)) {
			result = SDMMD_AMDeviceStartSession(device);
			if (SDM_MD_CallSuccessful(result)) {
				CFDictionaryRef response;
				CFArrayRef lookupValues = SDMMD_ApplicationLookupDictionary();
				CFMutableDictionaryRef optionsDict = SDMMD_create_dict();
				CFDictionarySetValue(optionsDict, CFSTR("ReturnAttributes"), lookupValues);

				result = SDMMD_AMDeviceLookupApplications(device, optionsDict, &response);
				if (SDM_MD_CallSuccessful(result)) {
					CFStringRef bundleIdentifier = CFStringCreateWithCString(kCFAllocatorDefault, identifier, kCFStringEncodingUTF8);
					CFDictionaryRef details = NULL;
					if (CFDictionaryContainsKey(response, bundleIdentifier)) {
						details = CFDictionaryGetValue(response, bundleIdentifier);
					}
					CFSafeRelease(bundleIdentifier);
					if (details) {
						SDMMD_AMDeviceStopSession(device);
						SDMMD_AMDeviceDisconnect(device);
						SDMMD_AMDebugConnectionRef dconn = SDMMD_AMDebugConnectionCreateForDevice(device);
						sdmmd_return_t result = SDMMD_AMDebugConnectionStart(dconn);
						bool launchSuccess = false;
						if (SDM_MD_CallSuccessful(result)) {

							// setting max packet size
							CFMutableArrayRef maxPacketArgs = CFArrayCreateMutable(kCFAllocatorDefault, 0x0, &kCFTypeArrayCallBacks);
							CFArrayAppendValue(maxPacketArgs, CFSTR("1024"));
							DebuggerCommandRef maxPacket = SDMMD_CreateDebuggingCommand(kDebugQSetMaxPacketSize, NULL, maxPacketArgs);
							CFSafeRelease(maxPacketArgs);

							CFDataRef maxPacketResponse = NULL;
							result = SDMMD_DebuggingSend(dconn, maxPacket, &maxPacketResponse);
							CFSafeRelease(maxPacketResponse);
							SDMMD_DebuggingCommandRelease(maxPacket);

							// setting the working directory
							CFStringRef path = CFDictionaryGetValue(details, CFSTR("Path"));
							CFStringRef container = CFDictionaryGetValue(details, CFSTR("Container"));
							if (!container) {
								CFURLRef pathURL = CFURLCreateWithString(kCFAllocatorDefault, path, NULL);
								CFURLRef containerURL = CFURLCreateCopyDeletingLastPathComponent(kCFAllocatorDefault, pathURL);
								container = CFURLGetString(containerURL);
								CFSafeRelease(pathURL);
							}
							CFMutableArrayRef containerPathArgs = CFArrayCreateMutable(kCFAllocatorDefault, 0x0, &kCFTypeArrayCallBacks);
							CFArrayAppendValue(containerPathArgs, container);
							DebuggerCommandRef containerPath = SDMMD_CreateDebuggingCommand(kDebugQSetWorkingDir, NULL, containerPathArgs);
							CFSafeRelease(containerPathArgs);

							CFDataRef containerPathResponse = NULL;
							result = SDMMD_DebuggingSend(dconn, containerPath, &containerPathResponse);
							CFSafeRelease(containerPathResponse);
							SDMMD_DebuggingCommandRelease(containerPath);

							// setting launch args
							CFStringRef commandFormat = CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR("A%d,0,"), (uint32_t)CFStringGetLength(path) * 0x2);

							CFMutableArrayRef setLaunchArgsArgs = CFArrayCreateMutable(kCFAllocatorDefault, 0x0, &kCFTypeArrayCallBacks);
							CFArrayAppendValue(setLaunchArgsArgs, path);
							DebuggerCommandRef setLaunchArgs = SDMMD_CreateDebuggingCommand(kDebugCUSTOMCOMMAND, commandFormat, setLaunchArgsArgs);
							CFSafeRelease(setLaunchArgsArgs);
							CFSafeRelease(commandFormat);

							CFDataRef setLaunchArgsResponse = NULL;
							result = SDMMD_DebuggingSend(dconn, setLaunchArgs, &setLaunchArgsResponse);
							CFSafeRelease(setLaunchArgsResponse);
							SDMMD_DebuggingCommandRelease(setLaunchArgs);

							// Check for launch success
							CFMutableArrayRef launchSuccessArgs = CFArrayCreateMutable(kCFAllocatorDefault, 0x0, &kCFTypeArrayCallBacks);
							DebuggerCommandRef launchSuccessCommand = SDMMD_CreateDebuggingCommand(kDebugqLaunchSuccess, NULL, launchSuccessArgs);
							CFSafeRelease(launchSuccessArgs);

							CFDataRef launchSuccessResponse = NULL;
							result = SDMMD_DebuggingSend(dconn, launchSuccessCommand, &launchSuccessResponse);

							if (launchSuccessResponse) {
								char *launchSuccessResponseAsString = (char *)CFDataGetBytePtr(launchSuccessResponse);
								launchSuccess = !strncmp(launchSuccessResponseAsString, "OK", 2);

								if (!launchSuccess) {
									printf("Launch failure: %s\n", launchSuccessResponseAsString);
								}
							}

							CFSafeRelease(launchSuccessResponse);
							SDMMD_DebuggingCommandRelease(launchSuccessCommand);

							if (launchSuccess) {
								printf("Launch success\n");

								if (!waitForDebugger) {
									printf("Continuing with execution...\n");

									// setting thread to attach
									CFMutableArrayRef setThreadArgs = CFArrayCreateMutable(kCFAllocatorDefault, 0x0, &kCFTypeArrayCallBacks);
									CFArrayAppendValue(setThreadArgs, CFSTR(""));
									DebuggerCommandRef setThread = SDMMD_CreateDebuggingCommand(kDebugCUSTOMCOMMAND, CFSTR("Hc0"), setThreadArgs);
									CFSafeRelease(setThreadArgs);

									CFDataRef setThreadResponse = NULL;
									result = SDMMD_DebuggingSend(dconn, setThread, &setThreadResponse);
									CFSafeRelease(setThreadResponse);
									SDMMD_DebuggingCommandRelease(setThread);

									// setting continue with execution
									CFMutableArrayRef contArgs = CFArrayCreateMutable(kCFAllocatorDefault, 0x0, &kCFTypeArrayCallBacks);
									CFArrayAppendValue(contArgs, CFSTR(""));
									DebuggerCommandRef cont = SDMMD_CreateDebuggingCommand(kDebugc, NULL, contArgs);
									CFSafeRelease(contArgs);

									CFDataRef contResponse = NULL;
									result = SDMMD_DebuggingSend(dconn, cont, &contResponse);
									CFSafeRelease(contResponse);
									SDMMD_DebuggingCommandRelease(cont);
								}
								else {
									printf("Waiting for debugger to attach...\n");

									CFRunLoopRun();
								}
							}
						}
						/*
						sdmmd_return_t result = SDMMD_StartDebuggingSessionOnDevice(device, &connection);
						if (SDM_MD_CallSuccessful(result)) {
							bool launchSuccess = false;
							CFStringRef path = CFDictionaryGetValue(details, CFSTR("Path"));
							CFStringRef encodedPath = SDMMD_EncodeDebuggingString(path);
							CFStringRef container = CFDictionaryGetValue(details, CFSTR("Container"));
							if (!container) {
								CFURLRef pathURL = CFURLCreateWithString(kCFAllocatorDefault, path, NULL);
								CFURLRef containerURL = CFURLCreateCopyDeletingLastPathComponent(kCFAllocatorDefault, pathURL);
								container = CFURLGetString(containerURL);
								CFSafeRelease(pathURL);
								//CFSafeRelease(containerURL);
							}
							if (container) {
								CFStringRef containerPath = SDMMD_EncodeDebuggingString(container);
								sdmmd_debug_return_t dresult;
								CFStringRef maxPacket = SDMMD_EncodeDebuggingString(CFSTR("1024"));
								dresult = SDMMD_DebuggingSend(connection, KnownDebugCommands[kDebugQSetMaxPacketSize], maxPacket);
								CFSafeRelease(maxPacket);
								dresult = SDMMD_DebuggingSend(connection, KnownDebugCommands[kDebugQSetWorkingDir], containerPath);
								CFSafeRelease(containerPath);
								CFStringRef commandFormat = CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR("%d,0,%s"), (uint32_t)CFStringGetLength(encodedPath), CFStringGetCStringPtr(encodedPath, kCFStringEncodingUTF8));
								dresult = SDMMD_DebuggingSend(connection, KnownDebugCommands[kDebugA], commandFormat);
								CFSafeRelease(commandFormat);
								dresult = SDMMD_DebuggingSend(connection, KnownDebugCommands[kDebugH], CFSTR("c0"));
								dresult = SDMMD_DebuggingSend(connection, KnownDebugCommands[kDebugc], CFSTR(""));
								launchSuccess = true;
							}
							CFSafeRelease(encodedPath);
							if (launchSuccess) {
								CFRunLoopRun();
							}
						}
						*/
					}
				}
			}
		}
	}
}
Ejemplo n.º 13
0
static boolean_t
updateConfiguration(int *newState)
{
	boolean_t		changed			= FALSE;
	CFStringRef		computerName;
	CFStringEncoding	computerNameEncoding;
	CFArrayRef		configuredServices	= NULL;
	CFDictionaryRef		dict;
	CFIndex			i;
	CFIndex			ifCount			= 0;
	CFMutableArrayRef	info			= NULL;
	CFArrayRef		interfaces		= NULL;
	CFStringRef		key;
	CFArrayRef		keys;
	CFIndex			n;
	CFMutableArrayRef	newConfigFile;
	CFMutableDictionaryRef	newDefaults;
	CFMutableDictionaryRef	newDict;
	CFMutableDictionaryRef	newGlobals;
	CFMutableDictionaryRef	newGlobalsX;			/* newGlobals without ServiceID */
	CFMutableDictionaryRef	newStartup;
	CFMutableDictionaryRef	newZones;
	CFNumberRef		num;
	CFMutableDictionaryRef	curGlobalsX;			/* curGlobals without ServiceID */
	CFStringRef		pattern;
	boolean_t		postGlobals		= FALSE;
	CFStringRef		primaryPort		= NULL;	/* primary interface */
	CFStringRef		primaryZone		= NULL;
	CFArrayRef		serviceOrder		= NULL;
	CFDictionaryRef		setGlobals		= NULL;

	cache_open();

	/*
	 * establish the "new" AppleTalk configuration
	 */
	*newState     = curState;
	newConfigFile = CFArrayCreateMutable(NULL, 0, &kCFTypeArrayCallBacks);
	newGlobals    = CFDictionaryCreateMutable(NULL,
						  0,
						  &kCFTypeDictionaryKeyCallBacks,
						  &kCFTypeDictionaryValueCallBacks);
	newDefaults   = CFDictionaryCreateMutable(NULL,
						  0,
						  &kCFTypeDictionaryKeyCallBacks,
						  &kCFTypeDictionaryValueCallBacks);
	newStartup    = CFDictionaryCreateMutable(NULL,
						  0,
						  &kCFTypeDictionaryKeyCallBacks,
						  &kCFTypeDictionaryValueCallBacks);
	newZones      = CFDictionaryCreateMutable(NULL,
						  0,
						  &kCFTypeDictionaryKeyCallBacks,
						  &kCFTypeDictionaryValueCallBacks);

	/* initialize overall state */
	CFDictionarySetValue(newStartup, CFSTR("APPLETALK"), CFSTR("-NO-"));

	/*
	 * get the global settings (ServiceOrder, ComputerName, ...)
	 */
	key = SCDynamicStoreKeyCreateNetworkGlobalEntity(NULL,
							 kSCDynamicStoreDomainSetup,
							 kSCEntNetAppleTalk);
	setGlobals = cache_SCDynamicStoreCopyValue(store, key);
	CFRelease(key);
	if (setGlobals) {
		if (isA_CFDictionary(setGlobals)) {
			/* get service order */
			serviceOrder = CFDictionaryGetValue(setGlobals,
							    kSCPropNetServiceOrder);
			serviceOrder = isA_CFArray(serviceOrder);
			if (serviceOrder) {
				CFRetain(serviceOrder);
			}
		} else {
			CFRelease(setGlobals);
			setGlobals = NULL;
		}
	}

	/*
	 * if we don't have an AppleTalk ServiceOrder, use IPv4's (if defined)
	 */
	if (!serviceOrder) {
		key = SCDynamicStoreKeyCreateNetworkGlobalEntity(NULL,
								 kSCDynamicStoreDomainSetup,
								 kSCEntNetIPv4);
		dict = cache_SCDynamicStoreCopyValue(store, key);
		CFRelease(key);
		if (dict) {
			if (isA_CFDictionary(dict)) {
				serviceOrder = CFDictionaryGetValue(dict,
								    kSCPropNetServiceOrder);
				serviceOrder = isA_CFArray(serviceOrder);
				if (serviceOrder) {
					CFRetain(serviceOrder);
				}
			}
			CFRelease(dict);
		}
	}

	/*
	 * get the list of ALL configured services
	 */
	configuredServices = entity_all(store, kSCEntNetAppleTalk, serviceOrder);
	if (configuredServices) {
		ifCount = CFArrayGetCount(configuredServices);
	}

	if (serviceOrder)	CFRelease(serviceOrder);

	/*
	 * get the list of ALL active interfaces
	 */
	key  = SCDynamicStoreKeyCreateNetworkInterface(NULL, kSCDynamicStoreDomainState);
	dict = cache_SCDynamicStoreCopyValue(store, key);
	CFRelease(key);
	if (dict) {
		if (isA_CFDictionary(dict)) {
			interfaces = CFDictionaryGetValue(dict,
							  kSCDynamicStorePropNetInterfaces);
			interfaces = isA_CFArray(interfaces);
			if (interfaces) {
				CFRetain(interfaces);
			}
		}
		CFRelease(dict);
	}

	/*
	 * get the list of previously configured services
	 */
	pattern = SCDynamicStoreKeyCreateNetworkServiceEntity(NULL,
							      kSCDynamicStoreDomainState,
							      kSCCompAnyRegex,
							      kSCEntNetAppleTalk);
	keys = SCDynamicStoreCopyKeyList(store, pattern);
	CFRelease(pattern);
	if (keys) {
		info = CFArrayCreateMutableCopy(NULL, 0, keys);
		CFRelease(keys);
	}

	/*
	 * iterate over each configured service to establish the new
	 * configuration.
	 */
	for (i = 0; i < ifCount; i++) {
		CFDictionaryRef		service;
		CFStringRef		ifName;
		CFStringRef		configMethod;
		CFMutableStringRef	portConfig	= NULL;
		CFArrayRef		networkRange;	/* for seed ports, CFArray[2] of CFNumber (lo, hi) */
		int			sNetwork;
		int			eNetwork;
		CFArrayRef		zoneList;	/* for seed ports, CFArray[] of CFString (zones names) */
		CFIndex			zCount;
		CFIndex			j;
		CFMutableDictionaryRef	ifDefaults	= NULL;
		CFNumberRef		defaultNetwork;
		CFNumberRef		defaultNode;
		CFStringRef		defaultZone;

		/* get AppleTalk service dictionary */
		service = CFArrayGetValueAtIndex(configuredServices, i);

		/* get interface name */
		ifName  = CFDictionaryGetValue(service, kSCPropNetInterfaceDeviceName);

		/* check inteface availability */
		if (!interfaces ||
		    !CFArrayContainsValue(interfaces, CFRangeMake(0, CFArrayGetCount(interfaces)), ifName)) {
			/* if interface not available */
			goto nextIF;
		}

		/* check interface link status */
		key = SCDynamicStoreKeyCreateNetworkInterfaceEntity(NULL,
								    kSCDynamicStoreDomainState,
								    ifName,
								    kSCEntNetLink);
		dict = cache_SCDynamicStoreCopyValue(store, key);
		CFRelease(key);
		if (dict) {
			Boolean	linkStatus	= TRUE;  /* assume the link is "up" */
			Boolean	ifDetaching	= FALSE; /* assume link is not detaching */

			/* the link key for this interface is available */
			if (isA_CFDictionary(dict)) {
				CFBooleanRef	bVal;

				bVal = CFDictionaryGetValue(dict, kSCPropNetLinkActive);
				if (isA_CFBoolean(bVal)) {
					linkStatus = CFBooleanGetValue(bVal);
				}

				/* check if interface is detaching - value
				   doesn't really matter, only that it exists */
				ifDetaching = CFDictionaryContainsKey(dict, kSCPropNetLinkDetaching);
			}
			CFRelease(dict);

			if (!linkStatus || ifDetaching) {
				/* if link status down or the interface is detaching */
				goto nextIF;
			}
		}

		/*
		 * Determine configuration method for this service
		 */
		configMethod = CFDictionaryGetValue(service, kSCPropNetAppleTalkConfigMethod);
		if (!isA_CFString(configMethod)) {
			/* if no ConfigMethod */
			goto nextIF;
		}

		if (!CFEqual(configMethod, kSCValNetAppleTalkConfigMethodNode      ) &&
		    !CFEqual(configMethod, kSCValNetAppleTalkConfigMethodRouter    ) &&
		    !CFEqual(configMethod, kSCValNetAppleTalkConfigMethodSeedRouter)) {
			/* if not one of the expected values, disable */
			SCLog(TRUE, LOG_NOTICE,
			      CFSTR("Unexpected AppleTalk ConfigMethod: %@"),
			      configMethod);
			goto nextIF;
		}

		/*
		 * the first service to be defined will always be "primary"
		 */
		if (CFArrayGetCount(newConfigFile) == 0) {
			CFDictionaryRef	active;

			CFDictionarySetValue(newGlobals,
					     kSCDynamicStorePropNetPrimaryService,
					     CFDictionaryGetValue(service, CFSTR("ServiceID")));
			CFDictionarySetValue(newGlobals,
					     kSCDynamicStorePropNetPrimaryInterface,
					     ifName);

			/* and check if AT newtorking is active on the primary interface */
			key = SCDynamicStoreKeyCreateNetworkInterfaceEntity(NULL,
									    kSCDynamicStoreDomainState,
									    ifName,
									    kSCEntNetAppleTalk);
			active = cache_SCDynamicStoreCopyValue(store, key);
			CFRelease(key);
			if (active) {
				if (isA_CFDictionary(active)) {
					postGlobals = TRUE;
				}
				CFRelease(active);
			}
		}

		/*
		 * define the port
		 */
		portConfig = CFStringCreateMutable(NULL, 0);
		CFStringAppendFormat(portConfig, NULL, CFSTR("%@:"), ifName);

		if (CFEqual(configMethod, kSCValNetAppleTalkConfigMethodSeedRouter)) {
			CFNumberRef	num;

			/*
			 * we have been asked to configure this interface as a
			 * seed port. Ensure that we have been provided at least
			 * one network number, have been provided with at least
			 * one zonename, ...
			 */

			networkRange = CFDictionaryGetValue(service,
							    kSCPropNetAppleTalkSeedNetworkRange);
			if (!isA_CFArray(networkRange) || (CFArrayGetCount(networkRange) == 0)) {
				SCLog(TRUE, LOG_NOTICE,
				      CFSTR("AppleTalk configuration error (%@)"),
				      kSCPropNetAppleTalkSeedNetworkRange);
				goto nextIF;
			}

			/*
			 * establish the starting and ending network numbers
			 */
			num = CFArrayGetValueAtIndex(networkRange, 0);
			if (!isA_CFNumber(num)) {
				SCLog(TRUE, LOG_NOTICE,
				      CFSTR("AppleTalk configuration error (%@)"),
				      kSCPropNetAppleTalkSeedNetworkRange);
				goto nextIF;
			}
			CFNumberGetValue(num, kCFNumberIntType, &sNetwork);
			eNetwork = sNetwork;

			if (CFArrayGetCount(networkRange) > 1) {
				num = CFArrayGetValueAtIndex(networkRange, 1);
				if (!isA_CFNumber(num)) {
					SCLog(TRUE, LOG_NOTICE,
					      CFSTR("AppleTalk configuration error (%@)"),
					      kSCPropNetAppleTalkSeedNetworkRange);
					goto nextIF;
				}
				CFNumberGetValue(num, kCFNumberIntType, &eNetwork);
			}
			CFStringAppendFormat(portConfig, NULL, CFSTR("%d:%d:"), sNetwork, eNetwork);

			/*
			 * establish the zones associated with this port
			 */
			zoneList = CFDictionaryGetValue(service,
							kSCPropNetAppleTalkSeedZones);
			if (!isA_CFArray(zoneList)) {
				SCLog(TRUE, LOG_NOTICE,
				      CFSTR("AppleTalk configuration error (%@)"),
				      kSCPropNetAppleTalkSeedZones);
				goto nextIF;
			}

			zCount = CFArrayGetCount(zoneList);
			for (j = 0; j < zCount; j++) {
				CFStringRef		zone;
				CFArrayRef		ifList;
				CFMutableArrayRef	newIFList;

				zone = CFArrayGetValueAtIndex(zoneList, j);
				if (!isA_CFString(zone)) {
					continue;
				}

				if (CFDictionaryGetValueIfPresent(newZones, zone, (const void **)&ifList)) {
					/* known zone */
					newIFList = CFArrayCreateMutableCopy(NULL, 0, ifList);
				} else {
					/* new zone */
					newIFList = CFArrayCreateMutable(NULL, 0, &kCFTypeArrayCallBacks);
				}
				CFArrayAppendValue(newIFList, ifName);
				CFArraySortValues(newIFList,
						  CFRangeMake(0, CFArrayGetCount(newIFList)),
						  (CFComparatorFunction)CFStringCompare,
						  NULL);
				CFDictionarySetValue(newZones, zone, newIFList);
				CFRelease(newIFList);

				/*
				 * flag the default zone
				 */
				if (!primaryZone) {
					primaryZone = CFRetain(zone);
				}
			}
			if (!primaryZone) {
				SCLog(TRUE, LOG_NOTICE,
				      CFSTR("AppleTalk configuration error (%@)"),
				      kSCPropNetAppleTalkSeedZones);
				goto nextIF;
			}
		}

		/* get the (per-interface) "Computer Name" */
		computerName = CFDictionaryGetValue(service,
						    kSCPropNetAppleTalkComputerName);
		if (CFDictionaryGetValueIfPresent(service,
						  kSCPropNetAppleTalkComputerNameEncoding,
						  (const void **)&num) &&
		    isA_CFNumber(num)) {
			CFNumberGetValue(num, kCFNumberIntType, &computerNameEncoding);
		} else {
			computerNameEncoding = CFStringGetSystemEncoding();
		}
		encodeName(computerName, computerNameEncoding, newStartup, newGlobals);

		/*
		 * declare the first configured AppleTalk service / interface
		 * as the "home port".
		 */
		if (CFArrayGetCount(newConfigFile) == 0) {
			CFStringAppend(portConfig, CFSTR("*"));
			primaryPort = CFRetain(ifName);
		}
		CFArrayAppendValue(newConfigFile, portConfig);

		/*
		 * get the per-interface defaults
		 */
		ifDefaults = CFDictionaryCreateMutable(NULL,
						       0,
						       &kCFTypeDictionaryKeyCallBacks,
						       &kCFTypeDictionaryValueCallBacks);

		defaultNetwork = CFDictionaryGetValue(service, kSCPropNetAppleTalkNetworkID);
		defaultNode    = CFDictionaryGetValue(service, kSCPropNetAppleTalkNodeID);
		if (isA_CFNumber(defaultNetwork) && isA_CFNumber(defaultNode)) {
			/*
			 * set the default node and network
			 */
			CFDictionarySetValue(ifDefaults,
					     kSCPropNetAppleTalkNetworkID,
					     defaultNetwork);
			CFDictionarySetValue(ifDefaults,
					     kSCPropNetAppleTalkNodeID,
					     defaultNode);
		}

		if ((CFDictionaryGetValueIfPresent(service,
						   kSCPropNetAppleTalkDefaultZone,
						   (const void **)&defaultZone) == TRUE)) {
			/*
			 * set the default zone for this interface
			 */
			CFDictionarySetValue(ifDefaults,
					     kSCPropNetAppleTalkDefaultZone,
					     defaultZone);
		}

		CFDictionarySetValue(newDefaults, ifName, ifDefaults);
		CFRelease(ifDefaults);

		switch (CFArrayGetCount(newConfigFile)) {
			case 1:
				/*
				 * first AppleTalk interface
				 */
				CFDictionarySetValue(newStartup, CFSTR("APPLETALK"), ifName);
				break;
			case 2:
				/* second AppleTalk interface */
				if (!CFEqual(CFDictionaryGetValue(newStartup, CFSTR("APPLETALK")),
					     CFSTR("-ROUTER-"))) {
					/*
					 * if not routing (yet), configure as multi-home
					 */
					CFDictionarySetValue(newStartup, CFSTR("APPLETALK"), CFSTR("-MULTIHOME-"));
				}
				break;
		}

		if (CFEqual(configMethod, kSCValNetAppleTalkConfigMethodRouter) ||
		    CFEqual(configMethod, kSCValNetAppleTalkConfigMethodSeedRouter)) {
			/* if not a simple node, enable routing */
			CFDictionarySetValue(newStartup, CFSTR("APPLETALK"), CFSTR("-ROUTER-"));
		}

		/*
		 * establish the State:/Network/Service/nnn/AppleTalk key info
		 */
		key = SCDynamicStoreKeyCreateNetworkServiceEntity(NULL,
								  kSCDynamicStoreDomainState,
								  CFDictionaryGetValue(service, CFSTR("ServiceID")),
								  kSCEntNetAppleTalk);
		newDict = CFDictionaryCreateMutable(NULL,
						    0,
						    &kCFTypeDictionaryKeyCallBacks,
						    &kCFTypeDictionaryValueCallBacks);
		CFDictionaryAddValue(newDict, kSCPropInterfaceName, ifName);
		cache_SCDynamicStoreSetValue(store, key, newDict);
		CFRelease(newDict);
		if (info) {
			j = CFArrayGetFirstIndexOfValue(info,
							CFRangeMake(0, CFArrayGetCount(info)),
							key);
			if (j != kCFNotFound) {
				CFArrayRemoveValueAtIndex(info, j);
			}
		}
		CFRelease(key);

	    nextIF :

		if (portConfig)	CFRelease(portConfig);
	}

	if (primaryZone) {
		CFArrayRef		ifList;
		CFMutableArrayRef	newIFList;

		ifList = CFDictionaryGetValue(newZones, primaryZone);
		if (CFArrayContainsValue(ifList,
					 CFRangeMake(0, CFArrayGetCount(ifList)),
					 primaryPort)) {
			newIFList = CFArrayCreateMutableCopy(NULL, 0, ifList);
			CFArrayAppendValue(newIFList, CFSTR("*"));
			CFDictionarySetValue(newZones, primaryZone, newIFList);
			CFRelease(newIFList);
		}
		CFRelease(primaryZone);
	}
	if (primaryPort) {
		CFRelease(primaryPort);
	}

	/* sort the ports */
	i = CFArrayGetCount(newConfigFile);
	CFArraySortValues(newConfigFile,
			  CFRangeMake(0, i),
			  (CFComparatorFunction)CFStringCompare,
			  NULL);

	/* add the zones to the configuration */
	CFDictionaryApplyFunction(newZones, addZoneToPorts, newConfigFile);
	CFRelease(newZones);

	/* sort the zones */
	CFArraySortValues(newConfigFile,
			  CFRangeMake(i, CFArrayGetCount(newConfigFile)-i),
			  (CFComparatorFunction)CFStringCompare,
			  NULL);

	/* ensure that the last line of the configuration file is terminated */
	CFArrayAppendValue(newConfigFile, CFSTR(""));

	/*
	 * Check if we have a "ComputerName" and look elsewhere if we don't have
	 * one yet.
	 */
	if (!CFDictionaryContainsKey(newStartup, CFSTR("APPLETALK_HOSTNAME")) &&
	    (setGlobals != NULL)) {
		computerName = CFDictionaryGetValue(setGlobals,
						    kSCPropNetAppleTalkComputerName);
		if (CFDictionaryGetValueIfPresent(setGlobals,
						  kSCPropNetAppleTalkComputerNameEncoding,
						  (const void **)&num) &&
		    isA_CFNumber(num)) {
			CFNumberGetValue(num, kCFNumberIntType, &computerNameEncoding);
		} else {
			computerNameEncoding = CFStringGetSystemEncoding();
		}
		encodeName(computerName, computerNameEncoding, newStartup, newGlobals);
	}
	if (!CFDictionaryContainsKey(newStartup, CFSTR("APPLETALK_HOSTNAME"))) {
		computerName = SCDynamicStoreCopyComputerName(store, &computerNameEncoding);
		if (computerName) {
			encodeName(computerName, computerNameEncoding, newStartup, newGlobals);
			CFRelease(computerName);
		}
	}
	if (!CFDictionaryContainsKey(newStartup, CFSTR("APPLETALK_HOSTNAME"))) {
		struct utsname	name;

		if (uname(&name) == 0) {
			computerName = CFStringCreateWithCString(NULL, name.nodename, kCFStringEncodingASCII);
			if (computerName) {
				encodeName(computerName, kCFStringEncodingASCII, NULL, newGlobals);
				CFRelease(computerName);
			}
		}
	}

	/* compare the previous and current configurations */

	curGlobalsX = CFDictionaryCreateMutableCopy(NULL, 0, curGlobals);
	CFDictionaryRemoveValue(curGlobalsX, kSCDynamicStorePropNetPrimaryService);

	newGlobalsX = CFDictionaryCreateMutableCopy(NULL, 0, newGlobals);
	CFDictionaryRemoveValue(newGlobalsX, kSCDynamicStorePropNetPrimaryService);

	key = SCDynamicStoreKeyCreateNetworkGlobalEntity(NULL,
							 kSCDynamicStoreDomainState,
							 kSCEntNetAppleTalk);

	if (CFEqual(curGlobalsX   , newGlobalsX   ) &&
	    CFEqual(curConfigFile , newConfigFile) &&
	    CFEqual(curDefaults   , newDefaults  ) &&
	    CFEqual(curStartup    , newStartup   )
	    ) {
		/*
		 * the configuration has not changed.
		 */

		if (postGlobals) {
			/*
			 * the requested configuration hasn't changed but we
			 * now need to tell everyone that AppleTalk is active.
			 */
			if (!SCDynamicStoreSetValue(store, key, newGlobals)) {
				SCLog(TRUE,
				      LOG_ERR,
				      CFSTR("SCDynamicStoreSetValue() failed: %s"),
				      SCErrorString(SCError()));
			}
		}

		CFRelease(newGlobals);
		CFRelease(newConfigFile);
		CFRelease(newDefaults);
		CFRelease(newStartup);
	} else if (CFArrayGetCount(newConfigFile) <= 1) {
		/*
		 * the configuration has changed but there are no
		 * longer any interfaces configured for AppleTalk
		 * networking.
		 */

		/*
		 * remove the global (State:/Network/Global/AppleTalk) key.
		 *
		 * Note: it will be restored later after AT networking has
		 *       been activated.
		 */

		/* remove the (/etc/appletalk.cfg) configuration file */
		(void)unlink(AT_CFG_FILE);

		/*
		 * update the per-service (and global) state
		 */
		cache_SCDynamicStoreRemoveValue(store, key);	// remove State:/Network/Global/AppleTalk
		n = CFArrayGetCount(info);
		for (i = 0; i < n; i++) {
			CFStringRef	xKey	= CFArrayGetValueAtIndex(info, i);

			cache_SCDynamicStoreRemoveValue(store, xKey);
		}
		cache_write(store);

		/* flag this as a new configuration */
		*newState = -(abs(curState) + 1);
		changed = TRUE;
	} else {
		/*
		 * the configuration has changed.
		 */

		/* update the (/etc/appletalk.cfg) configuration file */
		configWrite(AT_CFG_FILE, newConfigFile);

		/*
		 * update the per-service (and global) state
		 *
		 * Note: if present, we remove any existing global state key and allow it
		 *       to be restored after the stack has been re-started.
		 */
		CFDictionaryApplyFunction(newDefaults, updateDefaults, NULL);
		cache_SCDynamicStoreRemoveValue(store, key);	// remove State:/Network/Global/AppleTalk
		n = CFArrayGetCount(info);
		for (i = 0; i < n; i++) {
			CFStringRef	xKey	= CFArrayGetValueAtIndex(info, i);

			cache_SCDynamicStoreRemoveValue(store, xKey);
		}
		cache_write(store);

		/* flag this as a new configuration */
		*newState = abs(curState) + 1;
		changed = TRUE;
	}

	CFRelease(curGlobalsX);
	CFRelease(newGlobalsX);
	CFRelease(key);

	if (changed) {
		CFRelease(curGlobals);
		curGlobals    = newGlobals;
		CFRelease(curConfigFile);
		curConfigFile = newConfigFile;
		CFRelease(curDefaults);
		curDefaults   = newDefaults;
		CFRelease(curStartup);
		curStartup    = newStartup;
	}

	if (info)		CFRelease(info);
	if (interfaces)		CFRelease(interfaces);
	if (configuredServices)	CFRelease(configuredServices);
	if (setGlobals)		CFRelease(setGlobals);

	cache_close();

	return changed;
}
Ejemplo n.º 14
0
//////
//
// DBPluginLoadPlugins
//  returns -1 if the plugin dictionary cannot be
//   created, otherwise returns 0
//
/////
int DBPluginLoadPlugins(const char* plugin_path) {
    if (plugins == NULL) {
        plugins = CFDictionaryCreateMutable(NULL, 0, &kCFTypeDictionaryKeyCallBacks, &cfDictionaryPluginValueCallBacks);
    }
    if (plugins == NULL) return -1;

    //
    // If the path contains colons, split the path and
    // search each path component.  If there are no
    // colons, CFStringCreateArrayBySeparatingStrings()
    // will return an array with one element being the
    // entire path.
    //
    CFStringRef str = cfstr(plugin_path);
    CFArrayRef array = CFStringCreateArrayBySeparatingStrings(NULL, str, CFSTR(":"));
    CFRelease(str);
    CFIndex i, path_argc = CFArrayGetCount(array);
    char** path_argv = malloc(sizeof(char*)*(path_argc+1));
    for (i = 0; i < path_argc; ++i) {
        path_argv[i] = strdup_cfstr(CFArrayGetValueAtIndex(array, i));
    }
    path_argv[i] = NULL;
    CFRelease(array);

    //
    // Search the directories for plugins
    //
    FTSENT* ent;
    FTS* dir = fts_open((char * const *)path_argv, FTS_LOGICAL, NULL);
    while ((ent = fts_read(dir)) != NULL) {
        DBPlugin* plugin = NULL;
        if (strstr(ent->fts_name, ".so")) {
            //fprintf(stderr, "plugin: loading %s\n", ent->fts_accpath);
            void* handle = dlopen(ent->fts_accpath, RTLD_LAZY | RTLD_LOCAL);
            if (handle) {
                DBPluginInitializeFunc func = dlsym(handle, "initialize");
                if (!func) {
                    fprintf(stderr, "plugin: cannot find initialize for: %s\n%s\n", ent->fts_accpath, dlerror());
                    return -1;
                }
                plugin = _DBPluginInitialize();
                if (!plugin) {
                    fprintf(stderr, "plugin: failed to initialize %s\n", ent->fts_accpath);
                    return -1;
                }
                _DBPluginSetCurrentPlugin(plugin);
                (*func)(kDBPluginCurrentVersion);	// Call out to C plugin
                // XXX: check for error?
            } else {
                fprintf(stderr, "Could not dlopen plugin: %s\n", ent->fts_name);
            }
#if HAVE_TCL_PLUGINS
        } else if (strstr(ent->fts_name, ".tcl")) {
            plugin = _DBPluginInitialize();
            _DBPluginSetCurrentPlugin(plugin);
            load_tcl_plugin(plugin, ent->fts_accpath);	// Calls out to Tcl plugin
#endif
        }
        if (plugin) {
            if (plugin->name == NULL) {
                fprintf(stderr, "warning: plugin has no name (skipping): %s\n", ent->fts_name);
            } else if (plugin->type == kDBPluginNullType) {
                fprintf(stderr, "warning: plugin has no type (skipping): %s\n", ent->fts_name);
            } else {
                if (CFDictionaryContainsKey(plugins, plugin->name)) {
                    fprintf(stderr,
                            "Error: already have a plugin loaded with name '%s' when "
                            "trying to load %s\n",
                            strdup_cfstr(plugin->name), ent->fts_accpath);
                    return -1;
                }
                CFDictionarySetValue(plugins, plugin->name, plugin);
            }
        }
        ent = ent->fts_link;
    }
    fts_close(dir);

    //
    // Release the path array
    //
    for (i = 0; i < path_argc; ++i) {
        free(path_argv[i]);
    }
    free(path_argv);

    return 0;
}
static CFDictionaryRef
copy_app_layer_vpn_proxies(CFDictionaryRef services, CFArrayRef order, CFDictionaryRef services_info)
{
	CFMutableDictionaryRef	app_layer_proxies	= NULL;
	CFIndex			i;
	CFIndex			n_order;

	if (!isA_CFDictionary(services_info)) {
		return NULL;
	}

	// iterate over services

	n_order = isA_CFArray(order) ? CFArrayGetCount(order) : 0;
	for (i = 0; i < n_order; i++) {
		CFMutableDictionaryRef	newProxy;
		CFDictionaryRef		proxy;
		CFDictionaryRef		service;
		CFStringRef		serviceID;
		CFDictionaryRef		vpn;
		CFStringRef		vpn_key;

		serviceID = CFArrayGetValueAtIndex(order, i);
		service = CFDictionaryGetValue(services, serviceID);
		if (!isA_CFDictionary(service)) {
			// if no service
			continue;
		}

		proxy = CFDictionaryGetValue(service, kSCEntNetProxies);
		if (!isA_CFDictionary(proxy)) {
			// if no proxy
			continue;
		}

		vpn_key = SCDynamicStoreKeyCreateNetworkServiceEntity(NULL,
								      kSCDynamicStoreDomainSetup,
								      serviceID,
								      kSCEntNetVPN);
		vpn = CFDictionaryGetValue(services_info, vpn_key);
		CFRelease(vpn_key);

		if (!isA_CFDictionary(vpn) || !CFDictionaryContainsKey(vpn, kSCPropNetVPNAppRules)) {
			// if not app-layer vpn
			continue;
		}

		if ((app_layer_proxies != NULL) &&
		    CFDictionaryContainsKey(app_layer_proxies, serviceID)) {
			// if we've already processed this [app_layer_proxies] interface
			continue;
		}

		// add [app_layer_proxies] proxy entry
		newProxy = CFDictionaryCreateMutableCopy(NULL, 0, proxy);
		CFDictionaryRemoveValue(newProxy, kSCPropNetProxiesSupplementalMatchDomains);
		CFDictionaryRemoveValue(newProxy, kSCPropNetProxiesSupplementalMatchOrders);
		if (app_layer_proxies == NULL) {
			app_layer_proxies = CFDictionaryCreateMutable(NULL,
								      0,
								      &kCFTypeDictionaryKeyCallBacks,
								      &kCFTypeDictionaryValueCallBacks);
		}
		CFDictionarySetValue(app_layer_proxies, serviceID, newProxy);
		CFRelease(newProxy);
	}

	return app_layer_proxies;
}
bool	CACFDictionary::HasKey(const CFStringRef inKey) const
{
	return CFDictionaryContainsKey(mCFDictionary, inKey) != 0;
}
static CFDictionaryRef
copy_scoped_proxies(CFDictionaryRef services, CFArrayRef order)
{
	CFIndex			i;
	CFIndex			n_order;
	CFMutableDictionaryRef	scoped	= NULL;

	// iterate over services

	n_order = isA_CFArray(order) ? CFArrayGetCount(order) : 0;
	for (i = 0; i < n_order; i++) {
		char			if_name[IF_NAMESIZE];
		CFStringRef		interface;
		CFMutableDictionaryRef	newProxy;
		CFDictionaryRef		proxy;
		CFDictionaryRef		service;
		CFStringRef		serviceID;

		serviceID = CFArrayGetValueAtIndex(order, i);
		service = CFDictionaryGetValue(services, serviceID);
		if (!isA_CFDictionary(service)) {
			// if no service
			continue;
		}

		proxy = CFDictionaryGetValue(service, kSCEntNetProxies);
		if (!isA_CFDictionary(proxy)) {
			// if no proxy
			continue;
		}

		interface = CFDictionaryGetValue(proxy, kSCPropInterfaceName);
		if (interface == NULL) {
			// if no [scoped] interface
			continue;
		}
		if ((scoped != NULL) &&
		    CFDictionaryContainsKey(scoped, interface)) {
			// if we've already processed this [scoped] interface
			continue;
		}

		if ((_SC_cfstring_to_cstring(interface,
					     if_name,
					     sizeof(if_name),
					     kCFStringEncodingASCII) == NULL) ||
		    ((if_nametoindex(if_name)) == 0)) {
			// if interface index not available
			continue;
		}

		// add [scoped] proxy entry
		// ... and remove keys we don't want in a [scoped] proxy
		CFRetain(interface);
		newProxy = CFDictionaryCreateMutableCopy(NULL, 0, proxy);
		CFDictionaryRemoveValue(newProxy, kSCPropNetProxiesSupplementalMatchDomains);
		CFDictionaryRemoveValue(newProxy, kSCPropNetProxiesSupplementalMatchOrders);
		CFDictionaryRemoveValue(newProxy, kSCPropInterfaceName);
		if (scoped == NULL) {
			scoped = CFDictionaryCreateMutable(NULL,
							   0,
							   &kCFTypeDictionaryKeyCallBacks,
							   &kCFTypeDictionaryValueCallBacks);
		}
		CFDictionarySetValue(scoped, interface, newProxy);
		CFRelease(newProxy);
		CFRelease(interface);
	}

	return scoped;
}
Ejemplo n.º 18
0
CFDictionaryRef APCreateDictionaryForLicenseData(CFDataRef data)
{
    if (!rsaKey->n || !rsaKey->e)
        return NULL;
    
    // Make the property list from the data
    CFStringRef errorString = NULL;
    CFPropertyListRef propertyList;
    propertyList = CFPropertyListCreateFromXMLData(kCFAllocatorDefault, data, kCFPropertyListMutableContainers, &errorString);
    if (errorString || CFDictionaryGetTypeID() != CFGetTypeID(propertyList) || !CFPropertyListIsValid(propertyList, kCFPropertyListXMLFormat_v1_0)) {
        if (propertyList)
            CFRelease(propertyList);
        return NULL;
    }
    
    // Load the signature
    CFMutableDictionaryRef licenseDictionary = (CFMutableDictionaryRef)propertyList;
    if (!CFDictionaryContainsKey(licenseDictionary, CFSTR("Signature"))) {
        CFRelease(licenseDictionary);
        return NULL;
    }
    
    CFDataRef sigData = CFDictionaryGetValue(licenseDictionary, CFSTR("Signature"));
	CFIndex sigDataLength = CFDataGetLength(sigData);
	UInt8 sigBytes[sigDataLength];
    CFDataGetBytes(sigData, CFRangeMake(0, sigDataLength), sigBytes);
    CFDictionaryRemoveValue(licenseDictionary, CFSTR("Signature"));
    
    // Decrypt the signature
	int checkDigestMaxSize = RSA_size(rsaKey)-11;
    unsigned char checkDigest[checkDigestMaxSize];
    if (RSA_public_decrypt((int) sigDataLength, sigBytes, checkDigest, rsaKey, RSA_PKCS1_PADDING) != SHA_DIGEST_LENGTH) {
        CFRelease(licenseDictionary);
        return NULL;
    }
    
    // Get the license hash
    CFMutableStringRef hashCheck = CFStringCreateMutable(kCFAllocatorDefault,0);
    int hashIndex;
    for (hashIndex = 0; hashIndex < SHA_DIGEST_LENGTH; hashIndex++)
        CFStringAppendFormat(hashCheck, nil, CFSTR("%02x"), checkDigest[hashIndex]);
    APSetHash(hashCheck);
    CFRelease(hashCheck);
    
    if (blacklist && (CFArrayContainsValue(blacklist, CFRangeMake(0, CFArrayGetCount(blacklist)), hash) == true))
        return NULL;
    
    // Get the number of elements
    CFIndex count = CFDictionaryGetCount(licenseDictionary);
    // Load the keys and build up the key array
    CFMutableArrayRef keyArray = CFArrayCreateMutable(kCFAllocatorDefault, count, NULL);
    CFStringRef keys[count];
    CFDictionaryGetKeysAndValues(licenseDictionary, (const void**)&keys, NULL);
    int i;
    for (i = 0; i < count; i++)
        CFArrayAppendValue(keyArray, keys[i]);
    
    // Sort the array
    int context = kCFCompareCaseInsensitive;
    CFArraySortValues(keyArray, CFRangeMake(0, count), (CFComparatorFunction)CFStringCompare, &context);
    
    // Setup up the hash context
    SHA_CTX ctx;
    SHA1_Init(&ctx);
    // Convert into UTF8 strings
    for (i = 0; i < count; i++)
    {
        char *valueBytes;
        CFIndex valueLengthAsUTF8;
        CFStringRef key = CFArrayGetValueAtIndex(keyArray, i);
        CFStringRef value = CFDictionaryGetValue(licenseDictionary, key);
        
        // Account for the null terminator
        valueLengthAsUTF8 = CFStringGetMaximumSizeForEncoding(CFStringGetLength(value), kCFStringEncodingUTF8) + 1;
        valueBytes = (char *)malloc(valueLengthAsUTF8);
        CFStringGetCString(value, valueBytes, valueLengthAsUTF8, kCFStringEncodingUTF8);
        SHA1_Update(&ctx, valueBytes, strlen(valueBytes));
        free(valueBytes);
    }
    unsigned char digest[SHA_DIGEST_LENGTH];
    SHA1_Final(digest, &ctx);
    
    if (keyArray != NULL)
        CFRelease(keyArray);
    
    // Check if the signature is a match    
    for (i = 0; i < SHA_DIGEST_LENGTH; i++) {
        if (checkDigest[i] ^ digest[i]) {
            CFRelease(licenseDictionary);
            return NULL;
        }
    }
    
    // If it's a match, we return the dictionary; otherwise, we never reach this
    return licenseDictionary;
}
Ejemplo n.º 19
0
void simpleDictionaryExample(void) {

    CFMutableDictionaryRef dict;
    CFTypeRef value;
    Boolean booleanResult;
    CFNumberRef number;
    int someInt = 42;
    
    // Create a pretty standard mutable dictionary: CF type keys, CF type values.
    // If you only have a few values to initialize with, it might also make sense to use an immutable
    // dictionary, which is more efficient.
    
    // With the standard callbacks used below, the keys and values will be retained/released as they
    // are added to and removed from the CFDictionary. CFHash() and CFEqual() will be called 
    // on the keys to determine matches.
    
    // If you are using just CFStrings as keys, it might also make sense to use kCFCopyStringDictionaryKeyCallBacks
    // for the key callbacks. This callback set will copy the keys, which is more safe. (Note that copying is
    // fast for strings if the string is actually immutable, so there's no performance hit.)
    
    dict = CFDictionaryCreateMutable(NULL, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
    
    // Put some stuff in the dictionary
    
    CFDictionarySetValue(dict, CFSTR("A String Key"), CFSTR("A String Value"));
    
    // Use a CFNumber() as a value, also as a key

    number = CFNumberCreate(NULL, kCFNumberIntType, &someInt);
    
    CFDictionarySetValue(dict, CFSTR("Another string key"), number);
    CFDictionarySetValue(dict, number, CFSTR("Another string value"));

    // Because inserting the CFNumber in the CFDictionary retains it,
    // we can give up ownership and the number will be properly released
    // when the dictionary is released...
    
    CFRelease(number);
    
    // Now print the dictionary and do some queries...

    show(CFSTR("Dictionary: %@"), dict);

    // Should find the CFString "A String Value"
    // Note that the keys don't just have to be ==, because CFEqual() compares values of CFTypes
    // Also note that the returned value should not be freed, as it is owned by the dictionary
    
    value = CFDictionaryGetValue(dict, CFSTR("A String Key"));

    show(CFSTR("Value for key \"A String Key\": %@"), value);

    // Other ways to look up (in order to distinguish NULL value from whether the key is there at all...)
    
    booleanResult = CFDictionaryContainsKey(dict, CFSTR("A String Key"));

    booleanResult = CFDictionaryGetValueIfPresent(dict, CFSTR("A String Key"), &value);

    // Should return NULL, as this key doesn't exist
    
    value = CFDictionaryGetValue(dict, CFSTR("This key isn't in the dictionary"));

    // Now free the dictionary along with all the keys and values

    CFRelease(dict);
}
Ejemplo n.º 20
0
static void
flatten(SCPreferencesRef	prefs,
	CFStringRef		key,
	CFDictionaryRef		base)
{
	CFDictionaryRef		subset;
	CFStringRef		link;
	CFMutableDictionaryRef	myDict;
	CFStringRef		myKey;
	CFIndex			i;
	CFIndex			nKeys;
	const void		**keys;
	const void		**vals;

	if (!CFDictionaryGetValueIfPresent(base, kSCResvLink, (const void **)&link)) {
		/* if this dictionary is not linked */
		subset = base;
	} else {
		/* if __LINK__ key is present */
		subset = SCPreferencesPathGetValue(prefs, link);
		if (!subset) {
			/* if error with link */
			SCLog(TRUE, LOG_ERR,
			      CFSTR("SCPreferencesPathGetValue(,%@,) failed: %s"),
			      link,
			      SCErrorString(SCError()));
			return;
		}
	}

	if (CFDictionaryContainsKey(subset, kSCResvInactive)) {
		/* if __INACTIVE__ key is present */
		return;
	}

	myKey = CFStringCreateWithFormat(NULL,
					 NULL,
					 CFSTR("%@%@"),
					 kSCDynamicStoreDomainSetup,
					 key);

	myDict = (CFMutableDictionaryRef)CFDictionaryGetValue(newPrefs, myKey);
	if (myDict) {
		myDict = CFDictionaryCreateMutableCopy(NULL,
						       0,
						       (CFDictionaryRef)myDict);
	} else {
		myDict = CFDictionaryCreateMutable(NULL,
						   0,
						   &kCFTypeDictionaryKeyCallBacks,
						   &kCFTypeDictionaryValueCallBacks);
	}

	nKeys = CFDictionaryGetCount(subset);
	if (nKeys > 0) {
		keys  = CFAllocatorAllocate(NULL, nKeys * sizeof(CFStringRef)      , 0);
		vals  = CFAllocatorAllocate(NULL, nKeys * sizeof(CFPropertyListRef), 0);
		CFDictionaryGetKeysAndValues(subset, keys, vals);
		for (i = 0; i < nKeys; i++) {
			if (CFGetTypeID((CFTypeRef)vals[i]) != CFDictionaryGetTypeID()) {
				/* add this key/value to the current dictionary */
				CFDictionarySetValue(myDict, keys[i], vals[i]);
			} else {
				CFStringRef	subKey;

				/* flatten [sub]dictionaries */
				subKey = CFStringCreateWithFormat(NULL,
								  NULL,
								  CFSTR("%@%s%@"),
								  key,
								  CFEqual(key, CFSTR("/")) ? "" : "/",
								  keys[i]);
				flatten(prefs, subKey, vals[i]);
				CFRelease(subKey);
			}
		}
		CFAllocatorDeallocate(NULL, keys);
		CFAllocatorDeallocate(NULL, vals);
	}

	if (CFDictionaryGetCount(myDict) > 0) {
		/* add this dictionary to the new preferences */
		CFDictionarySetValue(newPrefs, myKey, myDict);
	}

	CFRelease(myDict);
	CFRelease(myKey);

	return;
}