int main (int argc, char **argv)
{
	static PRIntervalTime thread_start_time;
	static PRThread *housekeeping_tid = NULL;
	PLOptStatus os;
	PLOptState *opt = PL_CreateOptState(argc, argv, "d");

	while (PL_OPT_EOL != (os = PL_GetNextOpt(opt)))
	{
		if (PL_OPT_BAD == os) continue;
		switch (opt->option)
		{
			case 'd':  /* debug mode */
				_debug_on = 1;
				break;
			default:
				break;
		}
	}
	PL_DestroyOptState(opt);

	if (( housekeeping_tid = 
		PR_CreateThread (PR_USER_THREAD, housecleaning,  (void*)&thread_start_time,
						 PR_PRIORITY_NORMAL, PR_GLOBAL_THREAD, PR_UNJOINABLE_THREAD, 0)) 
																		== NULL ) {
		fprintf(stderr,
			"simple_test: Error - PR_CreateThread failed: (%ld, %ld)\n",
									  PR_GetError(), PR_GetOSError());
		exit( 1 );
	}
	PR_Cleanup();
	return(0);
}
Example #2
0
int main(int argc, char **argv)
{

	int count, errnum;

    /*
     * -d           debug mode
     */

    PLOptStatus os;
    PLOptState *opt = PL_CreateOptState(argc, argv, "d");
    while (PL_OPT_EOL != (os = PL_GetNextOpt(opt)))
    {
        if (PL_OPT_BAD == os) continue;
        switch (opt->option)
        {
        case 'd':  /* debug mode */
            _debug_on = 1;
            break;
        default:
            break;
        }
    }
    PL_DestroyOptState(opt);

	count = sizeof(errcodes)/sizeof(errcodes[0]);
	printf("\nNumber of error codes = %d\n\n",count);
	for (errnum = 0; errnum < count; errnum++) {
		printf("%-40s = %d\n",errcodes[errnum].errname,
						errcodes[errnum].errcode);
	}

	return 0;
}
int
main(int argc, char **argv)
{
  char *       progName = NULL;
  SECStatus    secStatus;
  PLOptState  *optstate;
  PLOptStatus  status;

  /* Call the NSPR initialization routines */
  PR_Init( PR_SYSTEM_THREAD, PR_PRIORITY_NORMAL, 1);

  progName = PL_strdup(argv[0]);

  hostName = NULL;
  optstate = PL_CreateOptState(argc, argv, "d:h:i:o:p:t:");
  while ((status = PL_GetNextOpt(optstate)) == PL_OPT_OK)
    {
      switch(optstate->option)
	{
	case 'd' : certDir = PL_strdup(optstate->value);      break;
	case 'h' : hostName = PL_strdup(optstate->value);     break;
	case 'i' : infileName = PL_strdup(optstate->value);   break;
	case 'o' : outfileName = PL_strdup(optstate->value);  break;
	case 'p' : port = PORT_Atoi(optstate->value);         break;
	case 't' : trustNewServer_p = PL_strdup(optstate->value);  break;
	case '?' :
	default  : Usage(progName);
	}
    }

  if (port == 0 || hostName == NULL || infileName == NULL || outfileName == NULL || certDir == NULL)
    Usage(progName);

#if 0 /* no client authentication */
  /* Set our password function callback. */
  PK11_SetPasswordFunc(myPasswd);
#endif

  /* Initialize the NSS libraries. */
  secStatus = NSS_InitReadWrite(certDir);
  if (secStatus != SECSuccess)
    {
      /* Try it again, readonly.  */
      secStatus = NSS_Init(certDir);
      if (secStatus != SECSuccess)
	exitErr("Error initializing NSS", GENERAL_ERROR);
    }

  /* All cipher suites except RSA_NULL_MD5 are enabled by Domestic Policy. */
  NSS_SetDomesticPolicy();

  client_main(port);

  NSS_Shutdown();
  PR_Cleanup();

  return 0;
}
Example #4
0
int main(int argc, char **argv)
{
	PRInt32 initial_threads = DEFAULT_INITIAL_THREADS;
	PRInt32 max_threads = DEFAULT_MAX_THREADS;
	PRInt32 stacksize = DEFAULT_STACKSIZE;
	PRThreadPool *tp = NULL;
	PRStatus rv;
	PRJob *jobp;

    /*
     * -d           debug mode
     */
    PLOptStatus os;
    PLOptState *opt;

	program_name = argv[0];
    opt = PL_CreateOptState(argc, argv, "d");
    while (PL_OPT_EOL != (os = PL_GetNextOpt(opt)))
    {
        if (PL_OPT_BAD == os) continue;
        switch (opt->option)
        {
        case 'd':  /* debug mode */
            _debug_on = 1;
            break;
        default:
            break;
        }
    }
    PL_DestroyOptState(opt);

    PR_Init(PR_USER_THREAD, PR_PRIORITY_NORMAL, 0);
    PR_STDIO_INIT();

    PR_SetConcurrency(4);

	tp = PR_CreateThreadPool(initial_threads, max_threads, stacksize);
    if (NULL == tp) {
        printf("PR_CreateThreadPool failed\n");
        failed_already=1;
        goto done;
	}
	jobp = PR_QueueJob(tp, TCP_Server, tp, PR_TRUE);
	rv = PR_JoinJob(jobp);		
	PR_ASSERT(PR_SUCCESS == rv);

	DPRINTF(("%s: calling PR_JoinThreadPool\n", program_name));
	rv = PR_JoinThreadPool(tp);
	PR_ASSERT(PR_SUCCESS == rv);
	DPRINTF(("%s: returning from PR_JoinThreadPool\n", program_name));

done:
    PR_Cleanup();
    if (failed_already) return 1;
    else return 0;
}
int main(int argc, char **argv)
{
    PLOptStatus os;
    PLOptState *opt = PL_CreateOptState(argc, argv, "dh");
    PRFileDesc* fd;
    PRErrorCode err;

    /* parse command line options */
    while (PL_OPT_EOL != (os = PL_GetNextOpt(opt))) {
        if (PL_OPT_BAD == os) continue;
        switch (opt->option) {
            case 'd':  /* debug mode */
                debug_mode = PR_TRUE;
                break;
            case 'h':
            default:
                Help();
                return 2;
        }
    }
    PL_DestroyOptState(opt);

    lm = PR_NewLogModule( "testcase" );

    (void) PR_MkDir( DIRNAME, 0777);
    fd = PR_Open( DIRNAME FILENAME, PR_CREATE_FILE|PR_RDWR, 0666);
    if (fd == 0) {
        PRErrorCode err = PR_GetError();
        fprintf(stderr, "create file fails: %d: %s\n", err,
            PR_ErrorToString(err, PR_LANGUAGE_I_DEFAULT));
        failed_already = PR_TRUE;
        goto Finished;
    }
 
    PR_Close(fd);

    if (PR_RmDir( DIRNAME ) == PR_SUCCESS) {
        fprintf(stderr, "remove directory succeeds\n");
        failed_already = PR_TRUE;
        goto Finished;
    }
 
    err = PR_GetError();
    fprintf(stderr, "remove directory fails with: %d: %s\n", err,
        PR_ErrorToString(err, PR_LANGUAGE_I_DEFAULT));

    (void) PR_Delete( DIRNAME FILENAME);
    (void) PR_RmDir( DIRNAME );

    return 0;

Finished:
    if ( debug_mode ) printf("%s\n", ( failed_already ) ? "FAILED" : "PASS" );
    return( (failed_already)? 1 : 0 );
}  /* --- end main() */
Example #6
0
PRIntn main(PRIntn argc, char *argv[])
{
    PLOptStatus os;
	PLOptState *opt = PL_CreateOptState(argc, argv, "dhp:P:a:A:i:s:t:");
	while (PL_OPT_EOL != (os = PL_GetNextOpt(opt)))
    {
		if (PL_OPT_BAD == os) continue;
        switch (opt->option)
        {
        case 'a':  /* arena Min size */
            arenaMin = atol( opt->value );
            break;
        case 'A':  /* arena Max size  */
            arenaMax = atol( opt->value );
            break;
        case 'p':  /* pool Min size */
            poolMin = atol( opt->value );
            break;
        case 'P':  /* pool Max size */
            poolMax = atol( opt->value );
            break;
        case 'i':  /* Iterations in stress tests */
            stressIterations = atol( opt->value );
            break;
        case 's':  /* storage to get per iteration */
            maxAlloc = atol( opt->value );
            break;
        case 't':  /* Number of stress threads to create */
            stressThreads = atol( opt->value );
            break;
        case 'd':  /* debug mode */
			debug_mode = 1;
            break;
        case 'h':  /* help */
        default:
            Help();
        } /* end switch() */
    } /* end while() */
	PL_DestroyOptState(opt);

    srand( (unsigned)time( NULL ) ); /* seed random number generator */
    tLM = PR_NewLogModule("testcase");


#if 0
	ArenaAllocate();
	ArenaGrow();
#endif

    MarkAndRelease();

    Stress();

    return(EvaluateResults());
} /* end main() */
Example #7
0
static PRIntn PR_CALLBACK RealMain(PRIntn argc, char **argv)
{
    Overlay_i si;
    Overlay_u ui;
    PLOptStatus os;
    PRBool bsi = PR_FALSE, bui = PR_FALSE;
    PLOptState *opt = PL_CreateOptState(argc, argv, "hi:u:");
    err = PR_GetSpecialFD(PR_StandardError);

    while (PL_OPT_EOL != (os = PL_GetNextOpt(opt)))
    {
        if (PL_OPT_BAD == os) continue;
        switch (opt->option)
        {
        case 'i':  /* signed integer */
            si.i = (PRInt32)atoi(opt->value);
            bsi = PR_TRUE;
            break;
        case 'u':  /* unsigned */
            ui.i = (PRUint32)atoi(opt->value);
            bui = PR_TRUE;
            break;
        case 'h':  /* user wants some guidance */
         default:
            Help();  /* so give him an earful */
            return 2;  /* but not a lot else */
        }
    }
    PL_DestroyOptState(opt);

#if defined(HAVE_LONG_LONG)
    PR_fprintf(err, "We have long long\n");
#else
    PR_fprintf(err, "We don't have long long\n");
#endif

    if (bsi)
    {
        PR_fprintf(err, "Converting %ld: ", si.i);
        LL_I2L(si.l, si.i);
        PR_fprintf(err, "%lld\n", si.l);
    }

    if (bui)
    {
        PR_fprintf(err, "Converting %lu: ", ui.i);
        LL_I2L(ui.l, ui.i);
        PR_fprintf(err, "%llu\n", ui.l);
    }
    return 0;

}  /* main */
Example #8
0
static PRIntn PR_CALLBACK RealMain( PRIntn argc, char **argv )
{
	/* The command line argument: -d is used to determine if the test is being run
	in debug mode. The regress tool requires only one line output:PASS or FAIL.
	All of the printfs associated with this test has been handled with a if (debug_mode)
	test.
	Usage: test_name -d
	*/
	
	PLOptStatus os;
	PLOptState *opt = PL_CreateOptState(argc, argv, "d:");
	while (PL_OPT_EOL != (os = PL_GetNextOpt(opt)))
    {
		if (PL_OPT_BAD == os) continue;
        switch (opt->option)
        {
        case 'd':  /* debug mode */
			debug_mode = 1;
            break;
         default:
            break;
        }
    }
	PL_DestroyOptState(opt);

    PR_Init(PR_USER_THREAD, PR_PRIORITY_NORMAL, 0);
    PR_STDIO_INIT();

#ifdef XP_MAC
	SetupMacPrintfLog("joinuk.log");
#endif

	
	
 /* main test */

    if (debug_mode) printf("User-Kernel test\n");
    runTest(PR_LOCAL_THREAD, PR_GLOBAL_THREAD);


	if(failed_already)	
	{
        printf("FAIL\n");
		return 1;
    } else 
    {
        printf("PASS\n");
		return 0;
    }
}
Example #9
0
static PRIntn PR_CALLBACK RealMain(int argc, char **argv)
{
    /* The command line argument: -d is used to determine if the test is being run
    in debug mode. The regress tool requires only one line output:PASS or FAIL.
    All of the printfs associated with this test has been handled with a if (debug_mode)
    test.
    Usage: test_name [-d] [-c n]
    */
    PLOptStatus os;
    PLOptState *opt = PL_CreateOptState(argc, argv, "dc:");
    while (PL_OPT_EOL != (os = PL_GetNextOpt(opt)))
    {
        if (PL_OPT_BAD == os) continue;
        switch (opt->option)
        {
        case 'd':  /* debug mode */
            debug_mode = 1;
            break;
        case 'c':  /* loop count */
            count = atoi(opt->value);
            break;
        default:
            break;
        }
    }
    PL_DestroyOptState(opt);

    if (0 == count) count = DEFAULT_COUNT;

#ifdef XP_MAC
    SetupMacPrintfLog("cvar.log");
    debug_mode = 1;
#endif

    mon = PR_NewMonitor();

    Measure(CondWaitContextSwitchUU, "cond var wait context switch- user/user");
    Measure(CondWaitContextSwitchUK, "cond var wait context switch- user/kernel");
    Measure(CondWaitContextSwitchKK, "cond var wait context switch- kernel/kernel");

    PR_DestroyMonitor(mon);

    if (debug_mode) printf("%s\n", (failed) ? "FAILED" : "PASSED");

    if(failed)
        return 1;
    else
        return 0;
}
Example #10
0
int main(int argc, char **argv)
{
	
	/* The command line argument: -d is used to determine if the test is being run
	in debug mode. The regress tool requires only one line output:PASS or FAIL.
	All of the printfs associated with this test has been handled with a if (debug_mode)
	test.
	Usage: test_name -d
	*/
	PLOptStatus os;
	PLOptState *opt = PL_CreateOptState(argc, argv, "d:");
	while (PL_OPT_EOL != (os = PL_GetNextOpt(opt)))
    {
		if (PL_OPT_BAD == os) continue;
        switch (opt->option)
        {
        case 'd':  /* debug mode */
			debug_mode = 1;
            break;
         default:
            break;
        }
    }
	PL_DestroyOptState(opt);

 /* main test */
	
    PR_Init(PR_USER_THREAD, PR_PRIORITY_NORMAL, 0);
    PR_STDIO_INIT();

    if (argc > 2) {
	count = atoi(argv[2]);
    } else {
	count = DEFAULT_COUNT;
    }

#if defined(XP_UNIX)
    Measure(NativeSelectTest, "time to call 1 element select()");
#endif
    Measure(EmptyPRSelect, "time to call Empty PR_select()");
    Measure(EmptyNativeSelect, "time to call Empty select()");
    Measure(PRSelectTest, "time to call 1 element PR_select()");

	if (!debug_mode) Test_Result (NOSTATUS);
    PR_Cleanup();


}
int main(int argc, char **argv)
{
    PRInt32 num_threads;

	/* The command line argument: -d is used to determine if the test is being run
	in debug mode. The regress tool requires only one line output:PASS or FAIL.
	All of the printfs associated with this test has been handled with a if (debug_mode)
	test.
	Usage: test_name -d
	*/
	PLOptStatus os;
	PLOptState *opt = PL_CreateOptState(argc, argv, "d:");
	while (PL_OPT_EOL != (os = PL_GetNextOpt(opt)))
    {
		if (PL_OPT_BAD == os) continue;
        switch (opt->option)
        {
        case 'd':  /* debug mode */
			debug_mode = 1;
            break;
         default:
            break;
        }
    }
	PL_DestroyOptState(opt);

 /* main test */
	
    if (argc > 2)
        num_threads = atoi(argv[2]);
    else
        num_threads = NUM_THREADS;

    PR_Init(PR_USER_THREAD, PR_PRIORITY_LOW, 0);
    PR_STDIO_INIT();

    if (debug_mode)     printf("kernel level test\n");
    thread_test(PR_GLOBAL_THREAD, num_threads);

     PR_Cleanup();
     
     if(failed_already)    
        return 1;
    else
        return 0;

}
Example #12
0
int main(int argc, char **argv)
{
    {
        /*
        ** Get command line options
        */
        PLOptStatus os;
        PLOptState *opt = PL_CreateOptState(argc, argv, "hdv");

	    while (PL_OPT_EOL != (os = PL_GetNextOpt(opt)))
        {
		    if (PL_OPT_BAD == os) continue;
            switch (opt->option)
            {
            case 'd':  /* debug */
                debug = 1;
			    msgLevel = PR_LOG_ERROR;
                break;
            case 'v':  /* verbose mode */
			    msgLevel = PR_LOG_DEBUG;
                break;
            case 'h':  /* help message */
			    Help();
                break;
             default:
                break;
            }
        }
	    PL_DestroyOptState(opt);
    }

    lm = PR_NewLogModule("Test");       /* Initialize logging */
    for ( i = 0; i < optRandCount ; i++ ) {
        memset( buf, 0, bufSize );
        rSize = PR_GetRandomNoise( buf, bufSize );
        if (!rSize) {
            fprintf(stderr, "Not implemented\n" );
            failed_already = PR_TRUE;
            break;
        }
        if (debug) PrintRand( buf, rSize );
    }

    if (debug) printf("%s\n", (failed_already)? "FAIL" : "PASS");
    return( (failed_already == PR_TRUE )? 1 : 0 );
}  /* main() */
Example #13
0
int main(int argc, char **argv)
{
	/* The command line argument: -d is used to determine if the test is being run
	in debug mode. The regress tool requires only one line output:PASS or FAIL.
	All of the printfs associated with this test has been handled with a if (debug_mode)
	test.
	Usage: test_name -d
	*/
	PLOptStatus os;
	PLOptState *opt = PL_CreateOptState(argc, argv, "d:");
	while (PL_OPT_EOL != (os = PL_GetNextOpt(opt)))
    {
		if (PL_OPT_BAD == os) continue;
        switch (opt->option)
        {
        case 'd':  /* debug mode */
			debug_mode = 1;
            break;
         default:
            break;
        }
    }
	PL_DestroyOptState(opt);

    PR_Init(PR_USER_THREAD, PR_PRIORITY_NORMAL, 0);
    PR_STDIO_INIT();

    if (argc > 1) {
	count = atoi(argv[1]);
    } else {
	count = DEFAULT_COUNT;
    }

    ftime_init();

    Measure(timeTime, "time to get time with time()");
    Measure(timeGethrtime, "time to get time with gethrtime()");
    Measure(timeGettimeofday, "time to get time with gettimeofday()");
    Measure(timePRTime32, "time to get time with PR_Time() (32bit)");
    Measure(timePRTime64, "time to get time with PR_Time() (64bit)");

	PR_Cleanup();
	return 0;
}
static PRIntn PR_CALLBACK RealMain( PRIntn argc, char **argv )
{
	PLOptStatus os;
  	PLOptState *opt = PL_CreateOptState(argc, argv, "dhlmc");
	PRBool locks = PR_FALSE, monitors = PR_FALSE, cmonitors = PR_FALSE;

    err = PR_GetSpecialFD(PR_StandardError);

	while (PL_OPT_EOL != (os = PL_GetNextOpt(opt)))
    {
		if (PL_OPT_BAD == os) continue;
        switch (opt->option)
        {
        case 'd':  /* debug mode (noop) */
            break;
        case 'l':  /* locks */
			locks = PR_TRUE;
            break;
        case 'm':  /* monitors */
			monitors = PR_TRUE;
            break;
        case 'c':  /* cached monitors */
			cmonitors = PR_TRUE;
            break;
        case 'h':  /* needs guidance */
         default:
            Help();
            return 2;
        }
    }
	PL_DestroyOptState(opt);

    ml = PR_NewLock();
    if (locks) T1Lock();
    if (monitors) T1Mon();
    if (cmonitors) T1CMon();

    PR_DestroyLock(ml);

    PR_fprintf(err, "Done!\n");    
    return 0;
}  /* main */
int main(int argc, char **argv)
{
	PLOptStatus os;
	PLOptState *opt = PL_CreateOptState(argc, argv, "dl:r:");
	while (PL_OPT_EOL != (os = PL_GetNextOpt(opt)))
    {
		if (PL_OPT_BAD == os) continue;
        switch (opt->option)
        {
        case 'd':  /* debug mode */
			debug = PR_TRUE;
            break;
         default:
            break;
        }
    }
	PL_DestroyOptState(opt);
    PR_STDIO_INIT();
    return PR_Initialize(Tpd, argc, argv, 0);
}  /* main */
Example #16
0
static PRIntn PR_CALLBACK RealMain(PRIntn argc, char **argv)
{
    PLOptStatus os;
    PRIntn loops = 1;
    PRFloat64 answer;
    const char *number = "1234567890123456789";
    PRFileDesc *err = PR_GetSpecialFD(PR_StandardError);
    PLOptState *opt = PL_CreateOptState(argc, argv, "hc:l:");

    while (PL_OPT_EOL != (os = PL_GetNextOpt(opt)))
    {
        if (PL_OPT_BAD == os) continue;
        switch (opt->option)
        {
        case 'n':  /* number to translate */
            number = opt->value;
            break;
        case 'l':  /* number of times to run the tests */
            loops = atoi(opt->value);
            break;
        case 'h':  /* user wants some guidance */
            Help();  /* so give him an earful */
            return 2;  /* but not a lot else */
            break;
         default:
            break;
        }
    }
    PL_DestroyOptState(opt);

    PR_fprintf(err, "Settings\n");
    PR_fprintf(err, "\tNumber to translate %s\n", number);
    PR_fprintf(err, "\tLoops to run test: %d\n", loops);

    while (loops--)
    {
        answer = PR_strtod(number, NULL);
        PR_fprintf(err, "Translation = %20.0f\n", answer);
    }
    return 2;
}
static PRIntn PR_CALLBACK RealMain(int argc, char **argv)
{
    /* The command line argument: -d is used to determine if the test is being run
    in debug mode. The regress tool requires only one line output:PASS or FAIL.
    All of the printfs associated with this test has been handled with a if (debug_mode)
    test.
    Usage: test_name -d
    */
    
    PLOptStatus os;
    PLOptState *opt = PL_CreateOptState(argc, argv, "d:");
    while (PL_OPT_EOL != (os = PL_GetNextOpt(opt)))
    {
        if (PL_OPT_BAD == os) continue;
        switch (opt->option)
        {
        case 'd':  /* debug mode */
            debug_mode = 1;
            break;
         default:
            break;
        }
    }
    PL_DestroyOptState(opt);

 /* main test */
    printf("User-User test\n");
    runTest(PR_LOCAL_THREAD, PR_LOCAL_THREAD);
    printf("User-Kernel test\n");
    runTest(PR_LOCAL_THREAD, PR_GLOBAL_THREAD);
    printf("Kernel-User test\n");
    runTest(PR_GLOBAL_THREAD, PR_LOCAL_THREAD);
    printf("Kernel-Kernel test\n");
    runTest(PR_GLOBAL_THREAD, PR_GLOBAL_THREAD);
    printf("Join with unjoinable thread\n");
    joinWithUnjoinable();

    printf("PASSED\n");

    return 0;
}
int main(int argc, char **argv)
{
    /*
     * -d           debug mode
     */
    PLOptStatus os;
    PLOptState *opt;
	program_name = argv[0];

    opt = PL_CreateOptState(argc, argv, "dp:");
    while (PL_OPT_EOL != (os = PL_GetNextOpt(opt)))
    {
        if (PL_OPT_BAD == os) continue;
        switch (opt->option)
        {
        case 'd':  /* debug mode */
            _debug_on = 1;
            break;
        case 'p':
            server_port = atoi(opt->value);
            break;
        default:
            break;
        }
    }
    PL_DestroyOptState(opt);

    PR_Init(PR_USER_THREAD, PR_PRIORITY_NORMAL, 0);
    PR_STDIO_INIT();

    PR_SetConcurrency(4);

	TCP_Socket_Client_Server_Test();

    PR_Cleanup();
    if (failed_already)
		return 1;
    else
		return 0;
}
int
main(int argc, char **argv) 
{
    PLOptState *opt;
    PLOptStatus ostat;

    opt = PL_CreateLongOptState(argc, argv, "a:b:c", optArray);

    while (PL_OPT_OK == (ostat = PL_GetNextOpt(opt))) {
	if (opt->option == 0 && opt->longOptIndex < 0) 
	    printf("Positional parameter: \"%s\"\n", opt->value);
	else
	    printf("%s option: %x (\'%c\', index %d), argument: \"%s\"\n",
		   (ostat == PL_OPT_BAD) ? "BAD" : "GOOD",
		   opt->longOption, opt->option ? opt->option : ' ',
		   opt->longOptIndex, opt->value);

    }
    printf("last result was %s\n", (ostat == PL_OPT_BAD) ? "BAD" : "EOL");
    PL_DestroyOptState(opt);
    return 0;
}
Example #20
0
int main(int argc, char **argv)
{
    const char* properties_filename = nsnull;

    PLOptState* optstate = PL_CreateOptState(argc, argv, "p:");
    
    while (PL_GetNextOpt(optstate) == PL_OPT_OK) {
        switch (optstate->option) {
        case 'p':               // output properties file
            properties_filename = optstate->value;
            break;
        case '?':
            print_help();
            exit(1);
            break;
        }
    }
    PL_DestroyOptState(optstate);

    NS_InitXPCOM2(nsnull, nsnull, nsnull);

    nsCOMPtr <nsIChromeRegistry> chromeReg = 
        do_GetService(kChromeRegistryCID);
    if (!chromeReg) {
        NS_WARNING("chrome check couldn't get the chrome registry");
        return NS_ERROR_FAILURE;
    }
    chromeReg->CheckForNewChrome();

    // ok, now load the rdf that just got written
    if (properties_filename)
        WriteProperties(properties_filename);

    // release the chrome registry before we shutdown XPCOM
    chromeReg = 0;
    NS_ShutdownXPCOM(nsnull);
    return 0;
}
static PRIntn PR_CALLBACK RealMain(int argc, char **argv)
{
    PRInt32 threads, default_threads = DEFAULT_THREADS;
	PLOptStatus os;
	PLOptState *opt = PL_CreateOptState(argc, argv, "vc:t:");
	while (PL_OPT_EOL != (os = PL_GetNextOpt(opt)))
    {
		if (PL_OPT_BAD == os) continue;
        switch (opt->option)
        {
        case 'v':  /* debug mode */
			_debug_on = 1;
            break;
        case 'c':  /* loop counter */
			count = atoi(opt->value);
            break;
        case 't':  /* number of threads involved */
			default_threads = atoi(opt->value);
            break;
         default:
            break;
        }
    }
	PL_DestroyOptState(opt);

    if (0 == count) count = DEFAULT_COUNT;
    if (0 == default_threads) default_threads = DEFAULT_THREADS;

    printf("\n\
CondVar Test:                                                           \n\
                                                                        \n\
Simple test creates several local and global threads; half use a single,\n\
shared condvar, and the other half have their own condvar.  The main    \n\
thread then loops notifying them to wakeup.                             \n\
                                                                        \n\
The timeout test is very similar except that the threads are not        \n\
notified.  They will all wakeup on a 1 second timeout.                  \n\
                                                                        \n\
The mixed test combines the simple test and the timeout test; every     \n\
third thread is notified, the other threads are expected to timeout     \n\
correctly.                                                              \n\
                                                                        \n\
Lastly, the combined test creates a thread for each of the above three  \n\
cases and they all run simultaneously.                                  \n\
                                                                        \n\
This test is run with %d, %d, %d, and %d threads of each type.\n\n",
default_threads, default_threads*2, default_threads*3, default_threads*4);

    PR_SetConcurrency(2);

    for (threads = default_threads; threads < default_threads*5; threads+=default_threads) {
        printf("\n%ld Thread tests\n", threads);
        Measure(CondVarTestSUU, threads, "Condvar simple test shared UU");
        Measure(CondVarTestSUK, threads, "Condvar simple test shared UK");
        Measure(CondVarTestPUU, threads, "Condvar simple test priv UU");
        Measure(CondVarTestPUK, threads, "Condvar simple test priv UK");
        Measure(CondVarTest, threads, "Condvar simple test All");
        Measure(CondVarTimeoutTest, threads,  "Condvar timeout test");
#if 0
        Measure(CondVarMixedTest, threads,  "Condvar mixed timeout test");
        Measure(CondVarCombinedTest, threads, "Combined condvar test");
#endif
    }

    printf("PASS\n");

    return 0;
}
int main(int argc, char **argv)
{
    int rv, ascii;
    char *progName;
    FILE *outFile;
    PRFileDesc *inFile;
    SECItem der, data;
    char *typeTag;
    PLOptState *optstate;

    progName = strrchr(argv[0], '/');
    progName = progName ? progName+1 : argv[0];

    ascii = 0;
    inFile = 0;
    outFile = 0;
    typeTag = 0;
    optstate = PL_CreateOptState(argc, argv, "at:i:o:");
    while ( PL_GetNextOpt(optstate) == PL_OPT_OK ) {
	switch (optstate->option) {
	  case '?':
	    Usage(progName);
	    break;

	  case 'a':
	    ascii = 1;
	    break;

	  case 'i':
	    inFile = PR_Open(optstate->value, PR_RDONLY, 0);
	    if (!inFile) {
		fprintf(stderr, "%s: unable to open \"%s\" for reading\n",
			progName, optstate->value);
		return -1;
	    }
	    break;

	  case 'o':
	    outFile = fopen(optstate->value, "w");
	    if (!outFile) {
		fprintf(stderr, "%s: unable to open \"%s\" for writing\n",
			progName, optstate->value);
		return -1;
	    }
	    break;

	  case 't':
	    typeTag = strdup(optstate->value);
	    break;
	}
    }
    PL_DestroyOptState(optstate);
    if (!typeTag) Usage(progName);

    if (!inFile) inFile = PR_STDIN;
    if (!outFile) outFile = stdout;

    PR_Init(PR_SYSTEM_THREAD, PR_PRIORITY_NORMAL, 1);
    rv = NSS_NoDB_Init(NULL);
    if (rv != SECSuccess) {
	fprintf(stderr, "%s: NSS_NoDB_Init failed (%s)\n",
		progName, SECU_Strerror(PORT_GetError()));
	exit(1);
    }
    SECU_RegisterDynamicOids();

    rv = SECU_ReadDERFromFile(&der, inFile, ascii, PR_FALSE);
    if (rv != SECSuccess) {
	fprintf(stderr, "%s: SECU_ReadDERFromFile failed\n", progName);
	exit(1);
    }

    /* Data is untyped, using the specified type */
    data.data = der.data;
    data.len = der.len;

    /* Pretty print it */
    if (PORT_Strcmp(typeTag, SEC_CT_CERTIFICATE) == 0) {
	rv = SECU_PrintSignedData(outFile, &data, "Certificate", 0,
			     SECU_PrintCertificate);
    } else if (PORT_Strcmp(typeTag, SEC_CT_CERTIFICATE_ID) == 0) {
        PRBool saveWrapeState = SECU_GetWrapEnabled();
        SECU_EnableWrap(PR_FALSE);
        rv = SECU_PrintSignedContent(outFile, &data, 0, 0,
                                     SECU_PrintDumpDerIssuerAndSerial);
        SECU_EnableWrap(saveWrapeState);
    } else if (PORT_Strcmp(typeTag, SEC_CT_CERTIFICATE_REQUEST) == 0) {
	rv = SECU_PrintSignedData(outFile, &data, "Certificate Request", 0,
			     SECU_PrintCertificateRequest);
    } else if (PORT_Strcmp (typeTag, SEC_CT_CRL) == 0) {
	rv = SECU_PrintSignedData (outFile, &data, "CRL", 0, SECU_PrintCrl);
#ifdef HAVE_EPV_TEMPLATE
    } else if (PORT_Strcmp(typeTag, SEC_CT_PRIVATE_KEY) == 0) {
	rv = SECU_PrintPrivateKey(outFile, &data, "Private Key", 0);
#endif
    } else if (PORT_Strcmp(typeTag, SEC_CT_PUBLIC_KEY) == 0) {
	rv = SECU_PrintSubjectPublicKeyInfo(outFile, &data, "Public Key", 0);
    } else if (PORT_Strcmp(typeTag, SEC_CT_PKCS7) == 0) {
	rv = SECU_PrintPKCS7ContentInfo(outFile, &data,
					"PKCS #7 Content Info", 0);
    } else if (PORT_Strcmp(typeTag, SEC_CT_NAME) == 0) {
	rv = SECU_PrintDERName(outFile, &data, "Name", 0);
    } else {
	fprintf(stderr, "%s: don't know how to print out '%s' files\n",
		progName, typeTag);
	SECU_PrintAny(outFile, &data, "File contains", 0);
	return -1;
    }

    if (inFile != PR_STDIN)
	PR_Close(inFile);
    PORT_Free(der.data);
    if (rv) {
	fprintf(stderr, "%s: problem converting data (%s)\n",
		progName, SECU_Strerror(PORT_GetError()));
    }
    if (NSS_Shutdown() != SECSuccess) {
	fprintf(stderr, "%s: NSS_Shutdown failed (%s)\n",
		progName, SECU_Strerror(PORT_GetError()));
	rv = SECFailure;
    }
    PR_Cleanup();
    return rv;
}
Example #23
0
int main(int argc, char **argv)
{
    CERTCertDBHandle *certHandle;
    PRFileDesc *inFile;
    PRFileDesc *inCrlInitFile = NULL;
    int generateCRL;
    int modifyCRL;
    int listCRL;
    int importCRL;
    int showFileCRL;
    int deleteCRL;
    int rv;
    char *nickName;
    char *url;
    char *dbPrefix = "";
    char *alg = NULL;
    char *outFile = NULL;
    char *slotName = NULL;
    int ascii = 0;
    int crlType;
    PLOptState *optstate;
    PLOptStatus status;
    SECStatus secstatus;
    PRInt32 decodeOptions = CRL_DECODE_DEFAULT_OPTIONS;
    PRInt32 importOptions = CRL_IMPORT_DEFAULT_OPTIONS;
    PRBool quiet = PR_FALSE;
    PRBool test = PR_FALSE;
    PRBool erase = PR_FALSE;
    PRInt32 i = 0;
    PRInt32 iterations = 1;
    PRBool readonly = PR_FALSE;

    secuPWData  pwdata          = { PW_NONE, 0 };

    progName = strrchr(argv[0], '/');
    progName = progName ? progName+1 : argv[0];

    rv = 0;
    deleteCRL = importCRL = listCRL = generateCRL = modifyCRL = showFileCRL = 0;
    inFile = NULL;
    nickName = url = NULL;
    certHandle = NULL;
    crlType = SEC_CRL_TYPE;
    /*
     * Parse command line arguments
     */
    optstate = PL_CreateOptState(argc, argv, "sqBCDGILMSTEP:f:d:i:h:n:p:t:u:r:aZ:o:c:");
    while ((status = PL_GetNextOpt(optstate)) == PL_OPT_OK) {
	switch (optstate->option) {
	  case '?':
	    Usage(progName);
	    break;

          case 'T':
            test = PR_TRUE;
            break;

          case 'E':
            erase = PR_TRUE;
            break;

	  case 'B':
            importOptions |= CRL_IMPORT_BYPASS_CHECKS;
            break;

	  case 'G':
	    generateCRL = 1;
	    break;

          case 'M':
            modifyCRL = 1;
            break;

	  case 'D':
	      deleteCRL = 1;
	      break;

	  case 'I':
	      importCRL = 1;
	      break;
	      
	  case 'S':
	      showFileCRL = 1;
	      break;
	           
	  case 'C':
	  case 'L':
	      listCRL = 1;
	      break;

	  case 'P':
 	    dbPrefix = strdup(optstate->value);
 	    break;
              
	  case 'Z':
              alg = strdup(optstate->value);
              break;
              
	  case 'a':
	      ascii = 1;
	      break;

	  case 'c':
              inCrlInitFile = PR_Open(optstate->value, PR_RDONLY, 0);
              if (!inCrlInitFile) {
                  PR_fprintf(PR_STDERR, "%s: unable to open \"%s\" for reading\n",
                             progName, optstate->value);
                  PL_DestroyOptState(optstate);
                  return -1;
              }
              break;
	    
	  case 'd':
              SECU_ConfigDirectory(optstate->value);
              break;

	  case 'f':
	      pwdata.source = PW_FROMFILE;
	      pwdata.data = strdup(optstate->value);
	      break;

	  case 'h':
              slotName = strdup(optstate->value);
              break;

	  case 'i':
	    inFile = PR_Open(optstate->value, PR_RDONLY, 0);
	    if (!inFile) {
		PR_fprintf(PR_STDERR, "%s: unable to open \"%s\" for reading\n",
			progName, optstate->value);
		PL_DestroyOptState(optstate);
		return -1;
	    }
	    break;
	    
	  case 'n':
	    nickName = strdup(optstate->value);
	    break;

	  case 'o':
	    outFile = strdup(optstate->value);
	    break;
	    
	  case 'p':
	    decodeOptions |= CRL_DECODE_SKIP_ENTRIES;
	    break;

	  case 'r': {
	    const char* str = optstate->value;
	    if (str && atoi(str)>0)
		iterations = atoi(str);
	    }
	    break;
	    
	  case 't': {
	    crlType = atoi(optstate->value);
	    if (crlType != SEC_CRL_TYPE && crlType != SEC_KRL_TYPE) {
		PR_fprintf(PR_STDERR, "%s: invalid crl type\n", progName);
		PL_DestroyOptState(optstate);
		return -1;
	    }
	    break;

	  case 'q':
            quiet = PR_TRUE;
	    break;

	  case 'w':
	      pwdata.source = PW_PLAINTEXT;
	      pwdata.data = strdup(optstate->value);
	      break;

	  case 'u':
	    url = strdup(optstate->value);
	    break;

          }
	}
    }
    PL_DestroyOptState(optstate);

    if (deleteCRL && !nickName) Usage (progName);
    if (importCRL && !inFile) Usage (progName);
    if (showFileCRL && !inFile) Usage (progName);
    if ((generateCRL && !nickName) ||
        (modifyCRL && !inFile && !nickName)) Usage (progName);
    if (!(listCRL || deleteCRL || importCRL || showFileCRL || generateCRL ||
	  modifyCRL || test || erase)) Usage (progName);

    if (listCRL || showFileCRL) {
        readonly = PR_TRUE;
    }
    
    PR_Init( PR_SYSTEM_THREAD, PR_PRIORITY_NORMAL, 1);

    PK11_SetPasswordFunc(SECU_GetModulePassword);

    if (showFileCRL) {
	NSS_NoDB_Init(NULL);
    }
    else {
	secstatus = NSS_Initialize(SECU_ConfigDirectory(NULL), dbPrefix, dbPrefix,
				"secmod.db", readonly ? NSS_INIT_READONLY : 0);
	if (secstatus != SECSuccess) {
	    SECU_PrintPRandOSError(progName);
	    return -1;
	}
    }
    
    SECU_RegisterDynamicOids();

    certHandle = CERT_GetDefaultCertDB();
    if (certHandle == NULL) {
	SECU_PrintError(progName, "unable to open the cert db");	    	
	/*ignoring return value of NSS_Shutdown() as code returns -1*/
	(void) NSS_Shutdown();
	return (-1);
    }

    CRLGEN_InitCrlGenParserLock();

    for (i=0; i<iterations; i++) {
	/* Read in the private key info */
	if (deleteCRL) 
	    DeleteCRL (certHandle, nickName, crlType);
	else if (listCRL) {
	    rv = ListCRL (certHandle, nickName, crlType);
	}
	else if (importCRL) {
	    rv = ImportCRL (certHandle, url, crlType, inFile, importOptions,
			    decodeOptions, &pwdata);
	}
	else if (showFileCRL) {
	    rv = DumpCRL (inFile);
	} else if (generateCRL || modifyCRL) {
	    if (!inCrlInitFile)
		inCrlInitFile = PR_STDIN;
	    rv = GenerateCRL (certHandle, nickName, inCrlInitFile,
			      inFile, outFile, ascii,  slotName,
			      importOptions, alg, quiet,
			      decodeOptions, url, &pwdata,
			      modifyCRL);
	}
	else if (erase) {
	    /* list and delete all CRLs */
	    ListCRLNames (certHandle, crlType, PR_TRUE);
	}
#ifdef DEBUG
	else if (test) {
	    /* list and delete all CRLs */
	    ListCRLNames (certHandle, crlType, PR_TRUE);
	    /* list CRLs */
	    ListCRLNames (certHandle, crlType, PR_FALSE);
	    /* import CRL as a blob */
	    rv = ImportCRL (certHandle, url, crlType, inFile, importOptions,
			    decodeOptions, &pwdata);
	    /* list CRLs */
	    ListCRLNames (certHandle, crlType, PR_FALSE);
	}
#endif    
    }

    CRLGEN_DestroyCrlGenParserLock();

    if (NSS_Shutdown() != SECSuccess) {
        rv = SECFailure;
    }

    return (rv != SECSuccess);
}
Example #24
0
int
main (int argc, char **argv)
{
    int		 retval;
    PRFileDesc	*in_file;
    FILE	*out_file;	/* not PRFileDesc until SECU accepts it */
    int		 crequest, dresponse;
    int		 prequest, presponse;
    int		 ccert, vcert;
    const char	*db_dir, *date_str, *cert_usage_str, *name;
    const char	*responder_name, *responder_url, *signer_name;
    PRBool	 add_acceptable_responses, add_service_locator;
    SECItem	*data = NULL;
    PLOptState	*optstate;
    SECStatus	 rv;
    CERTCertDBHandle *handle = NULL;
    SECCertUsage cert_usage;
    PRTime	 verify_time;
    CERTCertificate *cert = NULL;
    PRBool ascii = PR_FALSE;

    retval = -1;		/* what we return/exit with on error */

    program_name = PL_strrchr(argv[0], '/');
    program_name = program_name ? (program_name + 1) : argv[0];

    in_file = PR_STDIN;
    out_file = stdout;

    crequest = 0;
    dresponse = 0;
    prequest = 0;
    presponse = 0;
    ccert = 0;
    vcert = 0;

    db_dir = NULL;
    date_str = NULL;
    cert_usage_str = NULL;
    name = NULL;
    responder_name = NULL;
    responder_url = NULL;
    signer_name = NULL;

    add_acceptable_responses = PR_FALSE;
    add_service_locator = PR_FALSE;

    optstate = PL_CreateOptState (argc, argv, "AHLPR:S:V:d:l:pr:s:t:u:w:");
    if (optstate == NULL) {
	SECU_PrintError (program_name, "PL_CreateOptState failed");
	return retval;
    }

    while (PL_GetNextOpt (optstate) == PL_OPT_OK) {
	switch (optstate->option) {
	  case '?':
	    short_usage (program_name);
	    return retval;

	  case 'A':
	    add_acceptable_responses = PR_TRUE;
	    break;

	  case 'H':
	    long_usage (program_name);
	    return retval;

	  case 'L':
	    add_service_locator = PR_TRUE;
	    break;

	  case 'P':
	    presponse = 1;
	    break;

	  case 'R':
	    dresponse = 1;
	    name = optstate->value;
	    break;

	  case 'S':
	    ccert = 1;
	    name = optstate->value;
	    break;

	  case 'V':
	    vcert = 1;
	    name = optstate->value;
	    break;

	  case 'a':
	    ascii = PR_TRUE;
	    break;

	  case 'd':
	    db_dir = optstate->value;
	    break;

	  case 'l':
	    responder_url = optstate->value;
	    break;

	  case 'p':
	    prequest = 1;
	    break;

	  case 'r':
	    crequest = 1;
	    name = optstate->value;
	    break;

	  case 's':
	    signer_name = optstate->value;
	    break;

	  case 't':
	    responder_name = optstate->value;
	    break;

	  case 'u':
	    cert_usage_str = optstate->value;
	    break;

	  case 'w':
	    date_str = optstate->value;
	    break;
	}
    }

    PL_DestroyOptState(optstate);

    if ((crequest + dresponse + prequest + presponse + ccert + vcert) != 1) {
	PR_fprintf (PR_STDERR, "%s: must specify exactly one command\n\n",
		    program_name);
	short_usage (program_name);
	return retval;
    }

    if (vcert) {
	if (cert_usage_str == NULL) {
	    PR_fprintf (PR_STDERR, "%s: verification requires cert usage\n\n",
			program_name);
	    short_usage (program_name);
	    return retval;
	}

	rv = cert_usage_from_char (cert_usage_str, &cert_usage);
	if (rv != SECSuccess) {
	    PR_fprintf (PR_STDERR, "%s: invalid cert usage (\"%s\")\n\n",
			program_name, cert_usage_str);
	    long_usage (program_name);
	    return retval;
	}
    }

    if (ccert + vcert) {
	if (responder_url != NULL || responder_name != NULL) {
	    /*
	     * To do a full status check, both the URL and the cert name
	     * of the responder must be specified if either one is.
	     */
	    if (responder_url == NULL || responder_name == NULL) {
		if (responder_url == NULL)
		    PR_fprintf (PR_STDERR,
				"%s: must also specify responder location\n\n",
				program_name);
		else
		    PR_fprintf (PR_STDERR,
				"%s: must also specify responder name\n\n",
				program_name);
		short_usage (program_name);
		return retval;
	    }
	}

	if (date_str != NULL) {
	    rv = DER_AsciiToTime (&verify_time, (char *) date_str);
	    if (rv != SECSuccess) {
		SECU_PrintError (program_name, "error converting time string");
		PR_fprintf (PR_STDERR, "\n");
		long_usage (program_name);
		return retval;
	    }
	} else {
	    verify_time = PR_Now();
	}
    }

    retval = -2;		/* errors change from usage to runtime */

    /*
     * Initialize the NSPR and Security libraries.
     */
    PR_Init (PR_SYSTEM_THREAD, PR_PRIORITY_NORMAL, 1);
    db_dir = SECU_ConfigDirectory (db_dir);
    rv = NSS_Init (db_dir);
    if (rv != SECSuccess) {
	SECU_PrintError (program_name, "NSS_Init failed");
	goto prdone;
    }
    SECU_RegisterDynamicOids();

    if (prequest + presponse) {
	MAKE_FILE_BINARY(stdin);
	data = read_file_into_item (in_file, siBuffer);
	if (data == NULL) {
	    SECU_PrintError (program_name, "problem reading input");
	    goto nssdone;
	}
    }

    if (crequest + dresponse + presponse + ccert + vcert) {
	handle = CERT_GetDefaultCertDB();
	if (handle == NULL) {
	    SECU_PrintError (program_name, "problem getting certdb handle");
	    goto nssdone;
	}

	/*
	 * It would be fine to do the enable for all of these commands,
	 * but this way we check that everything but an overall verify
	 * can be done without it.  That is, that the individual pieces
	 * work on their own.
	 */
	if (vcert) {
	    rv = CERT_EnableOCSPChecking (handle);
	    if (rv != SECSuccess) {
		SECU_PrintError (program_name, "error enabling OCSP checking");
		goto nssdone;
	    }
	}

	if ((ccert + vcert) && (responder_name != NULL)) {
	    rv = CERT_SetOCSPDefaultResponder (handle, responder_url,
					       responder_name);
	    if (rv != SECSuccess) {
		SECU_PrintError (program_name,
				 "error setting default responder");
		goto nssdone;
	    }

	    rv = CERT_EnableOCSPDefaultResponder (handle);
	    if (rv != SECSuccess) {
		SECU_PrintError (program_name,
				 "error enabling default responder");
		goto nssdone;
	    }
	}
    }

#define NOTYET(opt)							\
	{								\
	    PR_fprintf (PR_STDERR, "%s not yet working\n", opt);	\
	    exit (-1);							\
	}

    if (name) {
        cert = find_certificate(handle, name, ascii);
    }

    if (crequest) {
	if (signer_name != NULL) {
	    NOTYET("-s");
	}
	rv = create_request (out_file, handle, cert, add_service_locator,
			     add_acceptable_responses);
    } else if (dresponse) {
	if (signer_name != NULL) {
	    NOTYET("-s");
	}
	rv = dump_response (out_file, handle, cert, responder_url);
    } else if (prequest) {
	rv = print_request (out_file, data);
    } else if (presponse) {
	rv = print_response (out_file, data, handle);
    } else if (ccert) {
	if (signer_name != NULL) {
	    NOTYET("-s");
	}
	rv = get_cert_status (out_file, handle, cert, name, verify_time);
    } else if (vcert) {
	if (signer_name != NULL) {
	    NOTYET("-s");
	}
	rv = verify_cert (out_file, handle, cert, name, cert_usage, verify_time);
    }

    if (rv != SECSuccess)
	SECU_PrintError (program_name, "error performing requested operation");
    else
	retval = 0;

nssdone:
    if (cert) {
        CERT_DestroyCertificate(cert);
    }

    if (data != NULL) {
	SECITEM_FreeItem (data, PR_TRUE);
    }

    if (handle != NULL) {
 	CERT_DisableOCSPDefaultResponder(handle);        
 	CERT_DisableOCSPChecking (handle);
    }

    if (NSS_Shutdown () != SECSuccess) {
	retval = 1;
    }

prdone:
    PR_Cleanup ();
    return retval;
}
Example #25
0
PRIntn main(PRIntn argc, char *argv[])
{
    PRStatus    rc;
    PRInt32     rv;
    PRFileDesc  *fd;
    PRIntn      i;
    PRInt32     sum = 0;

    {   /* Get command line options */
        PLOptStatus os;
        PLOptState *opt = PL_CreateOptState(argc, argv, "vd");

	    while (PL_OPT_EOL != (os = PL_GetNextOpt(opt)))
        {
		    if (PL_OPT_BAD == os) continue;
            switch (opt->option)
            {
            case 'd':  /* debug */
                debug = 1;
                break;
            case 'v':  /* verbose */
                verbose = 1;
                break;
             default:
                break;
            }
        }
	    PL_DestroyOptState(opt);
    } /* end block "Get command line options" */
/* ---------------------------------------------------------------------- */
    fd = PR_Open( "/tmp/nsprAppend", (PR_APPEND | PR_CREATE_FILE | PR_TRUNCATE | PR_WRONLY), 0666 );
    if ( NULL == fd )  {
        if (debug) printf("PR_Open() failed for writing: %d\n", PR_GetError());
        failedAlready = PR_TRUE;
        goto Finished;
    }

    for ( i = 0; i < addedBytes ; i++ ) {
        rv = PR_Write( fd, &buf, sizeof(buf));
        if ( sizeof(buf) != rv )  {
            if (debug) printf("PR_Write() failed: %d\n", PR_GetError());
            failedAlready = PR_TRUE;
            goto Finished;
        }
        rv = PR_Seek( fd, 0 , PR_SEEK_SET );
        if ( -1 == rv )  {
            if (debug) printf("PR_Seek() failed: %d\n", PR_GetError());
            failedAlready = PR_TRUE;
            goto Finished;
        }
    }
    rc = PR_Close( fd );
    if ( PR_FAILURE == rc ) {
        if (debug) printf("PR_Close() failed after writing: %d\n", PR_GetError());
        failedAlready = PR_TRUE;
        goto Finished;
    }
/* ---------------------------------------------------------------------- */
    fd = PR_Open( "/tmp/nsprAppend", PR_RDONLY, 0 );
    if ( NULL == fd )  {
        if (debug) printf("PR_Open() failed for reading: %d\n", PR_GetError());
        failedAlready = PR_TRUE;
        goto Finished;
    }

    for ( i = 0; i < addedBytes ; i++ ) {
        rv = PR_Read( fd, &inBuf, sizeof(inBuf));
        if ( sizeof(inBuf) != rv)  {
            if (debug) printf("PR_Write() failed: %d\n", PR_GetError());
            failedAlready = PR_TRUE;
            goto Finished;
        }
        sum += inBuf;
    }

    rc = PR_Close( fd );
    if ( PR_FAILURE == rc ) {
        if (debug) printf("PR_Close() failed after reading: %d\n", PR_GetError());
        failedAlready = PR_TRUE;
        goto Finished;
    }
    if ( sum != addedBytes )  {
        if (debug) printf("Uh Oh! addedBytes: %d. Sum: %d\n", addedBytes, sum);
        failedAlready = PR_TRUE;
        goto Finished;
    }

/* ---------------------------------------------------------------------- */
Finished:
    if (debug || verbose) printf("%s\n", (failedAlready)? "FAILED" : "PASSED" );
    return( (failedAlready)? 1 : 0 );
}  /* main() */
Example #26
0
int
main(int argc, char *argv[], char *envp[])
{
    char *               certDir      = NULL;
    char *               progName     = NULL;
    char *               oidStr       = NULL;
    CERTCertificate *    cert;
    CERTCertificate *    firstCert    = NULL;
    CERTCertificate *    issuerCert   = NULL;
    CERTCertDBHandle *   defaultDB    = NULL;
    PRBool               isAscii      = PR_FALSE;
    PRBool               trusted      = PR_FALSE;
    SECStatus            secStatus;
    SECCertificateUsage  certUsage    = certificateUsageSSLServer;
    PLOptState *         optstate;
    PRTime               time         = 0;
    PLOptStatus          status;
    int                  usePkix      = 0;
    int                  rv           = 1;
    int                  usage;
    CERTVerifyLog        log;
    CERTCertList        *builtChain = NULL;
    PRBool               certFetching = PR_FALSE;
    int                  revDataIndex = 0;
    PRBool               ocsp_fetchingFailureIsAFailure = PR_TRUE;
    PRBool               useDefaultRevFlags = PR_TRUE;
    int                  vfyCounts = 1;

    PR_Init( PR_SYSTEM_THREAD, PR_PRIORITY_NORMAL, 1);

    progName = PL_strdup(argv[0]);

    optstate = PL_CreateOptState(argc, argv, "ab:c:d:efg:h:i:m:o:prs:tu:vw:W:");
    while ((status = PL_GetNextOpt(optstate)) == PL_OPT_OK) {
	switch(optstate->option) {
	case  0  : /* positional parameter */  goto breakout;
	case 'a' : isAscii  = PR_TRUE;                        break;
	case 'b' : secStatus = DER_AsciiToTime(&time, optstate->value);
	           if (secStatus != SECSuccess) Usage(progName); break;
	case 'd' : certDir  = PL_strdup(optstate->value);     break;
	case 'e' : ocsp_fetchingFailureIsAFailure = PR_FALSE;  break;
	case 'f' : certFetching = PR_TRUE;                    break;
	case 'g' : 
                   if (revMethodsData[revDataIndex].testTypeStr ||
                       revMethodsData[revDataIndex].methodTypeStr) {
                       revDataIndex += 1;
                       if (revDataIndex == REV_METHOD_INDEX_MAX) {
                           fprintf(stderr, "Invalid revocation configuration"
                                   "specified.\n");
                           secStatus = SECFailure;
                           break;
                       }
                   }
                   useDefaultRevFlags = PR_FALSE;
                   revMethodsData[revDataIndex].
                       testTypeStr = PL_strdup(optstate->value); break;
	case 'h' : 
                   revMethodsData[revDataIndex].
                       testFlagsStr = PL_strdup(optstate->value);break;
        case 'i' : vfyCounts = PORT_Atoi(optstate->value);       break;
                   break;
	case 'm' : 
                   if (revMethodsData[revDataIndex].methodTypeStr) {
                       revDataIndex += 1;
                       if (revDataIndex == REV_METHOD_INDEX_MAX) {
                           fprintf(stderr, "Invalid revocation configuration"
                                   "specified.\n");
                           secStatus = SECFailure;
                           break;
                       }
                   }
                   useDefaultRevFlags = PR_FALSE;
                   revMethodsData[revDataIndex].
                       methodTypeStr = PL_strdup(optstate->value); break;
	case 'o' : oidStr = PL_strdup(optstate->value);       break;
	case 'p' : usePkix += 1;                              break;
	case 'r' : isAscii  = PR_FALSE;                       break;
	case 's' : 
                   revMethodsData[revDataIndex].
                       methodFlagsStr = PL_strdup(optstate->value); break;
	case 't' : trusted  = PR_TRUE;                        break;
	case 'u' : usage    = PORT_Atoi(optstate->value);
	           if (usage < 0 || usage > 62) Usage(progName);
		   certUsage = ((SECCertificateUsage)1) << usage; 
		   if (certUsage > certificateUsageHighest) Usage(progName);
		   break;
        case 'w':
                  pwdata.source = PW_PLAINTEXT;
                  pwdata.data = PORT_Strdup(optstate->value);
                  break;

        case 'W':
                  pwdata.source = PW_FROMFILE;
                  pwdata.data = PORT_Strdup(optstate->value);
                  break;
	case 'v' : verbose++;                                 break;
	default  : Usage(progName);                           break;
	}
    }
breakout:
    if (status != PL_OPT_OK)
	Usage(progName);

    if (usePkix < 2) {
        if (oidStr) {
            fprintf(stderr, "Policy oid(-o) can be used only with"
                    " CERT_PKIXVerifyChain(-pp) function.\n");
            Usage(progName);
        }
        if (trusted) {
            fprintf(stderr, "Cert trust flag can be used only with"
                    " CERT_PKIXVerifyChain(-pp) function.\n");
            Usage(progName);
        }
    }

    if (!useDefaultRevFlags && parseRevMethodsAndFlags()) {
        fprintf(stderr, "Invalid revocation configuration specified.\n");
        goto punt;
    }

    /* Set our password function callback. */
    PK11_SetPasswordFunc(SECU_GetModulePassword);

    /* Initialize the NSS libraries. */
    if (certDir) {
	secStatus = NSS_Init(certDir);
    } else {
	secStatus = NSS_NoDB_Init(NULL);

	/* load the builtins */
	SECMOD_AddNewModule("Builtins", DLL_PREFIX"nssckbi."DLL_SUFFIX, 0, 0);
    }
    if (secStatus != SECSuccess) {
	exitErr("NSS_Init");
    }
    SECU_RegisterDynamicOids();
    if (isOCSPEnabled()) {
        CERT_EnableOCSPChecking(CERT_GetDefaultCertDB());
        CERT_DisableOCSPDefaultResponder(CERT_GetDefaultCertDB());
        if (!ocsp_fetchingFailureIsAFailure) {
            CERT_SetOCSPFailureMode(ocspMode_FailureIsNotAVerificationFailure);
        }
    }

    while (status == PL_OPT_OK) {
	switch(optstate->option) {
	default  : Usage(progName);                           break;
	case 'a' : isAscii  = PR_TRUE;                        break;
	case 'r' : isAscii  = PR_FALSE;                       break;
	case 't' : trusted  = PR_TRUE;                       break;
	case  0  : /* positional parameter */
            if (usePkix < 2 && trusted) {
                fprintf(stderr, "Cert trust flag can be used only with"
                        " CERT_PKIXVerifyChain(-pp) function.\n");
                Usage(progName);
            }
	    cert = getCert(optstate->value, isAscii, progName);
	    if (!cert) 
	        goto punt;
	    rememberCert(cert, trusted);
	    if (!firstCert)
	        firstCert = cert;
            trusted = PR_FALSE;
	}
        status = PL_GetNextOpt(optstate);
    }
    PL_DestroyOptState(optstate);
    if (status == PL_OPT_BAD || !firstCert)
	Usage(progName);

    /* Initialize log structure */
    log.arena = PORT_NewArena(512);
    log.head = log.tail = NULL;
    log.count = 0;

    do {
        if (usePkix < 2) {
            /* NOW, verify the cert chain. */
            if (usePkix) {
                /* Use old API with libpkix validation lib */
                CERT_SetUsePKIXForValidation(PR_TRUE);
            }
            if (!time)
                time = PR_Now();

            defaultDB = CERT_GetDefaultCertDB();
            secStatus = CERT_VerifyCertificate(defaultDB, firstCert, 
                                               PR_TRUE /* check sig */,
                                               certUsage, 
                                               time,
                                               &pwdata, /* wincx  */
                                               &log, /* error log */
                                           NULL);/* returned usages */
        } else do {
                static CERTValOutParam cvout[4];
                static CERTValInParam cvin[6];
                SECOidTag oidTag;
                int inParamIndex = 0;
                static PRUint64 revFlagsLeaf[2];
                static PRUint64 revFlagsChain[2];
                static CERTRevocationFlags rev;
                
                if (oidStr) {
                    PRArenaPool *arena;
                    SECOidData od;
                    memset(&od, 0, sizeof od);
                    od.offset = SEC_OID_UNKNOWN;
                    od.desc = "User Defined Policy OID";
                    od.mechanism = CKM_INVALID_MECHANISM;
                    od.supportedExtension = INVALID_CERT_EXTENSION;

                    arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE);
                    if ( !arena ) {
                        fprintf(stderr, "out of memory");
                        goto punt;
                    }
                    
                    secStatus = SEC_StringToOID(arena, &od.oid, oidStr, 0);
                    if (secStatus != SECSuccess) {
                        PORT_FreeArena(arena, PR_FALSE);
                        fprintf(stderr, "Can not encode oid: %s(%s)\n", oidStr,
                                SECU_Strerror(PORT_GetError()));
                        break;
                    }
                    
                    oidTag = SECOID_AddEntry(&od);
                    PORT_FreeArena(arena, PR_FALSE);
                    if (oidTag == SEC_OID_UNKNOWN) {
                        fprintf(stderr, "Can not add new oid to the dynamic "
                                "table: %s\n", oidStr);
                        secStatus = SECFailure;
                        break;
                    }
                    
                    cvin[inParamIndex].type = cert_pi_policyOID;
                    cvin[inParamIndex].value.arraySize = 1;
                    cvin[inParamIndex].value.array.oids = &oidTag;
                    
                    inParamIndex++;
                }
                
                if (trustedCertList) {
                    cvin[inParamIndex].type = cert_pi_trustAnchors;
                    cvin[inParamIndex].value.pointer.chain = trustedCertList;
                    
                    inParamIndex++;
                }
                
                cvin[inParamIndex].type = cert_pi_useAIACertFetch;
                cvin[inParamIndex].value.scalar.b = certFetching;
                inParamIndex++;
                
                rev.leafTests.cert_rev_flags_per_method = revFlagsLeaf;
                rev.chainTests.cert_rev_flags_per_method = revFlagsChain;
                secStatus = configureRevocationParams(&rev);
                if (secStatus) {
                    fprintf(stderr, "Can not config revocation parameters ");
                    break;
                }
                
                cvin[inParamIndex].type = cert_pi_revocationFlags;
                cvin[inParamIndex].value.pointer.revocation = &rev;
                inParamIndex++;
                
                if (time) {
                    cvin[inParamIndex].type = cert_pi_date;
                    cvin[inParamIndex].value.scalar.time = time;
                    inParamIndex++;
                }
                
                cvin[inParamIndex].type = cert_pi_end;
                
                cvout[0].type = cert_po_trustAnchor;
                cvout[0].value.pointer.cert = NULL;
                cvout[1].type = cert_po_certList;
                cvout[1].value.pointer.chain = NULL;
                
                /* setting pointer to CERTVerifyLog. Initialized structure
                 * will be used CERT_PKIXVerifyCert */
                cvout[2].type = cert_po_errorLog;
                cvout[2].value.pointer.log = &log;
                
                cvout[3].type = cert_po_end;
                
                secStatus = CERT_PKIXVerifyCert(firstCert, certUsage,
                                                cvin, cvout, &pwdata);
                if (secStatus != SECSuccess) {
                    break;
                }
                issuerCert = cvout[0].value.pointer.cert;
                builtChain = cvout[1].value.pointer.chain;
            } while (0);
        
        /* Display validation results */
        if (secStatus != SECSuccess || log.count > 0) {
            CERTVerifyLogNode *node = NULL;
            PRIntn err = PR_GetError();
            fprintf(stderr, "Chain is bad, %d = %s\n", err, SECU_Strerror(err));
            
            SECU_displayVerifyLog(stderr, &log, verbose); 
            /* Have cert refs in the log only in case of failure.
             * Destroy them. */
            for (node = log.head; node; node = node->next) {
                if (node->cert)
                    CERT_DestroyCertificate(node->cert);
            }
            rv = 1;
        } else {
            fprintf(stderr, "Chain is good!\n");
            if (issuerCert) {
                if (verbose > 1) {
                    rv = SEC_PrintCertificateAndTrust(issuerCert, "Root Certificate",
                                                      NULL);
                    if (rv != SECSuccess) {
                        SECU_PrintError(progName, "problem printing certificate");
                    }
                } else if (verbose > 0) {
                    SECU_PrintName(stdout, &issuerCert->subject, "Root "
                                   "Certificate Subject:", 0);
                }
                CERT_DestroyCertificate(issuerCert);
            }
            if (builtChain) {
                CERTCertListNode *node;
                int count = 0;
                char buff[256];
                
                if (verbose) { 
                    for(node = CERT_LIST_HEAD(builtChain); !CERT_LIST_END(node, builtChain);
                        node = CERT_LIST_NEXT(node), count++ ) {
                        sprintf(buff, "Certificate %d Subject", count + 1);
                        SECU_PrintName(stdout, &node->cert->subject, buff, 0);
                    }
                }
                CERT_DestroyCertList(builtChain);
            }
            rv = 0;
        }
    } while (--vfyCounts > 0);

    /* Need to destroy CERTVerifyLog arena at the end */
    PORT_FreeArena(log.arena, PR_FALSE);

punt:
    forgetCerts();
    if (NSS_Shutdown() != SECSuccess) {
	SECU_PrintError(progName, "NSS_Shutdown");
	rv = 1;
    }
    PORT_Free(progName);
    PORT_Free(certDir);
    PORT_Free(oidStr);
    freeRevocationMethodData();
    if (pwdata.data) {
        PORT_Free(pwdata.data);
    }
    PR_Cleanup();
    return rv;
}
/***********************************************************************
** PRIVATE FUNCTION:    main
** DESCRIPTION:
**   Hammer on the file I/O system
** INPUTS:      The usual argc and argv
**              argv[0] - program name (not used)
**              argv[1] - the number of virtual_procs to execute the major loop
**              argv[2] - the number of threads to toss into the batch
**              argv[3] - the clipping number applied to randoms
**              default values: max_virtual_procs = 2, threads = 10, limit = 57
** OUTPUTS:     None
** RETURN:      None
** SIDE EFFECTS:
**      Creates, accesses and deletes lots of files
** RESTRICTIONS:
**      (Currently) must have file create permission in "/usr/tmp".
** MEMORY:      NA
** ALGORITHM:
**      1) Fork a "Thread()"
**      2) Wait for 'interleave' seconds
**      3) For [0..'threads') repeat [1..2]
**      4) Mark all objects to stop
**      5) Collect the threads, accumulating the results
**      6) For [0..'max_virtual_procs') repeat [1..5]
**      7) Print accumulated results and exit
**
**      Characteristic output (from IRIX)
**          Random File: Using max_virtual_procs = 2, threads = 10, limit = 57
**          Random File: [min [avg] max] writes/sec average
***********************************************************************/
PRIntn main (PRIntn argc, char *argv[])
{
    RCLock ml;
	PLOptStatus os;
    RCCondition cv(&ml);
    PRUint32 writesMax = 0, durationTot = 0;
    RCThread::Scope thread_scope = RCThread::local;
    PRUint32 writes, writesMin = 0x7fffffff, writesTot = 0;
    PRIntn active, poll, limit = 0, max_virtual_procs = 0, threads = 0, virtual_procs;
    RCInterval interleave(RCInterval::FromMilliseconds(10000)), duration(0);

    const char *where[] = {"okay", "open", "close", "delete", "write", "seek"};

	PLOptState *opt = PL_CreateOptState(argc, argv, "Gdl:t:i:");
	while (PL_OPT_EOL != (os = PL_GetNextOpt(opt)))
    {
		if (PL_OPT_BAD == os) continue;
        switch (opt->option)
        {
	case 0:
		baseName = opt->value;
		break;
        case 'G':  /* global threads */
		thread_scope = RCThread::global;
            break;
        case 'd':  /* debug mode */
			debug_mode = 1;
            break;
        case 'l':  /* limiting number */
			limit = atoi(opt->value);
            break;
        case 't':  /* number of threads */
			threads = atoi(opt->value);
            break;
        case 'i':  /* iteration counter */
			max_virtual_procs = atoi(opt->value);
            break;
         default:
            break;
        }
    }
	PL_DestroyOptState(opt);
    output = PR_GetSpecialFD(PR_StandardOutput);

 /* main test */
 
    cv.SetTimeout(interleave);
	
    if (max_virtual_procs == 0) max_virtual_procs = 2;
    if (limit == 0) limit = 57;
    if (threads == 0) threads = 10;

    if (debug_mode) PR_fprintf(output,
        "%s: Using %d virtual processors, %d threads, limit = %d and %s threads\n",
        programName, max_virtual_procs, threads, limit,
        (thread_scope == RCThread::local) ? "LOCAL" : "GLOBAL");

    for (virtual_procs = 0; virtual_procs < max_virtual_procs; ++virtual_procs)
    {
        if (debug_mode)
			PR_fprintf(output,
				"%s: Setting number of virtual processors to %d\n",
				programName, virtual_procs + 1);
		RCPrimordialThread::SetVirtualProcessors(virtual_procs + 1);
        for (active = 0; active < threads; active++)
        {
            hammer[active] = new Hammer(thread_scope, &ml, &cv, limit);
            hammer[active]->Start();  /* then make it roll */
            RCThread::Sleep(interleave);  /* start them slowly */
        }

        /*
         * The last thread started has had the opportunity to run for
         * 'interleave' seconds. Now gather them all back in.
         */
        {
            RCEnter scope(&ml);
            for (poll = 0; poll < threads; poll++)
            {
                if (hammer[poll]->action == HammerData::sg_go)  /* don't overwrite done */
                    hammer[poll]->action = HammerData::sg_stop;  /* ask him to stop */
            }
        }

        while (active > 0)
        {
            for (poll = 0; poll < threads; poll++)
            {
                ml.Acquire();
                while (hammer[poll]->action < HammerData::sg_done) cv.Wait();
                ml.Release();

                if (hammer[poll]->problem == HammerData::sg_okay)
                {
                    duration = RCInterval(RCInterval::now) - hammer[poll]->timein;
                    writes = hammer[poll]->writes * 1000 / duration;
                    if (writes < writesMin)  writesMin = writes;
                    if (writes > writesMax) writesMax = writes;
                    writesTot += hammer[poll]->writes;
                    durationTot += duration;
                }
                else
                {
                    if (debug_mode) PR_fprintf(output,
                        "%s: test failed %s after %ld seconds\n",
                        programName, where[hammer[poll]->problem], duration);
					else failed_already=1;
                }
                active -= 1;  /* this is another one down */
                (void)hammer[poll]->Join();
                hammer[poll] = NULL;
            }
        }
        if (debug_mode) PR_fprintf(output,
            "%s: [%ld [%ld] %ld] writes/sec average\n",
            programName, writesMin,
            writesTot * 1000 / durationTot, writesMax);
    }

        failed_already |= (PR_FAILURE == RCPrimordialThread::Cleanup());
	    PR_fprintf(output, "%s\n", (failed_already) ? "FAIL\n" : "PASS\n");
		return failed_already;
}  /* main */
Example #28
0
int
main(int argc, char **argv)
{
    char *progName;
    FILE *inFile, *outFile;
    char *certName;
    CERTCertDBHandle *certHandle;
    struct recipient *recipients, *rcpt;
    PLOptState *optstate;
    PLOptStatus status;
    SECStatus rv;

    progName = strrchr(argv[0], '/');
    progName = progName ? progName+1 : argv[0];

    inFile = NULL;
    outFile = NULL;
    certName = NULL;
    recipients = NULL;
    rcpt = NULL;

    /*
     * Parse command line arguments
     * XXX This needs to be enhanced to allow selection of algorithms
     * and key sizes (or to look up algorithms and key sizes for each
     * recipient in the magic database).
     */
    optstate = PL_CreateOptState(argc, argv, "d:i:o:r:");
    while ((status = PL_GetNextOpt(optstate)) == PL_OPT_OK) {
	switch (optstate->option) {
	  case '?':
	    Usage(progName);
	    break;

	  case 'd':
	    SECU_ConfigDirectory(optstate->value);
	    break;

	  case 'i':
	    inFile = fopen(optstate->value, "r");
	    if (!inFile) {
		fprintf(stderr, "%s: unable to open \"%s\" for reading\n",
			progName, optstate->value);
		return -1;
	    }
	    break;

	  case 'o':
	    outFile = fopen(optstate->value, "wb");
	    if (!outFile) {
		fprintf(stderr, "%s: unable to open \"%s\" for writing\n",
			progName, optstate->value);
		return -1;
	    }
	    break;

	  case 'r':
	    if (rcpt == NULL) {
		recipients = rcpt = PORT_Alloc (sizeof(struct recipient));
	    } else {
		rcpt->next = PORT_Alloc (sizeof(struct recipient));
		rcpt = rcpt->next;
	    }
	    if (rcpt == NULL) {
		fprintf(stderr, "%s: unable to allocate recipient struct\n",
			progName);
		return -1;
	    }
	    rcpt->nickname = strdup(optstate->value);
	    rcpt->cert = NULL;
	    rcpt->next = NULL;
	    break;
	}
    }

    if (!recipients) Usage(progName);

    if (!inFile) inFile = stdin;
    if (!outFile) outFile = stdout;

    /* Call the NSS initialization routines */
    PR_Init(PR_SYSTEM_THREAD, PR_PRIORITY_NORMAL, 1);
    rv = NSS_Init(SECU_ConfigDirectory(NULL));
    if (rv != SECSuccess) {
    	SECU_PrintPRandOSError(progName);
	return -1;
    }

    /* open cert database */
    certHandle = CERT_GetDefaultCertDB();
    if (certHandle == NULL) {
	return -1;
    }

    /* find certs */
    for (rcpt = recipients; rcpt != NULL; rcpt = rcpt->next) {
	rcpt->cert = CERT_FindCertByNickname(certHandle, rcpt->nickname);
	if (rcpt->cert == NULL) {
	    SECU_PrintError(progName,
			    "the cert for name \"%s\" not found in database",
			    rcpt->nickname);
	    return -1;
	}
    }

    if (EncryptFile(outFile, inFile, recipients, progName)) {
	SECU_PrintError(progName, "problem encrypting data");
	return -1;
    }

    return 0;
}
Example #29
0
SECStatus
SECU_ParseCommandLine(int argc, char **argv, char *progName,
                      const secuCommand *cmd)
{
    PRBool found;
    PLOptState *optstate;
    PLOptStatus status;
    char *optstring;
    PLLongOpt *longopts = NULL;
    int i, j;
    int lcmd = 0, lopt = 0;

    PR_ASSERT(HasNoDuplicates(cmd->commands, cmd->numCommands));
    PR_ASSERT(HasNoDuplicates(cmd->options, cmd->numOptions));

    optstring = (char *)PORT_Alloc(cmd->numCommands + 2 * cmd->numOptions + 1);
    if (optstring == NULL)
        return SECFailure;

    j = 0;
    for (i = 0; i < cmd->numCommands; i++) {
        if (cmd->commands[i].flag) /* single character option ? */
            optstring[j++] = cmd->commands[i].flag;
        if (cmd->commands[i].longform)
            lcmd++;
    }
    for (i = 0; i < cmd->numOptions; i++) {
        if (cmd->options[i].flag) {
            optstring[j++] = cmd->options[i].flag;
            if (cmd->options[i].needsArg)
                optstring[j++] = ':';
        }
        if (cmd->options[i].longform)
            lopt++;
    }

    optstring[j] = '\0';

    if (lcmd + lopt > 0) {
        longopts = PORT_NewArray(PLLongOpt, lcmd + lopt + 1);
        if (!longopts) {
            PORT_Free(optstring);
            return SECFailure;
        }

        j = 0;
        for (i = 0; j < lcmd && i < cmd->numCommands; i++) {
            if (cmd->commands[i].longform) {
                longopts[j].longOptName = cmd->commands[i].longform;
                longopts[j].longOption = 0;
                longopts[j++].valueRequired = cmd->commands[i].needsArg;
            }
        }
        lopt += lcmd;
        for (i = 0; j < lopt && i < cmd->numOptions; i++) {
            if (cmd->options[i].longform) {
                longopts[j].longOptName = cmd->options[i].longform;
                longopts[j].longOption = 0;
                longopts[j++].valueRequired = cmd->options[i].needsArg;
            }
        }
        longopts[j].longOptName = NULL;
    }

    optstate = PL_CreateLongOptState(argc, argv, optstring, longopts);
    if (!optstate) {
        PORT_Free(optstring);
        PORT_Free(longopts);
        return SECFailure;
    }
    /* Parse command line arguments */
    while ((status = PL_GetNextOpt(optstate)) == PL_OPT_OK) {
        const char *optstatelong;
        char option = optstate->option;

        /*  positional parameter, single-char option or long opt? */
        if (optstate->longOptIndex == -1) {
            /* not a long opt */
            if (option == '\0')
                continue; /* it's a positional parameter */
            optstatelong = "";
        } else {
            /* long opt */
            if (option == '\0')
                option = '\377'; /* force unequal with all flags */
            optstatelong = longopts[optstate->longOptIndex].longOptName;
        }

        found = PR_FALSE;

        for (i = 0; i < cmd->numCommands; i++) {
            if (cmd->commands[i].flag == option ||
                cmd->commands[i].longform == optstatelong) {
                cmd->commands[i].activated = PR_TRUE;
                if (optstate->value) {
                    cmd->commands[i].arg = (char *)optstate->value;
                }
                found = PR_TRUE;
                break;
            }
        }

        if (found)
            continue;

        for (i = 0; i < cmd->numOptions; i++) {
            if (cmd->options[i].flag == option ||
                cmd->options[i].longform == optstatelong) {
                cmd->options[i].activated = PR_TRUE;
                if (optstate->value) {
                    cmd->options[i].arg = (char *)optstate->value;
                } else if (cmd->options[i].needsArg) {
                    status = PL_OPT_BAD;
                    goto loser;
                }
                found = PR_TRUE;
                break;
            }
        }

        if (!found) {
            status = PL_OPT_BAD;
            break;
        }
    }

loser:
    PL_DestroyOptState(optstate);
    PORT_Free(optstring);
    if (longopts)
        PORT_Free(longopts);
    if (status == PL_OPT_BAD)
        return SECFailure;
    return SECSuccess;
}
Example #30
0
int main(int argc,  char **argv)
{
    PRBool rv = PR_TRUE;
    PRIntervalTime duration;
    PRUint32 cpu, cpus = 2, loops = 100;

	
    PR_STDIO_INIT();
    PR_Init(PR_USER_THREAD, PR_PRIORITY_NORMAL, 0);
    {
    	/* The command line argument: -d is used to determine if the test is being run
    	in debug mode. The regress tool requires only one line output:PASS or FAIL.
    	All of the printfs associated with this test has been handled with a if (debug_mode)
    	test.
        Command line argument -l <num> sets the number of loops.
        Command line argument -c <num> sets the number of cpus.
        Usage: lock [-d] [-l <num>] [-c <num>]
    	*/
    	PLOptStatus os;
    	PLOptState *opt = PL_CreateOptState(argc, argv, "dl:c:");
    	while (PL_OPT_EOL != (os = PL_GetNextOpt(opt)))
        {
    		if (PL_OPT_BAD == os) continue;
            switch (opt->option)
            {
            case 'd':  /* debug mode */
    			debug_mode = 1;
                break;
            case 'l':  /* number of loops */
                loops = atoi(opt->value);
                break;
            case 'c':  /* number of cpus */
                cpus = atoi(opt->value);
                break;
             default:
                break;
            }
        }
    	PL_DestroyOptState(opt);
    }

 /* main test */
    PR_SetConcurrency(8);

#ifdef XP_MAC
	SetupMacPrintfLog("lock.log");
	debug_mode = 1;
#endif

    if (loops == 0) loops = 100;
    if (debug_mode) printf("Lock: Using %d loops\n", loops);

    if (cpus == 0) cpus = 2;
    if (debug_mode) printf("Lock: Using %d cpu(s)\n", cpus);

    (void)Sleeper(10);  /* try filling in the caches */

    for (cpu = 1; cpu <= cpus; ++cpu)
    {
        if (debug_mode) printf("\nLock: Using %d CPU(s)\n", cpu);
        PR_SetConcurrency(cpu);

        duration = Test("Overhead of PR_Sleep", Sleeper, loops, 0);
        duration = 0;

        (void)Test("Lock creation/deletion", MakeLock, loops, 0);
        (void)Test("Lock non-contentious locking/unlocking", NonContentiousLock, loops, 0);
        (void)Test("Lock contentious locking/unlocking", ContentiousLock, loops, duration);
        (void)Test("Monitor creation/deletion", MakeMonitor, loops, 0);
        (void)Test("Monitor non-contentious locking/unlocking", NonContentiousMonitor, loops, 0);
        (void)Test("Monitor contentious locking/unlocking", ContentiousMonitor, loops, duration);

        (void)Test("Cached monitor non-contentious locking/unlocking", NonContentiousCMonitor, loops, 0);
        (void)Test("Cached monitor contentious locking/unlocking", ContentiousCMonitor, loops, duration);

        (void)ReentrantMonitor(loops);
    }

    if (debug_mode) printf("%s: test %s\n", "Lock(mutex) test", ((rv) ? "passed" : "failed"));
	else {
		 if (!rv)
			 failed_already=1;
	}

	if(failed_already)	
	{
	    printf("FAIL\n"); 
		return 1;
    } 
	else
    {
	    printf("PASS\n"); 
		return 0;
    }

}  /* main */