/* Initialize a block */ static void init_block(block_t *p_block, uint8_t type) { p_block->type = type; /* Set the number of hits for the block (ignore the special-flag) */ switch(p_block->type & (0xff ^ TYPE_SPECIAL)) { case TYPE_SIMPLE: p_block->hits = 1; break; case TYPE_HARD: p_block->hits = 2; break; case TYPE_IMPOSSIBLE: p_block->hits = 255; break; } if (p_block->type & TYPE_SPECIAL) { /* This block has a random special, 1/4 can be bad specials, 5/6 are only good. * 1/6 of the "only goods" can be very good (extra life, "destroyer" balls etc) */ if (rand_nr & 1) p_block->special = 1<<(SRAND()%(SPECIAL_MAX-4)); /* Good specials */ else p_block->special = 1<<(SRAND()%SPECIAL_MAX); /* Can be very good and bad specials */ DEBUG(printf("Init special %d\n", p_block->special)); } }
int InicGen2D(float func(int,int),int TimeSize,int FreqSize,int Srand) { /* Inicjacja generatora liczb z 2D rozkladu p-stwa func(x,y) */ register int i,j; float sum,norma=0.0F; if((DystMatrix=MakeTable(TimeSize,FreqSize))==NULL) return -1; if((DystVector=(float *)malloc(TimeSize*sizeof(float)))==NULL) { FreeTable(DystMatrix,TimeSize); DystMatrix=NULL; return -1; } if(Srand==0) SRAND(0U); else SRAND((unsigned short)time(NULL)); GlobTimeSize=TimeSize; GlobFreqSize=FreqSize; for(i=0 ; i<TimeSize ; i++) /* Generacja rozkladu p-stwa + normalizacja */ for(j=0 ; j<FreqSize ; j++) { const float ftmp=func(i,j); /* Wartosci ujemne nie maja interpretacji */ norma+=DystMatrix[i][j]=((ftmp<0.0F) ? 1.0F : ftmp); } for(i=0,sum=0.0F ; i<FreqSize ; i++) /* Dystrybuanta brzegowa */ sum+=DystMatrix[0][i]; DystVector[0]=sum/norma; for(i=1 ; i<TimeSize ; i++) { for(j=0,sum=0.0F ; j<FreqSize ; j++) sum+=DystMatrix[i][j]; DystVector[i]=DystVector[i-1]+sum/norma; } for(i=0 ; i<TimeSize ; i++) /* Dystrybuanty warunkowe */ { for(j=0,sum=0.0F ; j<FreqSize ; j++) sum+=DystMatrix[i][j]; DystMatrix[i][0]/=sum; for(j=1 ; j<FreqSize ; j++) DystMatrix[i][j]=DystMatrix[i][j-1]+DystMatrix[i][j]/sum; } return 0; }
void piglit_init(int argc, char **argv) { piglit_require_extension("GL_ARB_vertex_program"); glEnable(GL_VERTEX_PROGRAM_ARB); SRAND(17); }
static void seed_random(void) { SEED_T seed; struct timeval tv; /* * Seed from time of day and process id multiplied by small primes. */ (void) gettimeofday(&tv, NULL); seed = (tv.tv_sec % 10000) * 523 + tv.tv_usec * 13 + (getpid() % 1000) * 983; SRAND(seed); }
int main(int argc, const char **argv) { SRAND(); InitNetworking(); //1. Pick up the startup parameters and hold them inside the running status if (argc < 2) { fprintf(stdout, "Invalid command line. Use --help\n"); return -1; } if (!Variant::DeserializeFromCmdLineArgs(argc, argv, gRs.commandLine)) { PrintHelp(); return -1; } string configFile = argv[argc - 1]; if (configFile.find("--") == 0) configFile = ""; NormalizeCommandLine(configFile); if ((bool)gRs.commandLine["arguments"]["--help"]) { PrintHelp(); return 0; } if ((bool)gRs.commandLine["arguments"]["--version"]) { PrintVersion(); return 0; } do { //2. Reset the run flag gRs.run = false; //3. Initialize the running status if (Initialize()) { Run(); } else { gRs.run = false; } //5. Cleanup Cleanup(); } while (gRs.run); //6. We are done return 0; }
int main(int argc, char **argv) { int rsize = 0; int wsize = 0; int factor = atoi(argv[0] + 6); SRAND(factor); FPRINTF(STDERR, "seeded with %d\n", factor); /* copy all data from STDIN to STDOUT */ for(;;) { char buffer[CHUNK_SIZE]; // int plan = RAND() % sizeof buffer + 1; int plan = (rand() * rand()) % sizeof buffer + 1; /* read */ int count = READ(STDIN, buffer, plan); BREAKIF(count < 0, "read error %d\n", count); busy_loop(factor); /* eof */ if(count == 0) break; /* the read log */ rsize += count; FPRINTF(STDERR, "%5d(of %5d) read, ", count, plan); /* write */ count = WRITE(STDOUT, buffer, count); BREAKIF(count < 0, "write error %d\n", count); /* the write log */ FPRINTF(STDERR, "%5d written\n", count); wsize += count; } /* report results */ FPRINTF(STDERR, "\n%d bytes has been read\n", rsize); FPRINTF(STDERR, "%d bytes has been written\n", wsize); return rsize == wsize ? 0 : 1; }
int main(int argc, char *argv[]) { int i,n,ids[3],t; double p; char* filename = FILENAME; DESCRIPTION_HASH *s; SIMULATION sim; /* the sampling simulation data */ plan_tests(8); OPTIONSinit(); #ifdef HAVE_OPENMP n = omp_get_max_threads(); #else n=1; #endif Options.Verbosity = 0; SRAND(123,i, n); Options.Fullsibs = true; Options.IgnoreAge = true; Options.TypingErrorDefined = 0.; Options.NumLoci = 5; DATAIOinfile(filename); Options.SiblingsOutformat[0] = Options.SiblingsOutformat[2] = false; Options.SiblingsOutformat[1] = true; snprintf(Options.SiblingsOutfilename[1], PATHLEN, "%s.%s", "siblings", D_TEXTSUFFIX); FREQcalcAlleleFrequencies(); FREQcalcSummaryStatistics(); PROBinit(); sim = SIMstart(); PROBcalcTriplesAndDyads(); PROBcalcPosteriors(); /* parentage, no missing data */ HASH_FIND_STR(Data.sample_ids, "1574", s); ids[0] = s->id; HASH_FIND_STR(Data.sample_ids, "1578", s); ids[1] = s->id; HASH_FIND_STR(Data.sample_ids, "376", s); ids[2] = s->id; t = TIDXL(ids[0],ids[1]); p = Data.fs_matrix[t].ibd.fs; ok(fabs(p + 24.67) < 0.01, "FS ibd correct"); p = Data.fs_matrix[t].ibd.fs - Data.fs_matrix[t].ibd.u; ok(fabs(p - 9.66) < 0.01, "delta u ibd correct"); p = Data.fs_matrix[t].ibd.fs - Data.fs_matrix[t].ibd.hs; ok(fabs(p - 5.16) < 0.01, "delta hs ibd correct"); p = Data.fs_matrix[t].ibd.fs - Data.fs_matrix[t].ibd.po; ok(fabs(p - 3.19) < 0.01, "delta po ibd correct"); t = TIDXL(ids[2],ids[1]); p = Data.fs_matrix[t].ibd.fs; ok(fabs(p + 28.15) < 0.01, "FS ibd correct"); p = Data.fs_matrix[t].ibd.fs - Data.fs_matrix[t].ibd.u; ok(fabs(p - 6.66) < 0.01, "delta u ibd correct"); p = Data.fs_matrix[t].ibd.fs - Data.fs_matrix[t].ibd.hs; ok(fabs(p - 2.61) < 0.01, "delta hs ibd correct"); p = Data.fs_matrix[t].ibd.fs - Data.fs_matrix[t].ibd.po; ok(fabs(p - 0.48) < 0.01, "delta po ibd correct"); SIMdestroy(sim); PROBdestroyPreMCMC(); DATAIOdestroyPreMCMC(); FREQdestroyPreMCMC(); PROBdestroyPostMCMC(); DATAIOdestroyPostMCMC(); FREQdestroyPostMCMC(); RANDDESTROY(i, n); remove(Options.LociOutfilename); remove(Options.SiblingsOutfilename[1]); remove(Options.MismatchOutfilename); return exit_status(); /* Return the correct exit code */ }
int main(int argc, char **argv) { int arg; char *argp; giantDigit *digit1; // mallocd arrays giantDigit *digit2; giantDigit *vect1; giantDigit *vect2; giantDigit *dig1p; // ptr into mallocd arrays giantDigit *dig2p; giantDigit *vect1p; giantDigit *vect2p; unsigned numDigits; unsigned i; PLAT_TIME startTime; PLAT_TIME endTime; unsigned elapsed; giantDigit scr1; // op result giantDigit scr2; // op result int loops = LOOPS_DEF; int seedSpec = 0; unsigned seed = 0; unsigned maxSize = MAX_SIZE_DEF; unsigned minSize = MIN_SIZE_DEF; initCryptKit(); #if macintosh argc = ccommand(&argv); #endif for(arg=1; arg<argc; arg++) { argp = argv[arg]; switch(argp[0]) { case 'x': maxSize = atoi(&argp[2]); break; case 'n': minSize = atoi(&argp[2]); break; case 'l': loops = atoi(&argp[2]); break; case 's': seed = atoi(&argp[2]); seedSpec = 1; break; case 'h': default: usage(argv); } } if(!seedSpec) { unsigned long tim; time(&tim); seed = (unsigned)tim; } SRAND(seed); /* * Scratch digits, big enough for anything. Malloc here, init with * random data before each test. */ digit1 = malloc(sizeof(giantDigit) * loops * 2); digit2 = malloc(sizeof(giantDigit) * loops * 2); /* vect1 and vect2 are arrays of giantDigit arrays */ vect1 = malloc(sizeof(giantDigit) * loops * maxSize); vect2 = malloc(sizeof(giantDigit) * loops * maxSize); if((digit1 == NULL) || (digit1 == NULL) || (vect1 == NULL) || (vect2 == NULL)) { printf("malloc error\n"); exit(1); } printf("Starting giantAsm test: seed %d\n", seed); /* giantAddDigits test */ randDigits(loops, digit1); randDigits(loops, digit2); dig1p = digit1; dig2p = digit2; PLAT_GET_TIME(startTime); for(i=0; i<loops; i++) { scr1 = giantAddDigits(*dig1p++, *dig2p++, &scr2); } PLAT_GET_TIME(endTime); elapsed = PLAT_GET_NS(startTime, endTime); printf("giantAddDigits: %f ns\n", (double)elapsed / (double)loops); /* giantAddDouble test */ randDigits(loops, digit1); randDigits(loops * 2, digit2); dig1p = digit1; dig2p = digit2; PLAT_GET_TIME(startTime); for(i=0; i<loops; i++) { giantAddDouble(dig2p, dig2p+1, *dig1p++); dig2p += 2; } PLAT_GET_TIME(endTime); elapsed = PLAT_GET_NS(startTime, endTime); printf("giantAddDouble: %f ns\n", (double)elapsed / (double)loops); /* giantSubDigits test */ randDigits(loops, digit1); randDigits(loops, digit2); dig1p = digit1; dig2p = digit2; PLAT_GET_TIME(startTime); for(i=0; i<loops; i++) { scr1 = giantSubDigits(*dig1p++, *dig2p++, &scr2); } PLAT_GET_TIME(endTime); elapsed = PLAT_GET_NS(startTime, endTime); printf("giantSubDigits: %f ns\n", (double)elapsed / (double)loops); /* giantMulDigits test */ randDigits(loops, digit1); randDigits(loops, digit2); dig1p = digit1; dig2p = digit2; PLAT_GET_TIME(startTime); for(i=0; i<loops; i++) { giantMulDigits(*dig1p++, *dig2p++, &scr1, &scr2); } PLAT_GET_TIME(endTime); elapsed = PLAT_GET_NS(startTime, endTime); printf("giantMulDigits: %f ns\n", (double)elapsed / (double)loops); printf("\nvectorMultiply:\n"); for(numDigits=minSize; numDigits<=maxSize; numDigits*=2) { randDigits(loops, digit1); // plierDigit randDigits(loops * numDigits, vect1); // candVector randDigits(loops * numDigits, vect2); // prodVector dig1p = digit1; vect1p = vect1; vect2p = vect2; PLAT_GET_TIME(startTime); for(i=0; i<loops; i++) { scr1 = VectorMultiply(*dig1p++, // plierDigit vect1p, // candVector numDigits, vect2p); // prodVector vect1p += numDigits; vect2p += numDigits; } PLAT_GET_TIME(endTime); elapsed = PLAT_GET_NS(startTime, endTime); printf(" bits = %4d : %f ns\n", numDigits * GIANT_BITS_PER_DIGIT, (double)elapsed / (double)loops); } /* for numDigits */ return 0; }
int main(int argc, char *argv[]) { int c, glob_ret = EXIT_FAILURE; int total_ports, left_ports, accept_ret = -1, connect_ret = -1; struct sigaction sv; nc_port_t local_port; /* local port specified with -p option */ nc_host_t local_host; /* local host for bind()ing operations */ nc_host_t remote_host; nc_sock_t listen_sock; nc_sock_t connect_sock; nc_sock_t stdio_sock; nc_ports_t old_flag = NULL; memset(&local_port, 0, sizeof(local_port)); memset(&local_host, 0, sizeof(local_host)); memset(&remote_host, 0, sizeof(remote_host)); memset(&listen_sock, 0, sizeof(listen_sock)); memset(&connect_sock, 0, sizeof(connect_sock)); memset(&stdio_sock, 0, sizeof(stdio_sock)); listen_sock.domain = NETCAT_DOMAIN_IPV4; connect_sock.domain = NETCAT_DOMAIN_IPV4; #ifdef ENABLE_NLS setlocale(LC_MESSAGES, ""); bindtextdomain(PACKAGE, LOCALEDIR); textdomain(PACKAGE); #endif /* set up the signal handling system */ sigemptyset(&sv.sa_mask); sv.sa_flags = 0; sv.sa_handler = got_int; sigaction(SIGINT, &sv, NULL); sv.sa_handler = got_term; sigaction(SIGTERM, &sv, NULL); sv.sa_handler = got_usr1; sigaction(SIGUSR1, &sv, NULL); /* ignore some boring signals */ sv.sa_handler = SIG_IGN; sigaction(SIGPIPE, &sv, NULL); sigaction(SIGURG, &sv, NULL); /* if no args given at all, take them from stdin and generate argv */ if (argc == 1) netcat_commandline_read(&argc, &argv); /* check for command line switches */ while (TRUE) { int option_index = 0; static const struct option long_options[] = { { "close", no_argument, NULL, 'c' }, { "debug", no_argument, NULL, 'd' }, { "exec", required_argument, NULL, 'e' }, { "gateway", required_argument, NULL, 'g' }, { "pointer", required_argument, NULL, 'G' }, { "help", no_argument, NULL, 'h' }, { "interval", required_argument, NULL, 'i' }, { "ipv4", no_argument, NULL, '4' }, { "ipv6", no_argument, NULL, '6' }, { "listen", no_argument, NULL, 'l' }, { "tunnel", required_argument, NULL, 'L' }, { "dont-resolve", no_argument, NULL, 'n' }, { "convert", required_argument, NULL, 'N' }, /* FIXME: proposal: A Ascii? */ { "output", required_argument, NULL, 'o' }, { "local-port", required_argument, NULL, 'p' }, { "tunnel-port", required_argument, NULL, 'P' }, { "randomize", no_argument, NULL, 'r' }, { "source", required_argument, NULL, 's' }, { "tunnel-source", required_argument, NULL, 'S' }, #ifndef USE_OLD_COMPAT { "tcp", no_argument, NULL, 't' }, { "telnet", no_argument, NULL, 'T' }, #else { "tcp", no_argument, NULL, 1 }, { "telnet", no_argument, NULL, 't' }, #endif { "udp", no_argument, NULL, 'u' }, { "verbose", no_argument, NULL, 'v' }, { "version", no_argument, NULL, 'V' }, { "hexdump", no_argument, NULL, 'x' }, { "wait", required_argument, NULL, 'w' }, { "zero", no_argument, NULL, 'z' }, { 0, 0, 0, 0 } }; c = getopt_long(argc, argv, "46cde:g:G:hi:lL:no:p:P:rs:S:tTuvVxw:z", long_options, &option_index); if (c == -1) break; switch (c) { case '4': /* don't use IPv6 protocol */ opt_domain = NETCAT_DOMAIN_IPV4; break; case '6': /* use IPv6 protocol */ opt_domain = NETCAT_DOMAIN_IPV6; break; case 'c': /* close connection on EOF from stdin */ opt_eofclose = TRUE; break; case 'd': /* enable debugging */ opt_debug = TRUE; break; case 'e': /* prog to exec */ if (opt_exec) ncprint(NCPRINT_ERROR | NCPRINT_EXIT, _("Cannot specify `-e' option double")); opt_exec = strdup(optarg); break; case 'G': /* srcrt gateways pointer val */ break; case 'g': /* srcroute hops */ break; case 'h': /* display help and exit */ netcat_printhelp(argv[0]); exit(EXIT_SUCCESS); case 'i': /* line/ports interval time (seconds) */ opt_interval = atoi(optarg); if (opt_interval < 0) ncprint(NCPRINT_ERROR | NCPRINT_EXIT, _("Invalid interval time \"%s\""), optarg); break; case 'l': /* mode flag: listen mode */ if (netcat_mode != NETCAT_UNSPEC) ncprint(NCPRINT_ERROR | NCPRINT_EXIT, _("You can specify mode flags (`-l' and `-L') only once")); netcat_mode = NETCAT_LISTEN; break; case 'L': /* mode flag: tunnel mode */ if (netcat_mode != NETCAT_UNSPEC) ncprint(NCPRINT_ERROR | NCPRINT_EXIT, _("You can specify mode flags (`-l' and `-L') only once")); if (opt_zero) ncprint(NCPRINT_ERROR | NCPRINT_EXIT, _("`-L' and `-z' options are incompatible")); do { char *div, *p, *pbuf = strdup(optarg); div = p = pbuf; /* if the address has '[' unbalanced, threat is as plain address */ if (div[0] == '[') { div = strchr(div, ']'); if (div != NULL) { *div++ = '\0'; p++; /* skip the '[' */ } } div = strchr(div, ':'); if (div && *(div + 1)) *div++ = '\0'; else { ncprint(NCPRINT_ERROR | NCPRINT_EXIT, _("Invalid target string for `-L' option")); } /* lookup the remote address and the remote port for tunneling */ if (!netcat_resolvehost(&connect_sock.remote, optarg)) ncprint(NCPRINT_ERROR | NCPRINT_EXIT, _("Couldn't resolve tunnel target host: %s"), optarg); if (!netcat_getport(&connect_sock.port, div, 0)) ncprint(NCPRINT_ERROR | NCPRINT_EXIT, _("Invalid tunnel target port: %s"), div); /* takes the options configured so far as they may change */ connect_sock.domain = opt_domain; connect_sock.proto = opt_proto; connect_sock.timeout = opt_wait; netcat_mode = NETCAT_TUNNEL; } while (FALSE); break; case 'N': /* ascii line ends conversion, use with care */ if (!strcasecmp(optarg, "none")) opt_ascii_conversion = NETCAT_CONVERT_NONE; else if (!strcasecmp(optarg, "crlf")) opt_ascii_conversion = NETCAT_CONVERT_CRLF; else if (!strcasecmp(optarg, "cr")) opt_ascii_conversion = NETCAT_CONVERT_CR; else if (!strcasecmp(optarg, "lf")) opt_ascii_conversion = NETCAT_CONVERT_LF; else { ncprint(NCPRINT_NORMAL, _("Conversion must be one of: none crlf cr lf")); ncprint(NCPRINT_ERROR | NCPRINT_EXIT, _("Invalid conversion specified: %s"), optarg); } break; case 'n': /* numeric-only, no DNS lookups */ opt_numeric = TRUE; break; case 'o': /* output hexdump log to file */ opt_outputfile = strdup(optarg); opt_hexdump = TRUE; /* implied */ break; case 'p': /* local source port */ if (!netcat_getport(&local_port, optarg, 0)) ncprint(NCPRINT_ERROR | NCPRINT_EXIT, _("Invalid local port: %s"), optarg); break; case 'P': /* used only in tunnel mode (source port) */ if (!netcat_getport(&connect_sock.local_port, optarg, 0)) ncprint(NCPRINT_ERROR | NCPRINT_EXIT, _("Invalid tunnel connect port: %s"), optarg); break; case 'r': /* randomize various things */ opt_random = TRUE; break; case 's': /* local source address */ /* lookup the source address and assign it to the connection address */ if (!netcat_resolvehost(&local_host, optarg)) ncprint(NCPRINT_ERROR | NCPRINT_EXIT, _("Couldn't resolve local host: %s"), optarg); break; case 'S': /* used only in tunnel mode (source ip) */ if (!netcat_resolvehost(&connect_sock.local, optarg)) ncprint(NCPRINT_ERROR | NCPRINT_EXIT, _("Couldn't resolve tunnel local host: %s"), optarg); break; case 1: /* use TCP protocol (default) */ #ifndef USE_OLD_COMPAT case 't': #endif opt_proto = NETCAT_PROTO_TCP; break; #ifdef USE_OLD_COMPAT case 't': #endif case 'T': /* answer telnet codes */ opt_telnet = TRUE; break; case 'u': /* use UDP protocol */ opt_proto = NETCAT_PROTO_UDP; break; case 'v': /* be verbose (twice=more verbose) */ opt_verbose++; break; case 'V': /* display version and exit */ netcat_printversion(); exit(EXIT_SUCCESS); case 'w': /* wait time (in seconds), 0 means no timeout */ opt_wait = atoi(optarg); if (opt_wait < 0) ncprint(NCPRINT_ERROR | NCPRINT_EXIT, _("Invalid wait-time: %s"), optarg); break; case 'x': /* hexdump traffic */ opt_hexdump = TRUE; break; case 'z': /* little or no data xfer */ if (netcat_mode == NETCAT_TUNNEL) ncprint(NCPRINT_ERROR | NCPRINT_EXIT, _("`-L' and `-z' options are incompatible")); opt_zero = TRUE; break; default: ncprint(NCPRINT_EXIT, _("Try `%s --help' for more information."), argv[0]); } } if (opt_zero && opt_exec) ncprint(NCPRINT_ERROR | NCPRINT_EXIT, _("`-e' and `-z' options are incompatible")); /* initialize the flag buffer to keep track of the specified ports */ //netcat_flag_init(65535); old_flag = netcat_ports_init(); #ifndef DEBUG /* check for debugging support */ if (opt_debug) ncprint(NCPRINT_WARNING, _("Debugging support not compiled, option `-d' discarded. Using maximum verbosity.")); #endif /* randomize only if needed */ if (opt_random) #ifdef USE_RANDOM SRAND(time(0)); #else ncprint(NCPRINT_WARNING, _("Randomization support not compiled, option `-r' discarded.")); #endif /* handle the -o option. exit on failure */ if (opt_outputfile) { output_fp = fopen(opt_outputfile, "w"); if (!output_fp) ncprint(NCPRINT_ERROR | NCPRINT_EXIT, _("Failed to open output file: %s (%s)"), opt_outputfile, strerror(errno)); } else output_fp = stderr; /* FIXME: now we can resolve special hostnames */ debug_v(("Trying to parse non-args parameters (argc=%d, optind=%d)", argc, optind)); /* try to get an hostname parameter */ if (optind < argc) { const char *get_host = argv[optind++]; if (!netcat_resolvehost(&remote_host, get_host)) ncprint(NCPRINT_ERROR | NCPRINT_EXIT, _("Couldn't resolve host \"%s\""), get_host); } /* now loop all the other (maybe optional) parameters for port-ranges */ while (optind < argc) { const char *get_argv = argv[optind++]; char *q, *parse = strdup(get_argv); int port_lo = 0, port_hi = 65535; nc_port_t port_tmp; if (!(q = strchr(parse, '-'))) /* simple number? */ q = strchr(parse, ':'); /* try with the other separator */ if (!q) { if (netcat_getport(&port_tmp, parse, 0)) netcat_ports_insert(old_flag, port_tmp.num, port_tmp.num); else goto got_err; } else { /* could be in the forms: N1-N2, -N2, N1- */ *q++ = 0; if (*parse) { if (netcat_getport(&port_tmp, parse, 0)) port_lo = port_tmp.num; else goto got_err; } if (*q) { if (netcat_getport(&port_tmp, q, 0)) port_hi = port_tmp.num; else goto got_err; } if (!*parse && !*q) /* don't accept the form '-' */ goto got_err; netcat_ports_insert(old_flag, port_lo, port_hi); } free(parse); continue; got_err: free(parse); ncprint(NCPRINT_ERROR, _("Invalid port specification: %s"), get_argv); exit(EXIT_FAILURE); } debug_dv(("Arguments parsing complete! Total ports=%d", netcat_ports_count(old_flag))); #if 0 /* pure debugging code */ c = 0; while ((c = netcat_ports_next(old_flag, c))) { printf("Got port=%d\n", c); } exit(0); #endif /* Handle listen mode and tunnel mode (whose index number is higher) */ if (netcat_mode > NETCAT_CONNECT) { /* in tunnel mode the opt_zero flag is illegal, while on listen mode it means that no connections should be accepted. For UDP it means that no remote addresses should be used as default endpoint, which means that we can't send anything. In both situations, stdin is no longer useful, so close it. */ if (opt_zero) { close(STDIN_FILENO); use_stdin = FALSE; } /* prepare the socket var and start listening */ listen_sock.proto = opt_proto; listen_sock.timeout = opt_wait; memcpy(&listen_sock.local, &local_host, sizeof(listen_sock.local)); memcpy(&listen_sock.local_port, &local_port, sizeof(listen_sock.local_port)); memcpy(&listen_sock.remote, &remote_host, sizeof(listen_sock.remote)); accept_ret = core_listen(&listen_sock); /* in zero I/O mode the core_tcp_listen() call will always return -1 (ETIMEDOUT) since no connections are accepted, because of this our job is completed now. */ if (accept_ret < 0) { /* since i'm planning to make `-z' compatible with `-L' I need to check the exact error that caused this failure. */ if (opt_zero && (errno == ETIMEDOUT)) exit(0); ncprint(NCPRINT_VERB1 | NCPRINT_EXIT, _("Listen mode failed: %s"), strerror(errno)); } /* if we are in listen mode, run the core loop and exit when it returns. otherwise now it's the time to connect to the target host and tunnel them together (which means passing to the next section. */ if (netcat_mode == NETCAT_LISTEN) { if (opt_exec) { ncprint(NCPRINT_VERB2, _("Passing control to the specified program")); ncexec(&listen_sock); /* this won't return */ } core_readwrite(&listen_sock, &stdio_sock); debug_dv(("Listen: EXIT")); } else { /* otherwise we are in tunnel mode. The connect_sock var was already initialized by the command line arguments. */ assert(netcat_mode == NETCAT_TUNNEL); connect_ret = core_connect(&connect_sock); /* connection failure? (we cannot get this in UDP mode) */ if (connect_ret < 0) { assert(connect_sock.proto != NETCAT_PROTO_UDP); ncprint(NCPRINT_VERB1, "%s: %s", netcat_strid(connect_sock.domain, &connect_sock.remote, &connect_sock.port), strerror(errno)); } else { glob_ret = EXIT_SUCCESS; core_readwrite(&listen_sock, &connect_sock); debug_dv(("Tunnel: EXIT (ret=%d)", glob_ret)); } } /* all jobs should be ok, go to the cleanup */ goto main_exit; } /* end of listen and tunnel mode handling */ /* we need to connect outside, this is the connect mode */ netcat_mode = NETCAT_CONNECT; /* first check that a host parameter was given */ if (!remote_host.host.iaddrs[0].s_addr) { /* FIXME: The Networking specifications state that host address "0" is a valid host to connect to but this broken check will assume as not specified. */ ncprint(NCPRINT_NORMAL, _("%s: missing hostname argument"), argv[0]); ncprint(NCPRINT_EXIT, _("Try `%s --help' for more information."), argv[0]); } /* since ports are the second argument, checking ports might be enough */ total_ports = netcat_ports_count(old_flag); if (total_ports == 0) ncprint(NCPRINT_ERROR | NCPRINT_EXIT, _("No ports specified for connection")); c = 0; /* must be set to 0 for netcat_flag_next() */ left_ports = total_ports; while (left_ports > 0) { /* `c' is the port number independently of the sorting method (linear or random). While in linear mode it is also used to fetch the next port number */ if (opt_random) c = netcat_ports_rand(old_flag); else c = netcat_ports_next(old_flag, c); left_ports--; /* decrease the total ports number to try */ /* since we are nonblocking now, we can start as many connections as we want but it's not a great idea connecting more than one host at time */ connect_sock.proto = opt_proto; connect_sock.timeout = opt_wait; memcpy(&connect_sock.local, &local_host, sizeof(connect_sock.local)); memcpy(&connect_sock.local_port, &local_port, sizeof(connect_sock.local_port)); memcpy(&connect_sock.remote, &remote_host, sizeof(connect_sock.remote)); netcat_getport(&connect_sock.port, NULL, c); /* FIXME: in udp mode and NETCAT_CONNECT, opt_zero is senseless */ connect_ret = core_connect(&connect_sock); /* connection failure? (we cannot get this in UDP mode) */ if (connect_ret < 0) { int ncprint_flags = NCPRINT_VERB1; assert(connect_sock.proto != NETCAT_PROTO_UDP); /* if we are portscanning or multiple connecting show only open ports with verbosity level 1. */ if (total_ports > 1) ncprint_flags = NCPRINT_VERB2; ncprint(ncprint_flags, "%s: %s", netcat_strid(connect_sock.domain, &connect_sock.remote, &connect_sock.port), strerror(errno)); continue; /* go with next port */ } /* when portscanning (or checking a single port) we are happy if AT LEAST ONE port is available. */ glob_ret = EXIT_SUCCESS; if (opt_zero) { shutdown(connect_ret, 2); close(connect_ret); } else { if (opt_exec) { ncprint(NCPRINT_VERB2, _("Passing control to the specified program")); ncexec(&connect_sock); /* this won't return */ } core_readwrite(&connect_sock, &stdio_sock); /* FIXME: add a small delay */ debug_v(("Connect: EXIT")); /* both signals are handled inside core_readwrite(), but while the SIGINT signal is fully handled, the SIGTERM requires some action from outside that function, because of this that flag is not cleared. */ if (got_sigterm) break; } } /* end of while (left_ports > 0) */ /* all basic modes should return here for the final cleanup */ main_exit: debug_v(("Main: EXIT (cleaning up)")); netcat_printstats(FALSE); return glob_ret; } /* end of main() */
int main(int argc, char **argv) { int arg; char *argp; int loop; unsigned char *ptext; unsigned ptextLen; unsigned char passwd1[PASSWD_LENGTH]; unsigned char passwd2[PASSWD_LENGTH]; int encrType; int doEnc64; feePubKey myPrivKey; feePubKey theirPrivKey; feePubKey myPubKey; feePubKey theirPubKey; unsigned maxSize; /* * User-spec'd params */ unsigned loops = LOOPS_DEF; BOOL seedSpec = NO; unsigned seed; BOOL quiet = NO; BOOL verbose = NO; unsigned minExp = MIN_EXP; unsigned maxExp = MAX_EXP; BOOL incrOffset = NO; unsigned depth = DEPTH_DEFAULT; unsigned minOffset = MIN_OFFSET; #if macintosh argc = ccommand(&argv); #endif for(arg=1; arg<argc; arg++) { argp = argv[arg]; switch(argp[0]) { case 'l': loops = atoi(&argp[2]); break; case 'n': minExp = atoi(&argp[2]); break; case 'D': depth = atoi(&argp[2]); break; case 'N': minOffset = atoi(&argp[2]); if(minOffset > MAX_OFFSET) { minOffset = MIN_OFFSET; } sizeOffset = minOffset; break; case 'x': maxExp = atoi(&argp[2]); if(maxExp > MAX_EXP) { usage(argv); } break; case 's': seed = atoi(&argp[2]); seedSpec = YES; break; case 'I': incrOffset = YES; break; case 'q': quiet = YES; break; case 'v': verbose = YES; break; case 'h': default: usage(argv); } } if(seedSpec == NO) { time((unsigned long *)(&seed)); } SRAND(seed); maxSize = dataSizeFromExp(maxExp) + MAX_OFFSET + 8; dataPool = fmalloc(maxSize); printf("Starting cfileTest: loops %d seed %d depth %d\n", loops, seed, depth); for(loop=1; ; loop++) { ptext = genData(minExp, maxExp, DT_Random, incrOffset, minOffset, &ptextLen); if(!quiet) { printf("..loop %d plaintext size %d\n", loop, ptextLen); } /* * Generate a whole bunch of keys */ genPasswd(passwd1, PASSWD_LENGTH, NO); // not ascii! genPasswd(passwd2, PASSWD_LENGTH, NO); myPrivKey = genPrivKey(passwd1, PASSWD_LENGTH, depth); theirPrivKey = genPrivKey(passwd2, PASSWD_LENGTH, depth); myPubKey = genPubKey(myPrivKey); theirPubKey = genPubKey(theirPrivKey); for(encrType=CFE_PublicDES; encrType<=CFE_FEEDExp; encrType++) { if(verbose) { printf(" ..%s\n", stringFromEncrType(encrType)); } for(doEnc64=0; doEnc64<2; doEnc64++) { if(verbose) { printf(" ..doEnc64 %d\n", doEnc64); } if(verbose) { printf(" ..no sig\n"); } doTest(ptext, ptextLen, myPrivKey, myPubKey, theirPrivKey, theirPubKey, encrType, doEnc64, SIG_NO, EXPLICIT_NO); if(verbose) { printf(" ..sig, implicit sendPubKey\n"); } doTest(ptext, ptextLen, myPrivKey, myPubKey, theirPrivKey, theirPubKey, encrType, doEnc64, SIG_YES, EXPLICIT_NO); if(verbose) { printf(" ..sig, explicit sendPubKey\n"); } doTest(ptext, ptextLen, myPrivKey, myPubKey, theirPrivKey, theirPubKey, encrType, doEnc64, SIG_YES, EXPLICIT_YES); if(verbose) { printf(" ..sig, force error\n"); } doTest(ptext, ptextLen, myPrivKey, myPubKey, theirPrivKey, theirPubKey, encrType, doEnc64, SIG_YES, EXPLICIT_ERR); } /* for doEnc64 */ } /* for encrType */ feePubKeyFree(myPrivKey); feePubKeyFree(myPubKey); feePubKeyFree(theirPrivKey); feePubKeyFree(theirPubKey); if(loops) { if(loop == loops) { break; } } } /* main loop */ if(!quiet) { printf("cfile test complete\n"); } return 0; }
int main(int argc, char *argv[]) { unsigned int i, n; SIMULATION sim; MCMC mcmc; GraphvizCluster cluster; /* for the GRAPHVIZ output */ FILE *freqsout = NULL, *out = NULL, *pout = NULL; time_t now; /* make the cursor visible again when user killed FRANz */ (void)signal(SIGABRT, &sighandler); (void)signal(SIGTERM, &sighandler); (void)signal(SIGINT, &sighandler); #ifndef NDEBUG WARN("Reconfigure without --enable-assertions for optimal performance!"); #endif (void)time(&Data.StartTime); /* Load default and specified options and data */ OPTIONSinit(); CMDLINEparse(argc, argv); DATAIOinfile(Options.Infilename); /* load coordinates of sampling locations if available */ if (strlen(Options.Coordfilename) > 0) DATAIOgeofile(Options.Coordfilename, false); /* and/or use user provided distances of sampling locations */ if (strlen(Options.Geofilename) > 0) DATAIOgeofile(Options.Geofilename, true); /* use frequency file, otherwise calculate allele frequencies */ if (strlen(Options.FreqInfilename) > 0) DATAIOfreqfile(Options.FreqInfilename, 0); else { FREQcalcAlleleFrequencies(); /* and then dump the frequencies in our own format */ FOPENW(freqsout, Options.FreqOutfilename); FREQdump(freqsout); FCLOSE(freqsout); } /* load prior pedigree (known mothers, sub-pedigrees) */ if (strlen(Options.PedigreeInfilename) > 0) DATAIOinitInpedigree(); /* load known fullsibs if available */ if (strlen(Options.FullsibInfilename) > 0) DATAIOfullsibFile(Options.FullsibInfilename); /* create n random number streams, one for each thread */ #ifdef HAVE_OPENMP n = omp_get_max_threads(); #else n = 1; #endif VTPROGRESSBARinit(PROGRESSBARSIZE); SRAND(Options.Seed, i, n); /* calculate the loci summary statistics */ FREQcalcSummaryStatistics(); /* simulate the sampling (mismatch distributions, IBD deltas) */ sim = SIMstart(); FOPENW(out, Options.SimulationOutfilename); SIMdumpDetailed(out, sim); FCLOSE(out); /* Calculate probabilities of all parents-offspring triples * * and dyads with the allowed number of mismatches */ PROBcalcTriplesAndDyads(); /* This now generates an efficient data structure with the * * likelihoods of all possible arcs in the pedigree. It also * * filters very unlikely parentages. */ PROBcalcPosteriors(); /* Now we know all candidate parents, so we can create the * CERVUS output */ if (strlen(Options.GenotypeOutfilenameCERVUS) > 0) DATAIOdumpGenotypesCERVUS(); if (strlen(Options.OffspringOutfilenameCERVUS) > 0) DATAIOdumpOffspringCERVUS(); if (strlen(Options.GenotypeOutfilenameGenepop) > 0) DATAIOdumpGenotypesGenepop(); if (strlen(Options.GenotypeOutfilenameRMES) > 0) DATAIOdumpGenotypesRMES(); if (strlen(Options.GenotypeOutfilenamePARENTE) > 0) DATAIOdumpGenotypesParente(); /* Create the summary.txt file */ FOPENW(out, Options.Outfilename); DATAIOdumpDatasetDetails(out); FREQdumpSummaryStatistics(out); OPTIONSdump(out); DATAIOcheckData(out); if (Data.num_populations > 1) DATAIOdumpSamplingLocations(out); SIMdump(out, sim); /* Cleanup memory */ SIMdestroy(sim); PROBdestroyPreMCMC(); DATAIOdestroyPreMCMC(); FREQdestroyPreMCMC(); mcmc = MCMCinit(); if (!Options.NoReconstruction) { /* now start MCMC chains */ MCMCstart(&mcmc); if (Options.PedigreeOutformat[1]) { /* output DAG, cluster sampling locations in graphviz output */ cluster = DATAIOgraphvizCluster(); /* display meta data in graphviz output */ DATAIOaddGVNodeStyle(mcmc.best.D); DAGgraphviz(mcmc.best.D, Options.PedigreeOutfilename[1], cluster, true); DATAIOgraphvizClusterDestroy(cluster); } /* --pedigreeincheck compares our results with the true pedigree */ MCMCcheckML(&mcmc); MCMCdumpResults(out, &mcmc); } /* write parentage files */ for (i = 0; i < 2; i++) if (Options.POutformat[i]) { FOPENW(pout, Options.POutfilename[i]); PROBdumpPosteriors(pout, Probs.posteriors, mcmc.best.D, mcmc.D_true, i); FCLOSE(pout); } /* output pedigree in our input format */ if (Options.PedigreeOutformat[0]) DATAIOpedigreeout(Options.PedigreeOutfilename[0], mcmc.best.D); if (Options.PedigreeOutformat[2]) DATAIOpedigreeoutText(Options.PedigreeOutfilename[2], mcmc.best.D); (void)time(&now); fprintf(out, "\nRunning Time : %d sec.\n", (unsigned int)( now - Data.StartTime)); FCLOSE(out); DATAIOdumpMismatches(); MCMCdestroy(mcmc); PROBdestroyPostMCMC(); DATAIOdestroyPostMCMC(); FREQdestroyPostMCMC(); RANDDESTROY(i, n); VTPROGRESSBARcursorVisible(); exit(EXIT_SUCCESS); }
int main(int argc, char **argv) { int arg; char *argp; giant *g1; giant *g2; // ditto unsigned char *buf; // random data unsigned numDigits; unsigned i; unsigned numBytes; unsigned mulgElapsed; unsigned sqrElapsed; int loops = LOOPS_DEF; int seedSpec = 0; unsigned seed = 0; unsigned maxSize = MAX_SIZE_DEF; unsigned minSize = MIN_SIZE_DEF; int useOld = 0; initCryptKit(); #if macintosh argc = ccommand(&argv); #endif for(arg=1; arg<argc; arg++) { argp = argv[arg]; switch(argp[0]) { case 'x': maxSize = atoi(&argp[2]); break; case 'n': minSize = atoi(&argp[2]); break; case 'l': loops = atoi(&argp[2]); break; case 'o': useOld = 1; break; case 's': seed = atoi(&argp[2]); seedSpec = 1; break; case 'h': default: usage(argv); } } buf = malloc(maxSize); if(!seedSpec) { unsigned long tim; time(&tim); seed = (unsigned)tim; } SRAND(seed); /* * Scratch giants, big enough for anything. Malloc here, init with * random data before each test * note these mallocs will be too big in the useOld case... */ g1 = malloc(sizeof(giant) * loops); g2 = malloc(sizeof(giant) * loops); if((g1 == NULL) || (g2 == NULL)) { printf("malloc error\n"); exit(1); } if(useOld) { numDigits = ((2 * maxSize) + 1) / 2; } else { numDigits = BYTES_TO_GIANT_DIGITS(2 * maxSize); } for(i=0; i<loops; i++) { g1[i] = newGiant(numDigits); g2[i] = newGiant(numDigits); if((g1[i] == NULL) || (g2[i] == NULL)) { printf("malloc error\n"); exit(1); } } printf("Starting giants test: seed %d\n", seed); for(numBytes=minSize; numBytes<=maxSize; numBytes*=2) { initRandGiants(numBytes, buf, loops, g1, g2); mulgElapsed = mulgTest(loops, g1, g2); initRandGiants(numBytes, buf, loops, g1, g2); sqrElapsed = squareTest(loops, g1, g2); printf(" bits : %4d mulg : %3d ns gsquare : %3d ns\n", numBytes * 8, mulgElapsed / loops, sqrElapsed / loops); } /* for numBytes */ return 0; }
int main(int argc, char *argv[]) { int i,n,ids[3]; char* filename = FILENAME; char* filenamePedigree = FILENAMEPED; DESCRIPTION_HASH *s; SIMULATION sim; /* the sampling simulation data */ plan_tests(8); OPTIONSinit(); #ifdef HAVE_OPENMP n = omp_get_max_threads(); #else n=1; #endif Options.Verbosity = 0; SRAND(123,i, n); Options.TypingErrorDefined = 0.01; Options.FemRepro.min = Options.FemRepro.max = 1; Options.MaleRepro.min = Options.MaleRepro.max = 1; DATAIOinfile(filename); FREQcalcAlleleFrequencies(); FREQcalcSummaryStatistics(); PROBinit(); sim = SIMstart(); PROBcalcTriplesAndDyads(); PROBcalcPosteriors(); /* parentage, no missing data */ HASH_FIND_STR(Data.sample_ids, "1570", s); ids[0] = s->id; HASH_FIND_STR(Data.sample_ids, "221", s); ids[1] = s->id; HASH_FIND_STR(Data.sample_ids, "376", s); ids[2] = s->id; ok(CMP_DBL(Probs.posteriors[ids[0]][PROBsearchPosteriors(Probs.posteriors,ids[0],ids[1],ids[2])].lod, 1.98843824612410E+0001), "Triple LOD correct"); ok(CMP_DBL(Probs.posteriors[ids[0]][PROBsearchPosteriors(Probs.posteriors,ids[0],ids[1],-1)].lod, 1.08164969253876E+0001), "Pair LOD correct"); ok(CMP_DBL(Probs.posteriors[ids[0]][PROBsearchPosteriors(Probs.posteriors,ids[0],ids[2],-1)].lod, 6.94685569833075E+0000), "Pair LOD correct"); /* parentage, missing data */ HASH_FIND_STR(Data.sample_ids, "1810", s); ids[0] = s->id; HASH_FIND_STR(Data.sample_ids, "313", s); ids[1] = s->id; HASH_FIND_STR(Data.sample_ids, "222", s); ids[2] = s->id; ok(CMP_DBL(Probs.posteriors[ids[0]][PROBsearchPosteriors(Probs.posteriors,ids[0],ids[1],ids[2])].lod, 2.04404149122917E+0001), "Triple LOD correct (missing values)"); ok(CMP_DBL(Probs.posteriors[ids[0]][PROBsearchPosteriors(Probs.posteriors,ids[0],ids[1],-1)].lod, 8.61834142652084E+0000 ), "Pair LOD correct (missing values)"); ok(CMP_DBL(Probs.posteriors[ids[0]][PROBsearchPosteriors(Probs.posteriors,ids[0],ids[2],-1)].lod, 8.24729736134361E+0000), "Pair LOD correct (missing values)"); SIMdestroy(sim); PROBdestroyPreMCMC(); DATAIOdestroyPreMCMC(); FREQdestroyPreMCMC(); PROBdestroyPostMCMC(); DATAIOdestroyPostMCMC(); FREQdestroyPostMCMC(); DATAIOinfile(filename); strncpy(Options.PedigreeInfilename,filenamePedigree,200); DATAIOinitInpedigree(); FREQcalcAlleleFrequencies(); FREQcalcSummaryStatistics(); PROBinit(); sim = SIMstart(); PROBcalcTriplesAndDyads(); PROBcalcPosteriors(); // PROBdumpPosteriors(stderr,Probs.posteriors, NULL,NULL,2); HASH_FIND_STR(Data.sample_ids, "1570", s); ids[0] = s->id; HASH_FIND_STR(Data.sample_ids, "221", s); ids[1] = s->id; HASH_FIND_STR(Data.sample_ids, "376", s); ids[2] = s->id; /* paternity, no missing */ ok(CMP_DBL(Probs.posteriors[ids[0]][PROBsearchPosteriors(Probs.posteriors,ids[0],ids[1],ids[2])].lod, 1.29375267629102E+0001), "Triple LOD correct (mother known)"); HASH_FIND_STR(Data.sample_ids, "1810", s); ids[0] = s->id; HASH_FIND_STR(Data.sample_ids, "313", s); ids[1] = s->id; HASH_FIND_STR(Data.sample_ids, "222", s); ids[2] = s->id; ok(CMP_DBL(Probs.posteriors[ids[0]][PROBsearchPosteriors(Probs.posteriors,ids[0],ids[1],ids[2])].lod, 1.18220734857708E+0001), "Triple LOD correct (mother known, missing values)"); RANDDESTROY(i, n); remove(Options.LociOutfilename); return exit_status(); /* Return the correct exit code */ }
void piglit_init(int argc, char **argv) { SRAND(17); }
int main(int argc, char **argv) { krb5_context context; krb5_keytab kt; krb5_keytab_entry ktent; krb5_encrypt_block eblock; krb5_creds my_creds; krb5_get_init_creds_opt *opt; kadm5_principal_ent_rec princ_ent; krb5_principal princ, server; char pw[16]; char *whoami, *principal, *authprinc, *authpwd; krb5_data pwdata; void *handle; int ret, test, encnum; unsigned int i; whoami = argv[0]; if (argc < 2 || argc > 4) { fprintf(stderr, "Usage: %s principal [authuser] [authpwd]\n", whoami); exit(1); } principal = argv[1]; authprinc = (argc > 2) ? argv[2] : argv[0]; authpwd = (argc > 3) ? argv[3] : NULL; /* * Setup. Initialize data structures, open keytab, open connection * to kadm5 server. */ memset(&context, 0, sizeof(context)); kadm5_init_krb5_context(&context); ret = krb5_parse_name(context, principal, &princ); if (ret) { com_err(whoami, ret, "while parsing principal name %s", principal); exit(1); } if((ret = krb5_build_principal_ext(context, &server, krb5_princ_realm(kcontext, princ)->length, krb5_princ_realm(kcontext, princ)->data, tgtname.length, tgtname.data, krb5_princ_realm(kcontext, princ)->length, krb5_princ_realm(kcontext, princ)->data, 0))) { com_err(whoami, ret, "while building server name"); exit(1); } ret = krb5_kt_default(context, &kt); if (ret) { com_err(whoami, ret, "while opening keytab"); exit(1); } ret = kadm5_init(context, authprinc, authpwd, KADM5_ADMIN_SERVICE, NULL, KADM5_STRUCT_VERSION, KADM5_API_VERSION_4, NULL, &handle); if (ret) { com_err(whoami, ret, "while initializing connection"); exit(1); } /* these pw's don't need to be secure, just different every time */ SRAND((RAND_TYPE)time((void *) NULL)); pwdata.data = pw; pwdata.length = sizeof(pw); /* * For each test: * * For each enctype in the test, construct a random password/key. * Assign all keys to principal with kadm5_setkey_principal. Add * each key to the keytab, and acquire an initial ticket with the * keytab (XXX can I specify the kvno explicitly?). If * krb5_get_init_creds_keytab succeeds, then the keys were set * successfully. */ for (test = 0; tests[test] != NULL; test++) { krb5_keyblock *testp = tests[test]; kadm5_key_data *extracted; int n_extracted, match; printf("+ Test %d:\n", test); for (encnum = 0; testp[encnum].magic != -1; encnum++) { for (i = 0; i < sizeof(pw); i++) pw[i] = (RAND() % 26) + '0'; /* XXX */ krb5_use_enctype(context, &eblock, testp[encnum].enctype); ret = krb5_string_to_key(context, &eblock, &testp[encnum], &pwdata, NULL); if (ret) { com_err(whoami, ret, "while converting string to key"); exit(1); } } /* now, encnum == # of keyblocks in testp */ ret = kadm5_setkey_principal(handle, princ, testp, encnum); if (ret) { com_err(whoami, ret, "while setting keys"); exit(1); } ret = kadm5_get_principal(handle, princ, &princ_ent, KADM5_KVNO); if (ret) { com_err(whoami, ret, "while retrieving principal"); exit(1); } ret = kadm5_get_principal_keys(handle, princ, 0, &extracted, &n_extracted); if (ret) { com_err(whoami, ret, "while extracting keys"); exit(1); } for (encnum = 0; testp[encnum].magic != -1; encnum++) { printf("+ enctype %d\n", testp[encnum].enctype); for (match = 0; match < n_extracted; match++) { if (extracted[match].key.enctype == testp[encnum].enctype) break; } if (match >= n_extracted) { com_err(whoami, KRB5_WRONG_ETYPE, "while matching enctypes"); exit(1); } if (extracted[match].key.length != testp[encnum].length || memcmp(extracted[match].key.contents, testp[encnum].contents, testp[encnum].length) != 0) { com_err(whoami, KRB5_KDB_NO_MATCHING_KEY, "verifying keys"); exit(1); } memset(&ktent, 0, sizeof(ktent)); ktent.principal = princ; ktent.key = testp[encnum]; ktent.vno = princ_ent.kvno; ret = krb5_kt_add_entry(context, kt, &ktent); if (ret) { com_err(whoami, ret, "while adding keytab entry"); exit(1); } memset(&my_creds, 0, sizeof(my_creds)); my_creds.client = princ; my_creds.server = server; ktypes[0] = testp[encnum].enctype; ret = krb5_get_init_creds_opt_alloc(context, &opt); if (ret) { com_err(whoami, ret, "while allocating gic opts"); exit(1); } krb5_get_init_creds_opt_set_etype_list(opt, ktypes, 1); ret = krb5_get_init_creds_keytab(context, &my_creds, princ, kt, 0, NULL /* in_tkt_service */, opt); krb5_get_init_creds_opt_free(context, opt); if (ret) { com_err(whoami, ret, "while acquiring initial ticket"); exit(1); } krb5_free_cred_contents(context, &my_creds); /* since I can't specify enctype explicitly ... */ ret = krb5_kt_remove_entry(context, kt, &ktent); if (ret) { com_err(whoami, ret, "while removing keytab entry"); exit(1); } } (void)kadm5_free_kadm5_key_data(context, n_extracted, extracted); } ret = krb5_kt_close(context, kt); if (ret) { com_err(whoami, ret, "while closing keytab"); exit(1); } ret = kadm5_destroy(handle); if (ret) { com_err(whoami, ret, "while closing kadmin connection"); exit(1); } krb5_free_principal(context, princ); krb5_free_principal(context, server); krb5_free_context(context); return 0; }