Beispiel #1
0
/* IOCopyLoadAdvisoryLevelDetailed
 * In case of error, or inability to find system load advisory level,
 * returns NULL.
 */
CFDictionaryRef IOCopySystemLoadAdvisoryDetailed(void)
{
    CFDictionaryRef     gtDetailed = NULL;
    SCDynamicStoreRef   storage = NULL;
    CFStringRef         gtDetailedKey = SCDynamicStoreKeyCreate(
                            kCFAllocatorDefault, 
                            CFSTR("%@%@"),
                            _io_kSCDynamicStoreDomainState, 
                            kSLADetailedPath);

    storage = SCDynamicStoreCreate(
                            kCFAllocatorDefault,
                            CFSTR("IOKit IOGetSystemLoadAdvisoryDetailed"),
                            NULL,
                            NULL);

    if (!storage || !gtDetailedKey) {
        goto exit;
    }
    gtDetailed = SCDynamicStoreCopyValue(storage, gtDetailedKey);
    if(gtDetailed)
    {
        if(!isA_CFDictionary(gtDetailed)) {
            CFRelease(gtDetailed);
            gtDetailed = NULL;
        }
    }
exit:    
    if (gtDetailedKey) CFRelease(gtDetailedKey);
    if (storage) CFRelease(storage);    
    return gtDetailed;
}
__private_extern__
CFPropertyListRef
cache_SCDynamicStoreCopyValue(SCDynamicStoreRef store, CFStringRef key)
{
	CFPropertyListRef	value;

	value = CFDictionaryGetValue(cached_set, key);
	if (value) {
		// if we have "set" a new value
		return (CFRetain(value));
	}

	if (CFArrayContainsValue(cached_removals,
				 CFRangeMake(0, CFArrayGetCount(cached_removals)),
				 key)) {
		// if we have "removed" the key
		return NULL;
	}

	value = CFDictionaryGetValue(cached_keys, key);
	if (value) {
		// if we have a cached value
		return (CFRetain(value));
	}

	value = SCDynamicStoreCopyValue(store, key);
	if (value) {
		CFDictionarySetValue(cached_keys, key, value);
	}

	return value;
}
Beispiel #3
0
static CFStringRef
copy_primary_service(SCDynamicStoreRef store)
{
	CFDictionaryRef	dict;
	CFStringRef	key;
	CFStringRef	serviceID	= NULL;

	key = SCDynamicStoreKeyCreateNetworkGlobalEntity(NULL,
							 kSCDynamicStoreDomainState,
							 kSCEntNetIPv4);
	dict = SCDynamicStoreCopyValue(store, key);
	CFRelease(key);

	if (dict != NULL) {
		if (isA_CFDictionary(dict)) {
			serviceID = CFDictionaryGetValue(dict, kSCDynamicStorePropNetPrimaryService);
			if (isA_CFString(serviceID)) {
				CFRetain(serviceID);
			} else {
				serviceID = NULL;
			}
		}
		CFRelease(dict);
	}

	return serviceID;
}
Beispiel #4
0
static CFDictionaryRef
smb_copy_global_configuration(SCDynamicStoreRef store)
{
	CFDictionaryRef	dict;
	CFStringRef	key;

	key = SCDynamicStoreKeyCreateNetworkGlobalEntity(NULL,
							 kSCDynamicStoreDomainState,
							 kSCEntNetSMB);
	dict = SCDynamicStoreCopyValue(store, key);
	CFRelease(key);

	if (dict != NULL) {
		if (isA_CFDictionary(dict)) {
			return dict;
		}

		CFRelease(dict);
	}

	dict = CFDictionaryCreate(NULL,			// allocator
				  NULL,			// keys
				  NULL,			// values
				  0,			// numValues
				  &kCFTypeDictionaryKeyCallBacks,
				  &kCFTypeDictionaryValueCallBacks);
	return dict;
}
Beispiel #5
0
static CFStringRef
copy_primary_ip(SCDynamicStoreRef store, CFStringRef serviceID)
{
	CFStringRef	address	= NULL;
	CFDictionaryRef	dict;
	CFStringRef	key;

	key = SCDynamicStoreKeyCreateNetworkServiceEntity(NULL,
							  kSCDynamicStoreDomainState,
							  serviceID,
							  kSCEntNetIPv4);
	dict = SCDynamicStoreCopyValue(store, key);
	CFRelease(key);

	if (dict != NULL) {
		if (isA_CFDictionary(dict)) {
			CFArrayRef	addresses;

			addresses = CFDictionaryGetValue(dict, kSCPropNetIPv4Addresses);
			if (isA_CFArray(addresses) && (CFArrayGetCount(addresses) > 0)) {
				address = CFArrayGetValueAtIndex(addresses, 0);
				if (isA_CFString(address)) {
					CFRetain(address);
				} else {
					address = NULL;
				}
			}
		}
		CFRelease(dict);
	}

	return address;
}
Beispiel #6
0
static Boolean
quiet(Boolean *timeout)
{
	CFDictionaryRef	dict;
	Boolean		_quiet		= FALSE;
	Boolean		_timeout	= FALSE;

	// check if quiet
	dict = SCDynamicStoreCopyValue(store, initKey);
	if (dict != NULL) {
		if (isA_CFDictionary(dict)) {
			if (CFDictionaryContainsKey(dict, CFSTR("*QUIET*"))) {
				_quiet = TRUE;
			}
			if (CFDictionaryContainsKey(dict, CFSTR("*TIMEOUT*"))) {
				_timeout = TRUE;
			}
		}
		CFRelease(dict);
	}

	if (timeout != NULL) {
		*timeout = _timeout;
	}
	return _quiet;
}
Beispiel #7
0
static int
S_wait_all(mach_port_t server, int argc, char * argv[])
{
    CFMutableArrayRef	keys;
    SCDynamicStoreRef 	session;
    CFRunLoopSourceRef	rls;
    unsigned long	t = WAIT_ALL_DEFAULT_TIMEOUT;
    CFPropertyListRef	value;
    struct itimerval 	v;

    if (argc > 0) {
	t = strtoul(argv[0], 0, 0);
	if (t > WAIT_ALL_MAX_TIMEOUT) {
	    t = WAIT_ALL_MAX_TIMEOUT;
	}
    }

    session = SCDynamicStoreCreate(NULL, CFSTR("ipconfig command"), 
				   key_appeared, NULL);
    if (session == NULL) {
	fprintf(stderr, "SCDynamicStoreCreate failed: %s\n", 
		SCErrorString(SCError()));
	return (0);
    }
    keys = CFArrayCreateMutable(NULL, 0, &kCFTypeArrayCallBacks);
    CFArrayAppendValue(keys, STARTUP_KEY);
    SCDynamicStoreSetNotificationKeys(session, keys, NULL);
    CFRelease(keys);

    rls = SCDynamicStoreCreateRunLoopSource(NULL, session, 0);
    CFRunLoopAddSource(CFRunLoopGetCurrent(), rls, kCFRunLoopDefaultMode);
    CFRelease(rls);

    signal(SIGALRM, on_alarm);
    bzero(&v, sizeof(v));
    v.it_value.tv_sec = t;
    if (setitimer(ITIMER_REAL, &v, NULL) < 0) {
	perror("setitimer");
	return (0);
    }
    value = SCDynamicStoreCopyValue(session, STARTUP_KEY);
    if (value == NULL) {
	CFRunLoopRun();
	return (0);
    }
    CFRelease(value);
    CFRelease(session);
    return (0);
}
Beispiel #8
0
static
CFDictionaryRef _CFNetDiagnosticsGetDataFromSCDSAndThowAwayGarbage(CFAllocatorRef allocator, SCDynamicStoreRef store, 
	CFStringRef(*SCFunc)(CFAllocatorRef, CFStringRef, CFStringRef, CFStringRef), CFStringRef arg1, CFStringRef arg2, CFStringRef arg3) {
	CFStringRef pattern = NULL;
	CFDictionaryRef dict = NULL;

	
	
	pattern = SCFunc(allocator, arg1, arg2, arg3);
	if(pattern) {
		dict = SCDynamicStoreCopyValue( store, pattern );
		CFRelease(pattern);
	}
	
	return dict;
}
Beispiel #9
0
/* @function SystemLoadPrefsHaveChanged
 * @abstract We check whether DIsplay Sleep Timer == 0
 * Populates:
 *      displaySleepEnabled
 */
__private_extern__ void SystemLoadPrefsHaveChanged(void)
{
    SCDynamicStoreRef   _store       = _getSharedPMDynamicStore();
    CFDictionaryRef     liveSettings = NULL;
    CFNumberRef         displaySleep = NULL;
    CFTypeRef           dwbt = NULL;
    int                 idle, newDWBT;
    static bool         lastDisplaySleep = false;
    static int          lastDWBT = -1;
    bool                notify = false;

    liveSettings = SCDynamicStoreCopyValue(_store, 
                        CFSTR(kIOPMDynamicStoreSettingsKey));
    if (liveSettings) 
    {
        displaySleep = CFDictionaryGetValue(liveSettings, 
                                    CFSTR(kIOPMDisplaySleepKey));
        if (displaySleep) 
        {
            CFNumberGetValue(displaySleep, kCFNumberIntType, &idle);

            displaySleepEnabled = idle ? true:false;                

            if (displaySleepEnabled != lastDisplaySleep)
            {
                lastDisplaySleep = displaySleepEnabled;
                notify = true;
            }
        }
        dwbt = CFDictionaryGetValue(liveSettings, 
                                    CFSTR(kIOPMDarkWakeBackgroundTaskKey));
        if (dwbt)
        {
            newDWBT = CFBooleanGetValue(dwbt) ? 1 : 0;
            if (lastDWBT != newDWBT) 
            {
                lastDWBT = newDWBT;
                notify = true;
            }
        }
        CFRelease(liveSettings);
    }

    if (notify)
        shareTheSystemLoad(kYesNotify);
    return;
}
Beispiel #10
0
static
CFArrayRef copyCurrentDNSServers(void) {
	SCDynamicStoreRef store;
	CFPropertyListRef propList;
	CFStringRef scdsRegexp;
	CFArrayRef retval = NULL;
	CFStringRef serviceID;
	
	serviceID = copyCurrentPrimaryService();
	if(serviceID) {

		scdsRegexp = SCDynamicStoreKeyCreateNetworkServiceEntity (
						kCFAllocatorDefault,
						kSCDynamicStoreDomainState,
						serviceID,
						kSCEntNetDNS);
		
		if(scdsRegexp) {

			store = SCDynamicStoreCreate(kCFAllocatorDefault, CFSTR("Network Diagnostics"), NULL, NULL);

			if(store) {
				propList = SCDynamicStoreCopyValue(store, scdsRegexp);
				if(propList) {
					retval = CFDictionaryGetValue(propList, CFSTR("ServerAddresses"));
					if (retval) {
						CFRetain(retval);
					}
					CFRelease(propList);
				}
				
				CFRelease(store);
			}

			CFRelease(scdsRegexp);
		}
		
		CFRelease(serviceID);
	}
	
	return retval;
}
Beispiel #11
0
static char *
getVPNInterfaceBuf (struct service *serv)
{
	char *interface_buf;

	SCLog(TRUE, LOG_INFO, CFSTR("%s:"), __FUNCTION__);

	switch (serv->type) {
	case TYPE_IPSEC:
		interface_buf = serv->u.ipsec.lower_interface;
		break;
	case TYPE_PPP:
		if (!serv->u.ppp.lower_interface[0]) {
			CFStringRef     string, key;
			CFDictionaryRef dict;

			SCLog(TRUE, LOG_INFO, CFSTR("%s: lower_interface is null"), __FUNCTION__);

			/* TODO: this part should be change to grab the real lower interface instead of the primary */
			key = SCDynamicStoreKeyCreateNetworkGlobalEntity(NULL, kSCDynamicStoreDomainState, kSCEntNetIPv4);
			if (key) {
				dict = SCDynamicStoreCopyValue(gDynamicStore, key);
				CFRelease(key);
				if (dict) {
					if ((string = CFDictionaryGetValue(dict, kSCDynamicStorePropNetPrimaryInterface))) {
						CFStringGetCString(string, serv->u.ppp.lower_interface, sizeof(serv->u.ppp.lower_interface), kCFStringEncodingASCII);
						SCLog(TRUE, LOG_INFO, CFSTR("%s: lower_interface is gotten %@"), __FUNCTION__, string);
					}
					CFRelease(dict);
				}
			}
		}
		interface_buf = serv->u.ppp.lower_interface;
		SCLog(TRUE, LOG_INFO, CFSTR("%s: lower_interface is %s"), __FUNCTION__, interface_buf[0]? interface_buf : "null");
		break;
	default:
		interface_buf = NULL;
		break;
	}

	return interface_buf;
}
/* return AD realm if it exists */
const char *get_ad_realm ( struct auth_request *auth_request )
{
	const char *out_realm = NULL;

	SCDynamicStoreRef store = SCDynamicStoreCreate(kCFAllocatorDefault, CFSTR("dovecot.digest.auth"), NULL, NULL);
	if ( store ) {
		CFDictionaryRef dict = SCDynamicStoreCopyValue(store, CFSTR("com.apple.opendirectoryd.ActiveDirectory"));
		if (dict) {
			CFStringRef domain = CFDictionaryGetValue(dict, CFSTR("DomainNameFlat"));
			if (domain) {
				const char *ad_realm = CFStringGetCStringPtr(domain, kCFStringEncodingUTF8);
				if (ad_realm) {
					auth_request_log_info(auth_request, "digest-md5", "ad realm: %s", ad_realm);
					out_realm = t_strdup(ad_realm);
				}
			}
			CFRelease(dict);
		}
		CFRelease(store);
	}
	return( out_realm );
}
/* _weManageUPSPower
 *
 * Determines whether X Power Management should do the emergency shutdown when low on UPS power.
 * OS X should NOT manage low power situations if another third party application has already claimed
 * that emergency shutdown responsibility.
 *
 * Return value:
 * 	true == OS X should manage emergency shutdowns
 *  false == another installed & running application is managing shutdowns
 */
static bool
_weManageUPSPower(void)
{
    static CFStringRef                  ups_claimed = NULL;
    SCDynamicStoreRef                   ds_ref = NULL;
    CFTypeRef                           temp;
    bool                                ret_val = true;

    if(!ups_claimed) {
        ups_claimed = SCDynamicStoreKeyCreate(kCFAllocatorDefault, CFSTR("%@%@"), kSCDynamicStoreDomainState, CFSTR(kIOPSUPSManagementClaimed));
    }

    // Check for existence of "UPS Management claimed" key in SCDynamicStore
    if( ups_claimed && ds_ref &&
        (temp = SCDynamicStoreCopyValue(_getSharedPMDynamicStore(), ups_claimed)) ) 
    {
        if(kCFBooleanTrue == temp) 
            ret_val = false;
        CFRelease(temp);
    }
    return ret_val;
}
Beispiel #14
0
static 
CFStringRef copyCurrentPrimaryService(void) {
	SCDynamicStoreRef store;
	CFPropertyListRef propList;
	CFStringRef retval = NULL;
	
	store = SCDynamicStoreCreate(kCFAllocatorDefault, CFSTR("Network Diagnostics"), NULL, NULL);

	if(store) {
		propList = SCDynamicStoreCopyValue(store, CFSTR("State:/Network/Global/IPv4"));
		if(propList) {
			retval = CFDictionaryGetValue(propList, CFSTR("PrimaryService"));
			if (retval) {
				CFRetain(retval);
			}
			CFRelease(propList);
		}
		CFRelease(store);
	}
	
	return retval;
}
void NetworkStateNotifier::updateState()
{
    // Assume that we're offline until proven otherwise.
    m_isOnLine = false;
    
    RetainPtr<CFStringRef> str = adoptCF(SCDynamicStoreKeyCreateNetworkInterface(0, kSCDynamicStoreDomainState));
    
    RetainPtr<CFPropertyListRef> propertyList = adoptCF(SCDynamicStoreCopyValue(m_store.get(), str.get()));
    
    if (!propertyList)
        return;
    
    if (CFGetTypeID(propertyList.get()) != CFDictionaryGetTypeID())
        return;
    
    CFArrayRef netInterfaces = (CFArrayRef)CFDictionaryGetValue((CFDictionaryRef)propertyList.get(), kSCDynamicStorePropNetInterfaces);
    if (CFGetTypeID(netInterfaces) != CFArrayGetTypeID())
        return;
    
    for (CFIndex i = 0; i < CFArrayGetCount(netInterfaces); i++) {
        CFStringRef interface = (CFStringRef)CFArrayGetValueAtIndex(netInterfaces, i);
        if (CFGetTypeID(interface) != CFStringGetTypeID())
            continue;
        
        // Ignore the loopback interface.
        if (CFStringFind(interface, CFSTR("lo"), kCFCompareAnchored).location != kCFNotFound)
            continue;

        RetainPtr<CFStringRef> key = adoptCF(SCDynamicStoreKeyCreateNetworkInterfaceEntity(0, kSCDynamicStoreDomainState, interface, kSCEntNetIPv4));

        RetainPtr<CFArrayRef> keyList = adoptCF(SCDynamicStoreCopyKeyList(m_store.get(), key.get()));
    
        if (keyList && CFArrayGetCount(keyList.get())) {
            m_isOnLine = true;
            break;
        }
    }
}
Beispiel #16
0
static void
nc_ondemand_callback(SCDynamicStoreRef store, CFArrayRef changedKeys, void *info)
{
	CFStringRef		key		= NULL;
	CFDictionaryRef		ondemand_dict	= NULL;
	struct tm		tm_now;
	struct timeval		tv_now;

	if (CFArrayGetCount(changedKeys) < 1) {
		return;
	}

	(void)gettimeofday(&tv_now, NULL);
	(void)localtime_r(&tv_now.tv_sec, &tm_now);

	SCPrint(TRUE, stdout, CFSTR("\n*** %2d:%02d:%02d.%03d\n\n"),
		tm_now.tm_hour,
		tm_now.tm_min,
		tm_now.tm_sec,
		tv_now.tv_usec / 1000);

	if (ondemand_nodename) {
		checkOnDemandHost(store, ondemand_nodename, FALSE);
		checkOnDemandHost(store, ondemand_nodename, TRUE);
	} else {
		key = CFArrayGetValueAtIndex(changedKeys, 0);

		ondemand_dict = SCDynamicStoreCopyValue(store, key);
		if (ondemand_dict) {
			SCPrint(TRUE, stdout, CFSTR("%@ %@\n"), kSCEntNetOnDemand, ondemand_dict);
		} else {
			SCPrint(TRUE, stdout, CFSTR("%@ not configured\n"), kSCEntNetOnDemand);
		}

		my_CFRelease(&ondemand_dict);
	}
}
int
main(int argc, char **argv)
{
	CFDictionaryRef		entities;
	CFStringRef		key;
	CFDictionaryRef		newProxy	= NULL;
	CFStringRef		pattern;
	CFMutableArrayRef	patterns;
	CFStringRef		primary		= NULL;
	CFMutableDictionaryRef	primary_proxy	= NULL;
	CFArrayRef		service_order	= NULL;
	CFMutableDictionaryRef	service_state_dict;
	CFDictionaryRef		setup_global_ipv4;
	CFDictionaryRef		state_global_ipv4;
	SCDynamicStoreRef	store;

	_sc_log     = FALSE;
	_sc_verbose = (argc > 1) ? TRUE : FALSE;

	store = SCDynamicStoreCreate(NULL, CFSTR("TEST"), NULL, NULL);

	// get IPv4, IPv6, and Proxies entities
	patterns = CFArrayCreateMutable(NULL, 0, &kCFTypeArrayCallBacks);
	pattern = SCDynamicStoreKeyCreateNetworkServiceEntity(NULL,
							      kSCDynamicStoreDomainState,
							      kSCCompAnyRegex,
							      kSCEntNetIPv4);
	CFArrayAppendValue(patterns, pattern);
	CFRelease(pattern);
	pattern = SCDynamicStoreKeyCreateNetworkServiceEntity(NULL,
							      kSCDynamicStoreDomainState,
							      kSCCompAnyRegex,
							      kSCEntNetIPv6);
	CFArrayAppendValue(patterns, pattern);
	CFRelease(pattern);
	pattern = SCDynamicStoreKeyCreateNetworkServiceEntity(NULL,
							      kSCDynamicStoreDomainSetup,
							      kSCCompAnyRegex,
							      kSCEntNetProxies);
	CFArrayAppendValue(patterns, pattern);
	CFRelease(pattern);
	pattern = SCDynamicStoreKeyCreateNetworkServiceEntity(NULL,
							      kSCDynamicStoreDomainState,
							      kSCCompAnyRegex,
							      kSCEntNetProxies);
	CFArrayAppendValue(patterns, pattern);
	CFRelease(pattern);
	entities = SCDynamicStoreCopyMultiple(store, NULL, patterns);
	CFRelease(patterns);

	service_state_dict = CFDictionaryCreateMutable(NULL,
						       0,
						       &kCFTypeDictionaryKeyCallBacks,
						       &kCFTypeDictionaryValueCallBacks);
	CFDictionaryApplyFunction(entities, split, service_state_dict);
	CFRelease(entities);

	// get primary service ID
	key = SCDynamicStoreKeyCreateNetworkGlobalEntity(NULL,
							 kSCDynamicStoreDomainState,
							 kSCEntNetIPv4);
	state_global_ipv4 = SCDynamicStoreCopyValue(store, key);
	CFRelease(key);
	if (state_global_ipv4 != NULL) {
		primary = CFDictionaryGetValue(state_global_ipv4, kSCDynamicStorePropNetPrimaryService);
		if (primary != NULL) {
			CFDictionaryRef	service_dict;

			// get proxy configuration for primary service
			service_dict = CFDictionaryGetValue(service_state_dict, primary);
			if (service_dict != NULL) {
				CFDictionaryRef	service_proxy;

				service_proxy = CFDictionaryGetValue(service_dict, kSCEntNetProxies);
				if (service_proxy != NULL) {
					primary_proxy = CFDictionaryCreateMutableCopy(NULL, 0, service_proxy);
					CFDictionaryRemoveValue(primary_proxy, kSCPropInterfaceName);
				}
			}
		}
	}

	// get serviceOrder
	key = SCDynamicStoreKeyCreateNetworkGlobalEntity(NULL,
							 kSCDynamicStoreDomainSetup,
							 kSCEntNetIPv4);
	setup_global_ipv4 = SCDynamicStoreCopyValue(store, key);
	CFRelease(key);
	if (setup_global_ipv4 != NULL) {
		service_order = CFDictionaryGetValue(setup_global_ipv4, kSCPropNetServiceOrder);
	}

	// update proxy configuration
	proxy_configuration_init(CFBundleGetMainBundle());
	newProxy = proxy_configuration_update(primary_proxy,
					      service_state_dict,
					      service_order,
					      NULL);
	if (newProxy != NULL) {
		SCPrint(TRUE, stdout, CFSTR("%@\n"), newProxy);
		CFRelease(newProxy);
	}

	// cleanup
	if (setup_global_ipv4 != NULL)	CFRelease(setup_global_ipv4);
	if (state_global_ipv4 != NULL)	CFRelease(state_global_ipv4);
	CFRelease(service_state_dict);
	CFRelease(store);

	/* not reached */
	exit(0);
	return 0;
}
Beispiel #18
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;
}
Beispiel #19
0
/* -----------------------------------------------------------------------------
----------------------------------------------------------------------------- */
static void
nc_show(int argc, char **argv)
{
	SCNetworkServiceRef	service			= NULL;
	SCDynamicStoreRef	store			= NULL;
	int			exit_code		= 1;
	CFStringRef		serviceID		= NULL;
	CFStringRef		iftype			= NULL;
	CFStringRef		ifsubtype		= NULL;
	CFStringRef		type_entity_key		= NULL;
	CFStringRef		subtype_entity_key	= NULL;
	CFDictionaryRef		type_entity_dict	= NULL;
	CFDictionaryRef		subtype_entity_dict	= NULL;
	CFStringRef		vpnprefpath		= NULL;
#if !TARGET_OS_IPHONE
	CFDataRef		bookmarkData		= NULL;
	CFURLRef		directory		= NULL;
	Boolean			isStale			= FALSE;
	char			*path			= NULL;
	CFIndex			path_len		= 0;
#endif

	service = nc_copy_service_from_arguments(argc, argv, NULL);
	if (service == NULL) {
		SCPrint(TRUE, stderr, CFSTR("No service\n"));
		exit(exit_code);
	}

	serviceID = SCNetworkServiceGetServiceID(service);

	nc_get_service_type_and_subtype(service, &iftype, &ifsubtype);

	if (!CFEqual(iftype, kSCEntNetPPP) &&
	    !CFEqual(iftype, kSCEntNetIPSec) &&
	    !CFEqual(iftype, kSCEntNetVPN)) {
		SCPrint(TRUE, stderr, CFSTR("Not a connection oriented service: %@\n"), serviceID);
		goto done;
	}

	type_entity_key = SCDynamicStoreKeyCreateNetworkServiceEntity(NULL, kSCDynamicStoreDomainSetup, serviceID, iftype);

	nc_print_VPN_service(service);

#if !TARGET_OS_IPHONE
	vpnprefpath = CFStringCreateWithFormat(NULL, NULL, CFSTR("%@%@%@"), PREF_PREFIX, ifsubtype, PREF_SUFFIX);
	if (vpnprefpath == NULL) {
		goto skipURL;
	}

	path_len = CFStringGetLength(vpnprefpath) + 1;
	path = malloc(path_len);
	if (path == NULL) {
		goto skipURL;
	}

	if (!CFStringGetCString(vpnprefpath, path, path_len, kCFStringEncodingASCII)) {
		SCPrint(TRUE, stderr, CFSTR("CFStringGetCString failed\n"));
		goto done;
	}

	do_prefs_init();		/* initialization */
	do_prefs_open(1, &path);	/* open prefs */

	bookmarkData = SCPreferencesGetValue(prefs, CFSTR("ApplicationURL"));
	if (bookmarkData == NULL) {
		goto skipURL;
	}

	directory = CFURLCreateByResolvingBookmarkData(kCFAllocatorDefault, bookmarkData, 0, NULL, NULL, &isStale, NULL);
	if (directory == NULL) {
		goto skipURL;
	}

	SCPrint(TRUE, stdout, CFSTR("ApplicationURL: %@\n"), directory);
skipURL:
#endif

	store = SCDynamicStoreCreate(NULL, CFSTR("scutil --nc"), NULL, NULL);
	if (store == NULL) {
		SCPrint(TRUE, stderr, CFSTR("Unable to create dynamic store: %s\n"), SCErrorString(SCError()));
		goto done;
	}
	type_entity_dict = SCDynamicStoreCopyValue(store, type_entity_key);

	if (!type_entity_dict) {
		SCPrint(TRUE, stderr, CFSTR("No \"%@\" configuration available\n"), iftype);
	} else {
		SCPrint(TRUE, stdout, CFSTR("%@ %@\n"), iftype, type_entity_dict);
	}

	if (ifsubtype) {
		subtype_entity_key = SCDynamicStoreKeyCreateNetworkServiceEntity(NULL, kSCDynamicStoreDomainSetup, serviceID, ifsubtype);
		subtype_entity_dict = SCDynamicStoreCopyValue(store, subtype_entity_key);
		if (!subtype_entity_dict) {
			//
		}
		else {
			SCPrint(TRUE, stdout, CFSTR("%@ %@\n"), ifsubtype, subtype_entity_dict);
		}
	}

	exit_code = 0;

done:
	my_CFRelease(&type_entity_key);
	my_CFRelease(&type_entity_dict);
	my_CFRelease(&subtype_entity_key);
	my_CFRelease(&subtype_entity_dict);
	my_CFRelease(&store);
	my_CFRelease(&service);
	my_CFRelease(&vpnprefpath);
	_prefs_close();
	exit(exit_code);
}
Beispiel #20
0
static void
smb_set_configuration(SCDynamicStoreRef store, CFDictionaryRef dict)
{
	CFArrayRef		array;
	Boolean			changed		= FALSE;
	UInt32			dosCodepage	= 0;
	CFStringEncoding	dosEncoding	= 0;
	CFStringEncoding	macEncoding	= kCFStringEncodingMacRoman;
	uint32_t		macRegion	= 0;
	Boolean			ok;
	SCPreferencesRef	prefs;
	CFStringRef		str;

	prefs = SCPreferencesCreate(NULL, CFSTR("smb-configuration"), CFSTR(kSMBPreferencesAppID));
	if (prefs == NULL) {
		my_log(LOG_ERR,
		       "smb_set_configuration: SCPreferencesCreate() failed: %s",
		       SCErrorString(SCError()));
		return;
	}

	ok = SCPreferencesLock(prefs, TRUE);
	if (!ok) {
		my_log(LOG_ERR,
		       "smb_set_configuration: SCPreferencesLock() failed: %s",
		       SCErrorString(SCError()));
		goto done;
	}

	// Server description
	str = SCDynamicStoreCopyComputerName(store, &macEncoding);
	update_pref(prefs, CFSTR(kSMBPrefServerDescription), str, &changed);

	// DOS code page
	if (str != NULL) {
		if (macEncoding == kCFStringEncodingMacRoman) {
			CFStringRef	key;
			CFDictionaryRef	dict;

			// get region
			key = SCDynamicStoreKeyCreateComputerName(NULL);
			dict = SCDynamicStoreCopyValue(store, key);
			CFRelease(key);
			if (dict != NULL) {
				if (isA_CFDictionary(dict)) {
					CFNumberRef	num;
					SInt32		val;

					num = CFDictionaryGetValue(dict, kSCPropSystemComputerNameRegion);
					if (isA_CFNumber(num) &&
					    CFNumberGetValue(num, kCFNumberSInt32Type, &val)) {
						macRegion = (uint32_t)val;
					}
				}

				CFRelease(dict);
			}
		}

		CFRelease(str);
	} else {
		// Important: must have root acccess (eUID==0) to access the config file!
		__CFStringGetInstallationEncodingAndRegion((uint32_t *)&macEncoding, &macRegion);
	}
	_SC_dos_encoding_and_codepage(macEncoding, macRegion, &dosEncoding, &dosCodepage);
	str = CFStringCreateWithFormat(NULL, NULL, CFSTR("%d"), (unsigned int)dosCodepage);
	assert(str != NULL);
	update_pref(prefs, CFSTR(kSMBPrefDOSCodePage), str, &changed);
	CFRelease(str);

	// NetBIOS name
	str = CFDictionaryGetValue(dict, kSCPropNetSMBNetBIOSName);
	str = isA_CFString(str);
	update_pref(prefs, CFSTR(kSMBPrefNetBIOSName), str, &changed);

	// NetBIOS node type
	str = CFDictionaryGetValue(dict, kSCPropNetSMBNetBIOSNodeType);
	str = isA_CFString(str);
	if (str != NULL) {
		if (CFEqual(str, kSCValNetSMBNetBIOSNodeTypeBroadcast)) {
			// B-node
			str = CFSTR(kSMBPrefNetBIOSNodeBroadcast);
		} else if (CFEqual(str, kSCValNetSMBNetBIOSNodeTypePeer)) {
			// P-node
			str = CFSTR(kSMBPrefNetBIOSNodePeer);
		} else if (CFEqual(str, kSCValNetSMBNetBIOSNodeTypeMixed)) {
			// M-node
			str = CFSTR(kSMBPrefNetBIOSNodeMixed);
		} else if (CFEqual(str, kSCValNetSMBNetBIOSNodeTypeHybrid)) {
			// H-node
			str = CFSTR(kSMBPrefNetBIOSNodeHybrid);
		} else {
			str = NULL;
		}
	}
	update_pref(prefs, CFSTR(kSMBPrefNetBIOSNodeType), str, &changed);

#ifdef	ADD_NETBIOS_SCOPE
	// NetBIOS scope
	str = CFDictionaryGetValue(dict, kSCPropNetSMBNetBIOSScope);
	str = isA_CFString(str);
	update_pref(prefs, CFSTR(kSMBPrefNetBIOSScope), str, &changed);
#endif	// ADD_NETBIOS_SCOPE

	// WINS addresses
	array = CFDictionaryGetValue(dict, kSCPropNetSMBWINSAddresses);
	array = isA_CFArray(array);
	update_pref(prefs, CFSTR(kSMBPrefWINSServerAddressList), array, &changed);

	// Workgroup (or domain)
	str = CFDictionaryGetValue(dict, kSCPropNetSMBWorkgroup);
	str = isA_CFString(str);
	update_pref(prefs, CFSTR(kSMBPrefWorkgroup), str, &changed);

	if (changed) {
		ok = SCPreferencesCommitChanges(prefs);
		if (!ok) {
			if ((SCError() != EROFS)) {
				my_log(LOG_ERR,
				       "smb_set_configuration: SCPreferencesCommitChanges() failed: %s",
				       SCErrorString(SCError()));
			}
			goto done;
		}

		ok = SCPreferencesApplyChanges(prefs);
		if (!ok) {
			my_log(LOG_ERR,
			       "smb_set_configuration: SCPreferencesApplyChanges() failed: %s",
			       SCErrorString(SCError()));
			goto done;
		}
	}

    done :

	(void) SCPreferencesUnlock(prefs);
	CFRelease(prefs);
	return;
}
Beispiel #21
0
static void
nc_ondemand(int argc, char **argv)
{
	int			exit_code	= 1;
	CFStringRef		key		= NULL;
	CFDictionaryRef		ondemand_dict	= NULL;
	SCDynamicStoreRef	store;

	store = SCDynamicStoreCreate(NULL, CFSTR("scutil --nc"), nc_ondemand_callback, NULL);
	if (store == NULL) {
		SCPrint(TRUE, stderr, CFSTR("Unable to create dynamic store: %s\n"), SCErrorString(SCError()));
		goto done;
	}

	if (argc == 1) {
#if	!TARGET_IPHONE_SIMULATOR
		if (strcmp("--refresh", argv[0]) == 0) {
			SCNetworkConnectionRef	connection	= NULL;

			connection = SCNetworkConnectionCreate(kCFAllocatorDefault, NULL, NULL);
			if (connection && SCNetworkConnectionRefreshOnDemandState(connection)) {
				exit_code = 0;
			}

			if (exit_code) {
				SCPrint(TRUE, stderr, CFSTR("Unable to refresh OnDemand state: %s\n"), SCErrorString(SCError()));
			}

			my_CFRelease(&connection);
			goto done;
		}
#endif	// !TARGET_IPHONE_SIMULATOR

		ondemand_nodename = CFStringCreateWithCString(NULL, argv[0], kCFStringEncodingUTF8);
	} else if (argc != 0) {
		SCPrint(TRUE, stderr, CFSTR("Usage: scutil --nc ondemand [-W] [hostname]\n"
					    "       scutil --nc ondemand -- --refresh\n"));
		goto done;
	}

	key = SCDynamicStoreKeyCreateNetworkGlobalEntity(NULL, kSCDynamicStoreDomainState, kSCEntNetOnDemand);

	if (ondemand_nodename) {
		checkOnDemandHost(store, ondemand_nodename, FALSE);
		checkOnDemandHost(store, ondemand_nodename, TRUE);
	} else {
		ondemand_dict = SCDynamicStoreCopyValue(store, key);
		if (ondemand_dict) {
			SCPrint(TRUE, stdout, CFSTR("%@ %@\n"), kSCEntNetOnDemand, ondemand_dict);
		} else {
			SCPrint(TRUE, stdout, CFSTR("%@ not configured\n"), kSCEntNetOnDemand);
		}
	}

	if (ondemandwatch) {
		CFMutableArrayRef	keys	= NULL;

		keys = CFArrayCreateMutable(NULL, 0, &kCFTypeArrayCallBacks);
		CFArrayAppendValue(keys, key);
		SCDynamicStoreSetNotificationKeys(store, keys, NULL);

		my_CFRelease(&keys);

		SCDynamicStoreSetDispatchQueue(store, dispatch_get_main_queue());

		CFRunLoopRun();
	}

	exit_code = 0;
done:
	my_CFRelease(&ondemand_dict);
	my_CFRelease(&key);
	my_CFRelease(&store);
	my_CFRelease(&ondemand_nodename);
	exit(exit_code);
}
Beispiel #22
0
int set_global_proxy(int enable, const char* host, int port)
{
    printf("set global proxy %d %s %d\n", enable, host, port);
    SCPreferencesRef pref = SCPreferencesCreate(kCFAllocatorSystemDefault, CFSTR("setproxy"), 0); 
    if(!pref){
        printf("Failed to open preference.\n");
        return 1;
    }   
    CFDictionaryRef set = SCPreferencesPathGetValue(pref, CFSTR("/NetworkServices/"));
    if(!set){
        printf("Failed to get network services.\n");
    }   
    CFMutableDictionaryRef mset = CFDictionaryCreateMutableCopy(0, 0, set);

    SCDynamicStoreRef theDynamicStore = SCDynamicStoreCreate(nil, CFSTR("setproxy"), nil, nil);
    CFDictionaryRef returnedPList;
    returnedPList = (CFDictionaryRef)SCDynamicStoreCopyValue(theDynamicStore, CFSTR("State:/Network/Global/IPv4"));
    CFStringRef primaryService = NULL;
    if(returnedPList){
        primaryService = (CFStringRef)CFDictionaryGetValue(returnedPList, CFSTR("PrimaryService"));
    }   

    size_t size = CFDictionaryGetCount(set);
    CFTypeRef *keysTypeRef = (CFTypeRef *) malloc( size * sizeof(CFTypeRef) );
    CFTypeRef *valuesTypeRef = (CFTypeRef *) malloc( size * sizeof(CFTypeRef) );
    CFDictionaryGetKeysAndValues(set, (const void **) keysTypeRef, (const void**)valuesTypeRef);
    const void **keys = (const void **) keysTypeRef;
    printf("Number of interfaces = %ld\n", size);
    int i;
    for(i=0; i<size && keysTypeRef[i]; i++){
        Boolean success;
        CFStringRef service = (CFStringRef)keysTypeRef[i];

        printf("Setting interface %d\n", i);

        if(enable == 1 && primaryService && CFStringCompare(service, primaryService, kCFCompareCaseInsensitive) != 0){
            continue;
        }

        CFTypeRef value = valuesTypeRef[i];
        if(!value){
            continue;
        }
        CFDictionaryRef face = (CFDictionaryRef)value;

        CFMutableDictionaryRef mface = CFDictionaryCreateMutableCopy(0, 0, face);
        CFMutableDictionaryRef mproxy = NULL;
        CFDictionaryRef proxy = (CFDictionaryRef)CFDictionaryGetValue(mface, CFSTR("Proxies"));
        if(NULL == proxy){
            if(enable == 0){
                CFRelease(mface);
                continue;
            }
            printf("proxy = %p, try to create it\n", proxy);
            mproxy = CFDictionaryCreateMutable(kCFAllocatorDefault, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
        }else{
            mproxy = CFDictionaryCreateMutableCopy(0, 0, proxy);
            if(mproxy == NULL)
                return 4;
        }

        if(enable){
            CFStringRef cfHost = CFStringCreateWithCString(0, host, kCFStringEncodingASCII);
            CFDictionarySetValue(mproxy, CFSTR("HTTPEnable"), CFNumberCreate(0, kCFNumberIntType, &enable));
            CFDictionarySetValue(mproxy, CFSTR("HTTPProxy"), cfHost);
            CFDictionarySetValue(mproxy, CFSTR("HTTPPort"), CFNumberCreate(0, kCFNumberIntType, &port));
            CFDictionarySetValue(mproxy, CFSTR("HTTPSEnable"), CFNumberCreate(0, kCFNumberIntType, &enable));
            CFDictionarySetValue(mproxy, CFSTR("HTTPSProxy"), cfHost);
            CFDictionarySetValue(mproxy, CFSTR("HTTPSPort"), CFNumberCreate(0, kCFNumberIntType, &port));
            CFRelease(cfHost);
        }else{
            CFDictionaryRemoveValue(mproxy, CFSTR("HTTPEnable"));
            CFDictionaryRemoveValue(mproxy, CFSTR("HTTPProxy"));
            CFDictionaryRemoveValue(mproxy, CFSTR("HTTPPort"));
            CFDictionaryRemoveValue(mproxy, CFSTR("HTTPSEnable"));
            CFDictionaryRemoveValue(mproxy, CFSTR("HTTPSProxy"));
            CFDictionaryRemoveValue(mproxy, CFSTR("HTTPSPort"));
        }

        CFDictionarySetValue(mface, CFSTR("Proxies"), mproxy);
        CFDictionarySetValue(mset, service, mface);

        SCPreferencesPathSetValue(pref, CFSTR("/NetworkServices/"), mset);
        success = SCPreferencesCommitChanges(pref);
        printf("success: %d\n", success);
        success = SCPreferencesApplyChanges(pref);
        printf("success: %d\n", success);

        CFRelease(mface);
        CFRelease(mproxy);
    }

    CFRelease(mset);
    CFRelease(pref);
    free(keysTypeRef);
    free(valuesTypeRef);
}
void PcapLiveDeviceList::setDnsServers()
{
#ifdef WIN32
	FIXED_INFO * fixedInfo;
	ULONG    ulOutBufLen;
	DWORD    dwRetVal;
	IP_ADDR_STRING * pIPAddr;

	uint8_t buf1[sizeof(FIXED_INFO)];
	fixedInfo = (FIXED_INFO *) buf1;
	ulOutBufLen = sizeof( FIXED_INFO );

	dwRetVal = GetNetworkParams( fixedInfo, &ulOutBufLen );
	uint8_t buf2[ulOutBufLen];
	if(ERROR_BUFFER_OVERFLOW == dwRetVal)
	{
		fixedInfo = (FIXED_INFO *)buf2;
	}

	if ((dwRetVal = GetNetworkParams( fixedInfo, &ulOutBufLen )) != 0)
		LOG_ERROR("Call to GetNetworkParams failed. Return Value: %08lx\n", dwRetVal);
	else
	{
		m_DnsServers.push_back(IPv4Address(fixedInfo->DnsServerList.IpAddress.String));
		int i = 1;
		LOG_DEBUG("Default DNS server IP #%d: %s\n", i++, fixedInfo->DnsServerList.IpAddress.String );

		pIPAddr = fixedInfo->DnsServerList.Next;
		while ( pIPAddr )
		{
			m_DnsServers.push_back(IPv4Address(pIPAddr->IpAddress.String));
			LOG_DEBUG("Default DNS server IP #%d: %s\n", i++, pIPAddr->IpAddress.String);
			pIPAddr = pIPAddr -> Next;
		}
	}
#elif LINUX
	std::string command = "nmcli dev list | grep IP4.DNS";
	std::string dnsServersInfo = executeShellCommand(command);
	if (dnsServersInfo == "")
	{
		LOG_DEBUG("Error retrieving DNS server list: call to nmcli gave no output");
		return;
	}

	std::istringstream stream(dnsServersInfo);
	std::string line;
	int i = 1;
	while(std::getline(stream, line))
	{
		std::istringstream lineStream(line);
		std::string headline;
		std::string dnsIP;
		lineStream >> headline;
		lineStream >> dnsIP;
		IPv4Address dnsIPAddr(dnsIP);
		if (!dnsIPAddr.isValid())
			continue;

		if (std::find(m_DnsServers.begin(), m_DnsServers.end(), dnsIPAddr) == m_DnsServers.end())
		{
			m_DnsServers.push_back(dnsIPAddr);
			LOG_DEBUG("Default DNS server IP #%d: %s\n", i++, dnsIPAddr.toString().c_str());
		}
	}
#elif MAC_OS_X

	SCDynamicStoreRef dynRef = SCDynamicStoreCreate(kCFAllocatorSystemDefault, CFSTR("iked"), NULL, NULL);
	if (dynRef == NULL)
	{
		LOG_DEBUG("Couldn't set DNS server list: failed to retrieve SCDynamicStore");
		return;
	}

	CFDictionaryRef dnsDict = (CFDictionaryRef)SCDynamicStoreCopyValue(dynRef,CFSTR("State:/Network/Global/DNS"));

	if (dnsDict == NULL)
	{
		LOG_DEBUG("Couldn't set DNS server list: failed to get DNS dictionary");
		CFRelease(dynRef);
		return;
	}

	CFArrayRef serverAddresses = (CFArrayRef)CFDictionaryGetValue(dnsDict, CFSTR("ServerAddresses"));

	if (serverAddresses == NULL)
	{
		LOG_DEBUG("Couldn't set DNS server list: server addresses array is null");
		CFRelease(dynRef);
		CFRelease(dnsDict);
		return;
	}

	CFIndex count = CFArrayGetCount(serverAddresses);
	for (CFIndex i = 0; i < count; i++)
	{
		CFStringRef serverAddress = (CFStringRef)CFArrayGetValueAtIndex(serverAddresses, i);

		if (serverAddress == NULL)
			continue;

		uint8_t buf[20];
		char* serverAddressCString = (char*)buf;
		CFStringGetCString(serverAddress, serverAddressCString, 20, kCFStringEncodingUTF8);
		m_DnsServers.push_back(IPv4Address(serverAddressCString));
		LOG_DEBUG("Default DNS server IP #%d: %s\n", (int)(i+1), serverAddressCString);
	}

	CFRelease(dynRef);
	CFRelease(dnsDict);
#endif
}
Beispiel #24
0
static void
dnssdUpdateDNSSDName(int from_callback)	/* I - Called from callback? */
{
  char		webif[1024];		/* Web interface share name */
#  ifdef __APPLE__
  SCDynamicStoreRef sc;			/* Context for dynamic store */
  CFDictionaryRef btmm;			/* Back-to-My-Mac domains */
  CFStringEncoding nameEncoding;	/* Encoding of computer name */
  CFStringRef	nameRef;		/* Host name CFString */
  char		nameBuffer[1024];	/* C-string buffer */
#  endif /* __APPLE__ */


 /*
  * Only share the web interface and printers when non-local listening is
  * enabled...
  */

  if (!DNSSDPort)
  {
   /*
    * Get the port we use for registrations.  If we are not listening on any
    * non-local ports, there is no sense sharing local printers via Bonjour...
    */

    cupsd_listener_t	*lis;		/* Current listening socket */

    for (lis = (cupsd_listener_t *)cupsArrayFirst(Listeners);
	 lis;
	 lis = (cupsd_listener_t *)cupsArrayNext(Listeners))
    {
      if (httpAddrLocalhost(&(lis->address)))
	continue;

      DNSSDPort = httpAddrPort(&(lis->address));
      break;
    }
  }

  if (!DNSSDPort)
    return;

 /*
  * Get the computer name as a c-string...
  */

#  ifdef __APPLE__
  sc = SCDynamicStoreCreate(kCFAllocatorDefault, CFSTR("cupsd"), NULL, NULL);

  if (sc)
  {
   /*
    * Get the computer name from the dynamic store...
    */

    cupsdClearString(&DNSSDComputerName);

    if ((nameRef = SCDynamicStoreCopyComputerName(sc, &nameEncoding)) != NULL)
    {
      if (CFStringGetCString(nameRef, nameBuffer, sizeof(nameBuffer),
			     kCFStringEncodingUTF8))
      {
        cupsdLogMessage(CUPSD_LOG_DEBUG,
	                "Dynamic store computer name is \"%s\".", nameBuffer);
	cupsdSetString(&DNSSDComputerName, nameBuffer);
      }

      CFRelease(nameRef);
    }

    if (!DNSSDComputerName)
    {
     /*
      * Use the ServerName instead...
      */

      cupsdLogMessage(CUPSD_LOG_DEBUG,
                      "Using ServerName \"%s\" as computer name.", ServerName);
      cupsdSetString(&DNSSDComputerName, ServerName);
    }

   /*
    * Get the local hostname from the dynamic store...
    */

    cupsdClearString(&DNSSDHostName);

    if ((nameRef = SCDynamicStoreCopyLocalHostName(sc)) != NULL)
    {
      if (CFStringGetCString(nameRef, nameBuffer, sizeof(nameBuffer),
			     kCFStringEncodingUTF8))
      {
        cupsdLogMessage(CUPSD_LOG_DEBUG,
	                "Dynamic store host name is \"%s\".", nameBuffer);
	cupsdSetString(&DNSSDHostName, nameBuffer);
      }

      CFRelease(nameRef);
    }

    if (!DNSSDHostName)
    {
     /*
      * Use the ServerName instead...
      */

      cupsdLogMessage(CUPSD_LOG_DEBUG,
                      "Using ServerName \"%s\" as host name.", ServerName);
      cupsdSetString(&DNSSDHostName, ServerName);
    }

   /*
    * Get any Back-to-My-Mac domains and add them as aliases...
    */

    cupsdFreeAliases(DNSSDAlias);
    DNSSDAlias = NULL;

    btmm = SCDynamicStoreCopyValue(sc, CFSTR("Setup:/Network/BackToMyMac"));
    if (btmm && CFGetTypeID(btmm) == CFDictionaryGetTypeID())
    {
      cupsdLogMessage(CUPSD_LOG_DEBUG, "%d Back to My Mac aliases to add.",
		      (int)CFDictionaryGetCount(btmm));
      CFDictionaryApplyFunction(btmm, dnssdAddAlias, NULL);
    }
    else if (btmm)
      cupsdLogMessage(CUPSD_LOG_ERROR,
		      "Bad Back to My Mac data in dynamic store!");
    else
      cupsdLogMessage(CUPSD_LOG_DEBUG, "No Back to My Mac aliases to add.");

    if (btmm)
      CFRelease(btmm);

    CFRelease(sc);
  }
  else
#  endif /* __APPLE__ */
#  ifdef HAVE_AVAHI
  if (DNSSDClient)
  {
    const char	*host_name = avahi_client_get_host_name(DNSSDClient);
    const char	*host_fqdn = avahi_client_get_host_name_fqdn(DNSSDClient);

    cupsdSetString(&DNSSDComputerName, host_name ? host_name : ServerName);

    if (host_fqdn)
      cupsdSetString(&DNSSDHostName, host_fqdn);
    else if (strchr(ServerName, '.'))
      cupsdSetString(&DNSSDHostName, ServerName);
    else
      cupsdSetStringf(&DNSSDHostName, "%s.local", ServerName);
  }
  else
#  endif /* HAVE_AVAHI */
  {
    cupsdSetString(&DNSSDComputerName, ServerName);

    if (strchr(ServerName, '.'))
      cupsdSetString(&DNSSDHostName, ServerName);
    else
      cupsdSetStringf(&DNSSDHostName, "%s.local", ServerName);
  }

 /*
  * Then (re)register the web interface if enabled...
  */

  if (BrowseWebIF)
  {
    if (DNSSDComputerName)
      snprintf(webif, sizeof(webif), "CUPS @ %s", DNSSDComputerName);
    else
      strlcpy(webif, "CUPS", sizeof(webif));

    dnssdDeregisterInstance(&WebIFSrv, from_callback);
    dnssdRegisterInstance(&WebIFSrv, NULL, webif, "_http._tcp", "_printer", DNSSDPort, NULL, 1, from_callback);
  }
}
Beispiel #25
0
HRESULT HostDnsServiceDarwin::update()
{
    m_llNameServers.clear();
    m_llSearchStrings.clear();
    m_DomainName.setNull();

    CFPropertyListRef propertyRef = SCDynamicStoreCopyValue(g_store,
                                                            kStateNetworkGlobalDNSKey);
    /**
     * 0:vvl@nb-mbp-i7-2(0)# scutil
     * > get State:/Network/Global/DNS
     * > d.show
     * <dictionary> {
     * DomainName : vvl-domain
     * SearchDomains : <array> {
     * 0 : vvl-domain
     * 1 : de.vvl-domain.com
     * }
     * ServerAddresses : <array> {
     * 0 : 192.168.1.4
     * 1 : 192.168.1.1
     * 2 : 8.8.4.4
     *   }
     * }
     */

    if (!propertyRef)
        return S_OK;

    CFStringRef domainNameRef = (CFStringRef)CFDictionaryGetValue(
      static_cast<CFDictionaryRef>(propertyRef), CFSTR("DomainName"));
    if (domainNameRef)
    {
        const char *pszDomainName = CFStringGetCStringPtr(domainNameRef,
                                                    CFStringGetSystemEncoding());
        if (pszDomainName)
            m_DomainName = com::Utf8Str(pszDomainName);
    }

    int i, arrayCount;
    CFArrayRef serverArrayRef = (CFArrayRef)CFDictionaryGetValue(
      static_cast<CFDictionaryRef>(propertyRef), CFSTR("ServerAddresses"));
    if (serverArrayRef)
    {
        arrayCount = CFArrayGetCount(serverArrayRef);
        for (i = 0; i < arrayCount; ++i)
        {
            CFStringRef serverAddressRef = (CFStringRef)CFArrayGetValueAtIndex(serverArrayRef, i);
            if (!serverArrayRef)
                continue;

            const char *pszServerAddress = CFStringGetCStringPtr(serverAddressRef,
                                                           CFStringGetSystemEncoding());
            if (!pszServerAddress)
                continue;

            m_llNameServers.push_back(com::Utf8Str(pszServerAddress));
        }
    }

    CFArrayRef searchArrayRef = (CFArrayRef)CFDictionaryGetValue(
      static_cast<CFDictionaryRef>(propertyRef), CFSTR("SearchDomains"));
    if (searchArrayRef)
    {
        arrayCount = CFArrayGetCount(searchArrayRef);

        for (i = 0; i < arrayCount; ++i)
        {
            CFStringRef searchStringRef = (CFStringRef)CFArrayGetValueAtIndex(searchArrayRef, i);
            if (!searchArrayRef)
                continue;

            const char *pszSearchString = CFStringGetCStringPtr(searchStringRef,
                                                          CFStringGetSystemEncoding());
            if (!pszSearchString)
                continue;

            m_llSearchStrings.push_back(com::Utf8Str(pszSearchString));
        }
    }

    CFRelease(propertyRef);
    this->HostDnsService::update();

    return S_OK;
}
Beispiel #26
0
CFNetDiagnosticStatus CFNetDiagnosticCopyNetworkStatusPassively(CFNetDiagnosticRef details, CFStringRef *description) {
	CFMutableDictionaryRef detailsDict = (CFMutableDictionaryRef)details;
	CFNetDiagnosticStatus retval = kCFNetDiagnosticConnectionIndeterminate;
	CFStringRef serviceID;
	SCDynamicStoreRef store;

	
	store = SCDynamicStoreCreate(kCFAllocatorDefault, CFSTR("CFNetDiagnostics"), NULL, NULL);
	
	if(store) {
	
		
		serviceID = CFDictionaryGetValue(detailsDict, _CFNetDiagnosticServiceIDKey);
		if(serviceID) {
			//If there is a specific ServiceID we only scan on it. We can only get in this position through SPIs
			retval = _CFNetDiagnosticCopyNetworkStatusPassivelyInterfaceSpecific(store, serviceID, description);
		} else {
			//Iterate through all serviceIDs. If any are good, then we return it
			CFStringRef pattern = NULL;
			CFDictionaryRef dict = NULL;
			CFArrayRef serviceOrder = NULL;
			CFIndex i, count;
			CFNetDiagnosticStatus serviceState = kCFNetDiagnosticConnectionDown;
			
			pattern = SCDynamicStoreKeyCreateNetworkGlobalEntity( NULL,
                                        (CFStringRef) kSCDynamicStoreDomainSetup,
                                        (CFStringRef) kSCEntNetIPv4 );
			
			if(pattern) {
				dict =  SCDynamicStoreCopyValue( store, pattern );
				CFRelease( pattern );
			}
			
			if(dict) {
				serviceOrder = CFDictionaryGetValue(dict, CFSTR("ServiceOrder"));
				CFRetain(serviceOrder);
				CFRelease(dict);
			}
			
			if(serviceOrder) {
				count = CFArrayGetCount(serviceOrder);
				retval = kCFNetDiagnosticConnectionDown;
				
				for ( i = 0; i < count; i++ ) {
					serviceID = CFArrayGetValueAtIndex(serviceOrder, i);
					serviceState = _CFNetDiagnosticCopyNetworkStatusPassivelyInterfaceSpecific(store, serviceID, description);
				
					if(serviceState == kCFNetDiagnosticConnectionDown) {
						retval = kCFNetDiagnosticConnectionDown;
						if (description) {
							*description = CFCopyLocalizedStringFromTableInBundle( CFSTR("CONNECTION_DOWN"),
																		NULL,
																		CFBundleGetBundleWithIdentifier(CFSTR("com.apple.CFNetwork")),
																		"This computer's Internet connect appears to be offline.");
						}
					} else if (serviceState == kCFNetDiagnosticConnectionIndeterminate) {
						retval = kCFNetDiagnosticConnectionIndeterminate;
						if (description) {
							*description = CFCopyLocalizedStringFromTableInBundle( CFSTR("CONNECTION_INDETERMINATE"),
																		NULL,
																		CFBundleGetBundleWithIdentifier(CFSTR("com.apple.CFNetwork")),
																		"This computer's Internet may be offline.");
						}
					} else if (serviceState == kCFNetDiagnosticConnectionUp) {
						retval = kCFNetDiagnosticConnectionUp;
						if (description) {
							*description = CFCopyLocalizedStringFromTableInBundle( CFSTR("CONNECTION_UP"),
																		NULL,
																		CFBundleGetBundleWithIdentifier(CFSTR("com.apple.CFNetwork")),
																		"This computer's Internet may be online.");
						}
						break;
					} else {
						//FIXME
						//NOT REACHED log an error
					}
				}
				CFRelease(serviceOrder);
			}
		}
	
		CFRelease(store);
	}
	
	return retval;
}