コード例 #1
0
ファイル: main.cpp プロジェクト: Zhanyin/taomee
int main(int argc, char **argv)
{
    //配置数据库连接
    i_mysql_iface  *conf_db_conn = NULL;

    //grid name 列表
    char    grid_name_list[4096] = {0};
    //配置库的配置项
    unsigned short db_port = 3306;

    int     ch = 0;
    //处理命令行参数
    while(1) {   
        ch = getopt(argc, argv, "n:d:h:p:u:P:i:s:");
        if(ch == -1) {
            break;
        }

        unsigned short  tmp_port = 3306;
        switch(ch)
        {   
        case 'n':  //grid name
            if(strlen(optarg) >= sizeof(grid_name_list)) {
                fprintf(stderr, "The grid name list is too long,the max length of name is:%u.\n", 4096);
                return -1;
            }
            strcpy(grid_name_list, optarg);
            break;
        case 'd':  //db name 
            strncpy(g_db_name, optarg, sizeof(g_db_name) - 1);
            break;
        case 'h':  //db host
            strncpy(g_db_host, optarg, sizeof(g_db_host) - 1);
            break;
        case 'P':  //db port
            tmp_port = atoi(optarg);
            db_port = tmp_port <= 0 ? db_port : tmp_port;
            break;
        case 'u':   //db user 
            strncpy(g_db_user, optarg, sizeof(g_db_user) - 1);
            break;
        case 'p':  //db passwd
            strncpy(g_db_pass, optarg, sizeof(g_db_pass) - 1);
            break;
        case 'i':  //install dir
            if(access(optarg, F_OK | R_OK | W_OK | X_OK)) {
                fprintf(stderr, "Wrong install directory: %s.\n", strerror(errno));
                return -1;
            }
            strncpy(g_install_prefix, optarg, sizeof(g_install_prefix));
            break;
        case 's':  //service flag 主还是备
            if(!strcasecmp(optarg, "s")) {
                g_grid_service_flag = 2;
            }
            else if(!strcasecmp(optarg, "m")) {
                g_grid_service_flag = 1;
            }
            else {   
                fprintf(stderr, "The grid_service_flag is wrong it should be s(slave)|m(master).");
                return -1; 
            }   
            break;
           default: break;
        }
    }

    if(strlen(g_db_user) == 0 || strlen(g_db_pass) == 0) {
        fprintf(stderr, "Critical:No db_user|db_passwd argument.\n");
        fprintf(stderr, 
                "Usage:oa_head_installer -n <grid_name_list> [-d <db_name>] [-h <db_host>]\n\t\t[-P <db_port>] -u <db_user> -p <db_passwd>\n");
        return -1;
    }

    int   len = strlen(g_install_prefix);
    assert(len > 0);

    if(len < (int)sizeof(g_install_prefix) && g_install_prefix[len - 1] != '/') {
        g_install_prefix[len] = '/';
        g_install_prefix[len + 1] = '\0';
    }

    if(create_mysql_iface_instance(&conf_db_conn) != 0) {
        fprintf(stderr, "Create mysql connect instance failed.\n");
        return -1;
    }

    if(conf_db_conn->init(g_db_host, db_port, g_db_name, g_db_user, g_db_pass, "utf8") != 0) {
        fprintf(stderr, "Connect to db:[%s] of host:[%s] failed.\n", g_db_name, g_db_host);
        return -1;
    }

    //取得nobody的uid和gid
    struct passwd *pw = NULL;
    pw = getpwnam("nobody");
    if(pw != NULL) {
        g_nobody_uid = pw->pw_uid;
        g_nobody_gid = pw->pw_gid;
    }

    //取得当前目录的绝对路径
    getcwd(g_cur_path, sizeof(g_cur_path));

    char  quoted_grid_name_list[5000] = {0};

    if(strlen(grid_name_list) > 0) {
        str_trim(grid_name_list);
        //name_quoted(grid_name_list, quoted_grid_name_list, sizeof(quoted_grid_name_list));
        strcpy(quoted_grid_name_list, grid_name_list);
    }

    get_grid_info_and_install(conf_db_conn, quoted_grid_name_list);
    conf_db_conn->uninit();
    conf_db_conn->release();

    return 0;
}
コード例 #2
0
ファイル: main.cpp プロジェクト: roland-wilhelm/iot
//............................................................................
int main(int argc, char *argv[]) {
    int optChar;
    char comPort[FNAME_SIZE];
    char inpFileName[FNAME_SIZE];
    char outFileName[FNAME_SIZE];
    char savFileName[FNAME_SIZE];
    char matFileName[FNAME_SIZE];
    TargetLink link = NO_LINK;
                                              // default configuration options
    strcpy(inpFileName, "qs.bin");
    strcpy(comPort, "COM1");
    int tcpPort          = 6601;
    int baudRate         = 38400;
    uint8_t quiet        = 0;
    uint8_t tstampSize   = 4;
    uint8_t objPtrSize   = 4;
    uint8_t funPtrSize   = 4;
    uint8_t sigSize      = 1;
    uint8_t evtSize      = 2;
    uint8_t queueCtrSize = 1;
    uint8_t poolCtrSize  = 2;
    uint8_t poolBlkSize  = 2;
    uint8_t tevtCtrSize  = 2;
    outFileName[0]       = '\0';                  // Output file not specified
    savFileName[0]       = '\0';                    // Save file not specified
    matFileName[0]       = '\0';                  // Matlab file not specified

    time_t now = time(NULL);
    printf("QSPY host application %s\n"
           "Copyright (c) Quantum Leaps, LLC.\n"
           "%s\n", QSPY_VER, ctime(&now));

    static char const help[] =
        "Syntax is: qspy [options]          * = default\n\n"
        "OPTION                    DEFAULT  COMMENT\n"
        "----------------------------------------------------------------\n"
        "-h                                 help (this message)\n"
        "-q                                 quiet mode (no stdout output)\n"
        "-o<File_name>                      produce output to a file\n"
        "-s<File_name>                      save the binary data to a file\n"
        "-m<File_name>                      produce a Matlab file\n"
        "-c<COM_port>  *           COM1     com port input\n"
        "-b<Baud_rate>             38400    baud rate selection\n"
        "-f<File_name>             qs.bin   file input\n"
        "-t                                 TCP/IP input\n"
        "-p<TCP_Port_number>       6601     TCP/IP server port\n"
        "-T<tstamp_size>           4        QS timestamp size (bytes)\n"
        "-O<pointer_size>          4        object pointer size (bytes)\n"
        "-F<pointer_size>          4        function pointer size (bytes)\n"
        "-S<signal_size>           1        signal size (bytes)\n"
        "-E<event_size>            2        event size size (bytes)\n"
        "-Q<queue_counter_size>    1        queue counter size (bytes)\n"
        "-P<pool_counter_size>     2        pool counter size (bytes)\n"
        "-B<pool_blocksize_size>   2        pool blocksize size (bytes)\n"
        "-C<QTimeEvt_counter_size> 2        QTimeEvt counter size\n";

    while ((optChar = getopt(argc, argv,
                             "hqo:s:m:c:b:tp:f:T:O:F:S:E:Q:P:B:C:")) != -1)
    {
        switch (optChar) {
            case 'q': {                                          // quiet mode
                quiet = 1;
                break;
            }
            case 'o': {                                         // file output
                strncpy(outFileName, optarg, sizeof(outFileName));
                printf("-o %s\n", outFileName);
                break;
            }
            case 's': {                          // save binary data to a file
                strncpy(savFileName, optarg, sizeof(savFileName));
                printf("-s %s\n", savFileName);
                break;
            }
            case 'm': {                                  // Matlab file output
                strncpy(matFileName, optarg, sizeof(matFileName));
                printf("-m %s\n", matFileName);
                break;
            }
            case 'c': {                                            // COM port
                if ((link != NO_LINK) && (link != SERIAL_LINK)) {
                    printf("The -c option is incompatible with -p/-f\n");
                    return -1;                                      // failure
                }
                strncpy(comPort, optarg, sizeof(comPort));
                printf("-c %s\n", comPort);
                link = SERIAL_LINK;
                break;
            }
            case 'b': {                                           // baud rate
                if ((link != NO_LINK) && (link != SERIAL_LINK)) {
                    printf("The -b option is incompatible with -p/-f\n");
                    return -1;                                      // failure
                }
                if (sscanf(optarg, "%d", &baudRate) != 1) {
                    printf("incorrect baud rate: %s\n", optarg);
                    return -1;                                      // failure
                }
                printf("-b %d\n", baudRate);
                link = SERIAL_LINK;
                break;
            }
            case 'f': {                                          // File input
                if (link != NO_LINK) {
                    printf("The -f option is incompatible with -c/-b/-p\n");
                    return -1;                                      // failure
                }
                strncpy(inpFileName, optarg, sizeof(inpFileName));
                printf("-f %s\n", inpFileName);
                link = FILE_LINK;
                break;
            }
            case 't': {                                        // TCP/IP input
                if ((link != NO_LINK) && (link != TCP_LINK)) {
                    printf("The -t option is incompatible with -c/-b/-f\n");
                    return -1;
                }
                printf("-t\n");
                link = TCP_LINK;
                break;
            }
            case 'p': {                                         // TCP/IP port
                if ((link != NO_LINK) && (link != TCP_LINK)) {
                    printf("The -p option is incompatible with -c/-b/-f\n");
                    return -1;
                }
                tcpPort = (int)strtoul(optarg, NULL, 10);
                printf("-p %d\n", tcpPort);
                link = TCP_LINK;
                break;
            }
            case 'T': {                                      // timestamp size
                tstampSize = (uint8_t)strtoul(optarg, 0, 10);
                break;
            }
            case 'F': {                               // function pointer size
                funPtrSize = (uint8_t)strtoul(optarg, 0, 10);
                break;
            }
            case 'O': {                                 // object pointer size
                objPtrSize = (uint8_t)strtoul(optarg, 0, 10);
                break;
            }
            case 'S': {                                         // signal size
                sigSize = (uint8_t)strtoul(optarg, 0, 10);
                break;
            }
            case 'E': {                                         // event size
                evtSize = (uint8_t)strtoul(optarg, 0, 10);
                break;
            }
            case 'Q': {                                  // Queue counter size
                queueCtrSize = (uint8_t)strtoul(optarg, 0, 10);
                break;
            }
            case 'P': {                            // Memory-pool counter size
                poolCtrSize = (uint8_t)strtoul(optarg, 0, 10);
                break;
            }
            case 'B': {                          // Memory-pool blocksize size
                poolBlkSize = (uint8_t)strtoul(optarg, 0, 10);
                break;
            }
            case 'C': {                             // Time event counter size
                tevtCtrSize = (uint8_t)strtoul(optarg, 0, 10);
                break;
            }
            case 'h':                                                  // help
            default: {                                       // unknown option
                printf(help);
                return -1;                                     // error return
            }
        }
    }
    if (argc != optind) {
        printf(help);
        return -1;
    }

    // configure the Quantum Spy
    FILE *outFile = (outFileName[0] != '\0'
                     ? fopen(outFileName, "w")
                     : (FILE *)0);
    FILE *matFile = (matFileName[0] != '\0'
                     ? fopen(matFileName, "w")
                     : (FILE*)0);
    FILE *savFile = (savFileName[0] != '\0'
                     ? fopen(savFileName, "wb")     // open for writing binary
                     : (FILE*)0);
    qsConfig(quiet,
             objPtrSize,
             funPtrSize,
             tstampSize,
             sigSize,
             evtSize,
             queueCtrSize,
             poolCtrSize,
             poolBlkSize,
             tevtCtrSize,
             outFile,
             matFile);

    static unsigned char buf[BUF_SIZE];
    int n;

    switch (link) {
        case NO_LINK:                            // intentionally fall through
        case SERIAL_LINK: {           // input trace data from the serial port
            if (!comOpen(comPort, baudRate)) {
                return -1;
            }
            else {
                printf("\nSerial port %s opened, hit any key to quit...\n\n",
                       comPort);
            }
            while ((n = comRead(buf, sizeof(buf))) != -1) {
                if (n > 0) {
                    qsParse(buf, n);
                    if (savFile != (FILE *)0) {
                        fwrite(buf, 1, n, savFile);
                    }
                }
            }
            comClose();
            break;
        }
        case FILE_LINK: {                      // input trace data from a file
            FILE *f = fopen(inpFileName, "rb");     // open for reading binary
            if (f == (FILE *)0) {
                printf("file %s not found\n", inpFileName);
                return -1;
            }
            do {
                n = fread(buf, 1, sizeof(buf), f);
                qsParse(buf, n);
            } while (n == sizeof(buf));

            fclose(f);
            break;
        }
        case TCP_LINK: {                 // input trace data from the TCP port
            if (!tcpOpen(tcpPort)) {
                return -1;
            }
            else {
                printf("\nTCP/IP port %d opened, "
                       "hit any key to quit...\n"
                       "(the target must be stopped)\n",
                       tcpPort);
            }
            while ((n = tcpRead(buf, sizeof(buf))) != -1) {
                if (n > 0) {
                    qsParse(buf, n);
                    if (savFile != (FILE *)0) {
                        fwrite(buf, 1, n, savFile);
                    }
                }
            }
            tcpClose();
            break;
        }
    }
    if (savFile != (FILE *)0) {
        fclose(savFile);
    }
    if (matFile != (FILE *)0) {
        fclose(matFile);
    }

    printf("\nDone.\n");
    return 0;                                                       // success
}
コード例 #3
0
ファイル: tsh.c プロジェクト: jianggao0612/CSAPP15213
/*
 * main - The shell's main routine 
 */
int main(int argc, char **argv) 
{
    char c;
    char cmdline[MAXLINE];    /* cmdline for fgets */
    int emit_prompt = 1; /* emit prompt (default) */

    /* Redirect stderr to stdout (so that driver will get all output
     * on the pipe connected to stdout) */
    dup2(1, 2);

    /* Parse the command line */
    while ((c = getopt(argc, argv, "hvp")) != EOF) {
        switch (c) {
        case 'h':             /* print help message */
            usage();
            break;
        case 'v':             /* emit additional diagnostic info */
            verbose = 1;
            break;
        case 'p':             /* don't print a prompt */
            emit_prompt = 0;  /* handy for automatic testing */
            break;
        default:
            usage();
        }
    }

    /* Install the signal handlers */

    /* These are the ones you will need to implement */
    Signal(SIGINT,  sigint_handler);   /* ctrl-c */
    Signal(SIGTSTP, sigtstp_handler);  /* ctrl-z */
    Signal(SIGCHLD, sigchld_handler);  /* Terminated or stopped child */
    Signal(SIGTTIN, SIG_IGN);
    Signal(SIGTTOU, SIG_IGN);

    /* This one provides a clean way to kill the shell */
    Signal(SIGQUIT, sigquit_handler); 

    /* Initialize the job list */
    initjobs(job_list);


    /* Execute the shell's read/eval loop */
    while (1) {

        if (emit_prompt) {
            printf("%s", prompt);
            fflush(stdout);
        }
        if ((fgets(cmdline, MAXLINE, stdin) == NULL) && ferror(stdin))
            app_error("fgets error");
        if (feof(stdin)) { 
            /* End of file (ctrl-d) */
            printf ("\n");
            fflush(stdout);
            fflush(stderr);
            exit(0);
        }
        
        /* Remove the trailing newline */
        cmdline[strlen(cmdline)-1] = '\0';
        
        /* Evaluate the command line */
		//fprintf(stderr, "got cmd:%s\n", cmdline);
        eval(cmdline);
        
        fflush(stdout);
        fflush(stdout);
    } 
    
    exit(0); /* control never reaches here */
}
コード例 #4
0
ファイル: dioctrl.c プロジェクト: openttp/openttp
int
main(
	int argc,
	char **argv)
{

	int c;

	unsigned char currVal;
	unsigned char newVal;
	unsigned int bitmask=0xff;
	
	/* Process the command line options */
	while ((c=getopt(argc,argv,"b:dhv")) != -1)
	{
		switch(c)
		{
			case 'd':	/* enable debugging */
				printf("Debugging is ON\n");
				debugOn=TRUE;
				break;
			case 'b':
				bitmask=dioctrl_get_int(optarg);
				break;
			case 'h': /* print help */
				dioctrl_print_help();
				exit(EXIT_SUCCESS);
				break;
			case 'v':
				dioctrl_print_version();
				exit(EXIT_SUCCESS);
				break;
			default:
				dioctrl_print_help();
				exit(EXIT_FAILURE);
		}
	}
	
	if ((argc - optind != 1)){
		printf("\nError!: missing argument\n");
		dioctrl_print_help();
		exit(EXIT_FAILURE);
	}
	
	unsigned int val = dioctrl_get_int(argv[optind]);
	
	if (debugOn)
		printf("mask=0x%0x val=0x%0x (%i,%i)\n",bitmask,val,bitmask,val);
	
	/* Are we root ? */
	if ((getuid())){
		fprintf(stderr, "%s: must be run as root\n",APP_NAME);
		exit(1);
	}
	
#ifdef USE_SIO8186x
	if (!SIOF8186x_init())
		exit(EXIT_FAILURE);
	
	SIOF8186x_select_LDN_GPIO();
	currVal = LpcReadIndirectByte(RegGPIO0_PSR);
	if (debugOn)
		printf("current GPIO0 value = 0x%02x\n", currVal);
	newVal= (currVal & ~bitmask) | (val & bitmask);
	LpcWriteIndirectByte(RegGPIO0_ODR, newVal);
	currVal = LpcReadIndirectByte(RegGPIO0_PSR);
	if (debugOn)
		printf("new GPIO0 value = 0x%02x\n", currVal);
	SIOF8186x_close();
	
#endif
	
#ifdef USE_PARALLEL_PORT
	/* Get permission to access the parallel port */
	/* ioperm OK because BASE < 0x3ff */
	ioperm(PPBASE,1,1);
	currVal = inb(PPBASE);
	if (debugOn) printf("current value = 0x%02x\n",currVal);
	newVal= (currVal & ~bitmask) | (val & bitmask);
	outb(newVal,PPBASE);
	if (debugOn) printf("new value = 0x%02x\n",inb(PPBASE));
#endif 
	

	return EXIT_SUCCESS;
}
コード例 #5
0
ファイル: lu-block-th.c プロジェクト: bcernohous/ga
main(int argc, char *argv[])
{
    int i, j, l;
    int ch;
    extern char *optarg;
    int edge;
    int size;
    int lu_arg[MAX_THREADS][3];
    
    /* ARMCI */
    void **ptr;
    double **ptr_loc;

    THREAD_LOCK_INIT(mutex);
    
    armci_msg_init(&argc,&argv);
    nproc = armci_msg_nproc();
    me = armci_msg_me();
    
    while ((ch = getopt(argc, argv, "n:b:p:t:d:h")) != -1) {
        switch(ch) {
            case 'n': n = atoi(optarg); break;
            case 'b': block_size = atoi(optarg); break;
            case 'p': nproc = atoi(optarg); break;
            case 't': th_per_p = atoi(optarg); break;
            case 'd': d = atoi(optarg); break;
            case 'h': {
                printf("Usage: LU, or \n");
        printf("       LU -nMATRIXSIZE -bBLOCKSIZE -pNPROC -tTH_PER_P\n");
                armci_msg_barrier();
                armci_msg_finalize();
                exit(0);
            } 
        }
    }

    if(th_per_p>MAX_THREADS) {
        th_per_p=MAX_THREADS;
        if(me==0)printf("Warning: cannot run more than %d threads, adjust MAX_THREADS",MAX_THREADS);
    }

    if (d) {
        fprintf(stderr, "%d: %d\n", me, getpid());
        sleep(d);
    }

    nthreads = th_per_p * nproc;
    if(me == 0) {
        printf("\n Blocked Dense LU Factorization\n");
        printf("     %d by %d Matrix\n", n, n);
        printf("     %d Processors\n", nproc);
        printf("     %d thread(s) per processor, %d threads total\n", th_per_p, nthreads);
        printf("     %d by %d Element Blocks\n", block_size, block_size);
        printf("\n");
    }
    
    num_rows = (int) sqrt((double) nthreads);
    for (;;) {
        num_cols = nthreads/num_rows;
        if (num_rows*num_cols == nthreads)
            break;
        num_rows--;
    }
    
    nblocks = n/block_size;
    if (block_size * nblocks != n) {
        nblocks++;
    }
    
    num = (nblocks * nblocks)/nthreads;
    if((num * nthreads) != (nblocks * nblocks))
        num++;

    edge = n%block_size;
    if (edge == 0) {
        edge = block_size;
    }
#ifdef DEBUG
    if(me == 0)
        for (i=0;i<nblocks;i++) {
            for (j=0;j<nblocks;j++) 
                printf("%d ", block_owner(i, j));
            printf("\n");
        }
    armci_msg_barrier();
/*    armci_msg_finalize(); */
/*    exit(0); */
#endif
    
    for (l = 0; l < th_per_p; l++) {
        me_th[l] = me * th_per_p + l;
        for (i=0;i<nblocks;i++) {
            for (j=0;j<nblocks;j++) {
                if(block_owner(i,j) == me_th[l]) {
                    if ((i == nblocks-1) && (j == nblocks-1)) {
                        size = edge*edge;
                    }
                    else if ((i == nblocks-1) || (j == nblocks-1)) {
                        size = edge*block_size;
                    }
                    else {
                        size = block_size*block_size;
                    }
                    thread_doubles[l] += size;
                }
            }
        }
        proc_bytes += thread_doubles[l] * sizeof(double);
    }

    /* initialize ARMCI */
    ARMCI_Init();
    ptr = (void **)malloc(nproc * sizeof(void *));
    ARMCI_Malloc(ptr, proc_bytes);

    a = (double **)malloc(nblocks*nblocks*sizeof(double *));
    if (a == NULL) {
        fprintf(stderr, "Could not malloc memory for a\n");
        exit(-1);
    }
    ptr_loc = (double **)malloc(nthreads*sizeof(double *));
    for (i = 0; i < nproc; i++) {
        ptr_loc[i * th_per_p] = (double *)ptr[i];
        for (j = 1; j < th_per_p; j++)
            ptr_loc[i * th_per_p + j] = ptr_loc[i * th_per_p + j - 1] + thread_doubles[j - 1];
    }
    for(i=0; i<nblocks;i ++) {
        for(j=0; j<nblocks; j++) {
            a[i+j*nblocks] = ptr_loc[block_owner(i, j)];
            if ((i == nblocks-1) && (j == nblocks-1)) {
                size = edge*edge;
            } else if ((i == nblocks-1) || (j == nblocks-1)) {
                size = edge*block_size;
            } else {
                size = block_size*block_size;
            }
            ptr_loc[block_owner(i, j)] += size;
        }
    }
#if 0
    for(i=0; i<nblocks*nblocks;i ++) printf("%d: a[%d]=%p\n", me, i, a[i]);
    fflush(stdout);
#endif
    
    /* initialize the array */
    init_array();
    
    /* barrier to ensure all initialization is done */
    armci_msg_barrier();

    /* to remove cold-start misses, all processors touch their own data */
/*    for (l = 0; l < th_per_p; l++) touch_array(block_size, me_th[l]); */
    armci_msg_barrier();

    if(doprint) {
        if(me == 0) {
            printf("Matrix before LU decomposition\n");
            print_array(me); 
        }
        armci_msg_barrier();
    }

#if 1
    for (i = 0; i < nblocks; i++)
        for (j = 0; j < nblocks; j++)
            print_block_dbg(a[i + j * nblocks], "proc %d, a[%d, %d]:\n", me, i, j);
#endif

    TH_INIT(nproc,th_per_p);

    /* Starting the timer */
    if(me == 0) start_timer();

    for (l = 0; l < th_per_p; l++) {
        lu_arg[l][0] = n;
        lu_arg[l][1] = block_size;
        lu_arg[l][2] = l;
        THREAD_CREATE(threads + l, lu, lu_arg[l]);
    }
    
    for (l = 0; l < th_per_p; l++) THREAD_JOIN(threads[l], NULL);
    armci_msg_barrier();

    /* Timer Stops here */
    if(me == 0) 
        printf("\nRunning time = %lf milliseconds.\n\n",  elapsed_time());

    if(doprint) {        
        if(me == 0) {
            printf("after LU\n");
            print_array(me);
        }
        armci_msg_barrier();
    }
    
    /* done */
    ARMCI_Free(ptr[me]);
    ARMCI_Finalize();
    armci_msg_finalize();

    THREAD_LOCK_DESTROY(mutex);
}
コード例 #6
0
ファイル: printf.c プロジェクト: coyizumi/cs111
int
main(int argc, char *argv[])
{
	size_t len;
	int chopped, end, rval;
	char *format, *fmt, *start;
#ifndef SHELL
	int ch;

	(void) setlocale(LC_ALL, "");
#endif

#ifdef SHELL
	nextopt("");
	argc -= argptr - argv;
	argv = argptr;
#else
	while ((ch = getopt(argc, argv, "")) != -1)
		switch (ch) {
		case '?':
		default:
			usage();
			return (1);
		}
	argc -= optind;
	argv += optind;
#endif

	if (argc < 1) {
		usage();
		return (1);
	}

#ifdef SHELL
	INTOFF;
#endif
	/*
	 * Basic algorithm is to scan the format string for conversion
	 * specifications -- once one is found, find out if the field
	 * width or precision is a '*'; if it is, gather up value.  Note,
	 * format strings are reused as necessary to use up the provided
	 * arguments, arguments of zero/null string are provided to use
	 * up the format string.
	 */
	fmt = format = *argv;
	chopped = escape(fmt, 1, &len);		/* backslash interpretation */
	rval = end = 0;
	gargv = ++argv;
	for (;;) {
		start = fmt;
		while (fmt < format + len) {
			if (fmt[0] == '%') {
				fwrite(start, 1, fmt - start, stdout);
				if (fmt[1] == '%') {
					/* %% prints a % */
					putchar('%');
					fmt += 2;
				} else {
					fmt = printf_doformat(fmt, &rval);
					if (fmt == NULL) {
#ifdef SHELL
						INTON;
#endif
						return (1);
					}
					end = 0;
				}
				start = fmt;
			} else
				fmt++;
		}

		if (end == 1) {
			warnx("missing format character");
#ifdef SHELL
			INTON;
#endif
			return (1);
		}
		fwrite(start, 1, fmt - start, stdout);
		if (chopped || !*gargv) {
#ifdef SHELL
			INTON;
#endif
			return (rval);
		}
		/* Restart at the beginning of the format string. */
		fmt = format;
		end = 1;
	}
	/* NOTREACHED */
}
コード例 #7
0
ファイル: chown.c プロジェクト: FreeBSDFoundation/freebsd
int
main(int argc, char **argv)
{
	FTS *ftsp;
	FTSENT *p;
	int Hflag, Lflag, Rflag, fflag, hflag, vflag, xflag;
	int ch, fts_options, rval;
	char *cp;

	ischown = (strcmp(basename(argv[0]), "chown") == 0);

	Hflag = Lflag = Rflag = fflag = hflag = vflag = xflag = 0;
	while ((ch = getopt(argc, argv, "HLPRfhvx")) != -1)
		switch (ch) {
		case 'H':
			Hflag = 1;
			Lflag = 0;
			break;
		case 'L':
			Lflag = 1;
			Hflag = 0;
			break;
		case 'P':
			Hflag = Lflag = 0;
			break;
		case 'R':
			Rflag = 1;
			break;
		case 'f':
			fflag = 1;
			break;
		case 'h':
			hflag = 1;
			break;
		case 'v':
			vflag++;
			break;
		case 'x':
			xflag = 1;
			break;
		case '?':
		default:
			usage();
		}
	argv += optind;
	argc -= optind;

	if (argc < 2)
		usage();

	(void)signal(SIGINFO, siginfo_handler);

	if (Rflag) {
		if (hflag && (Hflag || Lflag))
			errx(1, "the -R%c and -h options may not be "
			    "specified together", Hflag ? 'H' : 'L');
		if (Lflag) {
			fts_options = FTS_LOGICAL;
		} else {
			fts_options = FTS_PHYSICAL;

			if (Hflag) {
				fts_options |= FTS_COMFOLLOW;
			}
		}
	} else if (hflag) {
		fts_options = FTS_PHYSICAL;
	} else {
		fts_options = FTS_LOGICAL;
	}

	if (xflag)
		fts_options |= FTS_XDEV;

	uid = (uid_t)-1;
	gid = (gid_t)-1;
	if (ischown) {
		if ((cp = strchr(*argv, ':')) != NULL) {
			*cp++ = '\0';
			a_gid(cp);
		}
#ifdef SUPPORT_DOT
		else if ((cp = strchr(*argv, '.')) != NULL) {
			warnx("separation of user and group with a period is deprecated");
			*cp++ = '\0';
			a_gid(cp);
		}
#endif
		a_uid(*argv);
	} else
		a_gid(*argv);

	if ((ftsp = fts_open(++argv, fts_options, NULL)) == NULL)
		err(1, NULL);

	for (rval = 0; (p = fts_read(ftsp)) != NULL;) {
		int atflag;

		if ((fts_options & FTS_LOGICAL) ||
		    ((fts_options & FTS_COMFOLLOW) &&
		    p->fts_level == FTS_ROOTLEVEL))
			atflag = 0;
		else
			atflag = AT_SYMLINK_NOFOLLOW;

		switch (p->fts_info) {
		case FTS_D:			/* Change it at FTS_DP. */
			if (!Rflag)
				fts_set(ftsp, p, FTS_SKIP);
			continue;
		case FTS_DNR:			/* Warn, chown. */
			warnx("%s: %s", p->fts_path, strerror(p->fts_errno));
			rval = 1;
			break;
		case FTS_ERR:			/* Warn, continue. */
		case FTS_NS:
			warnx("%s: %s", p->fts_path, strerror(p->fts_errno));
			rval = 1;
			continue;
		default:
			break;
		}
		if (siginfo) {
			print_info(p, 2);
			siginfo = 0;
		}
		if ((uid == (uid_t)-1 || uid == p->fts_statp->st_uid) &&
		    (gid == (gid_t)-1 || gid == p->fts_statp->st_gid))
			continue;
		if (fchownat(AT_FDCWD, p->fts_accpath, uid, gid, atflag)
		    == -1 && !fflag) {
			chownerr(p->fts_path);
			rval = 1;
		} else if (vflag)
			print_info(p, vflag);
	}
	if (errno)
		err(1, "fts_read");
	exit(rval);
}
コード例 #8
0
ファイル: neosc-appselect.c プロジェクト: not1337/neoscutils
int main(int argc,char *argv[])
{
	int c;
	int r=1;
	int mode=0;
	int serial=NEOSC_ANY_YUBIKEY;
	void *ctx;

	while((c=getopt(argc,argv,"NdoOps:unUCh"))!=-1)switch(c)
	{
	case 'N':
		if(mode)usage();
		mode=1;
		break;
	case 'd':
		if(mode)usage();
		mode=2;
		break;
	case 'o':
		if(mode)usage();
		mode=3;
		break;
	case 'O':
		if(mode)usage();
		mode=4;
		break;
	case 'p':
		if(mode)usage();
		mode=5;
		break;
	case 's':
		if(serial!=NEOSC_ANY_YUBIKEY)usage();
		if((serial=atoi(optarg))<=NEOSC_ANY_YUBIKEY)usage();
		break;
	case 'u':
		if(serial!=NEOSC_ANY_YUBIKEY)usage();
		serial=NEOSC_USB_YUBIKEY;
		break;
	case 'n':
		if(serial!=NEOSC_ANY_YUBIKEY)usage();
		serial=NEOSC_NFC_YUBIKEY;
		break;
	case 'U':
		if(serial!=NEOSC_ANY_YUBIKEY)usage();
		serial=NEOSC_U2F_YUBIKEY4;
		break;
	case 'C':
		if(serial!=NEOSC_ANY_YUBIKEY)usage();
		serial=NEOSC_NOU2F_YUBIKEY4;
		break;

	case 'h':
	default:usage();
	}

	if(!mode)usage();

	if(neosc_pcsc_open(&ctx,serial))
	{
		fprintf(stderr,"device open error.\n");
		goto err1;
	}

	if(neosc_pcsc_lock(ctx))
	{
		fprintf(stderr,"device lock error.\n");
		goto err2;
	}

	switch(mode)
	{
	case 1:	if(neosc_neo_select(ctx,NULL))goto err3;
		break;
	case 2:	if(neosc_ndef_select(ctx))goto err3;
		break;
	case 3:	if(neosc_oath_select(ctx,NULL))goto err3;
		break;
	case 4:	if(neosc_pgp_select(ctx))goto err3;
		break;
	case 5:	if(neosc_piv_select(ctx))goto err3;
		break;
	}

	r=0;

err3:	if(r)fprintf(stderr,"applet select error.\n");
	neosc_pcsc_unlock(ctx);
err2:	neosc_pcsc_close(ctx);
err1:	return r;
}
コード例 #9
0
ファイル: mdb_load.c プロジェクト: Smilefant/ReOpenLDAP
int main(int argc, char *argv[])
{
	int i, rc;
	MDB_env *env;
	MDB_txn *txn;
	MDB_cursor *mc;
	MDB_dbi dbi;
	char *envname;
	int envflags = 0, putflags = 0;

	prog = argv[0];

	if (argc < 2) {
		usage();
	}

	/* -f: load file instead of stdin
	 * -n: use NOSUBDIR flag on env_open
	 * -s: load into named subDB
	 * -N: use NOOVERWRITE on puts
	 * -T: read plaintext
	 * -V: print version and exit
	 */
	while ((i = getopt(argc, argv, "f:ns:NTV")) != EOF) {
		switch(i) {
		case 'V':
			printf("%s\n", MDB_VERSION_STRING);
			exit(0);
			break;
		case 'f':
			if (freopen(optarg, "r", stdin) == NULL) {
				fprintf(stderr, "%s: %s: reopen: %s\n",
					prog, optarg, strerror(errno));
				exit(EXIT_FAILURE);
			}
			break;
		case 'n':
			envflags |= MDB_NOSUBDIR;
			break;
		case 's':
			subname = strdup(optarg);
			break;
		case 'N':
			putflags = MDB_NOOVERWRITE|MDB_NODUPDATA;
			break;
		case 'T':
			mode |= NOHDR;
			break;
		default:
			usage();
		}
	}

	if (optind != argc - 1)
		usage();

	dbuf.mv_size = 4096;
	dbuf.mv_data = malloc(dbuf.mv_size);

	if (!(mode & NOHDR))
		readhdr();

	envname = argv[optind];
	rc = mdb_env_create(&env);
	if (rc) {
		fprintf(stderr, "mdb_env_create failed, error %d %s\n", rc, mdb_strerror(rc));
		return EXIT_FAILURE;
	}

	mdb_env_set_maxdbs(env, 2);

	if (info.me_maxreaders)
		mdb_env_set_maxreaders(env, info.me_maxreaders);

	if (info.me_mapsize)
		mdb_env_set_mapsize(env, info.me_mapsize);

	if (info.me_mapaddr)
		envflags |= MDB_FIXEDMAP;

	rc = mdb_env_open(env, envname, envflags, 0664);
	if (rc) {
		fprintf(stderr, "mdb_env_open failed, error %d %s\n", rc, mdb_strerror(rc));
		goto env_close;
	}

	kbuf.mv_size = mdb_env_get_maxkeysize(env) * 2 + 2;
	kbuf.mv_data = malloc(kbuf.mv_size);

	while(!Eof) {
		MDB_val key, data;
		int batch = 0;

		rc = mdb_txn_begin(env, NULL, 0, &txn);
		if (rc) {
			fprintf(stderr, "mdb_txn_begin failed, error %d %s\n", rc, mdb_strerror(rc));
			goto env_close;
		}

		rc = mdb_open(txn, subname, dbi_flags|MDB_CREATE, &dbi);
		if (rc) {
			fprintf(stderr, "mdb_open failed, error %d %s\n", rc, mdb_strerror(rc));
			goto txn_abort;
		}

		rc = mdb_cursor_open(txn, dbi, &mc);
		if (rc) {
			fprintf(stderr, "mdb_cursor_open failed, error %d %s\n", rc, mdb_strerror(rc));
			goto txn_abort;
		}

		while(1) {
			rc = readline(&key, &kbuf);
			if (rc == EOF)
				break;
			if (rc)
				goto txn_abort;

			rc = readline(&data, &dbuf);
			if (rc)
				goto txn_abort;

			rc = mdb_cursor_put(mc, &key, &data, putflags);
			if (rc == MDB_KEYEXIST && putflags)
				continue;
			if (rc)
				goto txn_abort;
			batch++;
			if (batch == 100) {
				rc = mdb_txn_commit(txn);
				if (rc) {
					fprintf(stderr, "%s: line %" Z "d: txn_commit: %s\n",
						prog, lineno, mdb_strerror(rc));
					goto env_close;
				}
				rc = mdb_txn_begin(env, NULL, 0, &txn);
				if (rc) {
					fprintf(stderr, "mdb_txn_begin failed, error %d %s\n", rc, mdb_strerror(rc));
					goto env_close;
				}
				rc = mdb_cursor_open(txn, dbi, &mc);
				if (rc) {
					fprintf(stderr, "mdb_cursor_open failed, error %d %s\n", rc, mdb_strerror(rc));
					goto txn_abort;
				}
				batch = 0;
			}
		}
		rc = mdb_txn_commit(txn);
		txn = NULL;
		if (rc) {
			fprintf(stderr, "%s: line %" Z "d: txn_commit: %s\n",
				prog, lineno, mdb_strerror(rc));
			goto env_close;
		}
		mdb_dbi_close(env, dbi);
		if(!(mode & NOHDR))
			readhdr();
	}

txn_abort:
	mdb_txn_abort(txn);
env_close:
	mdb_env_close(env);

	return rc ? EXIT_FAILURE : EXIT_SUCCESS;
}
コード例 #10
0
ファイル: parse_opts.c プロジェクト: boostsup/minix3
/**********************************************************************
 * parse_opts: 
 **********************************************************************/
char *
parse_opts(int ac, char **av, option_t *user_optarr, void (*uhf)(void))
{
    int found;		/* flag to indicate that an option specified was */
			/* found in the user's list */
    int k;		/* scratch integer for returns and short time usage */
    float  ftmp;	/* tmp float for parsing env variables */
    char *ptr;		/* used in getting env variables */
    int options=0;	/* no options specified */
    int optstrlen, i;
    char *optionstr;
    int opt;		/* return of getopt */

    /*
     * If not the first time this function is called, release the old STD_opt_arr
     * vector.
     */

    if ( STD_opt_arr != NULL ) {
	free(STD_opt_arr);
	STD_opt_arr=NULL;
    }
    /* Calculate how much space we need for the option string */
    optstrlen = 0;
    for (i = 0; std_options[i].optstr; ++i) 
	optstrlen += strlen(std_options[i].optstr);
    if (user_optarr)
	for (i = 0; user_optarr[i].option; ++i) {
	    if (strlen(user_optarr[i].option) > 2)
		return "parse_opts: ERROR - Only short options are allowed";
	    optstrlen += strlen(user_optarr[i].option);
	}
    optstrlen += 1;

    /* Create the option string for getopt */
    optionstr = (char *)malloc(optstrlen);
    if (!optionstr) 
	return "parse_opts: ERROR - Could not allocate memory for optionstr";

    optionstr[0] = '\0';

    for (i = 0; std_options[i].optstr; ++i)
	strcat(optionstr, std_options[i].optstr);
    if (user_optarr)
	for (i = 0; user_optarr[i].option; ++i)
	    /* only add the option if it wasn't there already */
	    if (strchr(optionstr, user_optarr[i].option[0]) == NULL) 
		strcat(optionstr, user_optarr[i].option);

#if DEBUG > 1
    printf("STD_nopts = %d\n", STD_nopts);
#endif

    /*
     *  Loop through av parsing options.
     */
    while ( (opt = getopt(ac, av, optionstr)) > 0) {

	STD_argind = optind;
#if DEBUG > 0
	printf("parse_opts: getopt returned '%c'\n", opt);
#endif

	switch (opt) {
		case '?': /* Unknown option */
			return "Unknown option";
			break;
		case ':': /* Missing Arg */
			return "Missing argument";
			break;
		case 'i': /* Iterations */
			options |= OPT_iteration;
			STD_LOOP_COUNT = atoi(optarg);
			if (STD_LOOP_COUNT == 0) STD_INFINITE = 1;
			break;
		case 'P': /* Delay between iterations */
			options |= OPT_delay;
			STD_LOOP_DELAY = atof(optarg);
			break;
		case 'I': /* Time duration */
			options |= OPT_duration;
			STD_LOOP_DURATION = atof(optarg);
			if ( STD_LOOP_DURATION == 0.0 ) STD_INFINITE=1; 
			break;
		case 'c': /* Copies */
			options |= OPT_copies;
			STD_COPIES = atoi(optarg);
			break;
		case 'f': /* Functional testing */
			STD_FUNCTIONAL_TEST = 0;
			break;
		case 'p': /* Pause for SIGUSR1 */
			STD_PAUSE = 1;
			break;
		case 't': /* syscall timing */
			STD_TIMING_ON = 1;
			break;
		case 'e': /* errno loggin */
			STD_ERRNO_LOG = 1;
			break;
		case 'h': /* Help */
			print_help(uhf);
			exit(0);
			break;
#ifdef UCLINUX
		case 'C': /* Run child */
			child_args = optarg;
			break;
#endif
		default:
			
            /* Check all the user specified options */
            found=0;
	    for(i = 0; user_optarr[i].option; ++i) {

		if (opt == user_optarr[i].option[0]) {
                    /* Yup, This is a user option, set the flag and look for argument */
		    if ( user_optarr[i].flag ) {
                        *user_optarr[i].flag=1;
		    }
                    found++;

		    /* save the argument at the user's location */
                    if ( user_optarr[i].option[strlen(user_optarr[i].option)-1] == ':' ) {  
                        *user_optarr[i].arg=optarg;
                    }
                    break;  /* option found - break out of the for loop */
                }
            }
	    /* This condition "should never happen".  SO CHECK FOR IT!!!! */
            if ( ! found ) { 
                sprintf(Mesg2,
		    "parse_opts: ERROR - option:\"%c\" NOT FOUND... INTERNAL ERROR", opt);
                return(Mesg2);
            }
	}

    }    /* end of while */
    free(optionstr);

    STD_argind = optind;

    /*
     * Turn on debug
     */
    if ( (ptr=getenv("USC_DEBUG")) != NULL ) {
	Debug=1;
        printf("env USC_DEBUG is defined, turning on debug\n");
    }
    if ( (ptr=getenv("USC_VERBOSE")) != NULL ) {
	Debug=1;
        printf("env USC_VERBOSE is defined, turning on debug\n");
    }

    /*
     * If the USC_ITERATION_ENV environmental variable is set to
     * a number, use that number as iteration count (same as -c option).
     * The -c option with arg will be used even if this env var is set.
     */
    if ( !(options & OPT_iteration) && (ptr=getenv(USC_ITERATION_ENV)) != NULL ) {
        if ( sscanf(ptr, "%i", &k) == 1) {
            if ( k == 0 ) {   /* if arg is 0, set infinite loop flag */
                STD_INFINITE=1;
		if ( Debug )
		   printf("Using env %s, set STD_INFINITE to 1\n",
			USC_ITERATION_ENV);
            } else {            /* else, set the loop count to the arguement */
                STD_LOOP_COUNT=k;
		if ( Debug )
		   printf("Using env %s, set STD_LOOP_COUNT to %d\n",
			USC_ITERATION_ENV, k);
            }
        }
    }

    /*
     * If the USC_NO_FUNC_CHECK environmental variable is set, we'll
     * unset the STD_FUNCTIONAL_TEST variable.
     */
    if ( !(options & OPT_nofunccheck) && (ptr=getenv(USC_NO_FUNC_CHECK)) != NULL ) {
        STD_FUNCTIONAL_TEST=0; /* Turn off functional testing */
	if ( Debug )
	    printf("Using env %s, set STD_FUNCTIONAL_TEST to 0\n",
		USC_NO_FUNC_CHECK);
    }

    /*
     * If the USC_LOOP_WALLTIME environmental variable is set,
     * use that number as duration (same as -I option).
     * The -I option with arg will be used even if this env var is set.
     */

    if ( !(options & OPT_duration) && (ptr=getenv(USC_LOOP_WALLTIME)) != NULL ) {
        if ( sscanf(ptr, "%f", &ftmp) == 1 && ftmp >= 0.0 ) {
	    STD_LOOP_DURATION=ftmp;
	    if ( Debug )
	        printf("Using env %s, set STD_LOOP_DURATION to %f\n",
		    USC_LOOP_WALLTIME, ftmp);
            if ( STD_LOOP_DURATION == 0.0 ) {   /* if arg is 0, set infinite loop flag */
                STD_INFINITE=1;
	        if ( Debug )
	            printf("Using env %s, set STD_INFINITE to 1\n", USC_LOOP_WALLTIME);
	    }
        }
    }
    if ( !(options & OPT_duration) && (ptr=getenv("USC_DURATION")) != NULL ) {
        if ( sscanf(ptr, "%f", &ftmp) == 1 && ftmp >= 0.0 ) {
	    STD_LOOP_DURATION=ftmp;
	    if ( Debug )
	        printf("Using env USC_DURATION, set STD_LOOP_DURATION to %f\n", ftmp);
            if ( STD_LOOP_DURATION == 0.0 ) {   /* if arg is 0, set infinite loop flag */
                STD_INFINITE=1;
	        if ( Debug )
	            printf("Using env USC_DURATION, set STD_INFINITE to 1\n");
	    }
        }
    }
    /*
     * If the USC_LOOP_DELAY environmental variable is set,
     * use that number as delay in factional seconds (same as -P option).
     * The -P option with arg will be used even if this env var is set.
     */
    if ( !(options & OPT_delay) && (ptr=getenv(USC_LOOP_DELAY)) != NULL ) {
        if ( sscanf(ptr, "%f", &ftmp) == 1 && ftmp >= 0.0 ) {
	    STD_LOOP_DELAY=ftmp;
	    if ( Debug )
		printf("Using env %s, set STD_LOOP_DELAY = %f\n",
		    USC_LOOP_DELAY, ftmp);
        }
    }

    /*
     * If the USC_COPIES environmental variable is set,
     * use that number as copies (same as -c option).
     * The -c option with arg will be used even if this env var is set.
     */
    if ( !(options & OPT_copies) && (ptr=getenv(USC_COPIES)) != NULL ) {
        if ( sscanf(ptr, "%d", &STD_COPIES) == 1 && STD_COPIES >= 0 ) {
	    if ( Debug )
		printf("Using env %s, set STD_COPIES = %d\n",
		    USC_COPIES, STD_COPIES);
        }
    }

    /*
     * The following are special system testing envs to turn on special
     * hooks in the code.
     */
    if ( (ptr=getenv("USC_TP_BARRIER")) != NULL ) {
        if ( sscanf(ptr, "%i", &k) == 1 && k >= 0 ) {
	    STD_TP_barrier=k;
	}
        else
	    STD_TP_barrier=1;
	if ( Debug )
	    printf("using env USC_TP_BARRIER, Set STD_TP_barrier to %d\n",
	        STD_TP_barrier);
    }

    if ( (ptr=getenv("USC_LP_BARRIER")) != NULL ) {
        if ( sscanf(ptr, "%i", &k) == 1 && k >= 0 ) {
	    STD_LP_barrier=k;
	}
        else
	    STD_LP_barrier=1;
	if ( Debug ) 
	    printf("using env USC_LP_BARRIER, Set STD_LP_barrier to %d\n",
	        STD_LP_barrier);
    }

    if ( (ptr=getenv("USC_TP_SHMEM")) != NULL ) {
        if ( sscanf(ptr, "%i", &k) == 1 && k >= 0 ) {
            STD_TP_shmem_sz=k;
	    if ( Debug )
	        printf("Using env USC_TP_SHMEM, Set STD_TP_shmem_sz to %d\n",
		    STD_TP_shmem_sz);
        }
    }

    if ( (ptr=getenv("USC_LP_SHMEM")) != NULL ) {
        if ( sscanf(ptr, "%i", &k) == 1 && k >= 0 ) {
            STD_LP_shmem=k;
	    if ( Debug )
	        printf("Using env USC_LP_SHMEM, Set STD_LP_shmem to %d\n",
		    STD_LP_shmem);
        }
    }

    if ( (ptr=getenv("USC_LD_SHMEM")) != NULL ) {
        if ( sscanf(ptr, "%i", &k) == 1 && k >= 0 ) {
            STD_LD_shmem=k;
	    if ( Debug )
	        printf("Using env USC_LD_SHMEM, Set STD_LD_shmem to %d\n",
		    STD_LD_shmem);
        }
    }

    if ( (ptr=getenv("USC_TP_SBRK")) != NULL ) {
        if ( sscanf(ptr, "%i", &k) == 1 && k >= 0 ) {
            STD_TP_sbrk=k;
	    if ( Debug )
	        printf("Using env USC_TP_SBRK, Set STD_TP_sbrk to %d\n",
		    STD_TP_sbrk);
        }
    }

#if !defined(UCLINUX)
    if ( (ptr=getenv("USC_LP_SBRK")) != NULL ) {
        if ( sscanf(ptr, "%i", &k) == 1 && k >= 0 ) {
            STD_LP_sbrk=k;
	    if ( Debug )
	        printf("Using env USC_LP_SBRK, Set STD_LP_sbrk to %d\n",
		    STD_LP_sbrk);
        }
    }
#endif /* if !defined(UCLINUX) */

    if ( (ptr=getenv("USC_LP_RECFUN")) != NULL ) {
        if ( sscanf(ptr, "%i", &k) == 1 && k >= 0 ) {
	    STD_LP_recfun=k;
	    if ( STD_bigstack != (struct usc_bigstack_t *)NULL )
		STD_bigstack=(struct usc_bigstack_t *)
			malloc(sizeof(struct usc_bigstack_t));
	    if ( Debug )
                printf("Using env USC_LP_RECFUN, Set STD_LP_recfun to %d\n",
		    STD_LP_recfun);
        }
    }

    if ( (ptr=getenv("USC_LD_RECFUN")) != NULL ) {
        if ( sscanf(ptr, "%i", &k) == 1 && k >= 0 ) {
	    STD_LD_recfun=k;
	    if ( STD_bigstack != (struct usc_bigstack_t *)NULL )
		STD_bigstack=(struct usc_bigstack_t *)
			malloc(sizeof(struct usc_bigstack_t));
	    if ( Debug )
                printf("Using env USC_LD_RECFUN, Set STD_LD_recfun to %d\n",
		    STD_LD_recfun);
        }
    }
 
#if UNIT_TEST
    printf("The following variables after option and env parsing:\n");
    printf("STD_FUNCTIONAL_TEST = %d\n", STD_FUNCTIONAL_TEST);
    printf("STD_LOOP_DURATION   = %f\n", STD_LOOP_DURATION);
    printf("STD_LOOP_DELAY      = %f\n", STD_LOOP_DELAY);
    printf("STD_COPIES          = %d\n", STD_COPIES);
    printf("STD_LOOP_COUNT      = %d\n", STD_LOOP_COUNT);
    printf("STD_INFINITE        = %d\n", STD_INFINITE);
    printf("STD_TIMING_ON       = %d\n", STD_TIMING_ON);
    printf("STD_ERRNO_LOG       = %d\n", STD_ERRNO_LOG);
    printf("STD_PAUSE           = %d\n", STD_PAUSE);
#endif

    return((char *) NULL);

}    /* end of parse_opts */
コード例 #11
0
ファイル: dsdtune.c プロジェクト: dreinhold/dsdtune
int main(int argc, char *argv[]) {
  int i = 0;
  FILE *fp;
  char buffer[1024];
  char decode_str[] = " decoding score = ";
  int c;
  extern char *optarg;
  extern int optind, opterr, optopt;
  int decode_str_len;
  char base_command[255];
  dsd_params params[] = {  { "ds", 55,  75, 0, 0, 1 }, /*DSDPlus 1.074 recognizes a range of 55-75*/
                           { "dv",  1,  30, 0, 0, 1 },
                           { "  ",  0,   0, 0, 0, 0 } }; /* GCC warns if this is 0 */
  options opts;
  /* Check if dsdplus.exe exists if so us that first */
  if(fileexists("dsdplus.exe") == 0) {
    strncpy(opts.exe_name, "dsdplus.exe", 12);
  } else {
    strncpy(opts.exe_name, "dsd.exe", 8);
  }
  opts.decode_option_set = 0;
  opts.infile_set = 0;
  opts.write_batch = 0;
  opts.batch_options[0] = '\0';
  opts.invert_x2_tdma_str[0] = '\0';
  opts.psk_mod_str[0] = '\0';
  opts.skip_params = 0;
  opts.infile_param[0] = '?'; /* dsdplus version > 1.5 */
  opts.infile_param[1] = '\0';
  strcpy(opts.logfile, "dsdtune.log");
  while ((c = getopt (argc, argv, "hf:i:x:b:o:m:")) != -1) {
    opterr = 0;
    switch (c) {
       case 'h':    usage();
                    exit(0);
       case 'b':    strncpy(opts.batch_name, optarg, 99);
                    opts.write_batch = 1;
                    break;
       /* not setup yet
       case 'v':    sscanf (optarg, "%d", &opts.verbose);
                    break; */
       case 'i':    strncpy(opts.infile, optarg, MAX_IN_FILE_LEN-1);
                    opts.infile[MAX_IN_FILE_LEN-1] = '\0';
                    opts.infile_set = 1;
                    break;
       case 'f':    opts.decode_option[0] = optarg[0];
                    opts.decode_option[1] = '\0';
                    opts.decode_option_set = 1;
                    if(optarg[0] == 'd' || optarg[0] == 'p')
                      opts.skip_params = 1;
                    break;
       case 'l':    strncpy(opts.logfile, optarg, 99);
                    break;
       case 'm':    if(*optarg == 'p' && *(optarg+1) == '\0') {
                      strncpy(opts.psk_mod_str, "-mp", 4);
                    } else {
                      usage();
                      exit(1);
                    }
                    break;
       case 'o':    strncpy(opts.batch_options, optarg, 99);
                    break;
       case 'x':    /* check for -xx first */
                    if(*optarg == 'x' && *(optarg+1) == '\0') {
                      strncpy(opts.invert_x2_tdma_str, "-xx", 4);
                    } else {
                      strncpy(opts.exe_name, optarg, 99);
                    }
                    break;
       default:     usage();
                    exit(1);
    }
  }
  if(!opts.infile_set) {
    fprintf(stderr, " Missing required argument of -i <input file>\n");
    usage();
    exit(1);
  }
  if(opts.decode_option_set)
    sprintf(base_command, "%s -o0 -O NUL -f%s", opts.exe_name, opts.decode_option);
  else
    sprintf(base_command, "%s -o0 -O NUL", opts.exe_name);
  strcat(base_command, opts.invert_x2_tdma_str);
  strcat(base_command, opts.psk_mod_str);
  decode_str_len = strlen(decode_str);

  while(params[i].name[0] != ' ') {
    int j = params[i].min;
    char tmp_command[255];
    if(opts.skip_params && params[i].skip) {
      i++;
      continue;
    }
    printf("Checking option -%s\n", params[i].name);
    printf("Running %s -%sXXX %s %s\n", base_command, params[i].name, opts.infile_param, opts.infile);
    while(j <= params[i].max) {
        char command[255];
        int found = 0;
        sprintf(command, "%s -%s%d %s %s 2>&1", base_command, params[i].name, j, opts.infile_param, opts.infile);
        if( (fp = popen( command, "r" )) == NULL ) {
           perror("Failed to open ");
           fprintf(stderr, "failed to open dsd\n");
           exit(5);
        }
        while(fgets(buffer, 1024, fp))  {
           if( strncmp(buffer, decode_str, decode_str_len-1) == 0) {
             unsigned int rate;
             found = 1;
             rate = decode_rate(buffer);
             if(rate > params[i].best_results) {
               params[i].best_results = rate;
               params[i].best_setting = j;
             }
           }
             
        }
        pclose( fp );
        if(!found) {
          fprintf(stderr, "Could not get decode string\n");
          exit(5);
        }
        j++;
    }
    printf("best value of %u with -%s%d\n", params[i].best_results, params[i].name, params[i].best_setting);
    sprintf(tmp_command, "%s -%s%d", base_command, params[i].name, params[i].best_setting);
    strcpy(base_command, tmp_command);
    i++;
  }
  /* Resutls */
  i=0;
  printf("\n+------ RESULTS -----+\n");
  printf("Switches you want to use :\n");
  printf("  ");
  while(params[i].name[0] != ' ') {
    if(opts.skip_params && params[i].skip) {
      i++;
      continue;
    }
    printf(" -%s%u",params[i].name, params[i].best_setting);
    i++;
  }
  printf("\n");
  write_log(params, &opts);
  if(opts.write_batch) 
    write_batch(params, &opts);
  return 0;
}
コード例 #12
0
ファイル: nmblookup.c プロジェクト: livebox/livebox2
/****************************************************************************
  main program
****************************************************************************/
int main(int argc,char *argv[])
{
  int opt;
  unsigned int lookup_type = 0x0;
  pstring lookup;
  extern int optind;
  extern char *optarg;
  BOOL find_master=False;
  int i;
  static pstring servicesf = CONFIGFILE;
  BOOL lookup_by_ip = False;

  DEBUGLEVEL = 1;
  /* Prevent smb.conf setting from overridding */
  AllowDebugChange = False;

  *lookup = 0;

  TimeInit();

  setup_logging(argv[0],True);

  charset_initialise();

  while ((opt = getopt(argc, argv, "d:fB:U:i:s:SMrhART")) != EOF)
    switch (opt)
      {
      case 'B':
	bcast_addr = *interpret_addr2(optarg);
	got_bcast = True;
	use_bcast = True;
	break;
      case 'f':
	give_flags = True;
	break;
      case 'U':
	bcast_addr = *interpret_addr2(optarg);
	got_bcast = True;
	use_bcast = False;
	break;
      case 'T':
        translate_addresses = !translate_addresses;
	break;
      case 'i':
	      {
		      extern pstring global_scope;
		      pstrcpy(global_scope,optarg);
		      strupper(global_scope);
	      }
	      break;
      case 'M':
	find_master = True;
	break;
      case 'S':
	find_status = True;
	break;
      case 'R':
	recursion_desired = True;
	break;
      case 'd':
	DEBUGLEVEL = atoi(optarg);
	break;
      case 's':
	pstrcpy(servicesf, optarg);
	break;
      case 'r':
        RootPort = True;
        break;
      case 'h':
	usage();
	exit(0);
	break;
      case 'A':
        lookup_by_ip = True;
        break;
      default:
	usage();
	exit(1);
      }

  if (argc < 2) {
    usage();
    exit(1);
  }

  if (!lp_load(servicesf,True,False,False)) {
    fprintf(stderr, "Can't load %s - run testparm to debug it\n", servicesf);
  }

  load_interfaces();
  if (!open_sockets()) return(1);

  for (i=optind;i<argc;i++)
  {
      char *p;
      struct in_addr ip;

      fstrcpy(lookup,argv[i]);

      if(lookup_by_ip)
      {
        fstrcpy(lookup,"*");
        ip = *interpret_addr2(argv[i]);
	do_node_status(ServerFD, lookup, lookup_type, ip);
        continue;
      }

      if (find_master) {
	if (*lookup == '-') {
	  fstrcpy(lookup,"\01\02__MSBROWSE__\02");
	  lookup_type = 1;
	} else {
	  lookup_type = 0x1d;
	}
      }

      p = strchr(lookup,'#');
      if (p) {
        *p = '\0';
        sscanf(++p,"%x",&lookup_type);
      }

      if (!query_one(lookup, lookup_type)) {
	printf( "name_query failed to find name %s", lookup );
        if( 0 != lookup_type )
          printf( "#%02x", lookup_type );
        printf( "\n" );
      }
  }
  
  return(0);
}
コード例 #13
0
ファイル: dreamchess.c プロジェクト: dreamchess/dreamchess
static void parse_options(int argc, char **argv, ui_driver_t **ui_driver, cl_options_t *cl_options) {
	int c;

#ifdef HAVE_GETOPT_LONG

	int optindex;

	struct option options[] = {{"help", no_argument, NULL, 'h'},
							   {"fullscreen", no_argument, NULL, 'f'},
							   {"width", required_argument, NULL, 'W'},
							   {"height", required_argument, NULL, 'H'},
							   {"1st-engine", required_argument, NULL, '1'},
							   {0, 0, 0, 0}};

	/* On macOS (under certain circumstances) a process serial number will be passed in. In this
	 * case we skip parsing the command line options.
	 */ 
	if (argc > 1 && strncmp(argv[1], "-psn_", 5) == 0) {
		DBG_WARN("Received '%s'; ignoring all command line arguments", argv[1]);
		return;
	}

	while ((c = getopt_long(argc, argv, "1:fhW:H:", options, &optindex)) > -1) {
#else

	while ((c = getopt(argc, argv, "1:fhW:H:")) > -1) {
#endif /* HAVE_GETOPT_LONG */
		switch (c) {
		case 'h':
			printf("Usage: dreamchess [options]\n\n"
				   "An xboard-compatible chess interface.\n\n"
				   "Options:\n"
                   OPTION_TEXT("--help\t", "-h\t", "show help")
				   OPTION_TEXT("--fullscreen\t", "-f\t", "run fullscreen")
				   OPTION_TEXT("--width\t", "-W<num>", "set screen width")
				   OPTION_TEXT("--height\t", "-H<num>", "set screen height")
				   OPTION_TEXT("--1st-engine <eng>", "-1<eng>", "use <eng> as first chess engine")
				   OPTION_TEXT("\t\t", "\t", "  defaults to 'dreamer'"));
			exit(0);
		case '1':
			cl_options->engine = optarg;
			break;
		case 'f':
			cl_options->fs = 1;
			break;
		case 'W':
			cl_options->width = atoi(optarg);
			break;
		case 'H':
			cl_options->height = atoi(optarg);
		}
	}
}

static void set_cl_options(cl_options_t *cl_options) {
	option_t *option;

	if (cl_options->engine) {
		option = config_get_option("first_engine");
		option_string_set_text(option, cl_options->engine);
	}

	if (cl_options->fs) {
		option = config_get_option("full_screen");
		option_select_value_by_name(option, "On");
	}

	if (cl_options->width) {
		option = config_get_option("custom_resolution_width");
		option->value = cl_options->width;
		option = config_get_option("resolution");
		option_select_value_by_name(option, "Custom");
	}

	if (cl_options->height) {
		option = config_get_option("custom_resolution_height");
		option->value = cl_options->height;
		option = config_get_option("resolution");
		option_select_value_by_name(option, "Custom");
	}
}
コード例 #14
0
ファイル: main.cpp プロジェクト: AALEKH/acl
int main(int argc, char* argv[])
{
	// initiation the acl library
	acl::acl_cpp_init();
	acl::log::stdout_open(true);

	int  ch;
	size_t replicas = 0;
	bool add_slave = false, just_display = false;
	acl::string addr, cmd, conf, new_addr, node_id, key;

	while ((ch = getopt(argc, argv, "hs:a:f:N:SI:r:dk:")) > 0)
	{
		switch (ch)
		{
		case 'h':
			usage(argv[0]);
			return 0;
		case 's':
			addr = optarg;
			break;
		case 'a':
			cmd = optarg;
			break;
		case 'f':
			conf = optarg;
			break;
		case 'N':
			new_addr = optarg;
			break;
		case 'S':
			add_slave = true;
			break;
		case 'I':
			node_id = optarg;
			break;
		case 'r':
			replicas = (size_t) atoi(optarg);
			break;
		case 'd':
			just_display = true;
			break;
		case 'k':
			key = optarg;
			break;
		default:
			break;
		}
	}

	int conn_timeout = 10, rw_timeout = 120;

	if (cmd == "hash_slot")
	{
		if (key.empty())
			printf("usage: %s -a hash_slot -k key\r\n", argv[0]);
		else
		{
			size_t max_slot = 16384;
			unsigned short n = acl_hash_crc16(key.c_str(), key.length());
			unsigned short slot = n %  max_slot;
			printf("key: %s, slot: %d\r\n", key.c_str(), (int) slot);
		}
	}
	else if (cmd == "nodes")
	{
		if (addr.empty())
			printf("usage: %s -s ip:port -a nodes\r\n", argv[0]);
		else {
			acl::redis_client client(addr, conn_timeout, rw_timeout);
			acl::redis redis(&client);
			redis_status status(addr, conn_timeout, rw_timeout);
			status.show_nodes(redis);
		}
	}
	else if (cmd == "slots")
	{
		if (addr.empty())
			printf("usage: %s -a ip:port -a slots\r\n", argv[0]);
		else
		{
			acl::redis_client client(addr, conn_timeout, rw_timeout);
			acl::redis redis(&client);
			redis_status status(addr, conn_timeout, rw_timeout);
			status.show_slots(redis);
		}
	}
	else if (cmd == "create")
	{
		if (conf.empty())
			printf("usage: %s -a create -f cluster.xml\r\n", argv[0]);
		else
		{
			redis_builder builder;
			builder.build(conf.c_str(), replicas, just_display);
		}
	}
	else if (cmd == "add_node")
	{
		if (addr.empty() || new_addr.empty())
			printf("usage: %s -s ip:port -a add_node -N ip:port -S\r\n", argv[0]);
		else
		{
			redis_builder builder;
			builder.add_node(addr, new_addr, add_slave);
		}
	}
	else if (cmd == "del_node")
	{
		if (addr.empty() || node_id.empty())
			printf("usage: %s -s ip:port -a del_node -I nod_id\r\n", argv[0]);
		else
		{
			redis_builder builder;
			builder.del_node(addr, node_id);
		}
	}
	else if (cmd == "node_id")
	{
		if (addr.empty())
			printf("usage: %s -s ip:port -a node_id\r\n", argv[0]);
		else
		{
			node_id.clear();
			if (redis_util::get_node_id(addr, node_id) == false)
				printf("can't get node id, addr: %s\r\n",
					addr.c_str());
			else
				printf("addr: %s, node_id: %s\r\n",
					addr.c_str(), node_id.c_str());
		}
	}
	else if (cmd == "reshard")
	{
		if (addr.empty())
			printf("usage: %s -s ip:port -a reshard\r\n", argv[0]);
		else
		{
			redis_reshard reshard(addr);
			reshard.run();
		}
	}
	else
		printf("unknown cmd: %s\r\n", cmd.c_str());

#ifdef WIN32
	printf("enter any key to exit\r\n");
	getchar();
#endif
	return 0;
}
コード例 #15
0
ファイル: main.cpp プロジェクト: gfblueprint/MiniLinker
int main( int argc,char *argv[] )
{
	const char *optStr = ":o:l:";
	vector<string> objPath;
	string libPath;
	string outputPath;

	int opt = 0;
	while((opt=getopt(argc,argv,optStr)) != -1 )
	{
		switch( opt )
		{
		case 'o':
			if(  outputPath.length() )
			{
				cout << "错误:定义了多个输出路径" << endl;
				return 0;
			}
			outputPath = optarg;
			break;
		case 'l':
			if( libPath.size() )
			{
				cout << "错误:定义了多个库路径" << endl;
				return 0;
			}
			libPath = optarg;
			break;
		case ':':
			cout << "缺少参数" << endl;
			break;
		case '?':
			cout << "忽略错误选项:" << (char)optopt << endl;
			break;
		}
	}
	if( !libPath.size() )
	{
		cout << "错误:缺少库" << endl;
		return 0;
	}
	if( !outputPath.size() )
	{
		cout << "错误:没有定义输出路径" << endl;
		return 0;
	}

	for( ;optind < argc;++optind )
		objPath.push_back(argv[optind]);
	if( objPath.size() == 0 )
	{
		cout << "错误:缺少输入" << endl;
		return 0;
	}

	Builder bd( objPath,libPath,outputPath);

	if( !bd.CollectSymbol() )
	{
		cout << "失败退出" << endl;
		return 0;
	}
	bd.DoMerge();
	bd.GetSymbolAddress();
	bd.Relocation();
	if( !bd.GenerateBinary() )
	{
		cout << "失败退出" << endl;
		return 0;
	}
	return 0;
}
コード例 #16
0
int main (int argc, char *argv[]) {
	int length = 1024, option;
	char str[length];
	bool batchOn, echoOn, invalid, isRPN, isIn;

	batchOn = false;
	echoOn = false;
	invalid = false;

	while ((option = getopt(argc - 1, argv, "be")) != -1) {
		switch(option) {
			case 'b':
				batchOn = true;
				break;
			case 'e':
				echoOn = true;
				break;
			default:
				invalid = true;
				break;
		}
	}

	if (invalid || argc == 1
			|| (argc == 2 && !(strcmp(argv[1], "--rpn") == 0 || strcmp(argv[1], "--in") == 0))
			|| (argc == 3 && !(strcmp(argv[2], "--rpn") == 0 || strcmp(argv[2], "--in") == 0))
			|| (argc == 4 && !(strcmp(argv[3], "--rpn") == 0 || strcmp(argv[3], "--in") == 0))
			|| argc > 4) {
		printf("Usage: calc [options] --rpn|--in\n");
		printf("\nCalculator modes:\n");
		printf("    --rpn\tReverse polish notation\n");
		printf("    --in\tInorder\n");
		printf("\nOptions:\n");
		printf("    -b\tBatch mode: No prompt will be printed\n");
		printf("    -e\tEcho mode: Input will be printed immediately after read\n");
	} else {
		isRPN = strcmp(argv[argc - 1], "--rpn") == 0;
		isIn = strcmp(argv[argc - 1], "--in") == 0;

		while (1) {
			if (batchOn && isatty(STDIN_FILENO)) printf("s3255350>>> ");

			char *input = fgets(str, length, stdin);
			if (input == NULL || input == (char *) EOF)	break;

			if (!(strlen(str) == 0 || strcmp(str, "\n") == 0 || strcmp(str, "\r\n") == 0)) {
				if (strlen(str) > 0) {
					if (str[strlen(str) - 2] == '\r') str[strlen(str) - 2] = '\0';
					if (str[strlen(str) - 1] == '\n') str[strlen(str) - 1] = '\0';

					if (batchOn) {
						printf("s3255350>>> ");
					}

					double value = 0;
					if (isRPN) {
						value = rpn_eval(str);
					} else if (isIn) {
						value = in_eval(str);
					}
			
					if (errorOccurs) {
						if (isRPN) {
							printf("Invalid RPN expression!\n");
						} else if (isIn) {
							printf("Invalid Inorder expression!\n");
						}
					} else {
						if (echoOn) printf("%s = ", str);
						printf("%lf\n", value);
					}
				}
			}
		}
	}

	return EXIT_SUCCESS;
}
コード例 #17
0
ファイル: guk_server.c プロジェクト: MRchildNEO/scholarzhang
int main(int argc, char **argv) {
	int opt;

	svname.sun_family = AF_UNIX;
	svname.sun_path[0] = '\0';
	strncpy(svname.sun_path + 1, GUK_ABSTRACT_SERV_PATH, UNIX_PATH_MAX - 1);
	sv_addrlen = sizeof(sa_family_t) + 1 + strlen(GUK_ABSTRACT_SERV_PATH);

	while ((opt = getopt(argc, argv, "i:a:U:s:f:h")) != -1) {
		switch (opt) {
		case 'i':
		case 's':
			break;
		case 'a':
			svname.sun_path[0] = '\0';
			strncpy(svname.sun_path + 1, optarg, UNIX_PATH_MAX - 1);
			sv_addrlen = sizeof(sa_family_t) + 1 + strlen(GUK_ABSTRACT_SERV_PATH);
		case 'U':
			if (strlen(optarg))
				strncpy(svname.sun_path, optarg, UNIX_PATH_MAX);
			else
				strncpy(svname.sun_path, GUK_UNIX_SERV_PATH, UNIX_PATH_MAX);
			sv_addrlen = sizeof(sa_family_t) + strlen(GUK_ABSTRACT_SERV_PATH);
		case 'f':
			strncpy(config_file, optarg, 1000);
			if (config_file[999]) {
				fputs("config_file name too long\n", stderr);
				return 1;
			}
			break;
		case 'c':
			max_client = atoi(optarg);
			break;
		case 'q':
			max_query = atoi(optarg);
			break;
		case 'h':
		default:
			printf("USAGE:\n"
			       "# %s [OPTIONS]\n"
			       "  -a <abstract_path> : listen on the specified abstract unix domain socket.\n"
			       "  -U <unix_path>     : listen on the specified unix domain socket.\n"
			       "  -i <device>        : network interface used for sending and receiving.\n"
			       "  -f <config_file>   : configuration file name.\n"
			       "  -s <ip addr>       : the source ip address of the current machine.\n"
			       "  -c <max_client>    : max number of clients server accepts.\n"
			       "  -q <max_query>     : max number of unanswered queries server will hold.\n", argv[0]);
			return 0;
		}
	}

	listenfd = socket(AF_UNIX, SOCK_STREAM, 0);
	if (listenfd == -1) {
		perror("socket");
		return -1;
	}
	if (fcntl(listenfd, F_SETFL, O_NONBLOCK) == -1) {
		perror("fcntl");
		goto quit;
	}
	if (setsockopt(listenfd, IPPROTO_TCP, TCP_NODELAY, &tcp_nodelay, sizeof(int)) < 0)
		perror("setsockopt");
	if (bind(listenfd, (struct sockaddr *)&svname, sv_addrlen) < 0) {
		perror("bind");
		goto quit;
	}
	if (listen(listenfd, max_client) < 0) {
		perror("listen");
		goto quit;
	}

	if (signal(SIGINT, inthandler) == SIG_ERR) {
		perror("signal");
		goto quit;
	}
	if (signal(SIGTERM, inthandler) == SIG_ERR) {
		perror("signal");
		goto quit;
	}
	if (signal(SIGHUP, SIG_IGN) == SIG_ERR) {
		perror("signal");
		goto quit;
	}

	if (gk_read_config_file(config_file, device, ip, &maxconn, &maxdst, candlist, &times, &time_interval, &expire_timeout, &tcp_mss, &kps, &pps))
		fprintf(stderr, "warning: configuration file %s doesn't exist.\n", config_file);
	else
		gk_cm_config(times, time_interval, expire_timeout, tcp_mss, kps, pps);

	optind = 1;
	while ((opt = getopt(argc, argv, "i:s:f:h")) != -1) {
		switch (opt) {
		case 'i':
			strncpy(device, optarg, 100);
			if (device[99]) {
				fputs("device name too long\n", stderr);
				return 1;
			}
			break;
		case 's':
			strncpy(ip, optarg, 100);
			if (ip[99]) {
				fputs("IP too long\n", stderr);
				return 1;
			}
			break;
		}
	}

	if ((dest = new_dstlist(maxdst)) == NULL) {
		fputs("new_dstlist: memory allocation failed.\n", stderr);
		goto quit;
	}
	if (candlist[0] == '\0') {
		fputs("critical: no dstlist specified.\n", stderr);
		goto quit;
	}
	cand = new_candlist(candlist, &cand_count);
	if (cand == NULL) {
		fputs("new_candlist: format error\n", stderr);
		goto quit;
	}
	if (init_dstlist(dest, cand, cand_count) != 0) {
		fputs("dstlist initialize failed.\n", stderr);
		goto quit;
	}
	if (gk_cm_init(device, ip, dest, maxconn)) {
		fputs("gk_cm_init: failed.\n", stderr);
		goto quit ;
	}
	pcap_fd = gk_cm_fd();

	run();
quit:
	clean();

	return 0;
}
コード例 #18
0
ファイル: PcapSelectDNS.c プロジェクト: kfujiwara/PcapParseC
int main(int argc, char *argv[])
{
	FILE *fp;
	char *p;
	char *outputfile = NULL;
	int len;
	char buff[256];
	int ret;
	int ch;
	struct pcap_file_header pfw;
	struct DNSdataControl c;

	memset((void *)&c, 0, sizeof(&c));

	while ((ch = getopt(argc, argv, "Ao:el:4:6:")) != -1) {
	switch (ch) {
	case 'A':
		debug |= FLAG_MODE_PARSE_ANSWER;
		break;
	case 'e':
		flag_exact_match = 1;
		break;
	case 'o':
		outputfile = strdup(optarg);
		break;
	case 'l':
		doms[ndoms].dom = strdup(optarg);
		doms[ndoms].len = strlen(optarg);
		ndoms++;
		break;
	case '4':
		if (inet_aton(optarg, (struct in_addr *)&client_ipv4) == 0)
			err(1, "bad IPv4 address: %s", optarg);
		check_v4 = 1;
		break;
#if defined(AF_INET6) && defined(HAVE_INET_PTON)
	case '6':
		if (inet_pton(AF_INET6, optarg, client_ipv6) != 1)
			err(1, "bad IPv6 address: %s", optarg);
		check_v6 = 1;
		break;
#endif
	case '?':
	default:
		usage();
	}}
	argc -= optind;
	argv += optind;

	c.callback = callback;
	c.otherdata = NULL;
	c.debug = FLAG_IGNOREERROR | FLAG_MODE_PARSE_QUERY;

	if (outputfile == NULL) { printf("#Error:No outputfilename\n"); exit(1); };
	if ((wfp = fopen(outputfile, "w")) == NULL) {
		printf("#Werror:Cannot write %s", outputfile);
		exit(1);
	}
	argv++;
	argc--;

	pfw.magic = 0xa1b2c3d4;
	pfw.version_major = 2;
	pfw.version_minor = 4;
	pfw.thiszone = 0;
	pfw.sigfigs = 0;
	pfw.snaplen = 1500;
	pfw.linktype = DLT_IP;
	fwrite(&pfw, sizeof(pfw), 1, wfp);

	while (*argv != NULL) {
		if (argc > 1) fprintf(stderr, "Loading %s\n", *argv);
		// fflush(stderr);
		ret = parse_pcap(*argv, &c);
		if (ret != ParsePcap_NoError) {
			printf("#Error:%s:%s\n", parse_pcap_error(ret), *argv);
		}
		argv++;
	}
	fclose(wfp);
	return 0;
}
コード例 #19
0
ファイル: tcpdump.c プロジェクト: BackupTheBerlios/wl530g-svn
int
main(int argc, char **argv)
{
	register int cnt, op, i;
	bpf_u_int32 localnet, netmask;
	register char *cp, *infile, *cmdbuf, *device, *RFileName, *WFileName;
	pcap_handler printer;
	struct bpf_program fcode;
	RETSIGTYPE (*oldhandler)(int);
	u_char *pcap_userdata;
	char ebuf[PCAP_ERRBUF_SIZE];

	cnt = -1;
	device = NULL;
	infile = NULL;
	RFileName = NULL;
	WFileName = NULL;
	if ((cp = strrchr(argv[0], '/')) != NULL)
		program_name = cp + 1;
	else
		program_name = argv[0];

	if (abort_on_misalignment(ebuf) < 0)
		error("%s", ebuf);

	opterr = 0;
	while (
	    (op = getopt(argc, argv, "ac:defF:i:lnNOpqr:s:StT:vw:xY")) != EOF)
		switch (op) {

		case 'a':
			++aflag;
			break;

		case 'c':
			cnt = atoi(optarg);
			if (cnt <= 0)
				error("invalid packet count %s", optarg);
			break;

		case 'd':
			++dflag;
			break;

		case 'e':
			++eflag;
			break;

		case 'f':
			++fflag;
			break;

		case 'F':
			infile = optarg;
			break;

		case 'i':
			device = optarg;
			break;

		case 'l':
#ifdef HAVE_SETLINEBUF
			setlinebuf(stdout);
#else
			setvbuf(stdout, NULL, _IOLBF, 0);
#endif
			break;

		case 'n':
			++nflag;
			break;

		case 'N':
			++Nflag;
			break;

		case 'O':
			Oflag = 0;
			break;

		case 'p':
			++pflag;
			break;

		case 'q':
			++qflag;
			break;

		case 'r':
			RFileName = optarg;
			break;

		case 's':
			snaplen = atoi(optarg);
			if (snaplen <= 0)
				error("invalid snaplen %s", optarg);
			break;

		case 'S':
			++Sflag;
			break;

		case 't':
			--tflag;
			break;

		case 'T':
			if (strcasecmp(optarg, "vat") == 0)
				packettype = PT_VAT;
			else if (strcasecmp(optarg, "wb") == 0)
				packettype = PT_WB;
			else if (strcasecmp(optarg, "rpc") == 0)
				packettype = PT_RPC;
			else if (strcasecmp(optarg, "rtp") == 0)
				packettype = PT_RTP;
			else if (strcasecmp(optarg, "rtcp") == 0)
				packettype = PT_RTCP;
			else
				error("unknown packet type `%s'", optarg);
			break;

		case 'v':
			++vflag;
			break;

		case 'w':
			WFileName = optarg;
			break;
#ifdef YYDEBUG
		case 'Y':
			{
			/* Undocumented flag */
			extern int yydebug;
			yydebug = 1;
			}
			break;
#endif
		case 'x':
			++xflag;
			break;

		default:
			usage();
			/* NOTREACHED */
		}

	if (aflag && nflag)
		error("-a and -n options are incompatible");

	if (tflag > 0)
		thiszone = gmt2local(0);

	if (RFileName != NULL) {
		/*
		 * We don't need network access, so set it back to the user id.
		 * Also, this prevents the user from reading anyone's
		 * trace file.
		 */
		setuid(getuid());

		pd = pcap_open_offline(RFileName, ebuf);
		if (pd == NULL)
			error("%s", ebuf);
		localnet = 0;
		netmask = 0;
		if (fflag != 0)
			error("-f and -r options are incompatible");
	} else {
		if (device == NULL) {
			device = pcap_lookupdev(ebuf);
			if (device == NULL)
				error("%s", ebuf);
		}
		pd = pcap_open_live(device, snaplen, !pflag, 1000, ebuf);
		if (pd == NULL)
			error("%s", ebuf);
		i = pcap_snapshot(pd);
		if (snaplen < i) {
			warning("snaplen raised from %d to %d", snaplen, i);
			snaplen = i;
		}
		if (pcap_lookupnet(device, &localnet, &netmask, ebuf) < 0) {
			localnet = 0;
			netmask = 0;
			warning("%s", ebuf);
		}
		/*
		 * Let user own process after socket has been opened.
		 */
		setuid(getuid());
	}
	if (infile)
		cmdbuf = read_infile(infile);
	else
		cmdbuf = copy_argv(&argv[optind]);

	if (pcap_compile(pd, &fcode, cmdbuf, Oflag, netmask) < 0)
		error("%s", pcap_geterr(pd));
	if (dflag) {
		bpf_dump(&fcode, dflag);
		exit(0);
	}
	init_addrtoname(localnet, netmask);

	(void)setsignal(SIGTERM, cleanup);
	(void)setsignal(SIGINT, cleanup);
	/* Cooperate with nohup(1) */
	if ((oldhandler = setsignal(SIGHUP, cleanup)) != SIG_DFL)
		(void)setsignal(SIGHUP, oldhandler);

	if (pcap_setfilter(pd, &fcode) < 0)
		error("%s", pcap_geterr(pd));
	if (WFileName) {
		pcap_dumper_t *p = pcap_dump_open(pd, WFileName);
		if (p == NULL)
			error("%s", pcap_geterr(pd));
		printer = pcap_dump;
		pcap_userdata = (u_char *)p;
	} else {
		printer = lookup_printer(pcap_datalink(pd));
		pcap_userdata = 0;
	}
	if (RFileName == NULL) {
		(void)fprintf(stderr, "%s: listening on %s\n",
		    program_name, device);
		(void)fflush(stderr);
	}
	if (pcap_loop(pd, cnt, printer, pcap_userdata) < 0) {
		(void)fprintf(stderr, "%s: pcap_loop: %s\n",
		    program_name, pcap_geterr(pd));
		exit(1);
	}
	pcap_close(pd);
	exit(0);
}
コード例 #20
0
ファイル: pbs_comm.c プロジェクト: A9-William/pbspro
int
main(int argc, char **argv)
#endif	/* WIN32 */
{
#ifdef	WIN32
	struct arg_param *p = (struct arg_param *)pv;
	int      		argc;
	char			**argv;
	SERVICE_STATUS          ss;
#endif	/* WIN32 */
	char *name = NULL;
	struct tpp_config conf;
	int rpp_fd;
	char *pc;
	int numthreads;
	char lockfile[MAXPATHLEN + 1];
	char path_log[MAXPATHLEN + 1];
	char svr_home[MAXPATHLEN + 1];
	char *log_file = 0;
	char *host;
	int port;
	char *routers = NULL;
	int c, i, rc;
	extern char *optarg;
	int	are_primary;
	int	num_var_env;
#ifndef WIN32
	struct sigaction act;
	struct sigaction oact;
#endif

#ifndef WIN32
	/*the real deal or just pbs_version and exit*/

	execution_mode(argc, argv);
#endif

	/* As a security measure and to make sure all file descriptors	*/
	/* are available to us,  close all above stderr			*/
#ifdef WIN32
	_fcloseall();
#else
	i = sysconf(_SC_OPEN_MAX);
	while (--i > 2)
		(void)close(i); /* close any file desc left open by parent */
#endif

	/* If we are not run with real and effective uid of 0, forget it */
#ifdef WIN32
	argc = p->argc;
	argv = p->argv;

	ZeroMemory(&ss, sizeof(ss));
	ss.dwCheckPoint = 0;
	ss.dwServiceType = SERVICE_WIN32_OWN_PROCESS;
	ss.dwCurrentState = g_dwCurrentState;
	ss.dwControlsAccepted = SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN;
	ss.dwWaitHint = 6000;

	if (g_ssHandle != 0)
		SetServiceStatus(g_ssHandle, &ss);

	if (!isAdminPrivilege(getlogin())) {
		fprintf(stderr, "%s: Must be run by root\n", argv[0]);
		return (2);
	}

#else
	if ((getuid() != 0) || (geteuid() != 0)) {
		fprintf(stderr, "%s: Must be run by root\n", argv[0]);
		return (2);
	}
#endif	/* WIN32 */

	/* set standard umask */
#ifndef WIN32
	umask(022);
#endif

	/* load the pbs conf file */
	if (pbs_loadconf(0) == 0) {
		fprintf(stderr, "%s: Configuration error\n", argv[0]);
		return (1);
	}

	umask(022);

#ifdef	WIN32
	save_env();
#endif
	/* The following is code to reduce security risks                */
	/* start out with standard umask, system resource limit infinite */
	if ((num_var_env = setup_env(pbs_conf.pbs_environment)) == -1) {
#ifdef	WIN32
		g_dwCurrentState = SERVICE_STOPPED;
		ss.dwCurrentState = g_dwCurrentState;
		ss.dwWin32ExitCode = ERROR_INVALID_ENVIRONMENT;
		if (g_ssHandle != 0) SetServiceStatus(g_ssHandle, &ss);
		return (1);
#else
		exit(1);
#endif	/* WIN32 */
	}

#ifndef WIN32
	i = getgid();
	(void)setgroups(1, (gid_t *)&i);	/* secure suppl. groups */
#endif

	/* set pbs_comm's process limits */
	set_limits();

	log_event_mask = &pbs_conf.pbs_comm_log_events;
	tpp_set_logmask(*log_event_mask);

#ifdef WIN32
	winsock_init();
#endif

	routers = pbs_conf.pbs_comm_routers;
	numthreads = pbs_conf.pbs_comm_threads;

	server_host[0] = '\0';
	if (pbs_conf.pbs_comm_name) {
		name = pbs_conf.pbs_comm_name;
		host = tpp_parse_hostname(name, &port);
		if (host)
			snprintf(server_host, sizeof(server_host), "%s", host);
		free(host);
		host = NULL;
	} else if (pbs_conf.pbs_leaf_name) {
		name = pbs_conf.pbs_leaf_name;
		host = tpp_parse_hostname(name, &port);
		if (host)
			snprintf(server_host, sizeof(server_host), "%s", host);
		free(host);
		host = NULL;
	} else {
		if (gethostname(server_host, (sizeof(server_host) - 1)) == -1) {
#ifndef WIN32
			sprintf(log_buffer, "Could not determine my hostname, errno=%d", errno);
#else
			sprintf(log_buffer, "Could not determine my hostname, errno=%d", WSAGetLastError());
#endif
			fprintf(stderr, "%s\n", log_buffer);
			return (1);
		}
		if ((get_fullhostname(server_host, server_host, (sizeof(server_host) - 1)) == -1)) {
			sprintf(log_buffer, "Could not determine my hostname");
			fprintf(stderr, "%s\n", log_buffer);
			return (1);
		}
		name = server_host;
	}
	if (server_host[0] == '\0') {
		sprintf(log_buffer, "Could not determine server host");
		fprintf(stderr, "%s\n", log_buffer);
		return (1);
	}

	while ((c = getopt(argc, argv, "r:t:e:N")) != -1) {
		switch (c) {
			case 'e': *log_event_mask = strtol(optarg, NULL, 0);
				break;
			case 'r':
				routers = optarg;
				break;
			case 't':
				numthreads = atol(optarg);
				if (numthreads == -1) {
					usage(argv[0]);
					return (1);
				}
				break;
			case 'N':
				stalone = 1;
				break;
			default:
				usage(argv[0]);
				return (1);
		}
	}

	(void)strcpy(daemonname, "Comm@");
	(void)strcat(daemonname, name);
	if ((pc = strchr(daemonname, (int)'.')) != NULL)
		*pc = '\0';

	if(set_msgdaemonname(daemonname)) {
		fprintf(stderr, "Out of memory\n");
		return 1;
	}



	(void) snprintf(path_log, sizeof(path_log), "%s/%s", pbs_conf.pbs_home_path, PBS_COMM_LOGDIR);
	(void) log_open(log_file, path_log);

	/* set tcp function pointers */
	set_tpp_funcs(log_tppmsg);

	(void) snprintf(svr_home, sizeof(svr_home), "%s/%s", pbs_conf.pbs_home_path, PBS_SVR_PRIVATE);
	if (chdir(svr_home) != 0) {
		(void) sprintf(log_buffer, msg_init_chdir, svr_home);
		log_err(-1, __func__, log_buffer);
		return (1);
	}

	(void) sprintf(lockfile, "%s/%s/comm.lock", pbs_conf.pbs_home_path, PBS_SVR_PRIVATE);
	if ((are_primary = are_we_primary()) == FAILOVER_SECONDARY) {
		strcat(lockfile, ".secondary");
	} else if (are_primary == FAILOVER_CONFIG_ERROR) {
		sprintf(log_buffer, "Failover configuration error");
		log_err(-1, __func__, log_buffer);
#ifdef WIN32
		g_dwCurrentState = SERVICE_STOPPED;
		ss.dwCurrentState = g_dwCurrentState;
		ss.dwWin32ExitCode = ERROR_SERVICE_NOT_ACTIVE;
		if (g_ssHandle != 0) SetServiceStatus(g_ssHandle, &ss);
#endif
		return (3);
	}

	if ((lockfds = open(lockfile, O_CREAT | O_WRONLY, 0600)) < 0) {
		(void) sprintf(log_buffer, "pbs_comm: unable to open lock file");
		log_err(errno, __func__, log_buffer);
		return (1);
	}

	if ((host = tpp_parse_hostname(name, &port)) == NULL) {
		sprintf(log_buffer, "Out of memory parsing leaf name");
		log_err(errno, __func__, log_buffer);
		return (1);
	}

	rc = 0;
	if (pbs_conf.auth_method == AUTH_RESV_PORT) {
		rc = set_tpp_config(&pbs_conf, &conf, host, port, routers, pbs_conf.pbs_use_compression,
				TPP_AUTH_RESV_PORT, NULL, NULL);
	} else {
		/* for all non-resv-port based authentication use a callback from TPP */
		rc = set_tpp_config(&pbs_conf, &conf, host, port, routers, pbs_conf.pbs_use_compression,
				TPP_AUTH_EXTERNAL, get_ext_auth_data, validate_ext_auth_data);
	}
	if (rc == -1) {
		(void) sprintf(log_buffer, "Error setting TPP config");
		log_err(-1, __func__, log_buffer);
		return (1);
	}
	free(host);

	i = 0;
	if (conf.routers) {
		while (conf.routers[i]) {
			sprintf(log_buffer, "Router[%d]:%s", i, conf.routers[i]);
			fprintf(stdout, "%s\n", log_buffer);		
			log_event(PBSEVENT_SYSTEM | PBSEVENT_FORCE, PBS_EVENTCLASS_SERVER, LOG_INFO, msg_daemonname, log_buffer);
			i++;
		}
	}

#ifndef DEBUG
#ifndef WIN32
	if (stalone != 1)
		go_to_background();
#endif
#endif


#ifdef WIN32
	ss.dwCheckPoint = 0;
	g_dwCurrentState = SERVICE_RUNNING;
	ss.dwCurrentState = g_dwCurrentState;
	if (g_ssHandle != 0) SetServiceStatus(g_ssHandle, &ss);
#endif

	if (already_forked == 0)
		lock_out(lockfds, F_WRLCK);

	/* go_to_backgroud call creates a forked process,
	 * thus print/log pid only after go_to_background()
	 * has been called
	 */
	sprintf(log_buffer, "%s ready (pid=%d), Proxy Name:%s, Threads:%d", argv[0], getpid(), conf.node_name, numthreads);
	fprintf(stdout, "%s\n", log_buffer);
	log_event(PBSEVENT_SYSTEM | PBSEVENT_FORCE, PBS_EVENTCLASS_SERVER, LOG_INFO, msg_daemonname, log_buffer);

#ifndef DEBUG
	pbs_close_stdfiles();
#endif

#ifdef WIN32
	signal(SIGINT, stop_me);
	signal(SIGTERM, stop_me);
#else
	sigemptyset(&act.sa_mask);
	act.sa_flags = 0;
	act.sa_handler = hup_me;
	if (sigaction(SIGHUP, &act, &oact) != 0) {
		log_err(errno, __func__, "sigaction for HUP");
		return (2);
	}
	act.sa_handler = stop_me;
	if (sigaction(SIGINT, &act, &oact) != 0) {
		log_err(errno, __func__, "sigaction for INT");
		return (2);
	}
	if (sigaction(SIGTERM, &act, &oact) != 0) {
		log_err(errno, __func__, "sigactin for TERM");
		return (2);
	}
	if (sigaction(SIGQUIT, &act, &oact) != 0) {
		log_err(errno, __func__, "sigactin for QUIT");
		return (2);
	}
#ifdef SIGSHUTDN
	if (sigaction(SIGSHUTDN, &act, &oact) != 0) {
		log_err(errno, __func__, "sigactin for SHUTDN");
		return (2);
	}
#endif	/* SIGSHUTDN */

	act.sa_handler = SIG_IGN;
	if (sigaction(SIGPIPE, &act, &oact) != 0) {
		log_err(errno, __func__, "sigaction for PIPE");
		return (2);
	}
	if (sigaction(SIGUSR1, &act, &oact) != 0) {
		log_err(errno, __func__, "sigaction for USR1");
		return (2);
	}
	if (sigaction(SIGUSR2, &act, &oact) != 0) {
		log_err(errno, __func__, "sigaction for USR2");
		return (2);
	}
#endif 	/* WIN32 */

	conf.node_type = TPP_ROUTER_NODE;
	conf.numthreads = numthreads;

	if ((rpp_fd = tpp_init_router(&conf)) == -1) {
		log_err(-1, __func__, "tpp init failed\n");
		return 1;
	}

	/* Protect from being killed by kernel */
	daemon_protect(0, PBS_DAEMON_PROTECT_ON);

	/* go in a while loop */
	while (get_out == 0) {

		if (hupped == 1) {
			struct pbs_config pbs_conf_bak;
			int new_logevent;

			hupped = 0; /* reset back */
			memcpy(&pbs_conf_bak, &pbs_conf, sizeof(struct pbs_config));

			if (pbs_loadconf(1) == 0) {
				log_tppmsg(LOG_CRIT, NULL, "Configuration error, ignoring");
				memcpy(&pbs_conf, &pbs_conf_bak, sizeof(struct pbs_config));
			} else {
				/* restore old pbs.conf */
				new_logevent = pbs_conf.pbs_comm_log_events;
				memcpy(&pbs_conf, &pbs_conf_bak, sizeof(struct pbs_config));
				pbs_conf.pbs_comm_log_events = new_logevent;
				log_tppmsg(LOG_INFO, NULL, "Processed SIGHUP");

				log_event_mask = &pbs_conf.pbs_comm_log_events;
				tpp_set_logmask(*log_event_mask);
			}
		}

		sleep(3);
	}

	tpp_router_shutdown();

	log_event(PBSEVENT_SYSTEM | PBSEVENT_FORCE, PBS_EVENTCLASS_SERVER, LOG_NOTICE, msg_daemonname, "Exiting");
	log_close(1);

	lock_out(lockfds, F_UNLCK);	/* unlock  */
	(void)close(lockfds);
	(void)unlink(lockfile);

	return 0;
}
コード例 #21
0
int main(int argc,char **argv)
	{
	int c,i;
	int verbose=0;
	int errors=0;
	int open_mode = O_RDONLY;
	gost_subst_block *b=  &GostR3411_94_CryptoProParamSet;
	TINYCLR_SSL_FILE *check_file = NULL;
	gost_hash_ctx ctx;
	
	while( (c=getopt(argc,argv,"bc::tv"))!=-1)
		{
		switch (c)
			{
			case 'v': verbose=1; break;
			case 't': b= &GostR3411_94_TestParamSet; break;
			case 'b': open_mode |= O_BINARY; break;
			case 'c':
				if (optarg)
					{
					check_file = TINYCLR_SSL_FOPEN(optarg,"r");
					if (!check_file)
						{
						TINYCLR_SSL_PERROR(optarg);
						TINYCLR_SSL_EXIT(2);
						}
					}
				else
					{
				  	check_file= OPENSSL_TYPE__FILE_STDIN;
					}
				break;
			default:
				TINYCLR_SSL_FPRINTF(OPENSSL_TYPE__FILE_STDERR,"invalid option %c",optopt);
				help();
			}
		}
	init_gost_hash_ctx(&ctx,b);
	if (check_file)
		{
		char inhash[65],calcsum[65],filename[PATH_MAX];
		int failcount=0,count=0;;
		if (check_file==OPENSSL_TYPE__FILE_STDIN && optind<argc)
			{
			check_file=TINYCLR_SSL_FOPEN(argv[optind],"r");
			if (!check_file)
				{	
				TINYCLR_SSL_PERROR(argv[optind]);
				TINYCLR_SSL_EXIT(2);
				}
			}	
		while (get_line(check_file,inhash,filename))
			{
			if (!hash_file(&ctx,filename,calcsum,open_mode))
				{
				TINYCLR_SSL_EXIT (2);
				}	
			count++;
			if (!TINYCLR_SSL_STRNCMP(calcsum,inhash,65))
				{
				if (verbose)
					{
					TINYCLR_SSL_FPRINTF(OPENSSL_TYPE__FILE_STDERR,"%s\tOK\n",filename);
					}
				}
			else
				{
				if (verbose)
					{
					TINYCLR_SSL_FPRINTF(OPENSSL_TYPE__FILE_STDERR,"%s\tFAILED\n",filename);
					}
				else
					{
					TINYCLR_SSL_FPRINTF(OPENSSL_TYPE__FILE_STDERR,"%s: GOST hash sum check failed for '%s'\n",
						argv[0],filename);
					}
				failcount++;
				}
			}	
		if (verbose && failcount)
			{
			TINYCLR_SSL_FPRINTF(OPENSSL_TYPE__FILE_STDERR,"%s: %d of %d file(f) failed GOST hash sum check\n",
				argv[0],failcount,count);
			}
		TINYCLR_SSL_EXIT (failcount?1:0);
		}
	if (optind==argc)
		{
		char sum[65];
		if (!hash_stream(&ctx,TINYCLR_SSL_FILENO(OPENSSL_TYPE__FILE_STDIN),sum))
			{
			TINYCLR_SSL_PERROR("OPENSSL_TYPE__FILE_STDIN");
			TINYCLR_SSL_EXIT(1);
			}	
		TINYCLR_SSL_PRINTF("%s -\n",sum);
		TINYCLR_SSL_EXIT(0);
		}	
	for (i=optind;i<argc;i++)
		{
		char sum[65];
		if (!hash_file(&ctx,argv[i],sum,open_mode))
			{
			errors++;
			}
		else
			{	
			TINYCLR_SSL_PRINTF("%s %s\n",sum,argv[i]);
			}
		}	
	TINYCLR_SSL_EXIT(errors?1:0);	
	}
コード例 #22
0
int main(int argc, char *argv[]) {
  unsigned char *pkt = NULL, *pkt_bak, *mcast6, *someaddr6 = NULL;
  unsigned char *dst6, *src6 = NULL, *mac = NULL, *routers[2], string[64] = "icmp6 and dst ";
  int rawmode = 0, test_start = 0, fragment = 0, alert = 0, sroute = 0;
  int do_type = DO_PING, do_alive = 1, hopbyhop = 0, destination = 0, jumbo = 0;
  int pkt_len = 0, offset = 0, test_current = 0, i, j, k, do_fuzz = 1, test_ptr = 0;
  int test_end = TEST_MAX, ping = NEVER, frag_offset = 0, header = 0, no_send = 1;
  int test_pos = 0, test_cnt = 0, do_it, extend = 0, mtu = 1500, size = 64, wait = 0;
  char *interface, fuzzbuf[256], *srcmac, *dns, *route6, *real_dst6 = NULL;
  unsigned char buf[256], buf2[100], buf3[16];
  unsigned short int *sip;
  pcap_t *p;
  thc_ipv6_hdr *hdr;

  if (argc < 3 || strncmp(argv[1], "-h", 2) == 0)
    help(argv[0]);

  while ((i = getopt(argc, argv, "123456789rxt:T:p:FSDHRIJan:")) >= 0) {
    switch (i) {
    case '1':
      do_type = DO_PING;
      break;
    case '2':
      do_type = DO_NEIGHSOL;
      break;
    case '3':
      do_type = DO_NEIGHADV;
      break;
    case '4':
      do_type = DO_RA;
      break;
    case '5':
      do_type = DO_MLD_REP;
      break;
    case '6':
      do_type = DO_MLD_DONE;
      break;
    case '7':
      do_type = DO_MLD_QUERY;
      wait = 0xff0000;
      break;
    case '8':
      do_type = DO_MLD2_REPORT;
      break;
    case '9':
      do_type = DO_MLD2_QUERY;
      wait = 0xff0000;
      break;
    case 'r':
      thc_ipv6_rawmode(1);
      rawmode = 1;
      test_pos -= 14;
      offset -= 14;
      break;
    case 't':
      test_start = atoi(optarg);
      break;
    case 'T':
      test_end = test_start = atoi(optarg);
      break;
    case 'p':
      ping = atoi(optarg);
      break;
    case 'a':
      do_alive = 0;
      break;
    case 'S':
      sroute = 1;
      break;
    case 'n':
      no_send = atoi(optarg);
      break;
    case 'F':
      fragment = 1;
      break;
    case 'R':
      alert = 1;
      break;
    case 'D':
      destination = 1;
      break;
    case 'H':
      hopbyhop = 1;
      break;
    case 'J':
      jumbo = 1;
      break;
    case 'I':
      header = 1;
      break;
    case 'x':
      extend = 1;
      break;
    }
  }
  if (argc - optind < 2) {
    fprintf(stderr, "ERROR: not enough options, interface and target address are required!\n");
    exit(-1);
  }
  interface = argv[optind];
  if (rawmode == 0 && (srcmac = thc_get_own_mac(interface)) == NULL) {
    fprintf(stderr, "ERROR: %s is not a valid interface which has a MAC, use raw mode?\n", interface);
    exit(-1);
  }
  if (no_send < 1) {
    fprintf(stderr, "ERROR: -n number must be between one and 2 billion\n");
    exit(-1);
  }
  if (do_type != DO_PING) {
    mcast6 = thc_resolve6(argv[optind + 1]);
    if (do_type == DO_NEIGHSOL) {
      dst6 = thc_resolve6("ff02::0001:ff00:0000");
      memcpy(dst6 + 13, mcast6 + 13, 3);
    } else
      dst6 = thc_resolve6("ff02::1");
  } else {
    dst6 = thc_resolve6(argv[optind + 1]);
  }
  if (argv[optind + 1] != NULL)
    real_dst6 = thc_resolve6(argv[optind + 1]);

  if (interface == NULL || argv[optind + 1] == NULL) {
    printf("Error: interface and target-ipv6-address are mandatory command line options\n");
    exit(-1);
  }
  if (ping < 1 || test_end < test_start) {
    printf("dont f**k up the command line options!\n");
    exit(-1);
  }
  if (argv[optind + 2] != NULL)
    someaddr6 = thc_resolve6(argv[optind + 2]);
  if (argc - optind > 3) {
    printf("Error: too many command line options\n");
    exit(-1);
  }
  if ((mac = thc_get_mac(interface, src6, dst6)) == NULL) {
    fprintf(stderr, "ERROR: Can not resolve mac address for %s\n", argv[2]);
    exit(-1);
  }
  if (rawmode)
    srcmac = mac;

  if (do_type == DO_PING)
    src6 = thc_get_own_ipv6(interface, dst6, PREFER_GLOBAL);
  else
    src6 = thc_get_own_ipv6(interface, dst6, PREFER_LINK);
  strcat(string, thc_ipv62notation(src6));
  if (sroute) {
    if (someaddr6 != NULL)
      routers[0] = someaddr6;
    else
      routers[0] = dst6;
    routers[1] = NULL;
  }
  setvbuf(stdout, NULL, _IONBF, 0);
  memset(buf, 0, sizeof(buf));
  memset(buf2, 0, sizeof(buf2));
  dns = thc_resolve6("FF02::FB");
  route6 = thc_resolve6("2a01::");

  if ((p = thc_pcap_init(interface, string)) == NULL) {
    fprintf(stderr, "Error: could not capture on interface %s with string %s\n", interface, string);
    exit(-1);
  }
  // ping before to check if it works
  if (do_alive)
    if (check_alive(p, interface, src6, real_dst6) == 0) {
      fprintf(stderr, "Error: target %s is not alive via direct ping6!\n", argv[optind + 1]);
      exit(-1);
    }
  // generate basic packet
  strcpy(fuzzbuf, fuzztype_ether);
  if ((pkt = thc_create_ipv6(interface, PREFER_GLOBAL, &pkt_len, src6, dst6, 0, 0, 0, 0, 0)) == NULL)
    return -1;
  if (header)
    strcat(fuzzbuf, fuzztype_ip6);
  else
    strcat(fuzzbuf, fuzztype_ip6no);

  if (alert || hopbyhop || jumbo) {
    memset(buf2, 0, sizeof(buf2));
    i = 0;

    if (alert) {
      buf2[i++] = 5;
      buf2[i++] = 2;
      i += 2;
      strcat(fuzzbuf, ".F.F");
    }

    if (jumbo) {
      buf2[i++] = 0xc2;
      buf2[i++] = 4;
      buf2[i++] = 'J';          // lookup code
      buf2[i++] = 'J';
      buf2[i++] = 'J';
      buf2[i++] = 'J';
      strcat(fuzzbuf, ".FBBBB");
    }

    if (hopbyhop) {
      memset(buf3, 0, sizeof(buf3));
      buf3[0] = 'X';
      buf3[1] = '.';
      for (j = 0; j < 10; j++) {
        buf2[i++] = 1;          // PadN, length
        buf2[i++] = j;
        if (j > 0) {
          memset(buf2 + i, 0xaa, j);
          buf3[2 + j] = '.';
          i += j;
        }
        strcat(fuzzbuf, buf3);  // always: X... for every new option
      }
    }

    if (thc_add_hdr_hopbyhop(pkt, &pkt_len, buf2, i) < 0)
      return -1;

    i += 2;
    if (i % 8 > 0)
      i = ((i / 8) + 1) * 8;

    offset += i;
  }

  if (sroute) {
    if (thc_add_hdr_route(pkt, &pkt_len, routers, 1) < 0)
      return -1;
    else {
      strcat(fuzzbuf, "FFFFBBBB................");
      offset += 24;
    }
  }

  if (fragment) {
    frag_offset = offset;
    if (thc_add_hdr_fragment(pkt, &pkt_len, 0, 0, 0) < 0)
      return -1;
    else {
      strcat(fuzzbuf, "FFWW..");
      offset += 8;
    }
  }

  if (destination) {
    memset(buf2, 0, sizeof(buf2));
    memset(buf3, 0, sizeof(buf3));
    buf3[0] = 'X';
    buf3[1] = '.';
    i = 0;
    for (j = 0; j < 10; j++) {
      buf2[i++] = 1;            // PadN, length
      buf2[i++] = j;
      if (j > 0) {
        memset(buf2 + i, 0xaa, j);
        buf3[2 + j] = '.';
        i += j;
      }
      strcat(fuzzbuf, buf3);    // always: X... for every new option
    }

    if (thc_add_hdr_dst(pkt, &pkt_len, buf2, i) < 0)
      return -1;

    i += 2;
    if (i % 8 > 0)
      i = ((i / 8) + 1) * 8;

    offset += i;
  }

  memset(buf, 0, sizeof(buf));
  if (header)
    strcat(fuzzbuf, fuzztype_icmp6);
  else
    strcat(fuzzbuf, fuzztype_icmp6no);
  switch (do_type) {
  case DO_PING:
    if (thc_add_icmp6(pkt, &pkt_len, ICMP6_PINGREQUEST, 0, test_current, (unsigned char *) &buf, 16, 0) < 0)
      return -1;
    strcat(fuzzbuf, fuzztype_icmp6ping);
    break;

  case DO_NEIGHSOL:
    if (someaddr6 != NULL)
      memcpy(buf, someaddr6, 16);
    else
      memcpy(buf, mcast6, 16);
    buf[16] = 1;
    buf[17] = 1;
    memcpy(buf + 18, srcmac, 6);
    if (thc_add_icmp6(pkt, &pkt_len, ICMP6_NEIGHBORSOL, 0, 0, (unsigned char *) &buf, 24, 0) < 0)
      return -1;
    strcat(fuzzbuf, fuzztype_icmp6ns);
    break;

  case DO_NEIGHADV:
    if (someaddr6 != NULL)
      memcpy(buf, someaddr6, 16);
    else
      memcpy(buf, src6, 16);
    buf[16] = 2;
    buf[17] = 1;
    memcpy(buf + 18, srcmac, 6);
    if (thc_add_icmp6(pkt, &pkt_len, ICMP6_NEIGHBORADV, 0, 0xe0000000, (unsigned char *) &buf, 24, 0) < 0)
      return -1;
    strcat(fuzzbuf, fuzztype_icmp6na);
    break;

  case DO_RA:
    //  buf[3] = 250; // 0-3: reachable timer
    buf[6] = 4;                 // 4-7: retrans timer
    // option mtu
    buf[8] = 5;
    buf[9] = 1;
    buf[12] = mtu / 16777216;

    buf[14] = (mtu % 65536) / 256;
    buf[15] = mtu % 256;
    // option prefix
    buf[16] = 3;
    buf[17] = 4;
    buf[18] = size;             // prefix length
    buf[19] = 128 + 64;
    memset(&buf[20], 17, 4);
    memset(&buf[24], 4, 4);
    if (someaddr6 != NULL)
      memcpy(&buf[32], someaddr6, 16);
    else
      memcpy(&buf[32], route6, 16);

    i = 48;
    // mac address option
    buf[i++] = 1;
    buf[i++] = 1;
    memcpy(buf + i, srcmac, 6);
    i += 6;

    // default route routing option
    buf[i++] = 0x18;            // routing entry option type
    buf[i++] = 0x03;            // length 3 == 24 bytes
    buf[i++] = 0x00;            // prefix length
    buf[i++] = 0x08;            // priority, highest of course
    i += 2;                     // 52-53 unknown
    buf[i++] = 0x11;            // lifetime, word
    buf[i++] = 0x11;            // lifetime, word
    i += 16;                    // 56-71 address, all zeros for default

    // dns option
    buf[i++] = 0x19;            // dns option type
    buf[i++] = 0x03;            // length
    i += 2;                     // 74-75 reserved
    memset(buf + i, 1, 4);      // validity time
    i += 4;
    if (someaddr6 != NULL)
      memcpy(buf + i, someaddr6, 16);   // dns server
    else
      memcpy(buf + i, dns, 16); // dns server
    i += 16;

    if (thc_add_icmp6(pkt, &pkt_len, ICMP6_ROUTERADV, 0, 0xff080800, buf, i, 0) < 0)
      return -1;
    strcat(fuzzbuf, fuzztype_icmp6ra);
    break;

  case DO_MLD_QUERY:
  case DO_MLD_DONE:
  case DO_MLD_REP:
    buf[0] = 0xff;
    buf[1] = 0x02;
    buf[15] = 0x05;
    if (someaddr6 != NULL)
      memcpy(buf, someaddr6, 16);
    if (thc_add_icmp6(pkt, &pkt_len, do_type, 0, wait, buf, 16, 0) < 0)
      return -1;
    strcat(fuzzbuf, fuzztype_icmp6mld);
    break;
  case DO_MLD2_QUERY:
    buf[0] = 0xff;
    buf[1] = 0x02;
    buf[15] = 0x05;
    if (someaddr6 != NULL)
      memcpy(buf, someaddr6, 16);
    buf[16] = 7;
    buf[17] = 120;
    buf[19] = 3;
    memcpy(buf + 20, dst6, 16);
    memcpy(buf + 36, buf, 16);
    if (thc_add_icmp6(pkt, &pkt_len, DO_MLD_QUERY, 0, wait, buf, 68, 0) < 0)
      return -1;
    strcat(fuzzbuf, fuzztype_icmp6mld2que);
    break;
  case DO_MLD2_REPORT:
    for (i = 0; i < 3; i++) {
      buf[0 + 68 * i] = 1 + i * 2 - i / 2;      //include new++, generates 1, 3 and 4
      buf[3 + 68 * i] = 3;      //3 sources
      buf[4 + 68 * i] = 0xff;
      buf[5 + 68 * i] = 0x02;
      buf[18 + 68 * i] = 0x82 + i % 256;
      buf[19 + 68 * i] = 0xff;
      memcpy(buf + 20 + 68 * i, src6, 16);
      buf[36 + 68 * i] = 0xfe;
      buf[37 + 68 * i] = 0x80;
      buf[46 + 68 * i] = 0xf0;
      if (someaddr6 != NULL)
        memcpy(buf + 52 + 68 * i, someaddr6, 16);
    }

    if (thc_add_icmp6(pkt, &pkt_len, do_type, 0, 3, buf, 208, 0) < 0)
      return -1;
    strcat(fuzzbuf, fuzztype_icmp6mld2rep);
    break;

  default:
    fprintf(stderr, "ERROR: Mode not implemented yet!\n");
    exit(-1);
  }

  if (thc_generate_pkt(interface, srcmac, mac, pkt, &pkt_len) < 0)
    return -1;
  hdr = (thc_ipv6_hdr *) pkt;

  if (jumbo) {
    i = 0;
    j = 1;
    while (i < hdr->pkt_len + 4 && j) {
      if (hdr->pkt[i] == 'J')
        if (memcmp(&hdr->pkt[i], "JJJJ", 4) == 0)
          j = 0;
      i++;
    }
    if (j) {
      fprintf(stderr, "ERROR: fuckup, cant find my own marker?!\n");
      exit(-1);
    } else
      i--;
    hdr->pkt[i] = 0;
    hdr->pkt[i + 1] = 0;
    hdr->pkt[i + 2] = hdr->pkt[4 + 14 - 14 * rawmode];
    hdr->pkt[i + 3] = hdr->pkt[5 + 14 - 14 * rawmode];
    hdr->pkt[4 + 14 - 14 * rawmode] = 0;
    hdr->pkt[5 + 14 - 14 * rawmode] = 0;
  }

  if (extend)
    for (i = 0; i < strlen(fuzzbuf); i++)
      if (fuzzbuf[i] == 'B' || fuzzbuf[i] == 'F')
        fuzzbuf[i] = 'X';

  // backup of generated packet
  pkt_bak = malloc(hdr->pkt_len);
  memcpy(pkt_bak, hdr->pkt, hdr->pkt_len);

  printf("Fuzzing packet, starting at fuzz case %d, ending at fuzz case %d, every packet sent denoted by a dot:\n", test_start, test_end);
//printf("buf(%d): %s\n", strlen(fuzzbuf), fuzzbuf);
  while (do_fuzz) {
    if (test_cnt == 0)
      while (fuzzbuf[test_ptr] == '.') {
        test_ptr++;
        test_pos++;
      }

    if (fuzzbuf[test_ptr] == 0)
      do_fuzz = 0;

    test_cnt++;
    do_it = 1;

//printf("[%s] pos[%d]=%c -> %d | pkt[%d] | %d (%d=>%d)| ", /*fuzzbuf*/"", test_ptr, fuzzbuf[test_ptr], test_cnt, test_pos, test_current, test_start, test_end);

    switch (fuzzbuf[test_ptr]) {
    case 0:
      break;
    case 'X':
      if (test_cnt <= COUNT_EXTEND) {
        if (pkt_bak[test_pos] != extends[test_cnt - 1])
          hdr->pkt[test_pos] = extends[test_cnt - 1];
        else
          do_it = 0;
      } else {
        test_cnt = 0;
        test_ptr++;
        test_pos++;
      }
      break;
    case 'B':
      if (test_cnt <= COUNT_BYTE) {
        if (pkt_bak[test_pos] != bytes[test_cnt - 1])
          hdr->pkt[test_pos] = bytes[test_cnt - 1];
        else
          do_it = 0;
      } else {
        i = 0;
        while (i < COUNT_BYTE && do_it) {
          if (bytes[i] == pkt_bak[test_pos])
            do_it = 0;
          i++;
        }
        if (do_it)
          hdr->pkt[test_pos] = hdr->pkt[test_pos] ^ xors[test_cnt - COUNT_BYTE - 1];
      }
      if (test_cnt == COUNT_BYTE + COUNT_XOR) {
        test_cnt = 0;
        test_ptr++;
        test_pos++;
      }
      break;
    case 'F':
      if (test_cnt <= COUNT_FLAG) {
        if (pkt_bak[test_pos] != flags[test_cnt - 1])
          hdr->pkt[test_pos] = flags[test_cnt - 1];
        else
          do_it = 0;
      } else {
        i = 0;
        while (i < COUNT_FLAG && do_it) {
          if (bytes[i] == pkt_bak[test_pos])    // yes, bytes[] is the right one even for flags
            do_it = 0;
          i++;
        }
        if (do_it)
          hdr->pkt[test_pos] = hdr->pkt[test_pos] ^ xors[test_cnt - COUNT_BYTE - 1];
      }
      if (test_cnt == COUNT_FLAG + COUNT_XOR) {
        test_cnt = 0;
        test_ptr++;
        test_pos++;
      }
      break;
    case 'W':
      sip = (unsigned short int *) &pkt_bak[test_pos];
      if (test_cnt <= COUNT_WORD) {
        if (*sip != words[test_cnt - 1])
          memcpy((char *) &hdr->pkt[test_pos], (char *) &words[test_cnt - 1], 2);
        else
          do_it = 0;
      } else {
        i = 0;
        while (i < COUNT_WORD && do_it) {
          if (words[i] == *sip)
            do_it = 0;
          i++;
        }
        if (do_it) {
          i = *sip ^ xors[test_cnt - COUNT_WORD - 1];
          sip = (unsigned short int *) &hdr->pkt[test_pos];
          *sip = i % 65536;
        }
      }
      if (test_cnt == COUNT_WORD + COUNT_XOR) {
        test_cnt = 0;
        test_ptr++;
        test_pos += 2;
      }
      break;
    default:
      fprintf(stderr, "This character should not be in the fuzz string, shoot the programmer: %c(%d) position %d string %s\n", fuzzbuf[test_ptr], fuzzbuf[test_ptr], test_ptr,
              fuzzbuf);
      exit(-1);
      break;
    }

    if (do_it && do_fuzz) {
      if (test_current >= test_start && test_current <= test_end && do_fuzz) {
        // fill icmp id+seq and unique buffer with test case number
        if (fragment)
          memcpy(hdr->pkt + frag_offset + 58, (char *) &test_current, 4);
        switch (do_type) {
        case DO_PING:
          for (i = 0; i < 4 + 1; i++)
            memcpy(hdr->pkt + offset + 58 + i * 4, (char *) &test_current, 4);
          break;
        case DO_NEIGHSOL:
        case DO_NEIGHADV:
          break;                // do nothing for these
        case DO_RA:
          memcpy(hdr->pkt + offset + 0x62, (char *) &test_current, 4);  // prefix update
          memcpy(hdr->pkt + offset + 0x7e, hdr->pkt + offset + 0x5e, 16);       // routing update
          if (rawmode == 0)
            memcpy(hdr->pkt + 8, (char *) &test_current, 4);    // srcmac update
          memcpy(hdr->pkt + offset + 0x72, (char *) &test_current, 4);  // srcmac update
          memcpy(hdr->pkt + 0x10 + 14 - 14 * rawmode, (char *) &test_current, 4);       // srcip update
          memcpy(hdr->original_src, hdr->pkt + 8 + 14 - 14 * rawmode, 16);      // srcip update for checksum
          break;
        case DO_MLD_QUERY:
        case DO_MLD_DONE:
        case DO_MLD_REP:
        case DO_MLD2_QUERY:
          memcpy(hdr->pkt + offset + 0x4a, (char *) &test_current, 4);
          break;
        case DO_MLD2_REPORT:   //??? XXX TODO CHECK
          memcpy(hdr->pkt + offset + 0x4d, (char *) &test_current, 4);
          memcpy(hdr->pkt + offset + 0x4d + 68, (char *) &test_current, 4);
          memcpy(hdr->pkt + offset + 0x4d + 136, (char *) &test_current, 4);
          break;
        default:
          fprintf(stderr, "ERROR!!!\n");
          exit(-1);
        }

        // regenerate checksum
        if (do_type == do_type) {       // maybe for later non-icmp stuff
          hdr->pkt[offset + 56] = 0;
          hdr->pkt[offset + 57] = 0;
          i = checksum_pseudo_header(hdr->original_src, hdr->final_dst, NXT_ICMP6, &hdr->pkt[offset + 54], hdr->pkt_len - offset - 54);
          hdr->pkt[offset + 56] = i / 256;
          hdr->pkt[offset + 57] = i % 256;
        }
        // send packet
        for (k = 0; k < no_send; k++) {
          if (thc_send_pkt(interface, pkt, &pkt_len) < 0)
            return -1;
          usleep(1);
        }
        printf(".");
        usleep(250);
        // if ping, check ping again
        if ((test_current - test_start) % ping == 0 && test_current != 0 && test_start != test_current)
          if (check_alive(p, interface, src6, real_dst6) == 0) {
            i = ((((test_current - test_start) / ping) - 1) * ping) + test_start + 1;
            printf("\nResult: target %s crashed during fuzzing, offending test case no. could be %d to %d\n", argv[optind + 1], i < 0 ? 0 : i, test_current);
            exit(-1);
          }
      }
//else printf("NOT SENT - NOT IN TEST LIST\n");
      // reset to basic packet
      memcpy(hdr->pkt, pkt_bak, hdr->pkt_len);
      test_current++;
    }
//else printf("NOT SENT!\n");
  }

  printf("\n");
  // ping afterwards to check if it worked
  if (do_alive) {
    if (check_alive(p, interface, src6, real_dst6) == 0)
      printf("Result: target %s is NOT alive via direct ping6 - good work! (position: %d)\n", argv[optind + 1], test_pos);
    else
      printf("Result: target %s is still alive via direct ping6, better luck next time.\n", argv[optind + 1]);
  }

  thc_pcap_close(p);
  return 0;
}
コード例 #23
0
ファイル: pap.c プロジェクト: BrianHoldsworth/netatalk2
int main( int ac, char	**av)
{
    ATP			atp;
    struct atp_block	atpb;
    int			c, err = 0, fd, cuts = 0;
    char		*obj = NULL, *type = "LaserWriter", *zone = "*";
    struct timeval	stv, tv;
    char		rbuf[ ATP_MAXDATA ];
    struct iovec	iov;
    unsigned short	waiting, result;
    int			connattempts = 10;
    int			waitforidle = 0;
    struct at_addr      addr;

    extern char		*optarg;
    extern int		optind;

    memset(&addr, 0, sizeof(addr));
    while (( c = getopt( ac, av, "dWwcep:s:EA:" )) != EOF ) {
	switch ( c ) {
#ifdef F****D
	case 'w' :
	    waitforprinter = 1;
	    break;

	case 'W' :
	    waitforidle = 1;
	    break;
#endif /* F****D */

	/* enable debugging */
	case 'd' :
	    debug++;
	    break;

	case 'c' :
	    cuts++;
	    break;

	case 'e' :	/* send stdout to stderr */
	    dup2( 2, 1 );
	    break;

	case 'p' :
	    printer = optarg;
	    break;

	case 's' :
	    status = optarg;
	    break;

	case 'E' :
	    noeof = 1;
	    break;
	   
	case 'A':
	    if (!atalk_aton(optarg, &addr)) {
	      fprintf(stderr, "Bad address.\n");
	      exit(1);
	    }
	    break;

	default :
	    err++;
	}
    }
    if ( err ) {
	usage( *av );
    }
    if ( printer == NULL && (( printer = paprc()) == NULL )) {
	fprintf( stderr, "No printer specified and ./.paprc not found.\n" );
	exit( 2 );
    }

    /*
     * Open connection.
     */
    if ( nbp_name( printer, &obj, &type, &zone ) < 0 ) {
	fprintf( stderr, "%s: Bad name\n", printer );
	exit( 2 );
    }
    if ( obj == NULL ) {
	fprintf( stderr, "%s: Bad name\n", printer );
	exit( 2 );
    }

    if ( nbp_lookup( obj, type, zone, &nn, 1, &addr ) <= 0 ) {
	if ( errno != 0 ) {
	    perror( "nbp_lookup" );
	    exit( 2 );
	}
	fprintf( stderr, "%s:%s@%s: NBP Lookup failed\n", obj, type, zone );
	exit( 1 );
    }

    if ( isatty( 1 )) {
	printf( "Trying %u.%d:%d ...\n", ntohs( nn.nn_sat.sat_addr.s_net ),
		nn.nn_sat.sat_addr.s_node, nn.nn_sat.sat_port );
    }

    if (( atp = atp_open( ATADDR_ANYPORT, &addr )) == NULL ) {
	perror( "atp_open" );
	exit( 2 );
    }
    if (( satp = atp_open( ATADDR_ANYPORT, &addr )) == NULL ) {
	perror( "atp_open" );
	exit( 2 );
    }

    while ( waitforidle ) {
	char	st_buf[ 1024 ];	/* XXX too big */

	cbuf[ 0 ] = 0;
	cbuf[ 1 ] = PAP_SENDSTATUS;
	cbuf[ 2 ] = cbuf[ 3 ] = 0;
	atpb.atp_saddr = &nn.nn_sat;
	atpb.atp_sreqdata = cbuf;
	atpb.atp_sreqdlen = 4;	/* bytes in SendStatus request */
	atpb.atp_sreqto = 2;		/* retry timer */
	atpb.atp_sreqtries = 5;		/* retry count */
	if ( atp_sreq( satp, &atpb, 1, 0 ) < 0 ) {
	    perror( "atp_sreq" );
	    exit( 1 );
	}

	if(debug){ printf( "SENDSTATUS >\n" ), fflush( stdout );}

	atpb.atp_saddr = &nn.nn_sat;
	rniov[ 0 ].iov_len = PAP_MAXDATA + 4;
	atpb.atp_rresiov = rniov;
	atpb.atp_rresiovcnt = 1;
	if ( atp_rresp( satp, &atpb ) < 0 ) {
	    perror( "atp_rresp" );
	    continue;
	}

#ifndef NONZEROSTATUS
	/*
	 * The stinking LaserWriter IINTX puts crap in this
	 * field.
	 */
	if ( ((char *)rniov[ 0 ].iov_base)[ 0 ] != 0 ) {
	    fprintf( stderr, "Bad status response!\n" );
	    exit( 1 );
	}
#endif /* NONZEROSTATUS */

	if ( ((char *)rniov[ 0 ].iov_base)[ 1 ] != PAP_STATUS ||
		atpb.atp_rresiovcnt != 1 ) {
	    fprintf( stderr, "Bad status response!\n" );
	    exit( 1 );
	}

	if(debug){ printf( "< STATUS\n" ), fflush( stdout );}

	memcpy( st_buf, (char *) rniov[ 0 ].iov_base + 9, 
		((char *)rniov[ 0 ].iov_base)[ 8 ] );
	st_buf[ (int) ((char *)rniov[ 0 ].iov_base)[ 8 ]] = '\0';
	if ( strstr( st_buf, "idle" ) != NULL ) {
	    waitforidle = 0;
	} else {
	    updatestatus( (char *) rniov[ 0 ].iov_base + 9,
		    ((char *)rniov[ 0 ].iov_base)[ 8 ] );
	    sleep( 5 );
	}
    }

    cbuf[ 0 ] = connid = getpid() & 0xff;
    cbuf[ 1 ] = PAP_OPEN;
    cbuf[ 2 ] = cbuf[ 3 ] = 0;
    cbuf[ 4 ] = atp_sockaddr( atp )->sat_port;
    cbuf[ 5 ] = oquantum;	/* flow quantum */
    if ( gettimeofday( &stv, NULL ) < 0 ) {
	perror( "gettimeofday" );
	exit( 2 );
    }
    for (;;) {
	if ( cuts ) {
	    waiting = 0xffff;
	} else {
	    if ( gettimeofday( &tv, NULL ) < 0 ) {
		perror( "gettimeofday" );
		exit( 2 );
	    }
	    waiting = htons( tv.tv_sec - stv.tv_sec );
	}
	memcpy(cbuf +  6, &waiting, sizeof( waiting ));

	atpb.atp_saddr = &nn.nn_sat;
	atpb.atp_sreqdata = cbuf;
	atpb.atp_sreqdlen = 8;		/* bytes in OpenConn request */
	atpb.atp_sreqto = 2;		/* retry timer */
	atpb.atp_sreqtries = 5;		/* retry count */
	if ( atp_sreq( atp, &atpb, 1, ATP_XO ) < 0 ) {
	    perror( "atp_sreq" );
	    exit( 1 );
	}

	if(debug){ printf( "OPEN >\n" ), fflush( stdout );}

	iov.iov_base = rbuf;
	iov.iov_len = sizeof( rbuf );
	atpb.atp_rresiov = &iov;
	atpb.atp_rresiovcnt = 1;
	if ( atp_rresp( atp, &atpb ) < 0 ) {
	    perror( "atp_rresp" );
	    if ( connattempts-- <= 0 ) {
		fprintf( stderr, "Can't connect!\n" );
		exit( 1 );
	    }
	    continue;
	}

	/* sanity */
	if ( iov.iov_len < 8 || (unsigned char)rbuf[ 0 ] != connid ||
		rbuf[ 1 ] != PAP_OPENREPLY ) {
	    fprintf( stderr, "Bad response!\n" );
	    continue;	/* This is weird, since TIDs must match... */
	}

	if(debug){ printf( "< OPENREPLY\n" ), fflush( stdout );}

	if ( isatty( 1 )) {
	    printf( "%.*s\n", (int)iov.iov_len - 9, (char *) iov.iov_base + 9 );
	}
	updatestatus( (char *) iov.iov_base + 9, iov.iov_len - 9 );

	memcpy( &result, rbuf +  6,  sizeof( result ));
	if ( result != 0 ) {
	    sleep( 2 );
	} else {
	    memcpy( &sat, &nn.nn_sat, sizeof( struct sockaddr_at ));
	    sat.sat_port = rbuf[ 4 ];
	    quantum = rbuf[ 5 ];
	    break;
	}
    }

    if ( isatty( 1 )) {
	printf( "Connected to %.*s:%.*s@%.*s.\n",
		nn.nn_objlen, nn.nn_obj,
		nn.nn_typelen, nn.nn_type,
		nn.nn_zonelen, nn.nn_zone );
    }

    if ( optind == ac ) {
	send_file( 0, atp, 1 );
    } else {
	for (; optind < ac; optind++ ) {
	    if ( strcmp( av[ optind ], "-" ) == 0 ) {
		fd = 0;
	    } else if (( fd = open( av[ optind ], O_RDONLY )) < 0 ) {
		perror( av[ optind ] );
		continue;
	    }
	    send_file( fd, atp, ( optind == ac - 1 ) ? 1 : 0 );
	    if ( fd != 0 ) {
		close( fd );
	    }
	}
    }

    /*
     * Close connection.
     */
    cbuf[ 0 ] = connid;
    cbuf[ 1 ] = PAP_CLOSE;
    cbuf[ 2 ] = cbuf[ 3 ] = 0;

    atpb.atp_saddr = &sat;
    atpb.atp_sreqdata = cbuf;
    atpb.atp_sreqdlen = 4;		/* bytes in CloseConn request */
    atpb.atp_sreqto = 2;		/* retry timer */
    atpb.atp_sreqtries = 5;		/* retry count */
    if ( atp_sreq( atp, &atpb, 1, ATP_XO ) < 0 ) {
	perror( "atp_sreq" );
	exit( 1 );
    }

	if(debug){ printf( "CLOSE >\n" ), fflush( stdout );}

    iov.iov_base = rbuf;
    iov.iov_len = sizeof( rbuf );
    atpb.atp_rresiov = &iov;
    atpb.atp_rresiovcnt = 1;
    if ( atp_rresp( atp, &atpb ) < 0 ) {
	perror( "atp_rresp" );
	exit( 1 );
    }

    /* sanity */
    if ( iov.iov_len != 4 || rbuf[ 1 ] != PAP_CLOSEREPLY ) {
	fprintf( stderr, "Bad response!\n" );
	exit( 1 );
    }

#ifndef ZEROCONNID
    /*
     * The AGFA Viper Rip doesn't have the connection id in the close request.
     */
    if ((unsigned char)rbuf[ 0 ] != connid ) {
	fprintf( stderr, "Bad connid in close!\n" );
	exit( 1 );
    }
#endif /* ZEROCONNID */

	if(debug){ printf( "< CLOSEREPLY\n" ), fflush( stdout );}

    if ( isatty( 1 )) {
	printf( "Connection closed.\n" );
    }
    exit( 0 );
}
コード例 #24
0
ファイル: trigcap.c プロジェクト: AndresVelasco/wireshark
int main(int argc, char** argv) {
	char errbuf[PCAP_ERRBUF_SIZE];
	char* interface = NULL;
	char* outfile = NULL;
	guint snaplen = 65536;
	char* start_filter_str = NULL;
	char* stop_filter_str = NULL;
	char* capture_filter_str = NULL;
	int promisc = 0;
	int quiet = 0;
	struct bpf_program start_filter;
	struct bpf_program capture_filter;
	pcap_t* capturer = NULL;
	pcap_dumper_t* dumper = NULL;
	int opt;

	while ((opt = getopt(argc, argv, "i:w:s:b:e:f:phdq")) != -1) {
		switch (opt) {
			case 'i':
				if (interface) panic(1,"interface already given");
				interface = g_strdup(optarg);
				break;
			case 'w':
				if (outfile) panic(3,"output file already given");
				outfile = g_strdup(optarg);
				break;
			case 's':
				snaplen = strtoul(optarg,NULL,10);
				if ( snaplen == 0 )
					panic(4,"invalid snaplen");
				break;
			case 'b':
				if (start_filter_str) panic(5,"start filter already given");
				start_filter_str = g_strdup(optarg);
				break;
			case 'e':
				if (stop_filter_str) panic(6,"stop filter already given");
				stop_filter_str = g_strdup(optarg);
				break;
			case 'f':
				if (capture_filter_str) panic(7,"capture filter already given");
				capture_filter_str = g_strdup(optarg);
				break;
			case 'p':
				promisc = 1;
				break;
			case 'q':
				quiet = 1;
				break;
			case 'd':
				debug_level++;
				break;
			case 'h':
			default:
				usage(0);
				break;
			}
		}

	dprintf(1,"starting with:\n interface: %s\n snaplen: %d\n promisc: %d"
			"\n outfile: %s\n capture filter: %s\n start: %s\n stop: %s\n debug level: %d\n",
			interface ? interface : "to be chosen",
			snaplen,
			promisc,
			outfile ? outfile : "** missing **",
			capture_filter_str ? capture_filter_str : "** none given **",
			start_filter_str ? start_filter_str : "** missing **",
			stop_filter_str ? stop_filter_str : "** missing **",
			debug_level);

	if (! ( start_filter_str && stop_filter_str && outfile ) ) {
		usage(10);
	}

	if (! interface) {
		interface = pcap_lookupdev(errbuf);
		if (!interface) {
			panic(11, "could not obtain an interface: %s\n",errbuf);
		}
	}

#ifdef HAVE_PCAP_OPEN
	if ( ! ( capturer = pcap_open(interface, snaplen, promisc, 1, NULL, errbuf) )) {
#else
	if ( ! ( capturer = pcap_open_live(interface, snaplen, promisc, 1, errbuf) )) {
#endif
		panic(12,"could not open interface '%s' for listener: %s\n",interface,errbuf);
	}

	dprintf(1,"opened listener (%s,%d,%d)\n",interface,snaplen, promisc);

	if (pcap_compile(listener, &start_filter, start_filter_str, 1, 0) < 0) {
		panic(13,"could not compile start filter: %s\n",pcap_geterr(listener));
	}

	dprintf(2,"compiled start filter %s\n",start_filter_str);

	if (pcap_compile(listener, &stop_filter, stop_filter_str, 1, 0) < 0) {
		panic(14,"could not compile stop filter: %s\n",pcap_geterr(listener));
	}

	dprintf(2,"compiled stop filter %s\n",stop_filter_str);

#ifdef HAVE_PCAP_OPEN
	if ( ! ( capturer = pcap_open(interface, snaplen, promisc, 1, NULL, errbuf) )) {
#else
	if ( ! ( capturer = pcap_open_live(interface, snaplen, promisc, 1, errbuf) )) {
#endif
		panic(15,"could not open interface '%s' for capturer: %s\n",interface, errbuf);
	}

	dprintf(1,"opened capturer (%s,%d,%d)\n",interface,snaplen, promisc);

	if (capture_filter_str) {
		if (pcap_compile(capturer, &capture_filter, capture_filter_str, 1, 0) < 0) {
			panic(16,"could not compile capture filter: %s\n",pcap_geterr(capturer));
		}
		if (pcap_setfilter(capturer, &capture_filter) < 0) {
			panic(17,"could not apply start filter to capturer: %s\n",pcap_geterr(capturer));
		}

		dprintf(2,"compiled and set capture filter (%s)\n",capture_filter_str);
	}

	if (pcap_setfilter(listener, &start_filter) < 0) {
		panic(18,"could not apply start filter to listener: %s\n",pcap_geterr(listener));
	}
	dprintf(2,"set start filter on listener\n");


	if (pcap_setnonblock(listener, 0, errbuf) < 0) {
		panic(19,"could not set listener in blocking mode: %s\n",errbuf);
	}
	dprintf(2,"listener -> blocking\n");

	if (pcap_setnonblock(capturer, 1, errbuf) < 0) {
		panic(20,"could not set capturer in non blocking mode: %s\n",errbuf);
	}
	dprintf(2,"capturer -> non_blocking\n");

	if (! (dumper = pcap_dump_open(listener,outfile)) ) {
		panic(21,"open dumper file '%s': %s\n",outfile,pcap_geterr(listener));
	}
	dprintf(2,"opened dumper file '%s'\n",outfile);

	signal(SIGINT, sig_int);
#ifdef SIGQUIT
	signal(SIGQUIT, sig_int);
#endif
#ifdef SIGTERM
	signal(SIGTERM, sig_int);
#endif
#ifdef SIGSTOP
	signal(SIGSTOP, sig_int);
#endif

	keep_going = 1;
	dumping = 0;

	do {
		if (pcap_dispatch(listener, -1, listener_handler, NULL) < 0 ) {
			panic(22,"pcap_dispatch(listener) failed: %s\n",pcap_geterr(listener));
		}

		if (pcap_dispatch(capturer, -1, capture_handler, (void*)dumper) < 0 ) {
			panic(23,"pcap_dispatch(capturer) failed: %s\n",pcap_geterr(capturer));
		}
	} while(keep_going);

	if (!quiet) {
		printf("%d packets captured\n",captured);
	}

	dprintf(1,"done!\n");

	pcap_dump_close(dumper);
	pcap_close(listener);
	pcap_close(capturer);

	return 0;
}
コード例 #25
0
ファイル: client_main.c プロジェクト: zioproto/ipudp
int main(int argc, char **argv) {
	int c = 0;	
	int console = 0;
	int port = 0, uport = 0, ka_time = 0, persistent = 0;
	char *addrstr = NULL, *viface = NULL, *dev = NULL;

	while((c = getopt(argc, argv, "u:p:a:n:k:i:bcvP"))!= -1) {
		switch (c) {
		case 'u':
			uport = atoi(optarg);
			break;
		case 'p':
			port = atoi(optarg);
			break;
		case 'v':
			verbose = 1;
			break;
		case 'c':
			console = 1;
			break;
		case 'a':
			addrstr = optarg;
			break;
		case 'i':
			dev = optarg;
			break;
		case 'n':
			viface = optarg;
			break;
		case 'k':
			ka_time = atoi(optarg);
			break;
		case 'b':
			background = 1;
			break;
		case 'P':
			persistent = 1;
			break;
		default:
			usage();
			exit(-1);
		}
	}
	if (!(port) || !(addrstr)) {
		printf("Error: both -a <address> and -p <port> must be specified\n");
		usage();
	}

	if (!uport)
		uport = DEFAULT_UDP_PORT;
	
	if (!ka_time)
		ka_time = DEFAULT_KEEPALIVE_TIMEOUT;	

	if (!viface)
		viface = DEFAULT_VIFACE_NAME;

	if ((!console) && (!dev)) {
		printf("Error: either -c or -i <dev> must be specified. If console mode is not used," 
				"the name of the outgoing tunnel interface must be specified\n");
		usage();
	}

	/*Initialization*/
	if (background) {
		if (log_init() < 0) {
			printf("error: log_init failed\n");
			exit(-1);
		}
	}

	memset(&c_data, 0, sizeof(struct client_data));

	/*TCP server addr*/
  	c_data.tcp_server.sin_family = AF_INET;
  	c_data.tcp_server.sin_port = htons(port);
  	if (inet_pton(AF_INET, addrstr, &c_data.tcp_server.sin_addr)<0) {
		printf("bad server ip address");
		exit(-1);
	}

	/*UDP server addr*/
	c_data.udp_server.sin_family = AF_INET;
  	c_data.udp_server.sin_port = htons(uport);
  	inet_pton(AF_INET, addrstr, &c_data.udp_server.sin_addr);

	if (client_init() < 0) {
		print_log("client_init() error", LOG_LEVEL_IMPORTANT);
		goto quit;
	}

	if (ipudp_conf_init() < 0) {
		print_log("ipudp_conf_init() error", LOG_LEVEL_IMPORTANT);
		goto quit;
	}

	if (sock_init_connect() < 0)
		goto quit;

	if ((ssl_init() < 0))
		goto quit;
	
	if (console) {
		if (console_ini() < 0) {
			console = 0;
			goto quit;
		}
	}
	/**/

	signal(SIGINT, sighand);
    signal(SIGTERM, sighand);
    signal(SIGKILL, sighand);

	if (console)
		do_select(0, ka_time);
	else {
		if (client_association(dev, viface) < 0) 
			goto quit;
		if (background) {
			if (daemonize() < 0) {
				printf("Error: couldn't demonize. Exit\n");
				goto quit;
			}
		}
		client_keepalive_cycle(persistent, ka_time);
	}

quit:
    client_fini();
	if (console)
		console_fini();

	return 0;
}
コード例 #26
0
ファイル: pjdfstest.c プロジェクト: JabirTech/Source
int
main(int argc, char *argv[])
{
	struct syscall_desc *scall;
	unsigned int n;
	char *gids, *endp;
	int uid, umsk, ch;

	uid = -1;
	gids = NULL;
	umsk = 0;

	while ((ch = getopt(argc, argv, "g:u:U:")) != -1) {
		switch(ch) {
		case 'g':
			gids = optarg;
			break;
		case 'u':
			uid = (int)strtol(optarg, &endp, 0);
			if (*endp != '\0' && !isspace((unsigned char)*endp)) {
				fprintf(stderr, "invalid uid '%s' - number "
				    "expected\n", optarg);
				exit(1);
			}
			break;
		case 'U':
			umsk = (int)strtol(optarg, &endp, 0);
			if (*endp != '\0' && !isspace((unsigned char)*endp)) {
				fprintf(stderr, "invalid umask '%s' - number "
				    "expected\n", optarg);
				exit(1);
			}
			break;
		default:
			usage();
		}
	}
	argc -= optind;
	argv += optind;

	if (argc < 1) {
		fprintf(stderr, "too few arguments\n");
		usage();
	}

	if (gids != NULL) {
		fprintf(stderr, "changing groups to %s\n", gids);
		set_gids(gids);
	}
	if (uid != -1) {
		fprintf(stderr, "changing uid to %d\n", uid);
		if (setuid(uid) < 0) {
			fprintf(stderr, "cannot change uid: %s\n",
			    strerror(errno));
			exit(1);
		}
	}

	/* Change umask to requested value or to 0, if not requested. */
	umask(umsk);

	for (;;) {
		scall = find_syscall(argv[0]);
		if (scall == NULL) {
			fprintf(stderr, "syscall '%s' not supported\n",
			    argv[0]);
			exit(1);
		}
		argc++;
		argv++;
		n = call_syscall(scall, argv);
		argc += n;
		argv += n;
		if (argv[0] == NULL)
			break;
		argc++;
		argv++;
	}

	exit(0);
}
コード例 #27
0
int
main(int argc, char *argv[])
{
	long long l;
	char *dummy, *afname;
	int ch, rc;

	afname = NULL;
	while ((ch = getopt(argc, argv, "A:dF:f:Np:t:T:")) != -1) {
		switch (ch) {
		case 'A':
			addr = optarg;
			break;
		case 'd':
			debug++;
			break;
		case 'F':
			l = strtoll(optarg, &dummy, 10);
			if (*dummy != '\0' || l < 0)
				errx(EX_USAGE, "Invalid FIB number");
			fib = (u_int)l;
			break;
		case 'f':
			l = strtoll(optarg, &dummy, 10);
			if (*dummy != '\0' || l < 0)
				errx(EX_USAGE, "Invalid FIB number");
			reflectfib = (u_int)l;
			break;
		case 'N':
			nostart=1;
			break;
		case 'p':
			l = strtoll(optarg, &dummy, 10);
			if (*dummy != '\0' || l < 0)
				errx(EX_USAGE, "Invalid port number");
			port = (uint16_t)l;
			break;
		case 't':
			testcase = optarg;
			break;
		case 'T':
			afname = optarg;
			break;
		case '?':
		default:
			errx(EX_USAGE, "Unknown command line option at '%c'",
			    optopt);
			/* NOTREACHED */
		}
	}

	if (testcase == NULL)
		errx(EX_USAGE, "Mandatory option -t <testcase> not given");
	if (afname == NULL)
		errx(EX_USAGE, "Mandatory option -T <afname> not given");

	if (strcmp(afname, "TCP6") == 0)
		rc = reflect_tcp6();
	else if (strcmp(afname, "UDP6") == 0)
		rc = reflect_udp6();
	else
		errx(EX_USAGE, "Mandatory option -T %s not a valid option",
		    afname);

	return (rc);
}
コード例 #28
0
ファイル: gitVCInfo.cpp プロジェクト: Lexus34/tdt-arp
int main (int argc, char **argv)
{
	switch (fork()) {
		case -1:
				perror("[gitVCInfo] fork");
				return -1;
		case 0:
				break;
		default:
				return 0;
	}

	if (setsid() < 0) {
		perror("[gitVCInfo] setsid");
		return 1;
	}

	unsigned int id = 1;
	int opt = -2;
	char buf[BUFFERSIZE] = "";
	int release_type = -1;
	int imageversion = 0;
	int imagesubver = 0;
	char imagesubver2[BUFFERSIZE] = "0";
	int year = 9999;
	int month = 99;
	int day = 99;
	int hour = 99;
	int minute = 99;
	bool delay = false;
	int dhcp = 0;
	int nic_on = 0;
	char* imagetyp = "squashfs";
	char linuxversion[24] = "";
	char gccversion[50] = "";
	char userpc[24];
	char ladename[BUFFERSIZE] = "System";
	char creator[BUFFERSIZE];
	char imagename[BUFFERSIZE];
	char homepage[BUFFERSIZE];
	char root[BUFFERSIZE];	
	char address[BUFFERSIZE];
	char broadcast[BUFFERSIZE];
	char netmask[BUFFERSIZE];
	char nameserver[BUFFERSIZE];
	char gateway[BUFFERSIZE];
	char null[BUFFERSIZE] = "";
	char versioninfo[20];
	char git_revision[] = "$Revision: 1.7 $";
	sscanf(git_revision, "%*s %s", versioninfo);

	while ((opt = getopt(argc, argv, "hgdn:")) != -1)
	{
		switch (opt)
		{
			case 'h':
					if (argc < 3)
					{
						printf("gitVCInfo - bootinfo on screen, v%s\n", versioninfo);
						printf("Usage: gitVCInfo [-d] [-g] [-n name] [-h]\n");
						printf("\nPossible options:\n");
						printf("\t-h\t\tprint this usage information\n");
						printf("\t-g\t\tprint bootinfo in german\n");
						printf("\t-d\t\tdelay on\n");
						printf("\t-n name\t\tspecial output (e.g. -n Neutrino)\n");
						exit(0);
					}
					break;
			case 'g':
					id = 0;
					break;
			case 'd':
						delay = true;
					break;
			case 'n':
					strcpy(ladename, optarg);
					break;
			default:
					break;
		}
	}

	strcpy(creator, info[UNKNOWN][id]);
	strcpy(imagename, info[UNKNOWN][id]);
	strcpy(homepage, info[UNKNOWN][id]);
	strcpy(root, info[INTERN][id]);	
	strcpy(address, info[UNKNOWN][id]);
	strcpy(broadcast, info[UNKNOWN][id]);
	strcpy(netmask, info[UNKNOWN][id]);
	strcpy(nameserver, info[UNKNOWN][id]);
	strcpy(gateway, info[UNKNOWN][id]);

	FILE* fv1 = fopen(VERSION_FILE, "r");
	if (fv1)
	{
		while (fgets(buf, BUFFERSIZE, fv1)) {
			sscanf(buf, "version=%1d%1d%1d%1s%4d%2d%2d%2d%2d", 
			&release_type, &imageversion, &imagesubver, (char *) &imagesubver2,
			&year, &month, &day, &hour, &minute);
			sscanf(buf, "creator=%[^\n]", (char *) &creator);
			sscanf(buf, "imagename=%[^\n]", (char *) &imagename);
			sscanf(buf, "homepage=%[^\n]", (char *) &homepage);
		}
		fclose(fv1);
	}

	FILE* fv2 = fopen(INTERFACES_FILE, "r");
	if (fv2)
	{
		while (fgets(buf, BUFFERSIZE, fv2)) {
			if (nic_on == 0) {
				if (sscanf(buf, "auto eth%[0]", (char *) &null)) {
					nic_on=1;
				}
			}
			if (sscanf(buf, "iface eth0 inet stati%[c]", (char *) &null)) {
				dhcp = 1;
			}
			else if (sscanf(buf, "iface eth0 inet dhc%[p]", (char *) &null)) {
				dhcp = 2;
			}
		}
		fclose(fv2);
	}

	FILE* fv3 = fopen(NAMENSSERVER_FILE, "r");
	if (fv3)
	{
		while (fgets(buf, BUFFERSIZE, fv3)) {
			sscanf(buf, "nameserver %[^\n]", (char *) &nameserver);
		}
		fclose(fv3);
	}

	FILE* fv4 = popen("/sbin/ifconfig eth0", "r");
	if (fv4)
	{
		while (fgets(buf, BUFFERSIZE, fv4)) {
			sscanf(buf, " inet addr:%s  Bcast:%s  Mask:%[^\n]", (char *) &address, (char *) &broadcast, (char *) &netmask);
		}
		pclose(fv4);
	}

	FILE* fv5 = popen("/sbin/route -n", "r");
	if (fv5)
	{
		fscanf(fv5, "%*[^\n]\n%*[^\n]\n%*[^\n]\n");
		while (fgets(buf, BUFFERSIZE, fv5)) {
			sscanf(buf, "%s %[0-9.]", (char *) &null, (char *) &gateway);
		}
		pclose(fv5);
	}

  FILE* fv6 = fopen(MOUNTS_FILE, "r"); //Root-Server IP ermitteln, falls nfsboot
  if (fv6) {
    while (fgets(buf, BUFFERSIZE, fv6)!=NULL) {
      sscanf(buf, "/dev/root / nfs rw,v2,rsize=4096,wsize=4096,hard,udp,nolock,addr=%s", (char *) &root);
    }
    fclose(fv6);
  }
  
  FILE* fv7 = fopen(VERSION_FILE2, "r"); //Versionsdatei (/proc/version) auswerten
  if (fv7) {
    while (fgets(buf, BUFFERSIZE, fv2)!=NULL) {
      sscanf(buf, "Linux version %s (%s) (%s) ", (char *) &linuxversion, (char *) &userpc, (char *) &gccversion/*, (char *) &gccversion, (char *) &gccversion*/);
      //Linux version 2.6.17.14_stm22_0041 (BrechREiZ@rhel) (gcc-Version 4.1.1 (STMicroelectronics/Linux Base 4.1.1-23)) #1 PREEMPT Sun Mar 28 20:58:08 CEST 
    }
    fclose(fv7);
  }
  
  FILE* fv8 = fopen(VERSION_FILE, "a"); //Versionsdatei (/.version) beschreibbar, dann jffs2/ext2...
  if (fv8) {
  fclose(fv8);
  imagetyp = "jffs2/ext2";
  }

	char message2[BUFFERSIZE];
	strcpy(message2, "");
	if (delay)
		sprintf(message2, "%s %s .... ", info[LOAD][id], ladename);
	else
		message2[0] = '\0';

	char message[BIGBUFFERSIZE];
	sprintf(message,
		"\n\n\n\n"
		"\t\t    ---------- Image Information ----------\n\n"
		"\t\t    %s %d.%d.%s\n"						//Image Version
		"\t\t    %s %s\n\n"						//Image Typ
		"\t\t    %s %02d.%02d.%d\n"					//Date
		"\t\t    %s %d:%02d\n"						//Time
		"\t\t    %s %s\n"						//Creator
		"\t\t    %s %s-%s\n"						//Image Name
		"\t\t    %s %s\n\n"						//Homepage
		"\t\t    %s\n\n"
		"\t\t    %s %s\n"						//Network state
		"\t\t    %s %s\n"						//DHCP state
		"\t\t    %s %s\n"						//Root-Server
		"\t\t    %s %s\n"						//IP Adress
		"\t\t    %s %s\n"						//Subnet
		"\t\t    %s %s\n"						//Broadcast
		"\t\t    %s %s\n"						//Gateway
		"\t\t    %s %s\n\n"						//Nameserver
		"\t\t    %s %s, %s %s\n "					//Linux Version, gcc Version
		"\t\t    %s %s\n\n"						//User, PC
		"\t\t\t\t%s",
		info[VERSION][id], imageversion, imagesubver, imagesubver2, 
		info[TYPE][id], release_type == 0 ? "Release" 
						: release_type == 1 ? "Snapshot" 
						: release_type == 2 ? "Intern" 
						:	info[UNKNOWN][id],
		info[DATE][id], day, month, year,
		info[TIME][id], hour, minute,
		info[CREATOR][id], creator,
		info[NAME][id], imagename, imagetyp,
		info[WWW][id], homepage,
		info[HEADLINE][id],
		info[NETW][id], nic_on == 0 ? info[DISABLED][id] : nic_on == 1 ? info[ENABLED][id] : info[UNKNOWN][id],
		info[DHCP][id], dhcp == 1 ? info[DISABLED][id] : dhcp == 2 ? info[ENABLED][id] : info[UNKNOWN][id],
		info[ROOT][id], root,
		info[IP][id], address,
		info[NETM][id], netmask,
		info[BROAD][id], broadcast,
		info[GATEWAY][id], gateway,
		info[DNS][id], nameserver,
		info[LINUX][id], linuxversion,
		info[GCC][id], gccversion,
		info[UPC][id], userpc,
		message2);

	FILE *fb = fopen(CONSOLE, "w");
	if (fb == 0) {
		perror("[gitVCInfo] fopen");
		exit(1);
	}

	if(!delay)
	{
		for (unsigned int i = 0; i < strlen(message); i++) {
			fputc(message[i], fb);
			fputc(message[i], stdout);
			fflush(fb);
			fflush(stdout);
		}
	}
	else
	{
		sprintf(message2, "%s %s .... ", info[LOAD][id], ladename);
		int test=0;
		for (unsigned int i = 0; i < strlen(message); i++) {
			fputc(message[i], fb);
			fputc(message[i], stdout);
			fflush(fb);
			fflush(stdout);
			usleep(CHARDELAY);
		}
	}
	fputc('\n', fb);
	fputc('\n', stdout);
	fclose(fb);
	return 0;
}
コード例 #29
0
ファイル: noaaportIngester.c プロジェクト: rmlawton/LDM
/**
 * Reads a NOAAPORT data stream, creates LDM data-products from the stream, and
 * inserts the data-products into an LDM product-queue.  The NOAAPORT data
 * stream can take the form of multicast UDP packets from (for example) a
 * Novra S300 DVB-S2 receiver or the standard input stream.
 *
 * Usage:
 *     noaaportIngester [-l <em>log</em>] [-n|-v|-x] [-q <em>queue</em>] [-u <em>n</em>] [-m <em>mcastAddr</em>] [-I <em>iface</em>] [-b <em>npages</em>]\n
 *
 * Where:
 * <dl>
 *      <dt>-b <em>npages</em></dt>
 *      <dd>Allocate \e npages pages of memory for the internal buffer.</dd>
 *
 *      <dt>-I <em>iface</em></dt>
 *      <dd>Listen for multicast packets on interface \e iface.</dd>
 *
 *      <dt>-l <em>log</em></dt>
 *      <dd>Log to file \e log. The default is to use the system logging daemon
 *      if the current process is a daemon; otherwise, the standard error
 *      stream is used.</dd>
 *
 *      <dt>-m <em>mcastAddr</em></dt>
 *      <dd>Use the multicast address \e mcastAddr. The default is to
 *      read from the standard input stream.</dd>
 *
 *      <dt>-n</dt>
 *      <dd>Log messages of level NOTE and higher priority. Each data-product
 *      will generate a log message.</dd>
 *
 *      <dt>-q <em>queue</em></dt>
 *      <dd>Use \e queue as the pathname of the LDM product-queue. The default
 *      is to use the default LDM pathname of the product-queue.</dd>
 *
 *      <dt>-u <em>n</em></dt>
 *      <dd>If logging is to the system logging daemon, then use facility 
 *      <b>local</b><em>n</em>. The default is to use the LDM facility.</dd>
 *
 *      <dt>-v</dt>
 *      <dd>Log messages of level INFO and higher priority.</dd>
 *
 *      <dt>-x</dt>
 *      <dd>Log messages of level DEBUG and higher priority.</dd>
 * </dl>
 *
 * If neither -n, -v, nor -x is specified, then logging will be restricted to
 * levels ERROR and WARN only.
 *
 * @retval 0 if successful.
 * @retval 1 if an error occurred. At least one error-message will be logged.
 */
int main(
    const int           argc,           /**< [in] Number of arguments */
    char* const         argv[])         /**< [in] Arguments */
{
    int                 status = 0;     /* default success */
    extern int          optind;
    extern int          opterr;
    int                 ch;
    const char* const   progName = ubasename(argv[0]);
    const char*         interface = NULL;
    int                 logmask = LOG_UPTO(LOG_WARNING);
    const unsigned      logOptions = LOG_CONS | LOG_PID;
    const char*         mcastSpec = NULL;
    const char*         prodQueuePath = NULL;
    size_t              npages = DEFAULT_NPAGES;
    Fifo*               fifo;
    int                 ttyFd = open("/dev/tty", O_RDONLY);
    int                 processPriority = 0;
    int                 idx;
    const char*         logPath = (-1 == ttyFd)
        ? NULL                          /* log to system logging daemon */
        : "-";                          /* log to standard error stream */

    (void)close(ttyFd);
    (void)setulogmask(logmask);

    status = initLogging(progName, logOptions, logFacility, logPath);
    opterr = 0;                         /* no error messages from getopt(3) */

    while (0 == status && (ch = getopt(argc, argv, "b:I:l:m:np:q:r:s:t:u:vx")) != -1)
    {
        switch (ch) {
            extern char*    optarg;
            extern int      optopt;

            case 'b': {
                unsigned long   n;

                if (sscanf(optarg, "%lu", &n) != 1) {
                    LOG_SERROR1("Couldn't decode FIFO size in pages: \"%s\"",
                            optarg);
                    status = 1;
                }
                else {
                    npages = n;
                }
                break;
            }
            case 'I':
                interface = optarg;
                break;
            case 'l':
                logPath = optarg;
                status = initLogging(progName, logOptions, logFacility,
                        logPath);
                break;
            case 'm':
                mcastSpec = optarg;
                break;
            case 'n':
                logmask |= LOG_MASK(LOG_NOTICE);
                (void)setulogmask(logmask);
                break;
            case 'p': {
                char* cp;

                errno = 0;
                processPriority = (int)strtol(optarg, &cp, 0);

                if (0 != errno) {
                    LOG_SERROR1("Couldn't decode priority \"%s\"", optarg);
                    log_log(LOG_ERR);
                }
                else {
                    if (processPriority < -20)
                        processPriority = -20;
                    else if (processPriority > 20)
                        processPriority = 20;
                }

                break;
            }
            case 'q':
                prodQueuePath = optarg;
                break;
            case 'r':
#ifdef RETRANS_SUPPORT
                retrans_xmit_enable = atoi(optarg);
                if(retrans_xmit_enable == 1)
                  retrans_xmit_enable = OPTION_ENABLE;
                else
                  retrans_xmit_enable = OPTION_DISABLE;
#endif
                break;
           case 's': {
#ifdef RETRANS_SUPPORT
			strcpy(sbn_channel_name, optarg);
                        if(!strcmp(optarg,NAME_SBN_TYP_GOES)) {
                                sbn_type = SBN_TYP_GOES;
                                break;
                        }
                        if(!strcmp(optarg,NAME_SBN_TYP_NOAAPORT_OPT)) {
                                sbn_type = SBN_TYP_NOAAPORT_OPT;
                                break;
                        }
                        if(!strcmp(optarg,"NWSTG")) {
                                sbn_type = SBN_TYP_NMC;
                                break;
                        }
                        if(!strcmp(optarg,NAME_SBN_TYP_NMC)) {
                                sbn_type = SBN_TYP_NMC;
                                break;
                        }
                        if(!strcmp(optarg,NAME_SBN_TYP_NMC2)) {
                                sbn_type = SBN_TYP_NMC2;
                                break;
                        }
                        if(!strcmp(optarg,NAME_SBN_TYP_NMC3)) {
                                sbn_type = SBN_TYP_NMC3;
                                break;
                        }
                        if(!strcmp(optarg,NAME_SBN_TYP_NWWS)) {
                                sbn_type = SBN_TYP_NWWS;
                                break;
                        }
                        if(!strcmp(optarg,NAME_SBN_TYP_ADD)) {
                                sbn_type = SBN_TYP_ADD;
                                break;
                        }
                        if(!strcmp(optarg,NAME_SBN_TYP_ENC)) {
                                sbn_type = SBN_TYP_ENC;
                                break;
                        }
                        if(!strcmp(optarg,NAME_SBN_TYP_EXP)) {
                                sbn_type = SBN_TYP_EXP;
                                break;
                        }
                        if(!strcmp(optarg,NAME_SBN_TYP_GRW)) {
                                sbn_type = SBN_TYP_GRW;
                                break;
                        }
                        if(!strcmp(optarg,NAME_SBN_TYP_GRE)) {
                                sbn_type = SBN_TYP_GRE;
                                break;
                        }
                        printf("Operator input: UNKNOWN type must be\n");
                        printf(" %s, %s, %s, %s, %s, %s, %s, %s, %s, %s  or %s \n",
                                NAME_SBN_TYP_NMC,
                                NAME_SBN_TYP_GOES,
                                NAME_SBN_TYP_NOAAPORT_OPT,
                                NAME_SBN_TYP_NMC2,
                                NAME_SBN_TYP_NMC3,
                                NAME_SBN_TYP_NWWS,
                                NAME_SBN_TYP_ADD,
                                NAME_SBN_TYP_ENC,
                                NAME_SBN_TYP_EXP,
                                NAME_SBN_TYP_GRW,
                                NAME_SBN_TYP_GRE);
#endif
                break;
              }
            case 't':
#ifdef RETRANS_SUPPORT
                strcpy(transfer_type, optarg);
                if(!strcmp(transfer_type,"MHS") || !strcmp(transfer_type,"mhs")){
                     /** Using MHS for communication with NCF  **/
                }else{
                     uerror("No other mechanism other than MHS is currently supported\n");
                     status  = 1;
                 }
#endif
                break;
            case 'u': {
                int         i = atoi(optarg);

                if (0 > i || 7 < i) {
                    LOG_START1("Invalid logging facility number: %d", i);
                    status = 1;
                }
                else {
                    static int  logFacilities[] = {LOG_LOCAL0, LOG_LOCAL1,
                        LOG_LOCAL2, LOG_LOCAL3, LOG_LOCAL4, LOG_LOCAL5,
                        LOG_LOCAL6, LOG_LOCAL7};

                    logFacility = logFacilities[i];

                    status = initLogging(progName, logOptions, logFacility,
                            logPath);
                }

                break;
            }
            case 'v':
                logmask |= LOG_MASK(LOG_INFO);
                (void)setulogmask(logmask);
                break;
            case 'x':
                logmask |= LOG_MASK(LOG_DEBUG);
                (void)setulogmask(logmask);
                break;
            default:
                optopt = ch;
                /*FALLTHROUGH*/
                /* no break */
            case '?': {
                uerror("Unknown option: \"%c\"", optopt);
                status = 1;
                break;
            }
        }                               /* option character switch */
    }                                   /* getopt() loop */

    if (0 == status) {
        if (optind < argc) {
            uerror("Extraneous command-line argument: \"%s\"",
                    argv[optind]);
            status = 1;
        }
    }

    if (0 != status) {
        uerror("Error decoding command-line");
        usage(progName);
    }
    else {
        unotice("Starting Up %s", PACKAGE_VERSION);
        unotice("%s", COPYRIGHT_NOTICE);

        if ((status = fifoNew(npages, &fifo)) != 0) {
            LOG_ADD0("Couldn't create FIFO");
            log_log(LOG_ERR);
        }
        else {
            LdmProductQueue*    prodQueue;

            if ((status = lpqGet(prodQueuePath, &prodQueue)) != 0) {
                LOG_ADD0("Couldn't open LDM product-queue");
                log_log(LOG_ERR);
            }
            else {
                if (NULL == mcastSpec) {
                    if (0 == (status = spawnProductMaker(NULL, fifo, prodQueue,
                                    &productMaker, &productMakerThread))) {
                        status = spawnFileReader(NULL, NULL, fifo, &reader,
                                &readerThread);
                    }
                }                               /* reading file */
                else {
                    pthread_attr_t  attr;

                    if (0 != (status = pthread_attr_init(&attr))) {
                        LOG_ERRNUM0(status,
                                "Couldn't initialize thread attribute");
                    }
                    else {
#ifndef _POSIX_THREAD_PRIORITY_SCHEDULING
                        uwarn("Can't adjust thread priorities due to lack of "
                                "necessary support from environment");
#else
                        /*
                         * In order to not miss any data, the reader thread
                         * should preempt the product-maker thread as soon as
                         * data is available and run as long as data is
                         * available.
                         */
                        const int           SCHED_POLICY = SCHED_FIFO;
                        struct sched_param  param;

                        param.sched_priority =
                            sched_get_priority_max(SCHED_POLICY) - 1;

                        (void)pthread_attr_setinheritsched(&attr,
                                PTHREAD_EXPLICIT_SCHED);
                        (void)pthread_attr_setschedpolicy(&attr, SCHED_POLICY);
                        (void)pthread_attr_setschedparam(&attr, &param);
                        (void)pthread_attr_setscope(&attr,
                                PTHREAD_SCOPE_SYSTEM);
#endif
#ifdef RETRANS_SUPPORT
                        if (retrans_xmit_enable == OPTION_ENABLE){
                         /* Copy mcastAddress needed to obtain the cpio entries */
                         strcpy(mcastAddr, mcastSpec);
                        }
#endif
                        if (0 == (status = spawnProductMaker(&attr, fifo,
                                        prodQueue, &productMaker,
                                        &productMakerThread))) {
#ifdef _POSIX_THREAD_PRIORITY_SCHEDULING
                            param.sched_priority++;
                            (void)pthread_attr_setschedparam(&attr, &param);
#endif
                            status = spawnMulticastReader(&attr, mcastSpec,
                                    interface, fifo, &reader, &readerThread);

                        }                       /* product-maker spawned */
                    }                           /* "attr" initialized */
                }                               /* reading multicast packets */

                if (0 != status) {
                    log_log(LOG_ERR);
                    status = 1;
                }
                else {
                    pthread_t   statThread;

                    (void)gettimeofday(&startTime, NULL);
                    reportTime = startTime;

                    (void)pthread_create(&statThread, NULL,
                            reportStatsWhenSignaled, NULL);

                    set_sigactions();

                    (void)pthread_join(readerThread, NULL);

                    status = readerStatus(reader);

                    (void)pthread_cancel(statThread);
                    (void)pthread_join(statThread, NULL);
                    (void)fifoCloseWhenEmpty(fifo);
                    (void)pthread_join(productMakerThread, NULL);

                    if (0 != status)
                        status = pmStatus(productMaker);

                    reportStats();
                    readerFree(reader);
#ifdef RETRANS_SUPPORT
					/** Release buffer allocated for retransmission **/
					if(retrans_xmit_enable == OPTION_ENABLE){
					  freeRetransMem();
					}
#endif
                }               /* "reader" spawned */

                (void)lpqClose(prodQueue);
            }                       /* "prodQueue" open */
        }                           /* "fifo" created */
    }                               /* command line decoded */

    return status;
}
コード例 #30
0
ファイル: test.cpp プロジェクト: trondkla/TDT4225
int main(int argc, char **argv)
{
    srand(time(0));
    
    std::string filename;
    std::string garbage;
    bool runGarbage = false;
    bool write = false;
    bool timing = true;
    
    int c;
    while ((c = getopt(argc, argv, "f:g:wtd")) != EOF)
        switch (c)
    {
        case 'f': filename = optarg; break;
        case 't': timing = true; break;
        case 'g': garbage = optarg; runGarbage=true; break;
        case 'w': write = true; break;
        case 'd': debug = true; break;
        case '?': return 1;
    }
    
    if (filename.empty()){
        fprintf(stderr, "-f <filename> is not set\n");
        return 1;
    }
    
    // Remember: mod(size, parallel files) must be zero
    if (write) {
        writeFile(filename.c_str(), 250000000);
    }
    std::streampos size = getSize(filename.c_str());
    if (size < 0) {
        fprintf(stderr, "File do not exists: %s\n", filename.c_str());
        return 1;
    }
    
    if (garbage.empty())
        fprintf(stderr, "-g <filename> is not set - Not running garbage file\n");
    
    std::streampos sizeGarbage;
    if (runGarbage){
        sizeGarbage = getSize(garbage.c_str());
        if (sizeGarbage < 0) {
            fprintf(stderr, "File do not exists: %s\n", garbage.c_str());
            return 1;
        }
    }
    
    std::vector<uint32_t> blocksizes;
    
    blocksizes.push_back(1024);
    blocksizes.push_back(4096);
    blocksizes.push_back(16384);
    
    
    std::vector<uint32_t>::const_iterator bs;
    
    for(bs=blocksizes.begin(); bs!=blocksizes.end(); bs++){

      //* Run parallel reads
      for (int i = 1; i<=32; i = i<<1){
	// Clear buffers
	if (runGarbage){
	  if(debug) printf("Reading garbage...\n");
	  read(garbage.c_str(), sizeGarbage, 1, sizeof(uint32_t));
	  system("sync; echo 3 > /proc/sys/vm/drop_caches");    
	}
        
	// Read file
	//printf("Reading with %d concurrent files open... bs: %d \n", i, *bs);
	double t = read(filename.c_str(), size, i, *bs);
	printf("%2d files(%d): %.6f sec\n", i, *bs, t);
      }
      //*/
      
      //* Run random read
      if (runGarbage){
	if(debug) printf("Reading garbage...\n");
	read(garbage.c_str(), sizeGarbage, 1, sizeof(uint32_t));
	system("sync; echo 3 > /proc/sys/vm/drop_caches");    
      }
      
      double t = random_read(filename.c_str(), size, *bs);
      printf("random block(%d): %.6f sec\n", *bs, t);
      //*/
    }
}