Beispiel #1
0
static void
encodeName(CFStringRef			name,
	   CFStringEncoding		encoding,
	   CFMutableDictionaryRef	startup,
	   CFMutableDictionaryRef	globals)
{
	CFDataRef		bytes;
	CFMutableStringRef	encodedName = NULL;
	CFIndex			len;

	if (!isA_CFString(name)) {
		return;
	}

	if (encoding == kCFStringEncodingASCII) {
		encodedName = (CFMutableStringRef)CFStringCreateCopy(NULL, name);
		goto done;
	}

	/*
	 * encode the potentially non-printable string
	 */
	bytes = CFStringCreateExternalRepresentation(NULL,
						     name,
						     encoding,
						     0);
	if (bytes) {
		unsigned char	*byte;
		CFIndex		i;

		/*
		 * check if the MacRoman string can be represented as ASCII
		 */
		if (encoding == kCFStringEncodingMacRoman) {
			CFDataRef       ascii;

			ascii = CFStringCreateExternalRepresentation(NULL,
								     name,
								     kCFStringEncodingASCII,
								     0);
			if (ascii) {
				CFRelease(ascii);
				CFRelease(bytes);
				encodedName = (CFMutableStringRef)CFStringCreateCopy(NULL, name);
				goto done;
			}
		}

		encodedName = CFStringCreateMutable(NULL, 0);

		len  = CFDataGetLength(bytes);
		byte = (unsigned char *)CFDataGetBytePtr(bytes);
		for (i = 0; i < len; i++, byte++) {
			CFStringAppendFormat(encodedName,
					     NULL,
					     CFSTR("%02x"),
					     *byte);
		}

		/*
		 * add "encoded string" markers
		 */
		CFStringInsert(encodedName, 0, CFSTR("*"));
		CFStringAppend(encodedName,    CFSTR("*"));

		CFRelease(bytes);
	}

    done :

	if (encodedName) {
		if (startup) {
			/* update "startup" dictionary */
			CFDictionaryAddValue(startup, CFSTR("APPLETALK_HOSTNAME"), encodedName);
		}

		if (globals) {
			CFNumberRef	num;

			/* update "global" dictionary */
			num = CFNumberCreate(NULL, kCFNumberIntType, &encoding);
			CFDictionaryAddValue(globals, kSCPropNetAppleTalkComputerName,         name);
			CFDictionaryAddValue(globals, kSCPropNetAppleTalkComputerNameEncoding, num);
			CFRelease(num);
		}

		CFRelease(encodedName);
	}

	return;
}
Beispiel #2
0
CFStringRef GetDataTypePropValueAndSizeAsString(QTPropertyValuePtr keyValuePtr, ByteCount propValueSize)
{
	CFMutableStringRef destStrRef = CFStringCreateMutable(kCFAllocatorDefault, 0);

	CFStringRef sizeStrRef = CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR("(%d bytes) : "), propValueSize);
	CFStringAppend (destStrRef, sizeStrRef);
	CFRelease(sizeStrRef);
	
	CFStringRef		vals[] = {	CFSTR("0=Binary"),
								CFSTR("1=UTF8"),
                                CFSTR("2=UTF16BE"),
                                CFSTR("3=MacEncodedText"),
                                CFSTR("12=GIF"),
                                CFSTR("13=JPEG"),
                                CFSTR("14=PNG"),
								CFSTR("21=SignedIntegerBE"),
                                CFSTR("22=UnsignedIntegerBE"), 
								CFSTR("23=Float32BE"),
                                CFSTR("24=Float64BE"),
                                CFSTR("27=BMP"),
                                CFSTR("28=QuickTimeMetaData")	};
                                
	UInt32 keyNums[] = {	kQTMetaDataTypeBinary,
    						kQTMetaDataTypeUTF8,
							kQTMetaDataTypeUTF16BE,
                            kQTMetaDataTypeMacEncodedText,
							kMyQTMetaDataTypeGIF,
							kQTMetaDataTypeJPEGImage,
							kQTMetaDataTypePNGImage,
							kQTMetaDataTypeSignedIntegerBE,
							kQTMetaDataTypeUnsignedIntegerBE,
							kQTMetaDataTypeFloat32BE,
							kQTMetaDataTypeFloat64BE,
                        	kQTMetaDataTypeBMPImage,
                            kQTMetaDataTypeQuickTimeMetaData	};

	CFTypeRef		keys[] = {	(CFTypeRef)CFNumberCreate(nil, kCFNumberLongType, (void *)&keyNums[0]), 
								(CFTypeRef)CFNumberCreate(nil, kCFNumberLongType, (void *)&keyNums[1]), 
								(CFTypeRef)CFNumberCreate(nil, kCFNumberLongType, (void *)&keyNums[2]),
								(CFTypeRef)CFNumberCreate(nil, kCFNumberLongType, (void *)&keyNums[3]), 
								(CFTypeRef)CFNumberCreate(nil, kCFNumberLongType, (void *)&keyNums[4]), 
								(CFTypeRef)CFNumberCreate(nil, kCFNumberLongType, (void *)&keyNums[5]),
								(CFTypeRef)CFNumberCreate(nil, kCFNumberLongType, (void *)&keyNums[6]), 
								(CFTypeRef)CFNumberCreate(nil, kCFNumberLongType, (void *)&keyNums[7]),
                                (CFTypeRef)CFNumberCreate(nil, kCFNumberLongType, (void *)&keyNums[8]),
                                (CFTypeRef)CFNumberCreate(nil, kCFNumberLongType, (void *)&keyNums[9]),
                                (CFTypeRef)CFNumberCreate(nil, kCFNumberLongType, (void *)&keyNums[10]),
                                (CFTypeRef)CFNumberCreate(nil, kCFNumberLongType, (void *)&keyNums[11]),
                                (CFTypeRef)CFNumberCreate(nil, kCFNumberLongType, (void *)&keyNums[12])		};
							 																			
	CFDictionaryRef dictRef = CFDictionaryCreate(kCFAllocatorDefault, (const void **)keys, (const void **)vals, 13, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);

	UInt32 *dataType = keyValuePtr;
	CFStringRef theStringRef = (CFStringRef)CFDictionaryGetValue(dictRef, (CFTypeRef)CFNumberCreate(nil, kCFNumberLongType, (void *)dataType));
	
    // be safe if the kQTMetaDataItemPropertyID_DataType isn't in our list
    if (theStringRef == NULL) theStringRef = CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR("kQTMetaDataItemPropertyID_DataType %d unknown"), *((UInt32 *)(keyValuePtr)));
        
    CFStringAppend(destStrRef, theStringRef);
    CFRelease(theStringRef);
    
	CFStringAppend (destStrRef, CFSTR("\n"));
    
    CFRelease(dictRef);

	return destStrRef;
}
Beispiel #3
0
/* 
   Parses command line options for the VM options, properties,
   main class, and main class args and returns them in the VMLaunchOptions
   structure.
*/
VMLaunchOptions * NewVMLaunchOptions(int argc, const char **currentArg) 
{
    int ArgIndex = 0; 
    
    /* The following Strings are used to convert the command line -cp to -Djava.class.path= */
    CFStringRef classPathOption = CFSTR("-cp");
    CFStringRef classPathDefine = CFSTR("-Djava.class.path=");

    /* vmOptionsCFArrayRef will temporarly hold a list of VM options and properties to be passed in when
       creating the JVM
    */
    CFMutableArrayRef vmOptionsCFArrayRef = CFArrayCreateMutable(NULL,0,&kCFTypeArrayCallBacks);
    
    /* mainArgsCFArrayRef will temporarly hold a list of arguments to be passed to the main method of the
       main class
    */
    CFMutableArrayRef mainArgsCFArrayRef = CFArrayCreateMutable(NULL,0,&kCFTypeArrayCallBacks);

    /* Allocated the structure that will be used to return the launch options */
    VMLaunchOptions * vmLaunchOptions = malloc(sizeof(VMLaunchOptions));
    
    /* Start with the first arg, not the path to the tool */
    ArgIndex++;
    currentArg++;
    
    /* JVM options start with - */
    while(ArgIndex < argc && **currentArg == '-') {
        CFMutableStringRef option = CFStringCreateMutable(NULL, 0);
        CFStringAppendCString(option, *currentArg, kCFStringEncodingUTF8);
        
        /* If the option string is '-cp', replace it with '-Djava.class.path=' and append
            then next option which contains the actuall class path.
        */
        CFRange rangeToSearch = CFRangeMake(0,CFStringGetLength(option));
        if (CFStringFindAndReplace(option, classPathOption, classPathDefine, rangeToSearch, kCFCompareAnchored) != 0) {
            /* So the option was -cp, and we replaced it with -Djava.class.path= */
            /* Now append the next option which is the actuall class path */
            currentArg++;
            ArgIndex++;        
            if (ArgIndex < argc) {
                CFStringAppendCString(option, *currentArg, kCFStringEncodingUTF8);
            } else {
                /* We shouldn't reach here unless the last arg was -cp */
                fprintf(stderr, "[JavaAppLauncher Error] Error parsing class path.\n");
                /* Release the option CFString heresince the break; statement is going */
                /* to skip the release in this loop */
                CFRelease(option);
                break;
            }
        }

        /* Add this to our list of JVM options */
        CFArrayAppendValue(vmOptionsCFArrayRef,option);
        /* When an object is added to a CFArray the array retains a reference to it, this means */
        /* we need to release the object so that the memory will be freed when we release the CFArray. */
        CFRelease(option);

        /* On to the next one */
        currentArg++;
        ArgIndex++;        
    }
    
    /* Now we know how many JVM options there are and they are all in a CFArray of CFStrings. */
    vmLaunchOptions->nOptions = CFArrayGetCount(vmOptionsCFArrayRef);
    /* We only need to do this if there are options */
    if ( vmLaunchOptions->nOptions > 0) {
        int index;
        /* Allocate some memory for the array of JavaVMOptions */
        JavaVMOption * option = malloc(vmLaunchOptions->nOptions*sizeof(JavaVMOption));
        vmLaunchOptions->options = option;

        /* Itterate over each option adding it to the JavaVMOptions array */
        for(index = 0;index < vmLaunchOptions->nOptions; index++, option++) {
            /* Allocate enough memory for each optionString char* to hold the max possible lengh a UTF8 */
            /* encoded copy of the string would require */
            CFStringRef optionStringRef = (CFStringRef)CFArrayGetValueAtIndex(vmOptionsCFArrayRef,index);
            CFIndex optionStringSize = CFStringGetMaximumSizeForEncoding(CFStringGetLength(optionStringRef), kCFStringEncodingUTF8);
            option->extraInfo = NULL;
            option->optionString = malloc(optionStringSize+1);
            /* Now copy the option into the the optionString char* buffer in a UTF8 encoding */
            if (!CFStringGetCString(optionStringRef, (char *)option->optionString, optionStringSize, kCFStringEncodingUTF8)) {
                fprintf(stderr, "[JavaAppLauncher Error] Error parsing JVM options.\n");
                exit(-1);
            }
        }
        
    } else {
        vmLaunchOptions->options = NULL;
    }

    /* Now we know how many args for main there are and they are all in a CFArray of CFStrings. */
    vmLaunchOptions->numberOfArgs = CFArrayGetCount(mainArgsCFArrayRef);
    /* We only need to do this if there are args */
    if ( vmLaunchOptions->numberOfArgs > 0) {
        int index;
        char ** arg;
        /* Allocate some memory for the array of char *'s */
        vmLaunchOptions->args = malloc(vmLaunchOptions->numberOfArgs*sizeof(char *));
                
        for(index = 0, arg = vmLaunchOptions->args;index < vmLaunchOptions->numberOfArgs; index++, arg++)
        {
            /* Allocate enough memory for each arg char* to hold the max possible lengh a UTF8 */
            /* encoded copy of the string would require */
            CFStringRef argStringRef = (CFStringRef)CFArrayGetValueAtIndex(mainArgsCFArrayRef,index);
            CFIndex argStringSize = CFStringGetMaximumSizeForEncoding(CFStringGetLength(argStringRef), kCFStringEncodingUTF8);
            *arg = (char*)malloc(argStringSize+1);
            /* Now copy the arg into the the args char* buffer in a UTF8 encoding */
            if (!CFStringGetCString(argStringRef, *arg, argStringSize, kCFStringEncodingUTF8)) {
                fprintf(stderr, "[JavaAppLauncher Error] Error parsing args.\n");
                exit(-1);
            }
        }
        
    } else {
        vmLaunchOptions->args = NULL;
    }    
    /* Free the Array's holding our options and args */
    /* Releaseing an array also releases its references to the objects it contains */
    CFRelease(vmOptionsCFArrayRef);
    CFRelease(mainArgsCFArrayRef);
    return vmLaunchOptions;
}
Beispiel #4
0
int main(int argc, char * argv[]) {
    signal(SIGINT, sigint_handler);

    bool israw = false;
    bool readstdin = false;
    char* code = NULL;
    bool usecolors = true;

    int ch;
    while ((ch = getopt(argc, argv, "nirc:t:sh")) != -1) {
        switch (ch) {
            case 'n': usecolors = false; break;
            case 'i': break;
            case 'r': israw = true; break;
            case 'c': code = optarg; break;
            case 't': recvTimeout = strtod(optarg, NULL); break;
            case 's': readstdin = true; break;
            case 'h': case '?': default:
                usage(argv[0]);
        }
    }

    if (optind != argc) usage(argv[0]);

    argc -= optind;
    argv += optind;

    CFMessagePortRef port = CFMessagePortCreateRemote(NULL, CFSTR("Hammerspoon"));

    if (!port) {
        fprintf(stderr, "error: can't access Hammerspoon; is it running with the ipc module loaded?\n");
        return 1;
    }

    CFMutableStringRef str = CFStringCreateMutable(NULL, 0);

    if (readstdin) {
        target_setprefix(str, israw);

        char buffer[BUFSIZ];
        while (fgets(buffer, BUFSIZ, stdin))
            CFStringAppendCString(str, buffer, kCFStringEncodingUTF8);

        if (ferror(stdin)) {
            perror("error reading from stdin.");
            exit(3);
        }

        target_send(port, str);
    }
    else if (code) {
        target_setprefix(str, israw);
        CFStringAppendCString(str, code, kCFStringEncodingUTF8);
        target_send(port, str);
    }
    else {
        if (usecolors)
            setupcolors();

        printf("%sHammerspoon interactive prompt.%s\n", COLOR_INITIAL, COLOR_RESET);

        while (1) {
            printf("\n%s", COLOR_INPUT);
            char* input = readline("> ");
            printf("%s", COLOR_RESET);
            if (!input) { printf("\n") ; exit(0); }
            add_history(input);

            if (!CFMessagePortIsValid(port)) {
                fprintf(stderr, "%sMessage port has become invalid.  Attempting to re-establish.%s\n", COLOR_INITIAL, COLOR_RESET);
                port = CFMessagePortCreateRemote(NULL, CFSTR("Hammerspoon"));
                if (!port) {
                    fprintf(stderr, "error: can't access Hammerspoon; is it running?\n");
                    exit(1);
                }

            }

            target_setprefix(str, israw);
            CFStringAppendCString(str, input, kCFStringEncodingUTF8);
            target_send(port, str);
            CFStringDelete(str, CFRangeMake(0, CFStringGetLength(str)));

            free(input);
        }
    }

    return 0;
}
Beispiel #5
0
void GourceSettings::importGourceSettings(ConfFile& conffile, ConfSection* gource_settings) {

    setGourceDefaults();

    if(gource_settings == 0) gource_settings = conffile.getSection(default_section_name);

    if(gource_settings == 0) {
        gource_settings = conffile.addSection("gource");
    }

    ConfEntry* entry = 0;

    //hide flags

    std::vector<std::string> hide_fields;

    if((entry = gource_settings->getEntry("hide")) != 0) {

        if(!entry->hasValue()) conffile.missingValueException(entry);

        std::string hide_string = entry->getString();

        size_t sep;
        while((sep = hide_string.find(",")) != std::string::npos) {

            if(sep == 0 && hide_string.size()==1) break;

            if(sep == 0) {
                hide_string = hide_string.substr(sep+1, hide_string.size()-1);
                continue;
            }

            std::string hide_field  = hide_string.substr(0, sep);
            hide_fields.push_back(hide_field);
            hide_string = hide_string.substr(sep+1, hide_string.size()-1);
        }

        if(hide_string.size() > 0 && hide_string != ",") hide_fields.push_back(hide_string);

        //validate field list

        for(std::vector<std::string>::iterator it = hide_fields.begin(); it != hide_fields.end(); it++) {
            std::string hide_field = (*it);

            if(   hide_field != "date"
               && hide_field != "users"
               && hide_field != "tree"
               && hide_field != "files"
               && hide_field != "usernames"
               && hide_field != "filenames"
               && hide_field != "dirnames"
               && hide_field != "bloom"
               && hide_field != "progress"
               && hide_field != "mouse"
               && hide_field != "root") {
                std::string unknown_hide_option = std::string("unknown option hide ") + hide_field;
                conffile.entryException(entry, unknown_hide_option);
            }
        }
    }

    //check hide booleans
    for(std::map<std::string,std::string>::iterator it = arg_types.begin(); it != arg_types.end(); it++) {
        if(it->first.find("hide-") == 0 && it->second == "bool") {

            if(gource_settings->getBool(it->first)) {
                std::string hide_field = it->first.substr(5, it->first.size()-5);
                hide_fields.push_back(hide_field);
            }
        }
    }

    if(hide_fields.size()>0) {

        for(std::vector<std::string>::iterator it = hide_fields.begin(); it != hide_fields.end(); it++) {
            std::string hidestr = (*it);

                if(hidestr == "date")       hide_date      = true;
            else if(hidestr == "users")     hide_users     = true;
            else if(hidestr == "tree")      hide_tree      = true;
            else if(hidestr == "files")     hide_files     = true;
            else if(hidestr == "usernames") hide_usernames = true;
            else if(hidestr == "filenames") hide_filenames = true;
            else if(hidestr == "dirnames")  hide_dirnames  = true;
            else if(hidestr == "bloom")     hide_bloom     = true;
            else if(hidestr == "progress")  hide_progress  = true;
            else if(hidestr == "root")      hide_root      = true;
            else if(hidestr == "mouse")     {
                hide_mouse     = true;
                hide_progress  = true;
            }
        }
    }

    if((entry = gource_settings->getEntry("date-format")) != 0) {

        if(!entry->hasValue()) conffile.missingValueException(entry);

        date_format = entry->getString();
    }

    if(gource_settings->getBool("disable-auto-rotate")) {
        disable_auto_rotate=true;
    }

    if(gource_settings->getBool("disable-auto-skip")) {
        auto_skip_seconds = -1.0;
    }

    if(gource_settings->getBool("loop")) {
        loop = true;
    }

    if((entry = gource_settings->getEntry("git-branch")) != 0) {

        if(!entry->hasValue()) conffile.missingValueException(entry);

        git_branch = entry->getString();
    }

    if(gource_settings->getBool("colour-images")) {
        colour_user_images = true;
    }

    if((entry = gource_settings->getEntry("crop")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify crop (vertical,horizontal)");

        std::string crop = entry->getString();

        if(crop == "vertical") {
            crop_vertical = true;
        } else if (crop == "horizontal") {
            crop_horizontal = true;
        } else {
            conffile.invalidValueException(entry);
        }
    }

    if((entry = gource_settings->getEntry("log-format")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify log-format (format)");

        log_format = entry->getString();

        if(log_format == "cvs") {
            conffile.entryException(entry, "please use either 'cvs2cl' or 'cvs-exp'");
        }

        if(   log_format != "git"
           && log_format != "cvs-exp"
           && log_format != "cvs2cl"
           && log_format != "svn"
           && log_format != "custom"
           && log_format != "hg"
           && log_format != "bzr"
           && log_format != "apache") {

            conffile.invalidValueException(entry);
        }
    }

    if((entry = gource_settings->getEntry("default-user-image")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify default-user-image (image path)");

        default_user_image = entry->getString();
    }

    if((entry = gource_settings->getEntry("user-image-dir")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify user-image-dir (directory)");

        user_image_dir = entry->getString();

        //append slash
        if(user_image_dir[user_image_dir.size()-1] != '/') {
            user_image_dir += std::string("/");
        }

        //get jpg and png images in dir
        DIR *dp;
        struct dirent *dirp;

        user_image_map.clear();

        if((dp = opendir(gGourceSettings.user_image_dir.c_str())) != 0) {

            while ((dirp = readdir(dp)) != 0) {
                std::string dirfile = std::string(dirp->d_name);

                size_t extpos = 0;

                if(   (extpos=dirfile.rfind(".jpg"))  == std::string::npos
                && (extpos=dirfile.rfind(".jpeg")) == std::string::npos
                && (extpos=dirfile.rfind(".png"))  == std::string::npos) continue;


                std::string image_path = gGourceSettings.user_image_dir + dirfile;
                std::string name       = dirfile.substr(0,extpos);

#ifdef __APPLE__
                CFMutableStringRef help = CFStringCreateMutable(kCFAllocatorDefault, 0);
                CFStringAppendCString(help, name.c_str(), kCFStringEncodingUTF8);
                CFStringNormalize(help, kCFStringNormalizationFormC);
                char data[4096];
                CFStringGetCString(help,
                                   data,
                                   sizeof(data),
                                   kCFStringEncodingUTF8);
                name = data;
#endif

                debugLog("%s => %s\n", name.c_str(), image_path.c_str());

                user_image_map[name] = image_path;
            }

            closedir(dp);
        }
    }

    if((entry = gource_settings->getEntry("bloom-intensity")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify bloom-intensity (float)");

        bloom_intensity = entry->getFloat();

        if(bloom_intensity<=0.0f) {
            conffile.invalidValueException(entry);
        }
    }

    if((entry = gource_settings->getEntry("bloom-multiplier")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify bloom-multiplier (float)");

        bloom_multiplier = entry->getFloat();

        if(bloom_multiplier<=0.0f) {
            conffile.invalidValueException(entry);
        }
    }

    if((entry = gource_settings->getEntry("elasticity")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify elasticity (float)");

        elasticity = entry->getFloat();

        if(elasticity<=0.0f) {
            conffile.invalidValueException(entry);
        }
    }

    if((entry = gource_settings->getEntry("font-size")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify font size");

        font_size = entry->getInt();

        if(font_size<1 || font_size>100) {
            conffile.invalidValueException(entry);
        }
    }

    if((entry = gource_settings->getEntry("hash-seed")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify hash seed (integer)");

        gStringHashSeed = entry->getInt();
    }

    if((entry = gource_settings->getEntry("font-colour")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify font colour (FFFFFF)");

        int r,g,b;

        std::string colstring = entry->getString();

        if(entry->isVec3()) {
            font_colour = entry->getVec3();
        } else if(colstring.size()==6 && sscanf(colstring.c_str(), "%02x%02x%02x", &r, &g, &b) == 3) {
            font_colour = vec3(r,g,b);
            font_colour /= 255.0f;
        } else {
            conffile.invalidValueException(entry);
        }
    }

    if((entry = gource_settings->getEntry("background-colour")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify background colour (FFFFFF)");

        int r,g,b;

        std::string colstring = entry->getString();

        if(entry->isVec3()) {
            background_colour = entry->getVec3();
        } else if(colstring.size()==6 && sscanf(colstring.c_str(), "%02x%02x%02x", &r, &g, &b) == 3) {
            background_colour = vec3(r,g,b);
            background_colour /= 255.0f;
        } else {
            conffile.invalidValueException(entry);
        }
    }

    if((entry = gource_settings->getEntry("highlight-colour")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify highlight colour (FFFFFF)");

        int r,g,b;

        std::string colstring = entry->getString();

        if(entry->isVec3()) {
            highlight_colour = entry->getVec3();
        } else if(colstring.size()==6 && sscanf(colstring.c_str(), "%02x%02x%02x", &r, &g, &b) == 3) {
            highlight_colour = vec3(r,g,b);
            highlight_colour /= 255.0f;
        } else {
            conffile.invalidValueException(entry);
        }
    }
    
    if((entry = gource_settings->getEntry("selection-colour")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify selection colour (FFFFFF)");

        int r,g,b;

        std::string colstring = entry->getString();

        if(entry->isVec3()) {
            selection_colour = entry->getVec3();
        } else if(colstring.size()==6 && sscanf(colstring.c_str(), "%02x%02x%02x", &r, &g, &b) == 3) {
            selection_colour = vec3(r,g,b);
            selection_colour /= 255.0f;
        } else {
            conffile.invalidValueException(entry);
        }
    }    
    
    if((entry = gource_settings->getEntry("dir-colour")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify dir colour (FFFFFF)");

        int r,g,b;

        std::string colstring = entry->getString();

        if(entry->isVec3()) {
            dir_colour = entry->getVec3();
        } else if(colstring.size()==6 && sscanf(colstring.c_str(), "%02x%02x%02x", &r, &g, &b) == 3) {
            dir_colour = vec3(r,g,b);
            dir_colour /= 255.0f;
        } else {
            conffile.invalidValueException(entry);
        }
    }

    if((entry = gource_settings->getEntry("background-image")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify background image (image path)");

        background_image = entry->getString();
    }

    if((entry = gource_settings->getEntry("title")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify title");

        title = entry->getString();
    }

    if((entry = gource_settings->getEntry("logo")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify logo (image path)");

        logo = entry->getString();
    }

    if((entry = gource_settings->getEntry("logo-offset")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify logo-offset (XxY)");

        std::string logo_offset_str = entry->getString();

        int posx = 0;
        int posy = 0;

        if(parseRectangle(logo_offset_str, posx, posy)) {
            logo_offset = vec2(posx, posy);
        } else {
            conffile.invalidValueException(entry);
        }

    }

    if((entry = gource_settings->getEntry("seconds-per-day")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify seconds-per-day (seconds)");

        float seconds_per_day = entry->getFloat();

        if(seconds_per_day<=0.0f) {
            conffile.invalidValueException(entry);
        }

        // convert seconds-per-day to days-per-second
        days_per_second = 1.0 / seconds_per_day;
    }

    if((entry = gource_settings->getEntry("auto-skip-seconds")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify auto-skip-seconds (seconds)");

        auto_skip_seconds = entry->getFloat();

        if(auto_skip_seconds <= 0.0) {
            conffile.invalidValueException(entry);
        }
    }

    if((entry = gource_settings->getEntry("file-idle-time")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify file-idle-time (seconds)");

        std::string file_idle_str = entry->getString();

        file_idle_time = (float) atoi(file_idle_str.c_str());

        if(file_idle_time<0.0f || file_idle_time == 0.0f && file_idle_str[0] != '0' ) {
            conffile.invalidValueException(entry);
        }
        if(file_idle_time==0.0f) {
            file_idle_time = 86400.0f;
        }
    }

    if((entry = gource_settings->getEntry("user-idle-time")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify user-idle-time (seconds)");

        user_idle_time = entry->getFloat();

        if(user_idle_time < 0.0f) {
            conffile.invalidValueException(entry);
        }
    }

    if((entry = gource_settings->getEntry("time-scale")) != 0) {

        if(!entry->hasValue())
            conffile.entryException(entry, "specify time-scale (scale)");

        time_scale = entry->getFloat();

        if(time_scale <= 0.0f || time_scale > 4.0f) {
            conffile.entryException(entry, "time-scale outside of range 0.0 - 4.0");
        }
    }

    if((entry = gource_settings->getEntry("start-position")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify start-position (float,random)");

        if(entry->getString() == "random") {
            srand(time(0));
            start_position = (rand() % 1000) / 1000.0f;
        } else {
            start_position = entry->getFloat();

            if(start_position<=0.0 || start_position>=1.0) {
                conffile.entryException(entry, "start-position outside of range 0.0 - 1.0 (non-inclusive)");
            }
        }
    }

    if((entry = gource_settings->getEntry("stop-position")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify stop-position (float)");

        stop_position = entry->getFloat();

        if(stop_position<=0.0 || stop_position>1.0) {
            conffile.entryException(entry, "stop-position outside of range 0.0 - 1.0 (inclusive)");
        }
    }

    if((entry = gource_settings->getEntry("stop-at-time")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify stop-at-time (seconds)");

        stop_at_time = entry->getFloat();

        if(stop_at_time <= 0.0) {
            conffile.invalidValueException(entry);
        }
    }

    if(gource_settings->getBool("key")) {
        show_key = true;
    }

    if(gource_settings->getBool("ffp")) {
        ffp = true;
    }

    if(gource_settings->getBool("realtime")) {
        days_per_second = 1.0 / 86400.0;
    }

    if(gource_settings->getBool("dont-stop")) {
        dont_stop = true;
    }

    if(gource_settings->getBool("stop-at-end")) {
        stop_at_end = true;
    }

    //NOTE: this no longer does anything
    if(gource_settings->getBool("stop-on-idle")) {
        stop_on_idle = true;
    }

    if((entry = gource_settings->getEntry("max-files")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify max-files (number)");

        max_files = entry->getInt();

        if(max_files<0 || max_files == 0 && entry->getString() != "0") {
            conffile.invalidValueException(entry);
        }
    }

    if((entry = gource_settings->getEntry("max-file-lag")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify max-file-lag (seconds)");

        max_file_lag = entry->getFloat();

        if(max_file_lag==0.0) {
            conffile.invalidValueException(entry);
        }
    }

    if((entry = gource_settings->getEntry("user-friction")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify user-friction (seconds)");

        user_friction = entry->getFloat();

        if(user_friction<=0.0) {
            conffile.invalidValueException(entry);
        }

        user_friction = 1.0 / user_friction;
    }

    if((entry = gource_settings->getEntry("user-scale")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify user-scale (scale)");

        user_scale = entry->getFloat();

        if(user_scale<=0.0 || user_scale>100.0) {
            conffile.invalidValueException(entry);
        }
    }

    if((entry = gource_settings->getEntry("max-user-speed")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify max-user-speed (units)");

        max_user_speed = entry->getFloat();

        if(max_user_speed<=0) {
            conffile.invalidValueException(entry);
        }
    }

    if(   gource_settings->getBool("highlight-users")
       || gource_settings->getBool("highlight-all-users")) {
        highlight_all_users = true;
    }

    if(gource_settings->getBool("highlight-dirs")) {
        highlight_dirs = true;
    }

    if((entry = gource_settings->getEntry("camera-mode")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify camera-mode (overview,track)");

        camera_mode = entry->getString();

        if(camera_mode != "overview" && camera_mode != "track") {
            conffile.invalidValueException(entry);
        }
    }

    if((entry = gource_settings->getEntry("padding")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify padding (float)");

        padding = entry->getFloat();

        if(padding <= 0.0f || padding >= 2.0f) {
            conffile.invalidValueException(entry);
        }
    }

    // multi-value entries

    if((entry = gource_settings->getEntry("highlight-user")) != 0) {

        ConfEntryList* highlight_user_entries = gource_settings->getEntries("highlight-user");

        for(ConfEntryList::iterator it = highlight_user_entries->begin(); it != highlight_user_entries->end(); it++) {

            entry = *it;

            if(!entry->hasValue()) conffile.entryException(entry, "specify highlight-user (user)");

            highlight_users.push_back(entry->getString());
        }
    }

    if((entry = gource_settings->getEntry("follow-user")) != 0) {

        ConfEntryList* follow_user_entries = gource_settings->getEntries("follow-user");

        for(ConfEntryList::iterator it = follow_user_entries->begin(); it != follow_user_entries->end(); it++) {

            entry = *it;

            if(!entry->hasValue()) conffile.entryException(entry, "specify follow-user (user)");

            follow_users.push_back(entry->getString());
        }
    }

    if(gource_settings->getBool("file-extensions")) {
        file_extensions=true;
    }

    if((entry = gource_settings->getEntry("file-filter")) != 0) {

        ConfEntryList* filters = gource_settings->getEntries("file-filter");

        for(ConfEntryList::iterator it = filters->begin(); it != filters->end(); it++) {

            entry = *it;

            if(!entry->hasValue()) conffile.entryException(entry, "specify file-filter (regex)");

            std::string filter_string = entry->getString();

            Regex* r = new Regex(filter_string, 1);

            if(!r->isValid()) {
                delete r;
                conffile.entryException(entry, "invalid file-filter regular expression");
            }

            file_filters.push_back(r);
        }
    }

    if((entry = gource_settings->getEntry("user-filter")) != 0) {

        ConfEntryList* filters = gource_settings->getEntries("user-filter");

        for(ConfEntryList::iterator it = filters->begin(); it != filters->end(); it++) {

            entry = *it;

            if(!entry->hasValue()) conffile.entryException(entry, "specify user-filter (regex)");

            std::string filter_string = entry->getString();

            Regex* r = new Regex(filter_string, 1);

            if(!r->isValid()) {
                delete r;
                conffile.entryException(entry, "invalid user-filter regular expression");
            }

            user_filters.push_back(r);
        }
    }

    //validate path
    if(gource_settings->hasValue("path")) {
        path = gource_settings->getString("path");
    }

    if(path == "-") {

        if(log_format.size() == 0) {
            throw ConfFileException("log-format required when reading from STDIN", "", 0);
        }

#ifdef _WIN32
        DWORD available_bytes;
        HANDLE stdin_handle = GetStdHandle(STD_INPUT_HANDLE);

        while(PeekNamedPipe(stdin_handle, 0, 0, 0,
            &available_bytes, 0) && available_bytes==0 && !std::cin.fail()) {
            SDL_Delay(100);
        }
#else
        while(std::cin.peek() == EOF && !std::cin.fail()) SDL_Delay(100);
#endif

        std::cin.clear();
    }

    //remove trailing slash and check if path is a directory
    if(path.size() &&
    (path[path.size()-1] == '\\' || path[path.size()-1] == '/')) {
        path = path.substr(0,path.size()-1);
    }

#ifdef _WIN32
    //on windows, pre-open console window if we think this is a directory the
    //user is trying to open, as system() commands will create a console window
    //if there isn't one anyway.

    bool isdir = false;

    if(path.size()>0) {
        struct stat fileinfo;
        int rc = stat(path.c_str(), &fileinfo);

        if(rc==0 && fileinfo.st_mode & S_IFDIR) isdir = true;
    }

    if(path.size()==0 || isdir) {
        SDLAppCreateWindowsConsole();
    }
#endif
}
Beispiel #6
0
void DAFileSystemMountWithArguments( DAFileSystemRef      filesystem,
                                     CFURLRef             device,
                                     CFURLRef             mountpoint,
                                     uid_t                userUID,
                                     gid_t                userGID,
                                     DAFileSystemCallback callback,
                                     void *               callbackContext,
                                     ... )
{
    /*
     * Mount the specified volume.  A status of 0 indicates success.  All arguments in
     * the argument list shall be of type CFStringRef.  The argument list must be NULL
     * terminated.
     */

    CFStringRef             argument       = NULL;
    va_list                 arguments;
    CFURLRef                command        = NULL;
    __DAFileSystemContext * context        = NULL;
    CFStringRef             devicePath     = NULL;
    CFStringRef             mountpointPath = NULL;
    CFMutableStringRef      options        = NULL;
    int                     status         = 0;

    /*
     * Prepare to mount the volume.
     */

    command = CFURLCreateWithFileSystemPath( kCFAllocatorDefault, CFSTR( "/sbin/mount" ), kCFURLPOSIXPathStyle, FALSE );
    if ( command == NULL )  { status = ENOTSUP; goto DAFileSystemMountErr; }

    context = malloc( sizeof( __DAFileSystemContext ) );
    if ( context == NULL )  { status = ENOMEM; goto DAFileSystemMountErr; }

    devicePath = CFURLCopyFileSystemPath( device, kCFURLPOSIXPathStyle );
    if ( devicePath == NULL )  { status = EINVAL; goto DAFileSystemMountErr; }

    mountpointPath = CFURLCopyFileSystemPath( mountpoint, kCFURLPOSIXPathStyle );
    if ( mountpointPath == NULL )  { status = EINVAL; goto DAFileSystemMountErr; }

    options = CFStringCreateMutable( kCFAllocatorDefault, 0 );
    if ( options == NULL )  { status = ENOMEM; goto DAFileSystemMountErr; }

    /*
     * Prepare the mount options.
     */

    va_start( arguments, callbackContext );

    while ( ( argument = va_arg( arguments, CFStringRef ) ) )
    {
        CFStringAppend( options, argument );
        CFStringAppend( options, CFSTR( "," ) );
    }

    va_end( arguments );

    CFStringTrim( options, CFSTR( "," ) );

    /*
     * Execute the mount command.
     */

    context->callback        = callback;
    context->callbackContext = callbackContext;

    if ( CFStringGetLength( options ) )
    {
        DACommandExecute( command,
                          kDACommandExecuteOptionDefault,
                          userUID,
                          userGID,
                          __DAFileSystemCallback,
                          context,
                          CFSTR( "-t" ),
                          DAFileSystemGetKind( filesystem ),
                          CFSTR( "-o" ),
                          options,
                          devicePath,
                          mountpointPath,
                          NULL );
    }
    else
    {
        DACommandExecute( command,
                          kDACommandExecuteOptionDefault,
                          userUID,
                          userGID,
                          __DAFileSystemCallback,
                          context,
                          CFSTR( "-t" ),
                          DAFileSystemGetKind( filesystem ),
                          devicePath,
                          mountpointPath,
                          NULL );
    }

DAFileSystemMountErr:

    if ( command        )  CFRelease( command        );
    if ( devicePath     )  CFRelease( devicePath     );
    if ( mountpointPath )  CFRelease( mountpointPath );
    if ( options        )  CFRelease( options        );

    if ( status )
    {
        if ( context )  free( context );

        if ( callback )
        {
            ( callback )( status, callbackContext );
        }
    }
}
/* TODO: Use the shared version of this function in print_cert.c. */
static void print_line(CFStringRef line) {
    UInt8 buf[256];
    CFRange range = { .location = 0 };
    range.length = CFStringGetLength(line);
    while (range.length > 0) {
        CFIndex bytesUsed = 0;
        CFIndex converted = CFStringGetBytes(line, range, kCFStringEncodingUTF8, 0, false, buf, sizeof(buf), &bytesUsed);
        fwrite(buf, 1, bytesUsed, stdout);
        range.length -= converted;
        range.location += converted;
    }
    fputc('\n', stdout);
}

static void printPlist(CFArrayRef plist, CFIndex indent, CFIndex maxWidth) {
    CFIndex count = CFArrayGetCount(plist);
    CFIndex ix;
    for (ix = 0; ix < count ; ++ix) {
        CFDictionaryRef prop = (CFDictionaryRef)CFArrayGetValueAtIndex(plist,
            ix);
        CFStringRef pType = (CFStringRef)CFDictionaryGetValue(prop,
            kSecPropertyKeyType);
        CFStringRef label = (CFStringRef)CFDictionaryGetValue(prop,
            kSecPropertyKeyLabel);
        CFStringRef llabel = (CFStringRef)CFDictionaryGetValue(prop,
            kSecPropertyKeyLocalizedLabel);
        CFTypeRef value = (CFTypeRef)CFDictionaryGetValue(prop,
            kSecPropertyKeyValue);

        bool isSection = CFEqual(pType, kSecPropertyTypeSection);
        CFMutableStringRef line = CFStringCreateMutable(NULL, 0);
        CFIndex jx = 0;
        for (jx = 0; jx < indent; ++jx) {
            CFStringAppend(line, CFSTR("    "));
        }
        if (llabel) {
            CFStringAppend(line, llabel);
            if (!isSection) {
                for (jx = CFStringGetLength(llabel) + indent * 4;
                    jx < maxWidth; ++jx) {
                    CFStringAppend(line, CFSTR(" "));
                }
                CFStringAppend(line, CFSTR(" : "));
            }
        }
        if (CFEqual(pType, kSecPropertyTypeWarning)) {
            CFStringAppend(line, CFSTR("*WARNING* "));
            CFStringAppend(line, (CFStringRef)value);
        } else if (CFEqual(pType, kSecPropertyTypeError)) {
            CFStringAppend(line, CFSTR("*ERROR* "));
            CFStringAppend(line, (CFStringRef)value);
        } else if (CFEqual(pType, kSecPropertyTypeSuccess)) {
            CFStringAppend(line, CFSTR("*OK* "));
            CFStringAppend(line, (CFStringRef)value);
        } else if (CFEqual(pType, kSecPropertyTypeTitle)) {
            CFStringAppend(line, CFSTR("*"));
            CFStringAppend(line, (CFStringRef)value);
            CFStringAppend(line, CFSTR("*"));
        } else if (CFEqual(pType, kSecPropertyTypeSection)) {
        } else if (CFEqual(pType, kSecPropertyTypeData)) {
            CFDataRef data = (CFDataRef)value;
            CFIndex length = CFDataGetLength(data);
            if (length > 20)
                CFStringAppendFormat(line, NULL, CFSTR("[%" PRIdCFIndex " bytes] "), length);
            const UInt8 *bytes = CFDataGetBytePtr(data);
            for (jx = 0; jx < length; ++jx) {
                if (jx == 0)
                    CFStringAppendFormat(line, NULL, CFSTR("%02X"), bytes[jx]);
                else if (jx < 15 || length <= 20)
                    CFStringAppendFormat(line, NULL, CFSTR(" %02X"),
                        bytes[jx]);
                else {
                    CFStringAppend(line, CFSTR(" ..."));
                    break;
                }
            }
        } else if (CFEqual(pType, kSecPropertyTypeString)) {
            CFStringAppend(line, (CFStringRef)value);
        } else if (CFEqual(pType, kSecPropertyTypeDate)) {
            CFLocaleRef lc = CFLocaleCopyCurrent();
            CFDateFormatterRef df = CFDateFormatterCreate(NULL, lc,
                kCFDateFormatterFullStyle, kCFDateFormatterFullStyle);
            //CFTimeZoneRef tz = CFTimeZoneCreateWithName(NULL, CFSTR("GMT"), false);
            //CFDateFormatterSetProperty(df, kCFDateFormatterTimeZone, tz);
            //CFRelease(tz);
            CFDateRef date = (CFDateRef)value;
            CFStringRef ds = CFDateFormatterCreateStringWithDate(NULL, df,
                date);
            CFStringAppend(line, ds);
            CFRelease(ds);
            CFRelease(df);
            CFRelease(lc);
        } else if (CFEqual(pType, kSecPropertyTypeURL)) {
            CFURLRef url = (CFURLRef)value;
            CFStringAppend(line, CFSTR("<"));
            CFStringAppend(line, CFURLGetString(url));
            CFStringAppend(line, CFSTR(">"));
        } else {
            CFStringAppendFormat(line, NULL, CFSTR("*unknown type %@* = %@"),
            pType, value);
        }

		if (!isSection || label)
			print_line(line);
		CFRelease(line);
        if (isSection) {
            printPlist((CFArrayRef)value, indent + 1, maxWidth);
        }
    }
}
Beispiel #8
0
CFStringRef Resources::getResourcePath(const char* resource){
    CFMutableStringRef path = CFStringCreateMutable(NULL,0);
    CFStringAppend(path,getResourcesPathFromDyldImage());
    CFStringAppend(path,  CFStringCreateWithCString(NULL,resource, kCFStringEncodingUTF8));
    return path;
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//	AURenderQualityPopup::AURenderQualityPopup
//
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
AURenderQualityPopup::AURenderQualityPopup (AUCarbonViewBase *inBase, 
				Point 					inLocation, 
				int 					inRightEdge, 
				ControlFontStyleRec & 	inFontStyle)
	: AUPropertyControl (inBase)
{
	Rect r;
	r.top = inLocation.v;		r.bottom = r.top + 17;
	r.left = inLocation.h;		r.right = r.left + inRightEdge;
	
	ControlFontStyleRec fontStyle = inFontStyle;
	inFontStyle.just = teFlushRight;

	ControlRef			ref;
		
	CFBundleRef mainBundle = CFBundleGetBundleWithIdentifier(CFSTR("com.apple.audio.units.Components"));
	if (mainBundle != NULL) {
		CFMutableStringRef renderTitle = CFStringCreateMutable(NULL, 0);
		CFStringAppend(renderTitle, CFCopyLocalizedStringFromTableInBundle(
			CFSTR("Render Quality"), CFSTR("CustomUI"), mainBundle,
			CFSTR("The Render Quality Popup menu title")));
		CFStringAppend(renderTitle, CFSTR(":"));
	
		OSErr theErr =  CreateStaticTextControl (GetCarbonWindow(), &r, renderTitle, &inFontStyle, &ref);
		if (theErr == noErr)
			EmbedControl(ref);
		
		r.left = r.right + 8;
		r.right = r.left + 100;

		short bundleRef = CFBundleOpenBundleResourceMap (mainBundle);
		
		theErr = CreatePopupButtonControl (mView->GetCarbonWindow(), &r, NULL,
			/*kQualityMenuID*/ -12345, false, -1, 0, 0, &mControl);	
			
		MenuRef menuRef;
		verify_noerr(CreateNewMenu(kQualityMenuID, 0, &menuRef));
		
		verify_noerr(AppendMenuItemTextWithCFString (menuRef, CFCopyLocalizedStringFromTableInBundle(CFSTR("Maximum"), CFSTR("CustomUI"), mainBundle, CFSTR("")), 0, kChangeRenderQualityCmd, 0));
		verify_noerr(AppendMenuItemTextWithCFString (menuRef, CFCopyLocalizedStringFromTableInBundle(CFSTR("High"), CFSTR("CustomUI"), mainBundle, CFSTR("")), 0, kChangeRenderQualityCmd, 0));
		verify_noerr(AppendMenuItemTextWithCFString (menuRef, CFCopyLocalizedStringFromTableInBundle(CFSTR("Medium"), CFSTR("CustomUI"), mainBundle, CFSTR("")), 0, kChangeRenderQualityCmd, 0));
		verify_noerr(AppendMenuItemTextWithCFString (menuRef, CFCopyLocalizedStringFromTableInBundle(CFSTR("Low"), CFSTR("CustomUI"), mainBundle, CFSTR("")), 0, kChangeRenderQualityCmd, 0));
		verify_noerr(AppendMenuItemTextWithCFString (menuRef, CFCopyLocalizedStringFromTableInBundle(CFSTR("Minimum"), CFSTR("CustomUI"), mainBundle, CFSTR("")), 0, kChangeRenderQualityCmd, 0));
																
		verify_noerr(SetControlData(mControl, 0, kControlPopupButtonMenuRefTag, sizeof(menuRef), &menuRef));
					
		verify_noerr(SetControlFontStyle (mControl, &inFontStyle));
			
		SetControl32BitMaximum(mControl, 5);
		UInt32 renderQuality;
		UInt32 size = sizeof(UInt32);
		AudioUnitGetProperty (mView->GetEditAudioUnit(), 
							kAudioUnitProperty_RenderQuality,
							kAudioUnitScope_Global, 
							0, 
							&renderQuality, 
							&size);
							
		HandlePropertyChange(renderQuality);

		EmbedControl(mControl);
		theErr = AudioUnitAddPropertyListener(mView->GetEditAudioUnit(), kAudioUnitProperty_RenderQuality, RenderQualityListener, this);
		CFBundleCloseBundleResourceMap (mainBundle, bundleRef);
		CFRelease(renderTitle);
	}
	RegisterEvents();
}
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 (sigDataLength < 0 || sigDataLength > INT_MAX ||
            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;
}
/* ------------------------------------------------------------------------------------------------------

SetDateValueFromFITSHeader: read FITS header and set striped string value to attribute name.

------------------------------------------------------------------------------------------------------ */
void SetDateValueFromFITSHeader(const char* filename, 
				CFMutableDictionaryRef attributes, 
				const char* importerAttrName, 
				char* mainKeyword, 
				char* secondaryKeyword1,
				char* secondaryKeyword2)
{
	CFMutableStringRef headerValue = CFStringCreateMutable(kCFAllocatorDefault, (CFIndex)80);

	CFStringRef value1 = getCleanedHeaderValue(filename, mainKeyword);
	if (value1 != NULL) {
		CFIndex valueLength1 = CFStringGetLength(value1);
		if ((valueLength1 >= 19) || (valueLength1 == 10)) {
			CFStringAppend(headerValue, value1); // value of mainKeyword looks OK.
		}
		CFRelease(value1);
	}

	CFStringRef value2 = getCleanedHeaderValue(filename, secondaryKeyword1);
	if (value2 != NULL) {
		CFIndex valueLength2 = CFStringGetLength(value2);
		CFIndex headerValueLength = CFStringGetLength(headerValue);
		if (headerValueLength == 0 && valueLength2 >= 10) {
			CFStringAppend(headerValueLength, value2); // Append value of secondaryKeyword1
		}
		else if (headerValueLength < 19 && valueLength2 >= 19) {
			CFRange range = CFRangeMake(0, headerValueLength);
			CFStringDelete(headerValue, range);
			CFStringAppend(headerValue, value2); // Replace value of current headerValue by value of secondaryKeyword1
		}
		CFRelease(value2);
	}

	CFStringRef value3 = getCleanedHeaderValue(filename, secondaryKeyword2);
	if (value3 != NULL) {
		CFRange r = CFStringFind(value3, CFSTR(":"), 0);
		CFIndex headerValueLength = CFStringGetLength(headerValue);
		if (headerValueLength == 10 && r.location != kCFNotFound) {
			CFStringAppend(headerValue, CFSTR("T"));
			CFStringAppend(headerValue, value3);
		}
		CFRelease(value3);
	}

	CFIndex headerValueLength = CFStringGetLength(headerValue);
	if (headerValueLength > 0) {
		
		CFArrayRef tArray   = CFStringCreateArrayBySeparatingStrings(kCFAllocatorDefault, headerValue, CFSTR("T"));
		CFArrayRef ymdArray = CFStringCreateArrayBySeparatingStrings(kCFAllocatorDefault, CFArrayGetValueAtIndex(tArray, 0), CFSTR("-"));

		CFGregorianDate gregDate;
		gregDate.year   = 0;
		gregDate.month  = 0;
		gregDate.day    = 0.;
		
		if (CFStringGetLength(CFArrayGetValueAtIndex(ymdArray, 0)) > 0) {
			gregDate.year   = CFStringGetIntValue(CFArrayGetValueAtIndex(ymdArray, 0));
		}
		if (CFStringGetLength(CFArrayGetValueAtIndex(ymdArray, 1)) > 0) {
			gregDate.month  = CFStringGetIntValue(CFArrayGetValueAtIndex(ymdArray, 1));
		}
		if (CFStringGetLength(CFArrayGetValueAtIndex(ymdArray, 2)) > 0) {
			gregDate.day    = CFStringGetIntValue(CFArrayGetValueAtIndex(ymdArray, 2));
		}
		CFRelease(ymdArray);

		gregDate.hour   = 0;
		gregDate.minute = 0;
		gregDate.second = 0.;
		
		CFIndex arraySize = CFArrayGetCount(tArray);
		if (arraySize == 2) {
			CFArrayRef hmsArray = CFStringCreateArrayBySeparatingStrings(kCFAllocatorDefault, CFArrayGetValueAtIndex(tArray, 1), CFSTR(":"));
			if (CFStringGetLength(CFArrayGetValueAtIndex(hmsArray, 0)) > 0) {
				gregDate.hour   = CFStringGetIntValue(CFArrayGetValueAtIndex(hmsArray, 0));
			}
			if (CFStringGetLength(CFArrayGetValueAtIndex(hmsArray, 1)) > 0) {
				gregDate.minute = CFStringGetIntValue(CFArrayGetValueAtIndex(hmsArray, 1));
			}
			if (CFStringGetLength(CFArrayGetValueAtIndex(hmsArray, 2)) > 0) {
				gregDate.second = CFStringGetDoubleValue(CFArrayGetValueAtIndex(hmsArray, 2));			
			}
			CFRelease(hmsArray);
		}

		CFRelease(tArray);

//		printf("%i %i %i %i %i %f\n\n", gregDate.year, gregDate.month, gregDate.day, gregDate.hour, gregDate.minute, gregDate.second);

		if ((gregDate.year > 0) && (gregDate.month > 0) && (gregDate.day > 0)) {
			CFTimeZoneRef timeZone = CFTimeZoneCreateWithName(kCFAllocatorDefault, CFSTR("GMT"), true);
			CFAbsoluteTime absTime = CFGregorianDateGetAbsoluteTime(gregDate, timeZone);
			CFDateRef date = CFDateCreate(kCFAllocatorDefault, absTime);

			if (timeZone != NULL) {
				CFRelease(timeZone);
			}

			CFStringRef cfImporterAttrName = CFStringCreateWithCString(kCFAllocatorDefault, importerAttrName, kCFStringEncodingUTF8);
			CFDictionaryAddValue(attributes, cfImporterAttrName, date);
			CFRelease(cfImporterAttrName);
			CFRelease(date);
		}
	}

	CFRelease(headerValue);
}
Beispiel #12
0
int main(int argc, const char *argv[]) {
    // http://developer.apple.com/library/IOs/#documentation/CoreFoundation/Conceptual/CFStrings/Articles/MutableStrings.html
    int i;
    CFMutableStringRef args = CFStringCreateMutable(NULL, 0);
    CFStringEncoding encoding = CFStringGetSystemEncoding();
    CFStringAppend(args, CFSTR("starting screenresolution argv="));
    for (i = 0 ; i < argc ; i++) {
        CFStringAppendCString(args, argv[i], encoding);
        // If I were so motivated, I'd probably use CFStringAppendFormat
        CFStringAppend(args, CFSTR(" "));
    }
    // This has security implications.  Will look at that later
    NSLog(CFSTR("%@"), args);
    unsigned int exitcode = 0;

    if (argc > 1) {
        int d;
        int keepgoing = 1;
        CGError rc;
        uint32_t displayCount = 0;
        uint32_t activeDisplayCount = 0;
        CGDirectDisplayID *activeDisplays = NULL;

        rc = CGGetActiveDisplayList(0, NULL, &activeDisplayCount);
        if (rc != kCGErrorSuccess) {
            NSLog(CFSTR("%s"), "Error: failed to get list of active displays");
            return 1;
        }
        // Allocate storage for the next CGGetActiveDisplayList call
        activeDisplays = (CGDirectDisplayID *) malloc(activeDisplayCount * sizeof(CGDirectDisplayID));
        if (activeDisplays == NULL) {
            NSLog(CFSTR("%s"), "Error: could not allocate memory for display list");
            return 1;
        }
        rc = CGGetActiveDisplayList(activeDisplayCount, activeDisplays, &displayCount);
        if (rc != kCGErrorSuccess) {
            NSLog(CFSTR("%s"), "Error: failed to get list of active displays");
            return 1;
        }

        // This loop should probably be in another function.
        for (d = 0; d < displayCount && keepgoing; d++) {
            if (strcmp(argv[1], "get") == 0) {
                if (!listCurrentMode(activeDisplays[d], d)) {
                    exitcode++;
                }
            } else if (strcmp(argv[1], "list") == 0) {
                if (!listAvailableModes(activeDisplays[d], d)) {
                    exitcode++;
                }
            } else if (strcmp(argv[1], "set") == 0) {
                if (d < (argc - 2)) {
                    if (strcmp(argv[d+2], "skip") == 0 && d < (argc - 2)) {
                        printf("Skipping display %d\n", d);
                    } else {
                        struct config newConfig;
                        if (parseStringConfig(argv[d + 2], &newConfig)) {
                            if (!configureDisplay(activeDisplays[d], &newConfig, d)) {
                                exitcode++;
                            }
                        } else {
                            exitcode++;
                        }
                    }
                }
            } else if (strcmp(argv[1], "-version") == 0) {
                printf("screenresolution version %s\nLicensed under GPLv2\n", VERSION);
                keepgoing = 0;
            } else {
                NSLog(CFSTR("I'm sorry %s. I'm afraid I can't do that"), getlogin());
                exitcode++;
                keepgoing = 0;
            }
        }
        free(activeDisplays);
        activeDisplays = NULL;
    } else {
        NSLog(CFSTR("%s"), "Incorrect command line");
        exitcode++;
    }
    return exitcode > 0;
}
Beispiel #13
0
CFStringRef getBuffer()
{
	kern_return_t kernResult;
	bufferStruct myBufStruct;
	size_t structSize = sizeof(myBufStruct);
	
	kernResult = IOConnectCallMethod(userClient,
									 klogKextBuffer,
									 NULL,
									 0,
									 NULL,
									 NULL,
									 NULL,
									 NULL,
									 &myBufStruct,
									 &structSize);
	
	CFDataRef result = CFDataCreate(kCFAllocatorDefault,myBufStruct.buffer,myBufStruct.bufLen);
	CFMutableStringRef decodedData = CFStringCreateMutable(kCFAllocatorDefault,0);
	
	if (!keymap)
		return decodedData;
	
	CFDictionaryRef flagsDict = (CFDictionaryRef)CFDictionaryGetValue(keymap,CFSTR("Flags"));
	if (!flagsDict)
		return decodedData;
	CFDictionaryRef ucDict = (CFDictionaryRef)CFDictionaryGetValue(keymap,CFSTR("Uppercase"));
	if (!ucDict)
		return decodedData;
	CFDictionaryRef lcDict = (CFDictionaryRef)CFDictionaryGetValue(keymap,CFSTR("Lowercase"));
	if (!lcDict)
		return decodedData;

	CFNumberFormatterRef myNF = CFNumberFormatterCreate(kCFAllocatorDefault,CFLocaleCopyCurrent(),kCFNumberFormatterNoStyle);
	
	for (int i=0; i<CFDataGetLength(result);i+=2)
	{
		u_int16_t curChar;
		CFDataGetBytes(result,CFRangeMake(i,2),(UInt8*)&curChar);
		bool isUpper = false;
		
		if (CFBooleanGetValue(showMods))
		{
			char flagTmp = (curChar >> 11);
			
			if (flagTmp & 0x01)
				CFStringAppend(decodedData,(CFStringRef)CFDictionaryGetValue(flagsDict,CFSTR("0x01")));

			if (flagTmp & 0x02)
				CFStringAppend(decodedData,(CFStringRef)CFDictionaryGetValue(flagsDict,CFSTR("0x02")));

			if (flagTmp & 0x04)
				CFStringAppend(decodedData,(CFStringRef)CFDictionaryGetValue(flagsDict,CFSTR("0x04")));

			if (flagTmp & 0x08)
				CFStringAppend(decodedData,(CFStringRef)CFDictionaryGetValue(flagsDict,CFSTR("0x08")));
				
			if (flagTmp & 0x10)
				isUpper = true;
		}

		curChar &= 0x07ff;		
		CFStringRef keyChar = CFNumberFormatterCreateStringWithValue(kCFAllocatorDefault,myNF,kCFNumberShortType,&curChar);
		CFStringRef text;

		if (isUpper)
			text = (CFStringRef)CFDictionaryGetValue(ucDict,keyChar);
		else
			text = (CFStringRef)CFDictionaryGetValue(lcDict,keyChar);		
		
		if (text)
		{
			if (CFStringCompare(text,CFSTR("\\n"),0)==kCFCompareEqualTo)
				text = CFSTR("\n");

			CFStringAppend(decodedData,text);
		}
		else
			syslog(LOG_ERR,"Unmapped key %d",curChar);		
	}

	return decodedData;
}
SOSCoderStatus SOSCoderUnwrap(SOSCoderRef coder, CFDataRef codedMessage, CFMutableDataRef *message,
                              CFStringRef clientId, CFErrorRef *error) {
    if(codedMessage == NULL) return kSOSCoderDataReturned;
    if(coder->sessRef == NULL) return nullCoder(codedMessage, message);
    CFMutableStringRef action = CFStringCreateMutable(kCFAllocatorDefault, 0);
    /* This should be the "normal" case.  We just use OTR to unwrap the received message. */
    SOSCoderStatus result = kSOSCoderFailure;

    CFStringRef beginState = CFCopyDescription(coder->sessRef);
    enum SecOTRSMessageKind kind = SecOTRSGetMessageKind(coder->sessRef, codedMessage);

    switch (kind) {
        case kOTRNegotiationPacket: {
            /* If we're in here we haven't completed negotiating a session.  Use SecOTRSProcessPacket() to go through
             the negotiation steps and immediately send a reply back if necessary using the sendBlock.  This
             assumes the sendBlock is still available.
             */
            CFMutableDataRef response = CFDataCreateMutable(kCFAllocatorDefault, 0);
            OSStatus ppstatus = errSecSuccess;
            if (response) {
                switch (ppstatus = SecOTRSProcessPacket(coder->sessRef, codedMessage, response)) {
                    case errSecSuccess:
                        if (CFDataGetLength(response) > 1) {
                            CFStringAppendFormat(action, NULL, CFSTR("Sending OTR Response %s"), SecOTRPacketTypeString(response));
                            CFRetainAssign(coder->pendingResponse, response);
                            result = kSOSCoderNegotiating;
                            if (SecOTRSGetIsReadyForMessages(coder->sessRef)) {
                                CFStringAppend(action, CFSTR(" begin waiting for data packet"));
                                coder->waitingForDataPacket = true;
                            }
                        } else if(!SecOTRSGetIsReadyForMessages(coder->sessRef)) {
                            CFStringAppend(action, CFSTR("stuck?"));
                            result = kSOSCoderNegotiating;
                        } else {
                            CFStringAppend(action, CFSTR("completed negotiation"));
                            result = kSOSCoderNegotiationCompleted;
                            coder->waitingForDataPacket = false;
                        }
                        break;
                    case errSecDecode:
                        CFStringAppend(action, CFSTR("resending dh"));
                        result = SOSCoderResendDH(coder, error);
                        break;
                    default:
                        SOSCreateErrorWithFormat(kSOSErrorEncodeFailure, (error != NULL) ? *error : NULL, error, NULL, CFSTR("%@ Cannot negotiate session (%ld)"), clientId, (long)ppstatus);
                        result = kSOSCoderFailure;
                        break;
                };
            } else {
                SOSCreateErrorWithFormat(kSOSErrorAllocationFailure, (error != NULL) ? *error : NULL, error, NULL, CFSTR("%@ Cannot allocate CFData"), clientId);
                result = kSOSCoderFailure;
            }
            
            CFReleaseNull(response);
            
            break;
        }

        case kOTRDataPacket:
            if(!SecOTRSGetIsReadyForMessages(coder->sessRef)) {
                CFStringAppend(action, CFSTR("not ready, resending DH packet"));
				SetCloudKeychainTraceValueForKey(kCloudKeychainNumberOfTimesSyncFailed, 1);
                CFStringAppend(action, CFSTR("not ready for data; resending dh"));
                result = SOSCoderResendDH(coder, error);
            } else {
                if (coder->waitingForDataPacket) {
                    CFStringAppend(action, CFSTR("got data packet we were waiting for "));
                    coder->waitingForDataPacket = false;
                }
                CFMutableDataRef exposed = CFDataCreateMutable(0, 0);
                OSStatus otrResult = SecOTRSVerifyAndExposeMessage(coder->sessRef, codedMessage, exposed);
                CFStringAppend(action, CFSTR("verify and expose message"));
                if (otrResult) {
                    if (otrResult == errSecOTRTooOld) {
                        CFStringAppend(action, CFSTR(" too old"));
                        result = kSOSCoderStaleEvent;
                    } else {
                        SecError(otrResult, error, CFSTR("%@ Cannot expose message: %" PRIdOSStatus), clientId, otrResult);
                        secerror("%@ Decode OTR Protected Packet: %@", clientId, error ? *error : NULL);
                        result = kSOSCoderFailure;
                    }
                } else {
                    CFStringAppend(action, CFSTR("decoded OTR protected packet"));
                    *message = exposed;
                    exposed = NULL;
                    result = kSOSCoderDataReturned;
                }
                CFReleaseNull(exposed);
            }
            break;

        default:
            secerror("%@ Unknown packet type: %@", clientId, codedMessage);
            SOSCreateError(kSOSErrorDecodeFailure, CFSTR("Unknown packet type"), (error != NULL) ? *error : NULL, error);
            result = kSOSCoderFailure;
            break;
    };

    // Uber state log
    if (result == kSOSCoderFailure && error && *error)
        CFStringAppendFormat(action, NULL, CFSTR(" %@"), *error);
    secnotice("coder", "%@ %@ %s %@ %@ returned %s", clientId, beginState,
              SecOTRPacketTypeString(codedMessage), action, coder->sessRef, SOSCoderString(result));
    CFReleaseSafe(beginState);
    CFRelease(action);

    return result;
}
Beispiel #15
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;
}
Beispiel #16
0
void	AUControlGroup::AddAUInfo (		AUCarbonViewBase *			auView, 
										const Point &				inLocation, 
										const SInt16 				inRightOffset,
										const SInt16				inTotalWidth)
{
#if !__LP64__
   // get component info
	ComponentDescription desc;
    Handle h1 = NewHandleClear(4);
	OSStatus err = GetComponentInfo ((Component)auView->GetEditAudioUnit(), &desc, h1, 0, 0);
    
    if (err == noErr) {        
        // Get the manufacturer's name... look for the ':' character convention
        HLock(h1);
        char* ptr1 = *h1;
        int len = *ptr1++;
        char* displayStr = 0;
        
        for (int i = 0; i < len; ++i) {
            if (ptr1[i] == ':') { // found the name
                ptr1[i++] = 0;
                displayStr = ptr1;
                break;
            }
        }
        
        // localize as necessary:
        if (!sLocalized) {
            CFBundleRef mainBundle = CFBundleGetBundleWithIdentifier(kLocalizedStringBundle_AUView);
            if (mainBundle) {
                kStringManufacturer = CFCopyLocalizedStringFromTableInBundle(
                                            kAUViewLocalizedStringKey_Manufacturer, kLocalizedStringTable_AUView,
                                            mainBundle, CFSTR("Manufacturer title string"));
                sLocalized = true;
            }
        }
        
        // display strings
        ControlRef newControl;
        Rect r;
        r.top = SInt16(inLocation.v);		r.bottom = SInt16(inLocation.v) + 16;
        ControlFontStyleRec fontStyle;
        fontStyle.flags = kControlUseFontMask | kControlUseJustMask;
        fontStyle.font = kControlFontSmallBoldSystemFont;
        
        // display manufacturer string
        if (displayStr) {
            CFMutableStringRef mfrstring = CFStringCreateMutable(NULL, 0);
            CFStringAppend(mfrstring, kStringManufacturer);		// "Manufacturer"
            CFStringAppend(mfrstring, kAUViewUnlocalizedString_TitleSeparator);
                                                                // "Manufacturer: "
            CFStringRef mfrname = CFStringCreateWithCString(NULL, displayStr, kCFStringEncodingUTF8);
            if (mfrname) {
                CFStringAppend(mfrstring, mfrname);	// "Manufacturer: MFRName"
                CFRelease (mfrname);
            }
            
            r.left = inLocation.h + inRightOffset;	
			r.right = inLocation.h + inTotalWidth - 28;
			fontStyle.just = teFlushRight;
            
            verify_noerr(CreateStaticTextControl(auView->GetCarbonWindow(), &r, mfrstring, &fontStyle, &newControl));
            verify_noerr(auView->EmbedControl(newControl));
            CFRelease (mfrstring);
                                        
            //move displayStr ptr past the manu, to the name
            // we move the characters down an index, because the handle doesn't have any room
            // at the end for the \0
			int i = strlen(displayStr), j = 0;
			while (displayStr[++i] == ' ' && i < len)
				;
			while (i < len)
				displayStr[j++] = displayStr[i++];
			displayStr[j] = 0;
        } else {
			displayStr = ptr1;
			int i = 0, j = 0;
			do {
				displayStr[j] = displayStr[i];
				++j; ++i;
			} while (i < len);
			
			displayStr[j] = 0;
        }
        
        // display AudioUnit string
        r.left = inLocation.h;	r.right = r.left + inRightOffset;
        fontStyle.just = 0;
        
        CFMutableStringRef cfstr = CFStringCreateMutable(NULL, 0);
        CFStringAppend(cfstr, kAUViewLocalizedStringKey_AudioUnit);		// "Audio Unit"
        CFStringAppend(cfstr, kAUViewUnlocalizedString_TitleSeparator);
                                                        // "Audio Unit: "
        
		CFStringRef auname = CFStringCreateWithCString(NULL, displayStr, kCFStringEncodingUTF8);
		CFStringAppend(cfstr, auname);				// "Audio Unit: AUName"
		CFRelease (auname);
        
        verify_noerr(CreateStaticTextControl(auView->GetCarbonWindow(), &r, cfstr, &fontStyle, &newControl));
		
		// size text control correctly
		Boolean bValue = false;
		SetControlData(newControl, kControlEntireControl, 'stim' /* kControlStaticTextIsMultilineTag */, sizeof(Boolean), &bValue);
		SInt16 baseLineOffset;
		Rect bestRect;
		err = GetBestControlRect(newControl, &bestRect, &baseLineOffset);  
		if (err == noErr)
		{
			int width = (bestRect.right - bestRect.left) + 1;
			int height = (bestRect.bottom - bestRect.top) + 1;
			SizeControl (newControl, width, height);
		}
		
        verify_noerr(auView->EmbedControl(newControl));
        CFRelease (cfstr);
    }
    
	DisposeHandle (h1);
#endif
}
static void printPlist(CFArrayRef plist, CFIndex indent, CFIndex maxWidth) {
    CFIndex count = CFArrayGetCount(plist);
    CFIndex ix;
    for (ix = 0; ix < count ; ++ix) {
        CFDictionaryRef prop = (CFDictionaryRef)CFArrayGetValueAtIndex(plist,
            ix);
        CFStringRef pType = (CFStringRef)CFDictionaryGetValue(prop,
            kSecPropertyKeyType);
        CFStringRef label = (CFStringRef)CFDictionaryGetValue(prop,
            kSecPropertyKeyLabel);
        CFStringRef llabel = (CFStringRef)CFDictionaryGetValue(prop,
            kSecPropertyKeyLocalizedLabel);
        CFTypeRef value = (CFTypeRef)CFDictionaryGetValue(prop,
            kSecPropertyKeyValue);

        bool isSection = CFEqual(pType, kSecPropertyTypeSection);
        CFMutableStringRef line = CFStringCreateMutable(NULL, 0);
        CFIndex jx = 0;
        for (jx = 0; jx < indent; ++jx) {
            CFStringAppend(line, CFSTR("    "));
        }
        if (llabel) {
            CFStringAppend(line, llabel);
            if (!isSection) {
                for (jx = CFStringGetLength(llabel) + indent * 4;
                    jx < maxWidth; ++jx) {
                    CFStringAppend(line, CFSTR(" "));
                }
                CFStringAppend(line, CFSTR(" : "));
            }
        }
        if (CFEqual(pType, kSecPropertyTypeWarning)) {
            CFStringAppend(line, CFSTR("*WARNING* "));
            CFStringAppend(line, (CFStringRef)value);
        } else if (CFEqual(pType, kSecPropertyTypeError)) {
            CFStringAppend(line, CFSTR("*ERROR* "));
            CFStringAppend(line, (CFStringRef)value);
        } else if (CFEqual(pType, kSecPropertyTypeSuccess)) {
            CFStringAppend(line, CFSTR("*OK* "));
            CFStringAppend(line, (CFStringRef)value);
        } else if (CFEqual(pType, kSecPropertyTypeTitle)) {
            CFStringAppend(line, CFSTR("*"));
            CFStringAppend(line, (CFStringRef)value);
            CFStringAppend(line, CFSTR("*"));
        } else if (CFEqual(pType, kSecPropertyTypeSection)) {
        } else if (CFEqual(pType, kSecPropertyTypeData)) {
            CFDataRef data = (CFDataRef)value;
            CFIndex length = CFDataGetLength(data);
            if (length > 20)
                CFStringAppendFormat(line, NULL, CFSTR("[%d bytes] "), length);
            const UInt8 *bytes = CFDataGetBytePtr(data);
            for (jx = 0; jx < length; ++jx) {
                if (jx == 0)
                    CFStringAppendFormat(line, NULL, CFSTR("%02X"), bytes[jx]);
                else if (jx < 15 || length <= 20)
                    CFStringAppendFormat(line, NULL, CFSTR(" %02X"),
                        bytes[jx]);
                else {
                    CFStringAppend(line, CFSTR(" ..."));
                    break;
                }
            }
        } else if (CFEqual(pType, kSecPropertyTypeString)) {
            CFStringAppend(line, (CFStringRef)value);
        } else if (CFEqual(pType, kSecPropertyTypeDate)) {
            CFDateRef date = (CFDateRef)value;
            CFLocaleRef lc = CFLocaleCopyCurrent();
            CFDateFormatterRef df = CFDateFormatterCreate(NULL, lc, kCFDateFormatterMediumStyle, kCFDateFormatterLongStyle);
            CFStringRef ds;
            if (df) {
                CFTimeZoneRef tz = CFTimeZoneCreateWithTimeIntervalFromGMT(NULL, 0.0);
                CFDateFormatterSetProperty(df, kCFDateFormatterTimeZone, tz);
                CFRelease(tz);
                ds = CFDateFormatterCreateStringWithDate(NULL, df, date);
                CFRelease(df);
            } else {
                ds = CFStringCreateWithFormat(NULL, NULL, CFSTR("%g"), CFDateGetAbsoluteTime(date));
            }
            CFStringAppend(line, ds);
            CFRelease(ds);
            CFRelease(lc);
        } else if (CFEqual(pType, kSecPropertyTypeURL)) {
            CFURLRef url = (CFURLRef)value;
            CFStringAppend(line, CFSTR("<"));
            CFStringAppend(line, CFURLGetString(url));
            CFStringAppend(line, CFSTR(">"));
        } else {
            CFStringAppendFormat(line, NULL, CFSTR("*unknown type %@* = %@"),
            pType, value);
        }

		if (!isSection || label)
			print_line(line);
		CFRelease(line);
        if (isSection) {
            printPlist((CFArrayRef)value, indent + 1, maxWidth);
        }
    }
}
Beispiel #18
0
AUVPresets::AUVPresets (AUCarbonViewBase* 		inParentView, 
						CFArrayRef& 			inPresets,
						Point 					inLocation, 
						int 					nameWidth, 
						int 					controlWidth, 
						ControlFontStyleRec & 	inFontStyle)
	: AUPropertyControl (inParentView),
	  mPresets (inPresets),
	  mView (inParentView)
{
#if !__LP64__
	Rect r;
	
	// ok we now have an array of factory presets
	// get their strings and display them

	r.top = inLocation.v;		r.bottom = r.top;
	r.left = inLocation.h;		r.right = r.left;
	
    // localize as necessary
    if (!sAUVPresetLocalized) {
        CFBundleRef mainBundle = CFBundleGetBundleWithIdentifier(kLocalizedStringBundle_AUView);
        if (mainBundle) {
            kStringFactoryPreset =	CFCopyLocalizedStringFromTableInBundle(
                                        kAUViewLocalizedStringKey_FactoryPreset, kLocalizedStringTable_AUView,
                                        mainBundle, CFSTR("FactoryPreset title string"));
            sAUVPresetLocalized = true;
        }
    }
    
    // create localized title string
    CFMutableStringRef factoryPresetsTitle = CFStringCreateMutable(NULL, 0);
    CFStringAppend(factoryPresetsTitle, kStringFactoryPreset);
    CFStringAppend(factoryPresetsTitle, kAUViewUnlocalizedString_TitleSeparator);
    
	ControlRef theControl;
    verify_noerr(CreateStaticTextControl(mView->GetCarbonWindow(), &r, factoryPresetsTitle, &inFontStyle, &theControl));
	SInt16 width = 0;
	AUCarbonViewControl::SizeControlToFit(theControl, &width, &mHeight);
    CFRelease(factoryPresetsTitle);
	EmbedControl(theControl);
	
	r.top -= 2;
	r.left += width + 10;
	r.right = r.left;
	r.bottom = r.top;
	
	verify_noerr(CreatePopupButtonControl (	mView->GetCarbonWindow(), &r, NULL, 
											-12345,	// DON'T GET MENU FROM RESOURCE mMenuID,!!!
											FALSE,	// variableWidth, 
											0,		// titleWidth, 
											0,		// titleJustification, 
											0,		// titleStyle, 
											&mControl));
	
	MenuRef menuRef;
	verify_noerr(CreateNewMenu(1, 0, &menuRef));
	
	int numPresets = CFArrayGetCount(mPresets);
	
	for (int i = 0; i < numPresets; ++i)
	{
		AUPreset* preset = (AUPreset*) CFArrayGetValueAtIndex (mPresets, i);
		verify_noerr(AppendMenuItemTextWithCFString (menuRef, preset->presetName, 0, 0, 0));
	}
	
	verify_noerr(SetControlData(mControl, 0, kControlPopupButtonMenuRefTag, sizeof(menuRef), &menuRef));
	verify_noerr (SetControlFontStyle (mControl, &inFontStyle));
	
	SetControl32BitMaximum (mControl, numPresets);
	
	// size popup
	SInt16 height = 0;
	
	AUCarbonViewControl::SizeControlToFit(mControl, &width, &height);
	
	if (height > mHeight) mHeight = height;
	if (mHeight < 0) mHeight = 0;
	
	// find which menu item is the Default preset
	UInt32 propertySize = sizeof(AUPreset);
	AUPreset defaultPreset;
	OSStatus result = AudioUnitGetProperty (mView->GetEditAudioUnit(), 
									kAudioUnitProperty_PresentPreset,
									kAudioUnitScope_Global, 
									0, 
									&defaultPreset, 
									&propertySize);
	
	mPropertyID = kAudioUnitProperty_PresentPreset;
#endif	
#ifndef __LP64__
	if (result != noErr) {	// if the PresentPreset property is not implemented, fall back to the CurrentPreset property
		OSStatus result = AudioUnitGetProperty (mView->GetEditAudioUnit(), 
									kAudioUnitProperty_CurrentPreset,
									kAudioUnitScope_Global, 
									0, 
									&defaultPreset, 
									&propertySize);
		mPropertyID = kAudioUnitProperty_CurrentPreset;
		if (result == noErr)
			CFRetain (defaultPreset.presetName);
	} 
#endif
#if !__LP64__		
	EmbedControl (mControl);
	
	HandlePropertyChange(defaultPreset);
	
	RegisterEvents();
#endif
}
Beispiel #19
0
static netfsError
CreateURL9P(CFDictionaryRef params, CFURLRef *url)
{
	CFMutableStringRef urlstr;
	CFStringRef str;
	int e;

	TRACE();
	if (url==NULL || params==NULL)
		return EINVAL;

DEBUG("params=%s", NetFSCFStringtoCString(CFCopyDescription(params)));
	urlstr = CFStringCreateMutable(kCFAllocatorDefault, 0);
	if (urlstr == NULL)
		return ENOMEM;

	str = CFDictionaryGetValue(params, kNetFSSchemeKey);
	if (str == NULL)
		goto error;

	CFStringAppend(urlstr, str);
	CFStringAppend(urlstr, CFSTR("://"));

	str = CFDictionaryGetValue(params, kNetFSUserNameKey);
	if (str != NULL) {
		str = CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, str, NULL, CFSTR("@:/?"), kCFStringEncodingUTF8);
		CFStringAppend(urlstr, str);
		CFRelease(str);
		str = CFDictionaryGetValue(params, kNetFSPasswordKey);
		if (str != NULL) {
			str = CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, str, NULL, CFSTR("@:/?"), kCFStringEncodingUTF8);
			CFStringAppend(urlstr, CFSTR(":"));
			CFStringAppend(urlstr, str);
			CFRelease(str);
		}
		CFStringAppend(urlstr, CFSTR("@"));
	}

	str = CFDictionaryGetValue(params, kNetFSHostKey);
	if (str == NULL)
		goto error;

	str = CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, str, CFSTR("[]"), CFSTR("/@:,?=;&+$"), kCFStringEncodingUTF8);
	CFStringAppend(urlstr, str);
	CFRelease(str);

	str = CFDictionaryGetValue(params, kNetFSAlternatePortKey);
	if (str != NULL) {
		str = CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, str, NULL, NULL, kCFStringEncodingUTF8);
		CFStringAppend(urlstr, CFSTR(":"));
		CFStringAppend(urlstr, str);
		CFRelease(str);
	}

/*
	str = CFDictionaryGetValue(params, kNetFSPathKey);
	if (str != NULL) {
		str = CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, str, NULL, CFSTR("?"), kCFStringEncodingUTF8);
		CFStringAppend(urlstr, str);
		CFRelease(str);
	}
*/
	*url = CFURLCreateWithString(kCFAllocatorDefault, urlstr, NULL);
	if (*url == NULL)
		goto error;

DEBUG("url=%s", NetFSCFStringtoCString(CFURLGetString(*url)));
	CFRelease(urlstr);
	return 0;

error:
	e = errno;
	*url = NULL;
	CFRelease(urlstr);
	return e;
}
Boolean GetMetadataForFile(void* thisInterface, 
			   CFMutableDictionaryRef attributes, 
			   CFStringRef contentTypeUTI,
			   CFStringRef pathToFile)
{
    Boolean success = false;

	CFDictionaryRef	tempDictRef;
	CFStringRef		tempTitleRef;
	CFArrayRef		tempContentRef;

	// load the document at the specified location	
	CFURLRef		pathToFileURL;
	pathToFileURL = CFURLCreateWithFileSystemPath(kCFAllocatorDefault, pathToFile, kCFURLPOSIXPathStyle, false);
	tempDictRef = (CFDictionaryRef)CreatePropertiesFromXMLFile(pathToFileURL);
    CFRelease(pathToFileURL);

    if (tempDictRef)
    {
		CFStringRef	tempBrdNameRef;
		CFStringRef	tempDatNumberRef;
		CFNumberRef	tempLengthRef;
		CFDateRef	tempCreatedDateRef;
		CFDateRef	tempModifiedDateRef;

		CFDictionarySetValue(attributes, kMDItemCreator, CFSTR("BathyScaphe"));

		// set the kMDItemTitle attribute to the Title
		tempTitleRef = CFDictionaryGetValue(tempDictRef, CFSTR("Title"));
		if (tempTitleRef != NULL) {
			CFDictionarySetValue(attributes, kMDItemTitle, tempTitleRef);
			CFDictionarySetValue(attributes, kMDItemDisplayName, tempTitleRef);
		}
		
		tempBrdNameRef = CFDictionaryGetValue(tempDictRef, CFSTR("BoardName"));
		if (tempBrdNameRef != NULL)
			CFDictionarySetValue(attributes, CFSTR("jp_tsawada2_bathyscaphe_thread_BoardName"), tempBrdNameRef);

		tempDatNumberRef = CFDictionaryGetValue(tempDictRef, CFSTR("dat"));
		if (tempDatNumberRef != NULL)
			CFDictionarySetValue(attributes, CFSTR("jp_tsawada2_bathyscaphe_thread_DatNumber"), tempDatNumberRef);

		tempLengthRef = CFDictionaryGetValue(tempDictRef, CFSTR("Length"));
		if (tempLengthRef != NULL)
			CFDictionarySetValue(attributes, CFSTR("jp_tsawada2_bathyscaphe_thread_DatSize"), tempLengthRef);

		tempCreatedDateRef = CFDictionaryGetValue(tempDictRef, CFSTR("CreatedDate"));
		if (tempCreatedDateRef != NULL)
			CFDictionarySetValue(attributes, kMDItemContentCreationDate, tempCreatedDateRef);

		tempModifiedDateRef = CFDictionaryGetValue(tempDictRef, CFSTR("ModifiedDate"));
		if (tempModifiedDateRef != NULL)
			CFDictionarySetValue(attributes, kMDItemContentModificationDate, tempModifiedDateRef);

		tempContentRef = CFDictionaryGetValue(tempDictRef, CFSTR("Contents"));
		if (tempContentRef) {
			CFIndex	i, count_;
			CFNumberRef	countRef_;
			CFMutableStringRef	cont_ = CFStringCreateMutable(kCFAllocatorDefault, 0);
			CFMutableArrayRef	nameArray_ = CFArrayCreateMutable(kCFAllocatorDefault, 0, &kCFTypeArrayCallBacks);
			CFDictionaryRef	obj;
			CFNumberRef		statusStr;

			count_ = CFArrayGetCount(tempContentRef);

			countRef_ = CFNumberCreate(kCFAllocatorDefault, kCFNumberCFIndexType, &count_);
			CFDictionarySetValue(attributes, CFSTR("jp_tsawada2_bathyscaphe_thread_ResCount"), countRef_);
			CFRelease(countRef_);
			
			for (i=0; i<count_; i++) {
				obj = CFArrayGetValueAtIndex(tempContentRef, i);

				if (obj == NULL) continue;
				statusStr = CFDictionaryGetValue(obj, CFSTR("Status"));
				if (isNotAbonedRes(statusStr)) {
					CFStringRef	msg_;
					CFStringRef	name_;

					msg_ = CFDictionaryGetValue(obj, CFSTR("Message"));
					if (msg_) {
						CFStringAppend(cont_, msg_);
					}

					name_ = CFDictionaryGetValue(obj, CFSTR("Name"));
					if (name_) {
						Boolean already_ = CFArrayContainsValue(nameArray_, CFRangeMake(0, CFArrayGetCount(nameArray_)), name_);
						if (already_ == false) CFArrayAppendValue(nameArray_, name_);
					}
				}
			}

			CFStringFindAndReplace(cont_, CFSTR(" <br> "), CFSTR(""), CFRangeMake(0, CFStringGetLength(cont_)), 0);
			CFStringTrimWhitespace(cont_);
																	
			CFIndex	len;
			CFRange	searchRange;
			CFRange	resultRange;
			CFRange	gtRange;

			len = CFStringGetLength(cont_);
			searchRange = CFRangeMake(0, len);

			while (1) {
				Boolean	found_ = CFStringFindWithOptions(cont_, CFSTR("<a "), searchRange, kCFCompareCaseInsensitive, &resultRange);
				if (found_ == false) break;
				// Start searching next to "<"
				searchRange.location = resultRange.location + resultRange.length;
				searchRange.length = (len - searchRange.location);

				found_ = CFStringFindWithOptions(cont_, CFSTR("</a>"), searchRange, kCFCompareCaseInsensitive, &gtRange);
				if (found_ == false) break;
				resultRange.length = gtRange.location + gtRange.length - resultRange.location;
				CFStringDelete(cont_, resultRange);

				searchRange.length -= resultRange.length;
				len -= resultRange.length;
				
				if (searchRange.location >= len) break;
			}

			CFDictionarySetValue(attributes, kMDItemTextContent, cont_);
			CFDictionarySetValue(attributes, kMDItemContributors, nameArray_);
			
			CFRelease(cont_);
			CFRelease(nameArray_);
		}
		// release the loaded document
		CFRelease(tempDictRef);
		// return YES so that the attributes are imported
		success = true;
    }
    return success;
}
Beispiel #21
0
static CFStringRef __CFUserNotificationCopyDescription(CFTypeRef cf) {
    CFMutableStringRef result;
    result = CFStringCreateMutable(CFGetAllocator(cf), 0);
    CFStringAppendFormat(result, NULL, CFSTR("<CFUserNotification %p>"), cf);
    return result;
}
Beispiel #22
0
CFStringRef
SMBCreateNetBIOSName(CFStringRef proposedName)
{
    CFMutableStringRef  composedName;
    CFStringEncoding    codepage;
    CFIndex		    nconverted = 0;
    CFIndex		    nused = 0;

    uint8_t		    name_buffer[NetBIOS_NAME_LEN];

    if (proposedName == NULL) {
        return NULL;
    }

    codepage = getPrefsCodePage();

    composedName = CFStringCreateMutableCopy(kCFAllocatorDefault,
                   0, proposedName);
    if (!composedName) {
        return NULL;
    }
    CFStringTrimWhitespace(composedName);
    CFStringUppercase(composedName, CFLocaleGetSystem());

    nconverted = CFStringGetBytes(composedName,
                                  CFRangeMake(0,
                                          MIN((CFIndex)sizeof(name_buffer), CFStringGetLength(composedName))),
                                  codepage, 0 /* loss byte */, false /* no BOM */,
                                  name_buffer, sizeof(name_buffer), &nused);

    /* We expect the conversion above to always succeed, given that we
     * tried to remove anything that might not convert to a code page.
     */
    if (nconverted == 0) {
        char buf[256];

        buf[0] = '\0';
        CFStringGetCString(composedName, buf, sizeof(buf), kCFStringEncodingUTF8);
        SMBLogInfo("failed to compose a NetBIOS name string from '%s'",
                   ASL_LEVEL_DEBUG, buf);

        CFRelease(composedName);
        return NULL;
    }

    CFRelease(composedName);

    /* Null terminate for the benefit of CFStringCreate. Be careful to be
     * no more that 15 bytes, since the last byte is reserved for the name
     * type.
     */
    name_buffer[MIN(nused, (CFIndex)sizeof(name_buffer) - 1)] = '\0';

    composedName = CFStringCreateMutable(kCFAllocatorDefault,
                                         NetBIOS_NAME_LEN);
    if (composedName == NULL) {
        return NULL;
    }

    CFStringAppendCString(composedName, (const char *)name_buffer, codepage);
    return composedName;
}
//http://iphonedevwiki.net/index.php/Lockdownd
void get_device_infos(CFMutableDictionaryRef out) {
    CC_SHA1_CTX sha1ctx;
    uint8_t udid[20];
    char udid1[100];
    CFStringRef serial;
    CFStringRef imei;
    CFStringRef macwifi;
    CFStringRef macbt;
    
    CFStringRef hw = copy_hardware_model(); 
    if (hw != NULL)
    {
        CFDictionaryAddValue(out, CFSTR("hwModel"), hw);
        CFRelease(hw);
    }
    
    serial = copy_device_serial_number();
    imei = copy_device_imei();
    macwifi = copy_wifi_mac_address();
    macbt = copy_bluetooth_mac_address();
    
    CFMutableStringRef udidInput = CFStringCreateMutable(kCFAllocatorDefault, 0);
    if (serial != NULL)
    {
        CFStringAppend(udidInput, serial);
        CFDictionaryAddValue(out, CFSTR("serialNumber"), serial);
        CFRelease(serial);
    }
    
    uint64_t _ecid = 0;
    CFNumberRef ecid = copyNumberFromChosen(CFSTR("unique-chip-id"));
    if (ecid != NULL)
    {
        CFDictionaryAddValue(out, CFSTR("ECID"), ecid);
    }
    
    if (ecid != NULL && useNewUDID(hw))
    {
        CFNumberGetValue(ecid, kCFNumberSInt64Type, &_ecid);
        CFStringAppendFormat(udidInput, NULL, CFSTR("%llu"), _ecid);
    }
    else if (imei != NULL)
    {
        CFStringAppend(udidInput, imei);
        CFDictionaryAddValue(out, CFSTR("imei"), imei);
        CFRelease(imei);
    }
    if (macwifi != NULL)
    {
        CFStringAppend(udidInput, macwifi);
        CFDictionaryAddValue(out, CFSTR("wifiMac"), macwifi);
        CFRelease(macwifi);
    }
    if (macbt != NULL)
    {
        CFStringAppend(udidInput, macbt);
        CFDictionaryAddValue(out, CFSTR("btMac"), macbt);
        CFRelease(macbt);
    }
    
    CFStringGetCString(udidInput, udid1, 99, kCFStringEncodingASCII);
    
    CC_SHA1_Init(&sha1ctx);
    CC_SHA1_Update(&sha1ctx, udid1, CFStringGetLength(udidInput));
    CC_SHA1_Final(udid, &sha1ctx);
    
    CFRelease(udidInput);
    addHexaString(out, CFSTR("udid"), udid, 20);

}
Beispiel #24
0
MenuRef IGraphicsCarbon::CreateMenu(IPopupMenu* pMenu)
{
  MenuRef menuRef = 0;
  ResID menuID = UniqueID ('MENU');

  int numItems = pMenu->GetNItems();

  if (numItems && CreateNewMenu(menuID, kMenuAttrCondenseSeparators, &menuRef) == noErr)
  {
    for (int i = 0; i < numItems; ++i)
    {
      IPopupMenuItem* menuItem = pMenu->GetItem(i);

      if (menuItem->GetIsSeparator())
      {
        AppendMenuItemTextWithCFString(menuRef, CFSTR(""), kMenuItemAttrSeparator, 0, NULL);
      }
      else
      {
        CFStringRef itemString = CFStringCreateWithCString(NULL, menuItem->GetText(), kCFStringEncodingUTF8);

        if (pMenu->GetPrefix())
        {
          CFStringRef prefixString = 0;

          switch (pMenu->GetPrefix())
          {
            case 0:
              prefixString = CFStringCreateWithCString(NULL, "", kCFStringEncodingUTF8); break;
            case 1:
              prefixString = CFStringCreateWithFormat(NULL, 0, CFSTR("%1d: "),i+1); break;
            case 2:
              prefixString = CFStringCreateWithFormat(NULL, 0, CFSTR("%02d: "),i+1); break;
            case 3:
              prefixString = CFStringCreateWithFormat(NULL, 0, CFSTR("%03d: "),i+1); break;
          }

          CFMutableStringRef newItemString = CFStringCreateMutable(0, 0);
          CFStringAppend (newItemString, prefixString);
          CFStringAppend (newItemString, itemString);
          CFRelease (itemString);
          CFRelease (prefixString);
          itemString = newItemString;
        }

        if (itemString == 0)
          continue;

        MenuItemAttributes itemAttribs = kMenuItemAttrIgnoreMeta;

        if (!menuItem->GetEnabled())
        {
          itemAttribs |= kMenuItemAttrDisabled;
        }

        if (menuItem->GetIsTitle())
        {
          itemAttribs |= kMenuItemAttrSectionHeader;
        }

        InsertMenuItemTextWithCFString(menuRef, itemString, i, itemAttribs, 0);

        if (menuItem->GetChecked())
        {
          CheckMenuItem(menuRef, i+1, true);
        }

        if (menuItem->GetSubmenu())
        {
          MenuRef submenu = CreateMenu(menuItem->GetSubmenu());

          if (submenu)
          {
            SetMenuItemHierarchicalMenu(menuRef, i+1, submenu);
            CFRelease (submenu);
          }
        }

        CFRelease (itemString);
      }
    }

    //  if (pMenu->getStyle() & kCheckStyle && !multipleCheck)
    //    CheckMenuItem (menuRef, pMenu->getCurrentIndex (true) + 1, true);
    SetMenuItemRefCon(menuRef, 0, (int32_t)pMenu);
    //swell collision
    #undef InsertMenu
    InsertMenu(menuRef, kInsertHierarchicalMenu);
    #define InsertMenu SWELL_InsertMenu
  }

  return menuRef;
}
Beispiel #25
0
int main (int argc, const char * argv[]) {
	// This string was generated by the AquaticPrime Developer tool.
	// (I've converted it to use CoreFoundation instead of Foundation, however, as the
	//  AP Dev tool doesn't generate CF-based string obfuscation yet.)
	// *** Begin Public Key ***
	CFMutableStringRef exampleKey = CFStringCreateMutable(NULL, 0);
	CFStringAppend(exampleKey, CFSTR("0xC21727A4604EF3C70959D8645FDA"));
	CFStringAppend(exampleKey, CFSTR("C3C5FD49F"));
	CFStringAppend(exampleKey, CFSTR("E"));
	CFStringAppend(exampleKey, CFSTR("E"));
	CFStringAppend(exampleKey, CFSTR("02E46DC154A74B302C0"));
	CFStringAppend(exampleKey, CFSTR("041C"));
	CFStringAppend(exampleKey, CFSTR("3"));
	CFStringAppend(exampleKey, CFSTR("3"));
	CFStringAppend(exampleKey, CFSTR("F26028D0F3BF120A262B5E53"));
	CFStringAppend(exampleKey, CFSTR("E3CA86528D702E40F4B5"));
	CFStringAppend(exampleKey, CFSTR("2"));
	CFStringAppend(exampleKey, CFSTR("2"));
	CFStringAppend(exampleKey, CFSTR("BFBCAEA6"));
	CFStringAppend(exampleKey, CFSTR("3E9D31FD6976DC6C"));
	CFStringAppend(exampleKey, CFSTR("7"));
	CFStringAppend(exampleKey, CFSTR("7"));
	CFStringAppend(exampleKey, CFSTR("97D8354F3629"));
	CFStringAppend(exampleKey, CFSTR("DEFEB572AFA4A"));
	CFStringAppend(exampleKey, CFSTR("2"));
	CFStringAppend(exampleKey, CFSTR("2"));
	CFStringAppend(exampleKey, CFSTR("96F24DAB115EE71"));
	CFStringAppend(exampleKey, CFSTR("C06"));
	CFStringAppend(exampleKey, CFSTR("1"));
	CFStringAppend(exampleKey, CFSTR("1"));
	CFStringAppend(exampleKey, CFSTR("5BF0CF6E4383ACB9EA4473396"));
	CFStringAppend(exampleKey, CFSTR("49397BE"));
	CFStringAppend(exampleKey, CFSTR("D"));
	CFStringAppend(exampleKey, CFSTR("D"));
	CFStringAppend(exampleKey, CFSTR("48F556054DD9274A85448"));
	CFStringAppend(exampleKey, CFSTR("69BADE5F51EF06D897"));
	// *** End Public Key ***
	
	// Convert the example license file string to a CFData.
	// In a real app, you'd get this from somewhere else (e.g. a server), or use 
	// one of the file-based AP methods.
	CFDataRef exampleLicenseFileData = CFDataCreate(NULL,
													(const UInt8 *)exampleLicenseFileContents,
													(CFIndex)strlen(exampleLicenseFileContents));
	
	// Now, verify the license.
	// Try changing the example license file contents above and see what happens.
	
	// Let AP know what our public key is, so it can verify the signature.
	APSetKey(exampleKey);
	
	// You can just get back a boolean whether the license data is valid or not:
	Boolean licenseIsValid = APVerifyLicenseData(exampleLicenseFileData);
	if(licenseIsValid)
		CFShow(CFSTR("License passed boolean verification!\n"));
	else
		CFShow(CFSTR("License failed boolean verification!\n"));
	
	// Or, you can get back a full dictionary:
	CFDictionaryRef licenseDictionary = APCreateDictionaryForLicenseData(exampleLicenseFileData);
	if(licenseDictionary) {
		CFShow(licenseDictionary);
		CFRelease(licenseDictionary);
	} else {
		CFShow(CFSTR("No license dictionary results.\n"));
	}
	
	CFRelease(exampleLicenseFileData);
	CFRelease(exampleKey);

    return 0;
}
int main(int argc, char **argv)
{
	bool quiet = false;
	bool doPause = false;
	
	int arg;
	while ((arg = getopt(argc, argv, "pqh")) != -1) {
		switch (arg) {
			case 'q':
				quiet = true;
				break;
			case 'p':
				doPause = true;
				break;
			case 'h':
				usage(argv);
		}
	}
	if(optind != argc) {
		usage(argv);
	}
	
	testStartBanner("certLabelTest", argc, argv);
	
	CSSM_CL_HANDLE	clHand = clStartup();
	CSSM_CSP_HANDLE cspHand = cspStartup();
	
	/* create a key pair */
	CSSM_RETURN crtn;
	CSSM_KEY pubKey;
	CSSM_KEY privKey;
	
	crtn = cspGenKeyPair(cspHand, KEY_ALG, 
		"someLabel", 8,
		KEY_SIZE,
		&pubKey, CSSM_FALSE, CSSM_KEYUSE_ANY, CSSM_KEYBLOB_RAW_FORMAT_NONE,
		&privKey, CSSM_FALSE, CSSM_KEYUSE_ANY, CSSM_KEYBLOB_RAW_FORMAT_NONE, 
		CSSM_FALSE);
	if(crtn) {
		printf("***Error generating RSA key pair. Aborting.\n");
		exit(1);
	}
	
	/* common params, reused for each test */
	notBefore = CB_BuildX509Time(0);
	notAfter = CB_BuildX509Time(100000);
	
	/* 
	 * Grind thru test cases.
	 */
	int ourRtn;
	
	/* very basic */
	ourRtn = doTest("simple ASCII common name", quiet, 
		cspHand, clHand, &privKey, &pubKey,
		"Simple Name", strlen("Simple Name"), BER_TAG_PRINTABLE_STRING, &CSSMOID_CommonName,
		NULL, 0, BER_TAG_UNKNOWN, NULL, 
		CFSTR("Simple Name"), true);
	if(ourRtn) {
		exit(1);
	}
	
	/* test concatentation of description */
	ourRtn = doTest("ASCII common name plus ASCII description", quiet, 
		cspHand, clHand, &privKey, &pubKey,
		"Simple Name", strlen("Simple Name"), BER_TAG_PRINTABLE_STRING, &CSSMOID_CommonName,
		"Description", strlen("Description"), BER_TAG_PRINTABLE_STRING, &CSSMOID_Description, 
		CFSTR("Simple Name (Description)"), false);
	if(ourRtn) {
		exit(1);
	}

	/* basic, specifying UTF8 (should be same as PRINTABLE) */
	ourRtn = doTest("simple UTF8 common name", quiet, 
		cspHand, clHand, &privKey, &pubKey,
		"Simple Name", strlen("Simple Name"), BER_TAG_PKIX_UTF8_STRING, &CSSMOID_CommonName,
		NULL, 0, BER_TAG_UNKNOWN, NULL, 
		CFSTR("Simple Name"), true);
	if(ourRtn) {
		exit(1);
	}

	/* label from org name instead of common name */
	ourRtn = doTest("label from OrgName", quiet, 
		cspHand, clHand, &privKey, &pubKey,
		"Simple Name", strlen("Simple Name"), BER_TAG_PRINTABLE_STRING, &CSSMOID_OrganizationName,
		NULL, 0, BER_TAG_UNKNOWN, NULL, 
		CFSTR("Simple Name"), false);
	if(ourRtn) {
		exit(1);
	}

	/* label from orgUnit name instead of common name */
	ourRtn = doTest("label from OrgUnit", quiet, 
		cspHand, clHand, &privKey, &pubKey,
		"Simple Name", strlen("Simple Name"), BER_TAG_PRINTABLE_STRING, &CSSMOID_OrganizationalUnitName,
		NULL, 0, BER_TAG_UNKNOWN, NULL, 
		CFSTR("Simple Name"), false);
	if(ourRtn) {
		exit(1);
	}

	/* label from orgUnit name, description is ignored (it's only used if the 
	 * label comes from CommonName) */
	ourRtn = doTest("label from OrgUnit, description is ignored", quiet, 
		cspHand, clHand, &privKey, &pubKey,
		"Simple Name", strlen("Simple Name"), BER_TAG_PRINTABLE_STRING, &CSSMOID_OrganizationalUnitName,
		"Description", strlen("Description"), BER_TAG_PRINTABLE_STRING, &CSSMOID_Description, 
		CFSTR("Simple Name"), false);
	if(ourRtn) {
		exit(1);
	}

	/* Radar 3529689: T61/Teletex, ISOLatin encoding, commonName only */
	CFStringRef t61Str = CFStringCreateWithBytes(NULL, JurgenPetersen, sizeof(JurgenPetersen),
				kCFStringEncodingISOLatin1, true);
	ourRtn = doTest("T61/Teletex name from Radar 3529689", quiet, 
		cspHand, clHand, &privKey, &pubKey,
		JurgenPetersen, sizeof(JurgenPetersen), BER_TAG_TELETEX_STRING, &CSSMOID_CommonName,
		NULL, 0, BER_TAG_UNKNOWN, NULL, 
		t61Str, true);
	if(ourRtn) {
		exit(1);
	}
	
	/* Now convert that ISOLatin into Unicode and try with that */
	CFDataRef unicodeStr = CFStringCreateExternalRepresentation(NULL, t61Str,
			kCFStringEncodingUnicode, 0);
	if(unicodeStr == NULL) {
		printf("***Error converting to Unicode\n");
		exit(1);
	}
	ourRtn = doTest("Unicode CommonName", quiet, 
		cspHand, clHand, &privKey, &pubKey,
		CFDataGetBytePtr(unicodeStr), CFDataGetLength(unicodeStr), 
				BER_TAG_PKIX_BMP_STRING, &CSSMOID_CommonName,
		NULL, 0, BER_TAG_UNKNOWN, NULL, 
		t61Str, true);
	if(ourRtn) {
		exit(1);
	}
	CFRelease(unicodeStr);
	
	/* Mix up ISOLatin Common Name and ASCII Description to ensure that the encodings
	 * of the two components are handled separately */
	CFMutableStringRef combo = CFStringCreateMutable(NULL, 0);
	CFStringAppend(combo, t61Str);
	CFStringAppendCString(combo, " (Description)", kCFStringEncodingASCII);
	ourRtn = doTest("ISOLatin Common Name and ASCII Description", quiet, 
		cspHand, clHand, &privKey, &pubKey,
		JurgenPetersen, sizeof(JurgenPetersen), BER_TAG_TELETEX_STRING, &CSSMOID_CommonName,
		"Description", strlen("Description"), BER_TAG_PRINTABLE_STRING, &CSSMOID_Description, 
		combo, false);
	if(ourRtn) {
		exit(1);
	}
	CFRelease(combo);
	CFRelease(t61Str);
				
	if(doPause) {
		fpurge(stdin);
		printf("Pausing for leaks testing; CR to continue: ");
		getchar();
	}
	if(!quiet) {
		printf("...success\n");
	}
	return 0;
}