Ejemplo n.º 1
0
enum tc_options_mode
tc_options_process(struct tc_options *opts, int argc, char **argv)
{
	void *opt = gopt_sort(&argc, (const char**)argv, opts_def);
	/* usage */
	if (gopt(opt, '?')) {
		opts->mode = TC_MODE_USAGE;
		goto done;
	}
	/* version */
	if (gopt(opt, 'V')) {
		opts->mode = TC_MODE_VERSION;
		goto done;
	}
	/* generate or verify */
	if (gopt_arg(opt, 'G', &opts->file)) {
		opts->mode = TC_MODE_GENERATE;
	} else
	if (gopt_arg(opt, 'W', &opts->file)) {
		opts->mode = TC_MODE_VERIFY;
	} else {
		opts->mode = TC_MODE_USAGE;
		goto done;
	}
	opts->file_config = argv[1];
done:	
	gopt_free(opt);
	return opts->mode;
}
Ejemplo n.º 2
0
/*======================================================================*/
int main(int argc, const char **argv) {
    int i;

    bool verbose = false;
    bool no_run = false;

    const char *prefix_option;
    const char *suite_name_option = NULL;
    const char *tmp;

    bool any_fail = false;

    atexit(cleanup);

	argc = initialize_option_handling(argc, argv);

    if (gopt_arg(options, 'x', &prefix_option))
        reporter = create_xml_reporter(prefix_option);
    else
        reporter = create_text_reporter();
    
    gopt_arg(options, 's', &suite_name_option);

    if (gopt_arg(options, 'v', &tmp))
        verbose = true;

    if (gopt_arg(options, 'n', &tmp))
        no_run = true;

    if (gopt_arg(options, 'c', &tmp))
        reporter_options.use_colours = true;
    else
        reporter_options.use_colours = false;

    if (gopt_arg(options, 'h', &tmp)) {
        usage(argv);
        return EXIT_SUCCESS;
    }

    if (argc < 2) {
        usage(argv);
        return EXIT_FAILURE;
    }


    set_reporter_options(reporter, &reporter_options);

    i = 1;
    while(i < argc) {
        const char *test_name = NULL;
        const char *test_library = argv[i++];

        bool fail;

        if (!file_exists(test_library)) {
            printf("Couldn't find library: %s\n", test_library);
            return EXIT_FAILURE;
        }

        /* Check if the next argument is not a filename, thus a test name, remember and move past it */
        if (!file_exists(argv[i])) {
            test_name = argv[i++];
        }

        fail = run_tests_in_library(suite_name_option, test_name, test_library, verbose, no_run);
        if (fail) any_fail = true;
    }
    
    return any_fail?EXIT_FAILURE:EXIT_SUCCESS;
}
Ejemplo n.º 3
0
Archivo: main.c Proyecto: nabto/unabto
static bool test_parse_args(const char * progname, int argc, char* argv[], nabto_main_setup* nms)
{
    const char *x1[] = { "help", 0 };
    const char *x2[] = { "version", 0 };
    const char *x3[] = { "config", 0 };
    const char *x4[] = { "size", 0 };
    const char *x5[] = { "deviceName", 0 };
    const char *x6[] = { "use_encryption", 0 };
    const char *x7[] = { "encryption_key", 0 };
    const char *x8[] = { "localport", 0 };
    const char *x11[] = { "nice_exit", 0};

    const struct { int k; int f; const char *s; const char*const* l; } opts[] = {
        { 'h', GOPT_NOARG,   "h?", x1 },
        { 'V', GOPT_NOARG,   "V",  x2 },
        { 'C', GOPT_NOARG,   "C",  x3 },
        { 'S', GOPT_NOARG,   "S",  x4 },
        { 'd', GOPT_ARG,     "d",  x5 },
        { 's', GOPT_NOARG,   "s",  x6 },
        { 'k', GOPT_ARG,     "k",  x7 },
        { 'p', GOPT_ARG,     "p",  x8 },
        { 'x', GOPT_NOARG,   "x",  x11 },
        { 0,0,0,0 }
    };

    void *options = gopt_sort(&argc, (const char**)argv, opts);

    if (gopt(options, 'h')) {
        printf("Usage: %s [options]\n", progname);
        printf("   -h  Print this help.\n");
        printf("   -V  Print release version.\n");
        printf("   -C  Print configuration (unabto_config.h).\n");
        printf("   -S  Print size (in bytes) of structures (memory usage).\n");
        exit(0);
    }
    
    if (gopt(options, 'V')) {
        printf("%s: %d.%d\n", progname, RELEASE_MAJOR, RELEASE_MINOR);
        exit(0);
    }
    
    if (gopt(options, 'C')) {
        unabto_printf_unabto_config(stdout, progname);
        exit(0);
    }
    
    if (gopt(options, 'S')) {
        unabto_printf_memory_sizes(stdout, progname);
        exit(0);
    }

    if (!gopt_arg(options, 'd', &nms->id)) {
        NABTO_LOG_FATAL(("Specify a serverId with -d"));
    }
    
    if (gopt(options, 's')) {
        const char* preSharedKey;
        if ( gopt_arg( options, 'k', &preSharedKey)) {
            if (!unabto_read_psk_from_hex(preSharedKey, nms->presharedKey, 16)) {
                NABTO_LOG_FATAL(("Cannot read presharedkey");
            }
        }
#if NABTO_ENABLE_CONNECTIONS
        nms->cryptoSuite = CRYPT_W_AES_CBC_HMAC_SHA256;
#endif
    }
Ejemplo n.º 4
0
Archivo: cmd.c Proyecto: ehalls/usbpcap
int __cdecl main(int argc, CHAR **argv)
{
    void *options;
    const char *tmp;
    struct thread_data data;
    HANDLE thread;
    DWORD thread_id;
    BOOL interactive;

    /* Too bad Microsoft compiler does not support C99...
    options = gopt_sort(&argc, argv, gopt_start(
        gopt_option('h', 0, gopt_shorts('h, '?'), gopt_longs("help")),
        gopt_option('d', GOPT_ARG, gopt_shorts('d'), gopt_longs("device")),
        gopt_option('o', GOPT_ARG, gopt_shorts('o'), gopt_longs("output")),
        gopt_option('s', GOPT_ARG, gopt_shorts('s'), gopt_longs("snaplen")),
        gopt_option('b', GOPT_ARG, gopt_shorts('b'), gopt_longs("bufferlen")),
        gopt_option('I', 0, gopt_shorts('I'), gopt_longs("init-non-standard-hwids"))));
    */

    const char *const h_long[] = {"help", NULL};
    const char *const d_long[] = {"device", NULL};
    const char *const o_long[] = {"output", NULL};
    const char *const s_long[] = {"snaplen", NULL};
    const char *const b_long[] = {"bufferlen", NULL};
    const char *const I_long[] = {"init-non-standard-hwids", NULL};
    opt_spec_t opt_specs[] = {
        {'h', 0, "h?", h_long},
        {'d', GOPT_ARG, "d", d_long},
        {'o', GOPT_ARG, "o", o_long},
        {'s', GOPT_ARG, "s", s_long},
        {'b', GOPT_ARG, "b", b_long},
        {'I', 0, "I", I_long},
    };

    options = gopt_sort(&argc, argv, (const void*)opt_specs);


    data.filename = NULL;
    data.device = NULL;
    data.snaplen = 65535;
    data.bufferlen = DEFAULT_INTERNAL_KERNEL_BUFFER_SIZE;

    if (gopt(options, 'h'))
    {
        printf("Usage: USBPcapCMD.exe [options]\n"
               "  -h, -?, --help\n"
               "    Prints this help.\n"
               "  -d <device>, --device <device>\n"
               "    USBPcap control device to open. Example: -d \\\\.\\USBPcap1.\n"
               "  -o <file>, --output <file>\n"
               "    Output .pcap file name.\n"
               "  -s <len>, --snaplen <len>\n"
               "    Sets snapshot length.\n"
               "  -b <len>, --bufferlen <len>\n"
               "    Sets internal capture buffer length. Valid range <4096,134217728>.\n"
               "  -I,  --init-non-standard-hwids\n"
               "    Initializes NonStandardHWIDs registry key used by USBPcapDriver.\n"
               "    This registry key is needed for USB 3.0 capture.\n");
        return 0;
    }

    if (gopt(options, 'I'))
    {
        init_non_standard_roothub_hwid();
        return 0;
    }

    if (gopt_arg(options, 'd', &tmp))
    {
        data.device = _strdup(tmp);
    }

    if (gopt_arg(options, 'o', &tmp))
    {
        data.filename = _strdup(tmp);
    }

    if (gopt_arg(options, 's', &tmp))
    {
        data.snaplen = atol(tmp);
        if (data.snaplen == 0)
        {
            printf("Invalid snapshot length!\n");
            return -1;
        }
    }

    if (gopt_arg(options, 'b', &tmp))
    {
        data.bufferlen = atol(tmp);
        /* Minimum buffer size if 4 KiB, maximum 128 MiB */
        if (data.bufferlen < 4096 || data.bufferlen > 134217728)
        {
            printf("Invalid buffer length! "
                   "Valid range <4096,134217728>.\n");
            return -1;
        }
    }

    if (data.filename != NULL && data.device != NULL)
    {
        interactive = FALSE;
    }
    else
    {
        interactive = TRUE;
        if (data.filename != NULL)
        {
            free(data.filename);
            data.filename = NULL;
        }

        if (data.device != NULL)
        {
            free(data.device);
            data.device = NULL;
        }

        if (cmd_interactive(&data) < 0)
        {
            return 0;
        }
    }

    data.process = TRUE;

    thread = CreateThread(NULL, /* default security attributes */
                          0,    /* use default stack size */
                          read_thread,
                          &data,
                          0,    /* use default creation flag */
                          &thread_id);

    if (thread == NULL)
    {
        if (interactive == TRUE)
        {
            printf("Failed to create thread\n");
        }
    }
    else
    {
        for (;;)
        {
            int c = getchar();
            if (c == (int)'q')
            {
                data.process = FALSE;
                break;
            }
        }

        WaitForSingleObject(thread, INFINITE);
    }

    filters_free();

    if (data.device != NULL)
    {
        free(data.device);
    }

    if (data.filename != NULL)
    {
        free(data.filename);
    }

    return 0;
}
Ejemplo n.º 5
0
Archivo: main.c Proyecto: nabto/unabto
static bool tunnel_parse_args(int argc, char* argv[], nabto_main_setup* nms) {

    const char *tunnel_port_str;

    const char x1s[] = "h";      const char* x1l[] = { "help", 0 };
    const char x2s[] = "V";      const char* x2l[] = { "version", 0 };
    const char x3s[] = "C";      const char* x3l[] = { "config", 0 };
    const char x4s[] = "S";      const char* x4l[] = { "size", 0 };
    const char x9s[] = "d";      const char* x9l[] = { "device_name", 0 };
    const char x10s[] = "H";     const char* x10l[] = { "tunnel_default_host", 0 }; // only used together with the tunnel.
    const char x11s[] = "P";     const char* x11l[] = { "tunnel_default_port", 0 };
    const char x12s[] = "s";     const char* x12l[] = { "use_encryption", 0 };
    const char x13s[] = "k";     const char* x13l[] = { "encryption_key", 0 };
    const char x14s[] = "p";     const char* x14l[] = { "localport", 0 };
    const char x15s[] = "a";     const char* x15l[] = { "check_acl", 0 };
    const char x16s[] = "";      const char* x16l[] = { "allow_port", 0};
    const char x17s[] = "";      const char* x17l[] = { "allow_host", 0};
    const char x18s[] = "x";     const char* x18l[] = { "nice_exit", 0};
    const char x19s[] = "";      const char* x19l[] = { "allow_all_ports", 0};
    const char x21s[] = "l";     const char* x21l[] = { "nabtolog", 0 };
    const char x22s[] = "A";     const char* x22l[] = { "controller", 0 };
    const char x23s[] = "";      const char* x23l[] = { "disable_tcp_fb", 0 };
    const char x24s[] = "";      const char* x24l[] = { "controller_port", 0 };
#if NABTO_ENABLE_EPOLL
    const char x25s[] = "";      const char* x25l[] = { "select_based", 0 };
#endif

    const char x26s[] = "";      const char* x26l[] = { "tunnels", 0 };
    const char x27s[] = "";      const char* x27l[] = { "stream_window_size",0 };
    const char x28s[] = "";      const char* x28l[] = { "connections", 0 };
    const char x29s[] = "";      const char* x29l[] = { "disable_extended_rendezvous_multiple_sockets", 0 };
// uart options
    const char x30s[] = "";      const char* x30l[] = { "uart_device", 0 }; 

    const struct { int k; int f; const char *s; const char*const* l; } opts[] = {
        { 'h', GOPT_NOARG,   x1s, x1l },
        { 'V', GOPT_NOARG,   x2s, x2l },
        { 'C', GOPT_NOARG,   x3s, x3l },
        { 'S', GOPT_NOARG,   x4s, x4l },
        { 'd', GOPT_ARG,     x9s, x9l },
        { 'H', GOPT_ARG,     x10s, x10l },
        { 'P', GOPT_ARG,     x11s, x11l },
        { 's', GOPT_NOARG,   x12s, x12l },
        { 'k', GOPT_ARG,     x13s, x13l },
        { 'p', GOPT_ARG,     x14s, x14l },
        { 'a', GOPT_NOARG,   x15s, x15l },
        { ALLOW_PORT_OPTION, GOPT_REPEAT|GOPT_ARG, x16s, x16l },
        { ALLOW_HOST_OPTION, GOPT_REPEAT|GOPT_ARG, x17s, x17l },
        { 'x', GOPT_NOARG, x18s, x18l },
        { ALLOW_ALL_PORTS_OPTION, GOPT_NOARG, x19s, x19l },
        { 'l', GOPT_REPEAT|GOPT_ARG,  x21s, x21l },
        { 'A', GOPT_ARG, x22s, x22l },
        { DISABLE_TCP_FALLBACK_OPTION, GOPT_NOARG, x23s, x23l },
        { CONTROLLER_PORT_OPTION, GOPT_ARG, x24s, x24l },
#if NABTO_ENABLE_EPOLL
        { SELECT_BASED_OPTION, GOPT_NOARG, x25s, x25l },
#endif
#if NABTO_ENABLE_DYNAMIC_MEMORY
        { TUNNELS_OPTION, GOPT_ARG, x26s, x26l },
        { STREAM_WINDOW_SIZE_OPTION, GOPT_ARG, x27s, x27l },
        { CONNECTIONS_SIZE_OPTION, GOPT_ARG, x28s, x28l },
#endif
#if NABTO_ENABLE_EXTENDED_RENDEZVOUS_MULTIPLE_SOCKETS
        { DISABLE_EXTENDED_RENDEZVOUS_MULTIPLE_SOCKETS, GOPT_NOARG, x29s, x29l },
#endif
        { UART_DEVICE_OPTION, GOPT_ARG, x30s, x30l },
        { 0,0,0,0 }
    };

    void *options = gopt_sort( & argc, (const char**)argv, opts);

    const char * h;
    int p;
    const char* localPortStr;
    const char* optionString;
    const char* basestationAddress;
    const char* controllerPort;
    const char* tunnelsOption;
    const char* streamWindowSizeOption;
    const char* connectionsOption;
    const char* uartDevice = 0;
    uint32_t addr;


    if (gopt(options, 'h')) {
        printf("Usage: unabto_tunnel [options] -d devicename\n");
        printf("  -h, --help                  Print this help.\n");
        printf("  -V, --version               Print version.\n");
        printf("  -C, --config                Print configuration (unabto_config.h).\n");
        printf("  -S, --size                  Print size (in bytes) of memory usage.\n");
        printf("  -l, --nabtolog              Speficy log level such as *.trace.\n");
        printf("  -d, --device_name           Specify name of this device.\n");
        printf("  -H, --tunnel_default_host   Set default host name for tunnel (%s).\n", UNABTO_TUNNEL_TCP_DEFAULT_HOST);
        printf("  -P, --tunnel_default_port   Set default port for tunnel (%u).\n", UNABTO_TUNNEL_TCP_DEFAULT_PORT);
        printf("  -s, --use_encryption        Encrypt communication.\n");
        printf("  -k, --encryption_key        Specify encryption key.\n");
        printf("  -p, --localport             Specify port for local connections.\n");
        printf("  -A, --controller            Specify controller address\n");
        printf("      --controller_port       sets the controller port number.\n");
        printf("  -a, --check_acl             Perform ACL check when establishing connection.\n");
        printf("      --allow_all_ports       Allow connections to all port numbers.\n");
        printf("      --allow_port            Ports that are allowed. Requires -a.\n");
        printf("      --allow_host            Hostnames that are allowed. Requires -a.\n");
        printf("      --uart_device           Sets the uart device\n");
        printf("  -x, --nice_exit             Close the tunnels nicely when pressing Ctrl+C.\n");
#if NABTO_ENABLE_TCP_FALLBACK
        printf("      --disable_tcp_fb        Disable tcp fallback.\n");
#endif
#if NABTO_ENABLE_EPOLL
        printf("      --select_based          Use select instead of epoll.\n");
#endif
#if NABTO_ENABLE_DYNAMIC_MEMORY
        printf("      --tunnels               Specify how many concurrent tcp streams should be possible.\n");
        printf("      --stream_window_size    Specify the stream window size, the larger the value the more memory the aplication will use, but higher throughput will be possible.\n");
        printf("      --connections           Specify the maximum number of allowed concurrent connections.\n");
#endif
#if NABTO_ENABLE_EXTENDED_RENDEZVOUS_MULTIPLE_SOCKETS
        printf("      --disable_extended_rendezvous_multiple_sockets     Disable multiple sockets in extended rendezvous.\n");
#endif
        exit(0);
    }

    if (gopt(options, 'V')) {
        printf("%d.%d\n", RELEASE_MAJOR, RELEASE_MINOR);
        exit(0);
    }

    if (gopt(options, 'C')) {
        unabto_printf_unabto_config(stdout, "unabto_tunnel");
        exit(0);
    }

    if (gopt(options, 'S')) {
        unabto_printf_memory_sizes(stdout, "unabto_tunnel");
        exit(0);
    }
    
    { 
        size_t optionsLength = gopt(options, 'l');
        int i;
        if (optionsLength > 0) {
            for (i = 0; i < optionsLength; i++) {
                optionString = gopt_arg_i(options, 'l', i);
                if (!unabto_log_system_enable_stdout_pattern(optionString)) {
                    NABTO_LOG_FATAL(("Logstring %s is not a valid logsetting", optionString));
                }
            }
        } else {
            unabto_log_system_enable_stdout_pattern("*.info");
        }
        
    } 
    

    if (!gopt_arg( options, 'd', &nms->id)) {
        NABTO_LOG_FATAL(("Specify a serverId with -d. Try -h for help."));
    }

    if(gopt_arg(options, 'H', &h)) {
        unabto_tunnel_tcp_set_default_host(h);
    }

    if (gopt_arg(options, 'P', &tunnel_port_str)) {
        if(1 != sscanf(tunnel_port_str, "%d", &p)) {
            NABTO_LOG_TRACE(("Reading of port parameter failed."));
        } else {
            unabto_tunnel_tcp_set_default_port(p);
        }
    }
     
    if( gopt_arg( options, 'p', &localPortStr) ){
        int localPort = atoi(localPortStr);
        nms->localPort = localPort;
    }


    if (gopt(options, 's')) {
        const char* preSharedKey;
        uint8_t key[16];
        memset(key, 0, 16);
        if ( gopt_arg( options, 'k', &preSharedKey)) {
            size_t i;
            size_t pskLen = strlen(preSharedKey);
            // read the pre shared key as a hexadecimal string.
            for (i = 0; i < pskLen/2 && i < 16; i++) {
                sscanf(preSharedKey+(2*i), "%02hhx", &key[i]);
            }
        }
        memcpy(nms->presharedKey,key,16);
        nms->cryptoSuite = CRYPT_W_AES_CBC_HMAC_SHA256;
        nms->secureAttach = true;
        nms->secureData = true;
    }

    if (gopt(options, 'a')) {
        check_acl = true;
    }

    if( gopt_arg( options, 'A', & basestationAddress ) ){
        addr = inet_addr(basestationAddress);
        if (addr == INADDR_NONE) {
            NABTO_LOG_FATAL(("Invalid basestation address"));
        }
        nms->controllerArg.addr = htonl(addr);
    }

    if (gopt(options, 'x')) {
        nice_exit = true;
    }
    
    ports_length = gopt(options, ALLOW_PORT_OPTION);
    if (ports_length > 0) {
        size_t i;
        ports = (uint16_t*) malloc(ports_length*sizeof(uint16_t));
        memset(ports,0,ports_length*sizeof(uint16_t));
        for (i = 0; i < ports_length; i++) {
            const char* opt = gopt_arg_i(options, ALLOW_PORT_OPTION, i);
            ports[i] = atoi(opt);
        }
    }
    
    hosts_length = gopt(options, ALLOW_HOST_OPTION);
    if (hosts_length > 0) {
        size_t i;
        hosts = (char**) malloc(hosts_length*sizeof(char*));
        for (i = 0; i < hosts_length; i++) {
            const char* opt = gopt_arg_i(options, ALLOW_HOST_OPTION, i);
            hosts[i] = strdup(opt);
        }
    }

    if (gopt(options, ALLOW_ALL_PORTS_OPTION)) {
        allow_all_ports = true;
    }

    if(gopt_arg(options, UART_DEVICE_OPTION, &uartDevice)) {
        uart_tunnel_set_default_device(uartDevice);
    } else {
        NABTO_LOG_TRACE(("Missing uart device option."));
        uartDevice = 0;
    }
    
#if NABTO_ENABLE_TCP_FALLBACK
    if (gopt(options, DISABLE_TCP_FALLBACK_OPTION)) {
        nms->enableTcpFallback = false;
    }
#endif

    if (gopt_arg(options, CONTROLLER_PORT_OPTION, &controllerPort)) {
        nms->controllerArg.port = atoi(controllerPort);
    }

#if NABTO_ENABLE_EPOLL
    if (gopt(options, SELECT_BASED_OPTION)) {
        useSelectBased = true;
    }
#endif

#if NABTO_ENABLE_DYNAMIC_MEMORY
    if (gopt_arg(options, TUNNELS_OPTION, &tunnelsOption)) {
        nms->streamMaxStreams = atoi(tunnelsOption);
    }

    if (gopt_arg(options, STREAM_WINDOW_SIZE_OPTION, &streamWindowSizeOption)) {
        uint16_t windowSize = atoi(streamWindowSizeOption);
        nms->streamReceiveWindowSize = windowSize;
        nms->streamSendWindowSize = windowSize;
    }

    if (gopt_arg(options, CONNECTIONS_SIZE_OPTION, &connectionsOption)) {
        nms->connectionsSize = atoi(connectionsOption);
    }
#endif

#if NABTO_ENABLE_EXTENDED_RENDEZVOUS_MULTIPLE_SOCKETS
    if (gopt(options, DISABLE_EXTENDED_RENDEZVOUS_MULTIPLE_SOCKETS)) {
        nms->enableExtendedRendezvousMultipleSockets = false;
    }
#endif

    return true;
}
static bool parse_args(int argc, char* argv[])
{
    const char x1s[] = "h";      const char* x1l[] = { "help", 0 };
    const char x21s[] = "l";     const char* x21l[] = { "nabtolog", 0 };
    const char x30s[] = "";      const char* x30l[] = { "rangestart", 0 };
    const char x31s[] = "";      const char* x31l[] = { "rangeend", 0 };
    const char x32s[] = "";      const char* x32l[] = { "basename", 0 };
    const char x33s[] = "";      const char* x33l[] = { "random-local-address", 0 };
    
    const char *option;

    const struct { int k; int f; const char *s; const char*const* l; } opts[] = {
        { OPTION_HELP, GOPT_NOARG,           x1s,  x1l  },
        { OPTION_LOG,  GOPT_REPEAT|GOPT_ARG, x21s, x21l },
        { OPTION_RANGE_START, GOPT_ARG, x30s, x30l},
        { OPTION_RANGE_END, GOPT_ARG, x31s, x31l},
        { OPTION_BASENAME, GOPT_ARG, x32s, x32l},
        { OPTION_RANDOM_LOCAL_ADDRESS, GOPT_NOARG, x33s, x33l },
        {0,0,0,0}
    };
    
    void *options = gopt_sort( & argc, (const char**)argv, opts);
    
    if (gopt(options, OPTION_HELP)) {
        help();
        exit(0);
    }
    
    if (gopt_arg( options, OPTION_BASENAME, &base_name)) {
        
    }
    
    if (gopt_arg(options, OPTION_RANGE_START, &option)) {
        range_start = atoi(option);
    }
    
    if (gopt_arg(options, OPTION_RANGE_END, &option)) {
        range_end = atoi(option);
    }
    
    { 
        const char* optionString;
        size_t optionsLength = gopt(options, OPTION_LOG);
        int i;
        if (optionsLength > 0) {
            for (i = 0; i < optionsLength; i++) {
                optionString = gopt_arg_i(options, OPTION_LOG, i);
                if (!unabto_log_system_enable_stdout_pattern(optionString)) {
                    NABTO_LOG_FATAL(("Logstring %s is not a valid logsetting", optionString));
                }
            }
        } else {
            unabto_log_system_enable_stdout_pattern("*.info");
        }
        
    }

    if (gopt(options, OPTION_RANDOM_LOCAL_ADDRESS)) {
        random_local_address = true;
    }
    
    return true;
}
Ejemplo n.º 7
0
int main(int argc, const char **argv) {
	FILE *fdin, *fdout;
	char ch;
	int cid, secu_flag, sim_unlock, verify = 0;
	const char* s_secu_flag;
	const char* s_cid;

	if (argc>1) {

		void *options= gopt_sort( & argc, argv, gopt_start(
		  gopt_option( 'h', 0, gopt_shorts( 'h', '?' ), gopt_longs( "help", "HELP" )),
		  gopt_option( 'v', 0, gopt_shorts( 'v' ), gopt_longs( "version" )),
		  gopt_option( 's', GOPT_ARG, gopt_shorts( 's' ), gopt_longs( "secu_flag" )),
		  gopt_option( 'c', GOPT_ARG, gopt_shorts( 'c' ), gopt_longs( "cid" )),
		  gopt_option( 'S', 0, gopt_shorts( 'S' ), gopt_longs( "sim_unlock" )),
		  gopt_option( 'V', 0, gopt_shorts( 'V' ), gopt_longs( "verify" ))));
		/*
		* there are possible options to this program, some of which have multiple names:
		*
		* -h -? --help --HELP
		* -v --version
		* -s --secu_flag	(which requires an option argument on|off)
		* -c --cid			(which requires an option 8-character string argument <CID>)
		* -S --sim_unlock
		*/

		if( gopt( options, 'h' ) ){
			//if any of the help options was specified
			fprintf( stdout, "gfree usage:\n" );
			fprintf( stdout, "gfree [-h|-?|--help] [-v|--version] [-s|--secu_flag on|off]\n" );
			fprintf( stdout, "\t-h | -? | --help: display this message\n" );
			fprintf( stdout, "\t-v | --version: display program version\n" );
			fprintf( stdout, "\t-s | --secu_flag on|off: turn secu_flag on or off\n" );
			fprintf( stdout, "\t-c | --cid <CID>: set the CID to the 8-char long CID\n" );
			fprintf( stdout, "\t-S | --sim_unlock: remove the SIMLOCK\n" );
			fprintf( stdout, "\t-V | --verify: verify the CID, secu_flag, SIMLOCK\n" );
			fprintf( stdout, "\n" );
			fprintf( stdout, "calling gfree without arguments is the same as calling it:\n" );
			fprintf( stdout, "\tgfree --secu_flag off --sim_unlock --cid 11111111\n" );
			exit( 0 );
		}

		if( gopt( options, 'v' ) ){
			//if any of the version options was specified
			fprintf( stdout, "gfree version: %d.%d\n",VERSION_A,VERSION_B);
			exit (0);
		}

		if( gopt_arg(options, 's', &s_secu_flag)){
			// if -s or --secu_flag was specified, check s_secu_flag
			if (strcmp(s_secu_flag, "on")==0){
				secu_flag = 1;
				fprintf( stdout, "--secu_flag on set\n");
			} else if (strcmp(s_secu_flag, "off")==0){
				secu_flag = 2;
				fprintf( stdout, "--secu_flag off set\n");
			}
		}

		if( gopt_arg(options, 'c', &s_cid)){
			// if -c or --cid was specified, check s_cid
			size_t size;
			size = strlen(s_cid);
			if (size!=8){
				fprintf( stderr, "Error: CID must be a 8 character string. Length of specified string: %d\n",(int)size);
				exit (1);
			} else {
				cid = 1;
				fprintf( stdout, "--cid set. CID will be changed to: %s\n",s_cid);
			}
		}

		if( gopt( options, 'S' ) ){
			//if any of the sim_unlock options was specified
			sim_unlock = 1;
			fprintf( stdout, "--sim_unlock. SIMLOCK will be removed\n");
		}

		if( gopt( options, 'V' ) ){
			//if any of the sim_unlock options was specified
			verify = 1;
			fprintf( stdout, "--verify. CID, secu_flag, SIMLOCK will be verified\n");
		}

	} else {
		secu_flag = 2;
		fprintf( stdout, "--secu_flag off set\n");
		cid = 1;
		s_cid = "11111111";
		fprintf( stdout, "--cid set. CID will be changed to: %s\n",s_cid);
		sim_unlock = 1;
		fprintf( stdout, "--sim_unlock. SIMLOCK will be removed\n");
	}

	// if verify is set just verify and exit
	if (verify==1){
		if (verify_init_device()!=0){
			fprintf( stderr, "Error: verify could not initialize device!");
			exit (-1);
		}
		if (verify_init_modem()!=0){
			fprintf( stderr, "Error: verify could not initialize radio!");
			exit (-1);
		}
		verify_set_verbose();
		verify_cid();
		verify_secu_flag();
		verify_simlock();
		verify_close_device();
		exit (0);
	}

	fdin = fopen(INFILE, "rb");
	if (fdin == NULL){
		printf("Error opening input file.\n");
		return -1;
	}

	fdout = fopen(CPYFILE, "wb");
	if (fdout == NULL){
		printf("Error opening copy file.\n");
		return -1;
	}

//  create a copy of the partition
	while(!feof(fdin)) {
	    ch = fgetc(fdin);
	    if(ferror(fdin)) {
	      printf("Error reading input file.\n");
	      exit(1);
	    }
	    if(!feof(fdin)) fputc(ch, fdout);
	    if(ferror(fdout)) {
	      printf("Error writing copy file.\n");
	      exit(1);
	    }
	}
	if(fclose(fdin)==EOF) {
		printf("Error closing input file.\n");
		exit(1);
	}

	if(fclose(fdout)==EOF) {
		printf("Error closing copy file.\n");
		exit(1);
	}

//  copy back and patch
	long i;

	fdin = fopen(CPYFILE, "rb");
	if (fdin == NULL){
		printf("Error opening copy file.\n");
		return -1;
	}

	fdout = fopen(OUTFILE, "wb");
	if (fdout == NULL){
		printf("Error opening output file.\n");
		return -1;
	}

	i = 0;

	while(!feof(fdin)) {
	    ch = fgetc(fdin);
	    if(ferror(fdin)) {
	      printf("Error reading copy file.\n");
	      exit(1);
	    }
	    // secu_flag
	    if (i==0xa00 && secu_flag!=0) {
	    	ch = secu_flag==2 ? 0x00 : 0x01;
	    }
	    // CID
	    if ((i>=0x200 && i<=0x207)&& (cid!=0)) {
	    	ch = s_cid[i-0x200];
	    }
	    // SIM LOCK
	    if (sim_unlock!=0){
			if ((i>0x80003 && i<0x807fc) || (i>=0x80800 && i<=0x82fff)){
				ch = 0x00;
			} else if (i==0x80000) {
				ch = 0x78;
			} else if (i==0x80001) {
				ch = 0x56;
			} else if (i==0x80002) {
				ch = 0xF3;
			} else if (i==0x80003) {
				ch = 0xC9;
			} else if (i==0x807fc) {
				ch = 0x49;
			} else if (i==0x807fd) {
				ch = 0x53;
			} else if (i==0x807fe) {
				ch = 0xF4;
			} else if (i==0x807ff) {
				ch = 0x7D;
			}
	    }
		if(!feof(fdin)) fputc(ch, fdout);
		if(ferror(fdout)) {
		  printf("Error writing output file.\n");
		  exit(1);
		}
		i++;
	}
	if(fclose(fdin)==EOF) {
		printf("Error closing copy file.\n");
		exit(1);
	}

	if(fclose(fdout)==EOF) {
		printf("Error closing output file.\n");
		exit(1);
	}

	return 0;
}
Ejemplo n.º 8
0
int main(int argc, const char **argv)
{
	int i=0; /* holds the return (read bytes) from fread() */
	int nc=0; /* Sum of read bytes. */
	int loopc=0; /* number of loop iterations */
	char inbuf[BUFLEN+1]; /* Input-buffer */
	const char *out_filename =0; 
	const char *str_address, *str_port, *str_address_family;
	FILE *fout;
	int af=0;
	int fd_sock, fd_in;
	socklen_t sa_len;
	struct sockaddr *sa;
	struct sockaddr_in ip4_sa;


	void *options= gopt_sort( &argc, argv, gopt_start(
					  gopt_option( 'h', 0, gopt_shorts( 'h', '?' ), gopt_longs( "help", "HELP" )),
					  gopt_option( 'o', GOPT_ARG, gopt_shorts( 'o' ), gopt_longs( "out" )), 
					  gopt_option( 'a', GOPT_ARG, gopt_shorts( 0 ), gopt_longs( "address" )),
					  gopt_option( 't', GOPT_ARG, gopt_shorts( 0 ), gopt_longs( "address_family", "af" )),
					  gopt_option( 'p', GOPT_ARG, gopt_shorts( 'p' ), gopt_longs( "port" )) 
					  ));

	if( gopt( options, 'h' ) ) {
		/*
		 * if any of the help options was specified
		 */
		fprintf( stdout, "Usage: sender  \n" );
		fprintf( stdout, "              [-o file| --out file] \n" );
		fprintf( stdout, "\n" );
		fprintf( stdout, "Report bugs to <javier at ubillos.org>.\n" );
		exit( EXIT_SUCCESS );
	}
	
        /* If we have specified an output file, or it is specified to "-" */
	
	if( !gopt_arg( options, 'p', &str_port ) || 
	    !gopt_arg( options, 't', &str_address_family) ) {
		fprintf(stderr, "To use \"network\" as an output, --port and --af need to be specified\n");
		exit( EXIT_FAILURE );	
	}

	str_address = 0;
	gopt_arg( options, 'a', &str_address );
	
	if( 0 == strcmp("AF_INET", str_address_family) ) {

		ip4_sa.sin_family = af = AF_INET;
		memset(&ip4_sa, 0, sizeof(ip4_sa));
		sa = (struct sockaddr *)&ip4_sa;
		
		ip4_sa.sin_port = htons(atoi(str_port));
		
		if( gopt_arg( options, 'a', &str_address) ) {
			fprintf(stderr, "ERROR binding to specific address not yet supported.\n");
			exit( EXIT_FAILURE );
		}
		else {
			ip4_sa.sin_addr.s_addr = INADDR_ANY;
		}	  

		if( 0 > (fd_sock = socket(AF_INET, SOCK_STREAM, 0)) ) {
			perror("ERROR opening socket\n");
			exit( EXIT_FAILURE );
		}
		ip4_sa.sin_port = htons(atoi(str_port));

		fprintf(stderr, "bind()\n");
		if( 0 > bind(fd_sock, (struct sockaddr *)&ip4_sa, sizeof(ip4_sa)) ) {
			perror("ERROR could not bind\n");
			exit( EXIT_FAILURE );	
		}
		fprintf(stderr, "listen()\n");
		if( 0 > listen(fd_sock,5) ) {
			perror("ERROR could not listen\n");
			exit( EXIT_FAILURE );	
		}


	}
	else {
		fprintf(stderr, "Address family: %s is not a supported address family\n", str_address_family);
		exit( EXIT_FAILURE );	
	}

	if ( gopt_arg( options, 'o', &out_filename ) && strcmp( out_filename, "-" ) ) {
		fout = fopen( out_filename, "wb" );
		
		if( ! fout ) {
			fprintf(stderr, "Could not open output (-o/--out) file.\n");
			exit( EXIT_FAILURE );
		}
	}
        /* If we have not specified an output file, or it is specified to "-" */
	else { 
		fout = stdout;
	}

	/* Prepare (zero) the data-buffer */
	memset(inbuf, 0, BUFLEN+1);


	while(1) {
		sa_len = sizeof(ip4_sa);
		fprintf(stderr, "accept()\n");
		if ( 0 > (fd_in = accept(fd_sock, (struct sockaddr *)&ip4_sa, &sa_len)) )  {
			perror( "ERROR accept failed\n");
			exit( EXIT_FAILURE );
		}
		fprintf(stderr, "read()\n");
		while( 0 < (i = read(fd_in, inbuf, BUFLEN )) ) {
			fprintf(stderr, "loopc: %d\n", loopc);
			nc += i;
			fprintf(stderr, "Read characters: i:%d, %s\n", i, inbuf);
			/* Output to stdout */
			fwrite(inbuf, sizeof(char), i, fout);
		}
	}


	fprintf(stderr, "Counted characters: %d\n", nc);

	return EXIT_SUCCESS;
}
Ejemplo n.º 9
0
int main(int argc, const char *argv[]) {
    
    const char* argument;
    
    long int initial_timestamp;
    float initial_lat, initial_lng, initial_alt;
    float burst_alt, ascent_rate, drag_coeff, rmswinderror;
    int descent_mode;
    int scenario_idx, n_scenarios;
    int alarm_time;
    char* endptr;       // used to check for errors on strtod calls 
    
    wind_file_cache_t* file_cache;
    dictionary*        scenario = NULL;
    
    // configure command-line options parsing
    void *options = gopt_sort(&argc, argv, gopt_start(
        gopt_option('h', 0, gopt_shorts('h', '?'), gopt_longs("help")),
        gopt_option('z', 0, gopt_shorts(0), gopt_longs("version")),
        gopt_option('v', GOPT_REPEAT, gopt_shorts('v'), gopt_longs("verbose")),
        gopt_option('o', GOPT_ARG, gopt_shorts('o'), gopt_longs("output")),
        gopt_option('k', GOPT_ARG, gopt_shorts('k'), gopt_longs("kml")),
        gopt_option('t', GOPT_ARG, gopt_shorts('t'), gopt_longs("start_time")),
        gopt_option('i', GOPT_ARG, gopt_shorts('i'), gopt_longs("data_dir")),
        gopt_option('d', 0, gopt_shorts('d'), gopt_longs("descending")),
        gopt_option('e', GOPT_ARG, gopt_shorts('e'), gopt_longs("wind_error")),
        gopt_option('a', GOPT_ARG, gopt_shorts('a'), gopt_longs("alarm"))
    ));

    if (gopt(options, 'h')) {
        // Help!
        // Print usage information
        printf("Usage: %s [options] [scenario files]\n", argv[0]);
        printf("Options:\n\n");
        printf(" -h --help               Display this information.\n");
        printf(" --version               Display version information.\n");
        printf(" -v --verbose            Display more information while running,\n");
        printf("                           Use -vv, -vvv etc. for even more verbose output.\n");
        printf(" -t --start_time <int>   Start time of model, defaults to current time.\n");
        printf("                           Should be a UNIX standard format timestamp.\n");
        printf(" -o --output <file>      Output file for CSV data, defaults to stdout. Overrides scenario.\n");
        printf(" -k --kml <file>         Output KML file.\n");
        printf(" -d --descending         We are in the descent phase of the flight, i.e. after\n");
        printf("                           burst or cutdown. burst_alt and ascent_rate ignored.\n");
        printf(" -i --data_dir <dir>     Input directory for wind data, defaults to current dir.\n\n");
        printf(" -e --wind_error <err>   RMS windspeed error (m/s).\n");
        printf(" -a --alarm <seconds>    Use alarm() to kill pred incase it hangs.\n");
        printf("The scenario file is an INI-like file giving the launch scenario. If it is\n");
        printf("omitted, the scenario is read from standard input.\n");
      exit(0);
    }

    if (gopt(options, 'z')) {
      // Version information
      printf("Landing Prediction version: %s\nCopyright (c) CU Spaceflight 2009\n", VERSION);
      exit(0);
    }

    if (gopt_arg(options, 'a', &argument) && strcmp(argument, "-")) {
      alarm_time = strtol(argument, &endptr, 0);
      if (endptr == argument) {
        fprintf(stderr, "ERROR: %s: invalid alarm length\n", argument);
        exit(1);
      }
      alarm(alarm_time);
    }
    
    verbosity = gopt(options, 'v');
    
    if (gopt(options, 'd'))
        descent_mode = DESCENT_MODE_DESCENDING;
    else
        descent_mode = DESCENT_MODE_NORMAL;
      
    if (gopt_arg(options, 'k', &argument) && strcmp(argument, "-")) {
      kml_file = fopen(argument, "wb");
      if (!kml_file) {
        fprintf(stderr, "ERROR: %s: could not open KML file for output\n", argument);
        exit(1);
      }
    }
    else
      kml_file = NULL;

    if (gopt_arg(options, 't', &argument) && strcmp(argument, "-")) {
      initial_timestamp = strtol(argument, &endptr, 0);
      if (endptr == argument) {
        fprintf(stderr, "ERROR: %s: invalid start timestamp\n", argument);
        exit(1);
      }
    } else {
      initial_timestamp = time(NULL);
    }
    
    if (!(gopt_arg(options, 'i', &data_dir) && strcmp(data_dir, "-")))
      data_dir = "./";


    // populate wind data file cache
    file_cache = wind_file_cache_new(data_dir);

    // read in flight parameters
    n_scenarios = argc - 1;
    if(n_scenarios == 0) {
        // we'll parse from std in
        n_scenarios = 1;
    }

    for(scenario_idx = 0; scenario_idx < n_scenarios; ++scenario_idx) {
        char* scenario_output = NULL;

        if(argc > scenario_idx+1) {
            scenario = iniparser_load(argv[scenario_idx+1]);
        } else {
            scenario = iniparser_loadfile(stdin);
        }

        if(!scenario) {
            fprintf(stderr, "ERROR: could not parse scanario file.\n");
            exit(1);
        }

        if(verbosity > 1) {
            fprintf(stderr, "INFO: Parsed scenario file:\n");
            iniparser_dump_ini(scenario, stderr);
        }

        scenario_output = iniparser_getstring(scenario, "output:filename", NULL);

        if (gopt_arg(options, 'o', &argument) && strcmp(argument, "-")) {
            if(verbosity > 0) {
                fprintf(stderr, "INFO: Writing output to file specified on command line: %s\n", argument);
            }
            output = fopen(argument, "wb");
            if (!output) {
                fprintf(stderr, "ERROR: %s: could not open CSV file for output\n", argument);
                exit(1);
            }
        } else if (scenario_output != NULL) {
            if(verbosity > 0) {
                fprintf(stderr, "INFO: Writing output to file specified in scenario: %s\n", scenario_output);
            }
            output = fopen(scenario_output, "wb");
            if (!output) {
                fprintf(stderr, "ERROR: %s: could not open CSV file for output\n", scenario_output);
                exit(1);
            }
        } else {
            if(verbosity > 0) {
                fprintf(stderr, "INFO: Writing output to stdout.\n");
            }
            output = stdout;
        }

        // write KML header
        if (kml_file)
            start_kml();

        // The observant amongst you will notice that there are default values for
        // *all* keys. This information should not be spread around too well.
        // Unfortunately, this means we lack some error checking.

        initial_lat = iniparser_getdouble(scenario, "launch-site:latitude", 0.0);
        initial_lng = iniparser_getdouble(scenario, "launch-site:longitude", 0.0);
        initial_alt = iniparser_getdouble(scenario, "launch-site:altitude", 0.0);

        ascent_rate = iniparser_getdouble(scenario, "altitude-model:ascent-rate", 1.0);

        // The 1.1045 comes from a magic constant buried in
        // ~cuspaceflight/public_html/predict/index.php.
        drag_coeff = iniparser_getdouble(scenario, "altitude-model:descent-rate", 1.0) * 1.1045;

        burst_alt = iniparser_getdouble(scenario, "altitude-model:burst-altitude", 1.0);

        rmswinderror = iniparser_getdouble(scenario, "atmosphere:wind-error", 0.0);
        if(gopt_arg(options, 'e', &argument) && strcmp(argument, "-")) {
            rmswinderror = strtod(argument, &endptr);
            if (endptr == argument) {
                fprintf(stderr, "ERROR: %s: invalid RMS wind speed error\n", argument);
                exit(1);
            }
        }

        {
            int year, month, day, hour, minute, second;
            year = iniparser_getint(scenario, "launch-time:year", -1);
            month = iniparser_getint(scenario, "launch-time:month", -1);
            day = iniparser_getint(scenario, "launch-time:day", -1);
            hour = iniparser_getint(scenario, "launch-time:hour", -1);
            minute = iniparser_getint(scenario, "launch-time:minute", -1);
            second = iniparser_getint(scenario, "launch-time:second", -1);

            if((year >= 0) && (month >= 0) && (day >= 0) && (hour >= 0)
                    && (minute >= 0) && (second >= 0)) 
            {
                struct tm timeval = { 0 };
                time_t scenario_launch_time = -1;

                if(verbosity > 0) {
                    fprintf(stderr, "INFO: Using launch time from scenario: "
                            "%i/%i/%i %i:%i:%i\n",
                            year, month, day, hour, minute, second);
                }

                timeval.tm_sec = second;
                timeval.tm_min = minute;
                timeval.tm_hour = hour;
                timeval.tm_mday = day; /* 1 - 31 */
                timeval.tm_mon = month - 1; /* 0 - 11 */
                timeval.tm_year = year - 1900; /* f**k you Millenium Bug! */

#ifndef _BSD_SOURCE
#               warning This version of mktime does not allow explicit setting of timezone. 
#else
                timeval.tm_zone = "UTC";
#endif

                scenario_launch_time = mktime(&timeval);
                if(scenario_launch_time <= 0) {
                    fprintf(stderr, "ERROR: Launch time in scenario is invalid\n");
                    exit(1);
                } else {
                    initial_timestamp = scenario_launch_time;
                }
            }
        }

        if(verbosity > 0) {
            fprintf(stderr, "INFO: Scenario loaded:\n");
            fprintf(stderr, "    - Initial latitude  : %lf deg N\n", initial_lat);
            fprintf(stderr, "    - Initial longitude : %lf deg E\n", initial_lng);
            fprintf(stderr, "    - Initial altitude  : %lf m above sea level\n", initial_alt);
            fprintf(stderr, "    - Initial timestamp : %li\n", initial_timestamp);
            fprintf(stderr, "    - Drag coeff.       : %lf\n", drag_coeff);
            if(!descent_mode) {
                fprintf(stderr, "    - Ascent rate       : %lf m/s\n", ascent_rate);
                fprintf(stderr, "    - Burst alt.        : %lf m\n", burst_alt);
            }
            fprintf(stderr, "    - Windspeed err.    : %f m/s\n", rmswinderror);
        }
        
        {
            // do the actual stuff!!
            altitude_model_t* alt_model = altitude_model_new(descent_mode, burst_alt, 
                                                             ascent_rate, drag_coeff);
            if(!alt_model) {
                    fprintf(stderr, "ERROR: error initialising altitude profile\n");
                    exit(1);
            }

            if (!run_model(file_cache, alt_model, 
                           initial_lat, initial_lng, initial_alt, initial_timestamp,
                           rmswinderror)) {
                    fprintf(stderr, "ERROR: error during model run!\n");
                    exit(1);
            }

            altitude_model_free(alt_model);
        }

        // release the scenario
        iniparser_freedict(scenario);
        
        // write footer to KML and close output files
        if (kml_file) {
            finish_kml();
            fclose(kml_file);
        }

        if (output != stdout) {
            fclose(output);
        }
    }

    // release gopt data, 
    gopt_free(options);

    // release the file cache resources.
    wind_file_cache_free(file_cache);

    return 0;
}
Ejemplo n.º 10
0
enum tc_opt_mode tc_opt_init(struct tc_opt *opt, int argc, char **argv)
{
	/* usage */
	void *tc_options = gopt_sort(&argc, (const char**)argv, tc_options_def);
	if (gopt(tc_options, '?')) {
		opt->mode = TC_OPT_USAGE;
		goto done;
	}

	/* version */
	if (gopt(tc_options, 'v')) {
		opt->mode = TC_OPT_VERSION;
		goto done;
	}

	/* server host */
	gopt_arg(tc_options, 'h', &opt->host);
	if (opt->host == NULL)
		opt->host = TC_DEFAULT_HOST;

	/* server port */
	const char *arg = NULL;
	opt->port = 0;
	if (gopt_arg(tc_options, 'p', &arg))
		opt->port = atoi(arg);

	/* server admin port */
	opt->port_admin = TC_DEFAULT_PORT_ADMIN;
	if (gopt_arg(tc_options, 'a', &arg))
		opt->port_admin = atoi(arg);

	/* space */
	opt->space = 0;
	opt->space_set = 0;
	if (gopt_arg(tc_options, 'S', &arg)) {
		opt->space = atoi(arg);
		opt->space_set = 1;
	}

	/* from lsn */
	opt->lsn_from = 0;
	if (gopt_arg(tc_options, 'F', &arg)) {
		opt->lsn_from = strtoll(arg, NULL, 10);
		opt->lsn_from_set = 1;
	}

	/* to lsn */
	opt->lsn_to = 0;
	if (gopt_arg(tc_options, 'T', &arg)) {
		opt->lsn_to = strtoll(arg, NULL, 10);
		opt->lsn_to_set = 1;
	}

	/* output format */
	opt->raw = 0;
	opt->format = NULL;
	if (gopt_arg(tc_options, 'M', &arg))
		opt->format = arg;

	opt->raw_with_headers = 0;
	if (gopt(tc_options, 'H'))
		opt->raw_with_headers = 1;

	/* string instead of num and num64 */
	opt->str_instead_int = 0;
	if (gopt(tc_options, 'B'))
		opt->str_instead_int = 1;

	/* set delimiter on start */
	opt->delim = "";
	opt->delim_len = 0;
	if (gopt_arg(tc_options, 'D', &opt->delim))
		opt->delim_len = strlen(opt->delim);

	/* replica mode */
	if (gopt_arg(tc_options, 'R', &arg)) {
		opt->mode = TC_OPT_RPL;
		opt->lsn = strtoll(arg, NULL, 10);
		goto done;
	}

	/* wal-cat mode */
	if (gopt_arg(tc_options, 'C', &opt->file)) {
		opt->mode = TC_OPT_WAL_CAT;
		if (strcmp(opt->file, "-") == 0)
			opt->file = NULL;
		goto done;
	}

	/* wal-play mode */
	if (gopt_arg(tc_options, 'P', &opt->file)) {
		opt->mode = TC_OPT_WAL_PLAY;
		goto done;
	}

	/* default */
	if (argc >= 2) {
		opt->cmdv = argv + 1;
		opt->cmdc = argc - 1;
		opt->mode = TC_OPT_CMD;
	} else {
		opt->mode = TC_OPT_INTERACTIVE;
	}
done:
	gopt_free(tc_options);
	return opt->mode;
}
bool check_args(int argc, char* argv[], nabto_main_setup *nms)
{
    const char *address;
    const char *basestationAddress;
    const char *preSharedKey;
    const char *localPortStr;
    const char *bufferSizeStr;
    const char *idParam;
    const char *interfaceParam;
    const char *htmlddurloverride;
    uint32_t addr;
    const char *progname;
#ifdef WIN32
    char modulename[MAX_PATH];
#endif

    
    const char x0s[] = "h?";     const char* x0l[] = { "help", "HELP", 0 };
    const char x1s[] = "a";      const char* x1l[] = { "localAddress", 0 };
    const char x2s[] = "d";      const char* x2l[] = { "deviceName", 0 };
    const char x3s[] = "l";      const char* x3l[] = { "log", 0 };
    const char x4s[] = "A";      const char* x4l[] = { "controllerAddress", 0 };
    const char x5s[] = "p";      const char* x5l[] = { "localport", 0 };
    const char x6s[] = "b";      const char* x6l[] = { "buffersize", 0 };
    const char x7s[] = "k";      const char* x7l[] = { "presharedkey", 0 };
    const char x8s[] = "s";      const char* x8l[] = { "securedevice", 0 };
    const char x9s[] = "n";      const char* x9l[] = { "datanullencrypted", 0 };
    const char x10s[] = "i";     const char* x10l[] = { "interface", 0 };
    const char x11s[] = "U";     const char* x11l[] = { "htmlddurloverride", 0 };
    const char x12s[] = "V";     const char* x12l[] = { "version", 0 };
    const char x13s[] = "C";     const char* x13l[] = { "config", 0 };
    const char x14s[] = "S";     const char* x14l[] = { "size", 0 };

    const struct { int k; int f; const char *s; const char*const* l; } opts[] = {
        { 'h', 0,           x0s, x0l },
        { 'a', GOPT_ARG,    x1s, x1l },
        { 'd', GOPT_ARG,    x2s, x2l },
        { 'l', GOPT_REPEAT, x3s, x3l },
        { 'A', GOPT_ARG,    x4s, x4l },
        { 'p', GOPT_ARG,    x5s, x5l },
        { 'b', GOPT_ARG,    x6s, x6l },
        { 'k', GOPT_ARG,    x7s, x7l },
        { 's', 0,           x8s, x8l },
        { 'n', 0,           x9s, x9l },
        { 'i', GOPT_ARG,    x10s, x10l },
        { 'U', GOPT_ARG,    x11s, x11l },
        { 'V', GOPT_NOARG,  x12s, x12l },
        { 'C', GOPT_NOARG,  x13s, x13l },
        { 'S', GOPT_NOARG,  x14s, x14l },
        { 0,0,0,0 }
    };

    void *options = gopt_sort( & argc, (const char**)argv, opts);

#ifdef WIN32
    modulename[0] = 0;
    GetModuleFileNameA(NULL, modulename, sizeof(modulename));
    progname = strrchr(modulename, '\\');
    if (!progname)
        progname = modulename;
    else
        progname++;
#else
    progname = strrchr(argv[0], '/');
    if (!progname)
        progname = argv[0];
    else
        progname++;
#endif

    if( gopt( options, 'h')) {
        help("Help", progname);
        return false;
    }
    
    if (gopt(options, 'V')) {
        fprintf(stdout, "%d.%d\n", RELEASE_MAJOR, RELEASE_MINOR);
        return false;
    }

    if( gopt( options, 'C')) {
        unabto_printf_unabto_config(stdout, progname);
        return false;
    }
    
    if (gopt(options, 'S')) {
        unabto_printf_memory_sizes(stdout, progname);
        return false;
    }

    if( gopt_arg( options, 'a', & address ) ){
        addr = inet_addr(address);
        if (addr == INADDR_NONE) {
            help("Illegal local address", progname);
            gopt_free(options);
            return false;
        }
		nms->ipAddress = htonl(addr);
    } 

    if( gopt_arg( options, 'd', &idParam ) ){
        nms->id = strdup(idParam);
    } else {
        help("You must specify an id for your uNabto device", progname);
        gopt_free(options);
        return false;
    }

    if( gopt_arg( options, 'p', &localPortStr) ){
		nms->localPort = atoi(localPortStr);
    }

    if( gopt_arg( options, 'b', &bufferSizeStr) ){
        nms->bufsize = (size_t)atoi(bufferSizeStr);
    }

    if( gopt_arg( options, 'A', & basestationAddress ) ){
        addr = inet_addr(basestationAddress);
        if (addr == INADDR_NONE) {
            help("Illegal basestation address", progname);
            gopt_free(options);
            return false;
        }
        nms->controllerArg.addr = htonl(addr);
    }

    if ( gopt_arg( options, 'k', &preSharedKey)) {
        size_t i;
        size_t pskLen = strlen(preSharedKey);
        // read the pre shared key as a hexadecimal string.
        for (i = 0; i < pskLen/2 && i < 16; i++) {
            sscanf_s(preSharedKey+(2*i), "%02hhx", &nms->presharedKey[i]);
        }
    }

    if (gopt(options, 's')) {
        nms->secureAttach= true;
        nms->secureData = true;
#if NABTO_ENABLE_CONNECTIONS
        nms->cryptoSuite = CRYPT_W_AES_CBC_HMAC_SHA256;
#endif
    }
    if (gopt(options, 'n')) {
        nms->secureData = false;
    }

    if (gopt_arg(options, 'i', &interfaceParam)) {
        nms->interfaceName = strdup(interfaceParam);
    }

    if (gopt_arg(options, 'U', &htmlddurloverride)) {
        nms->url = strdup(htmlddurloverride);
    }

    gopt_free(options);
    
    return true;
}
Ejemplo n.º 12
0
int main(int argc, const char **argv) {
    int status, i;

    bool verbose = false;
    bool no_run = false;

    const char *prefix_option;
    const char *suite_option = NULL;
    const char *tmp;

    atexit(cleanup);

    options = gopt_sort(&argc, argv, gopt_start(
                                                      gopt_option('x', 
                                                                  GOPT_ARG, 
                                                                  gopt_shorts('x'), 
                                                                  gopt_longs("xml")
                                                                  ),
                                                      gopt_option('s', 
                                                                  GOPT_ARG, 
                                                                  gopt_shorts('s'), 
                                                                  gopt_longs("suite")
                                                                  ),
                                                      gopt_option('v',
                                                                  GOPT_NOARG,
                                                                  gopt_shorts('v'),
                                                                  gopt_longs("verbose")
                                                                  ),
                                                      gopt_option('c',
                                                                  GOPT_NOARG,
                                                                  gopt_shorts('c'),
                                                                  gopt_longs("colours")
                                                                  ),
                                                      gopt_option('c',
                                                                  GOPT_NOARG,
                                                                  gopt_shorts('c'),
                                                                  gopt_longs("colors")
                                                                  ),
                                                      gopt_option('n',
                                                                  GOPT_NOARG,
                                                                  gopt_shorts('n'),
                                                                  gopt_longs("no-run")
                                                                  ),
                                                      gopt_option('h',
                                                                  GOPT_NOARG,
                                                                  gopt_shorts('h'),
                                                                  gopt_longs("help")
                                                                  )
                                                      )
                              );

    if (gopt_arg(options, 'x', &prefix_option))
        reporter = create_xml_reporter(prefix_option);
    else
        reporter = create_text_reporter();
    
    gopt_arg(options, 's', &suite_option);

    if (gopt_arg(options, 'v', &tmp))
        verbose = true;

    if (gopt_arg(options, 'n', &tmp))
        no_run = true;

    if (gopt_arg(options, 'c', &tmp))
        reporter_options.use_colours = true;
    else
        reporter_options.use_colours = false;

    if (gopt_arg(options, 'h', &tmp)) {
        usage(argv);
        return EXIT_SUCCESS;
    }

    if (argc < 2) {
        usage(argv);
        return EXIT_FAILURE;
    }


    set_reporter_options(reporter, &reporter_options);

    i = 1;
    while(i < argc) {
        const char *suite_name = suite_option;
        const char *test_name = NULL;
        const char *test_library = argv[i++];

        if (!file_exists(test_library)) {
            printf("Couldn't find library: %s\n", test_library);
            return EXIT_FAILURE;
        }

        suite_name = get_a_suite_name(suite_option, test_library);

        /* Check if the next argument is not a filename, thus a test name */
        if (!file_exists(argv[i])) {
            test_name = argv[i++];
        }

        status = runner(reporter, test_library, suite_name, test_name, verbose, no_run);
        if (status != 0) {
            printf("Library %s resulted in error status: %i\n", test_library, status);
            return status;
        }
    }
    
    return EXIT_SUCCESS;
}
Ejemplo n.º 13
0
int main(int argc, const char* argv[]) {
    void *options = gopt_sort(&argc, argv, gopt_start(
            gopt_option('h', 0, gopt_shorts('h', '?'), gopt_longs("help", "HELP")),
            gopt_option('m', 0, gopt_shorts('m'), gopt_longs("mute")),
            gopt_option('v', GOPT_REPEAT, gopt_shorts('v'), gopt_longs("verbose")),
            gopt_option('i', GOPT_ARG, gopt_shorts('i'), gopt_longs("icon"))));
    int help = gopt(options, 'h');
    int debug = gopt(options, 'v');
    int muted = gopt(options, 'm');
	const char *icon;

	if (gopt_arg(options, 'i', &icon) == 0) {
		icon = "speaker";
	}

    gopt_free(options);

    if (help)
        print_usage(argv[0], FALSE);  

    gint volume;
    if (muted) {
        if (argc > 2) {
            print_usage(argv[0], TRUE);
        } else if (argc == 2) {
            if (sscanf(argv[1], "%d", &volume) != 1)
                print_usage(argv[0], TRUE);

            if (volume > 100 || volume < 0)
                print_usage(argv[0], TRUE);
        } else {
            volume = 0;
        }
    } else {
        if (argc != 2)
            print_usage(argv[0], TRUE);

        if (sscanf(argv[1], "%d", &volume) != 1)
            print_usage(argv[0], TRUE);

        if (volume > 100 || volume < 0)
            print_usage(argv[0], TRUE);
    }

    // round volume
    volume = (int)(round(volume / 5.0) * 5.0);

    DBusGConnection *bus = NULL;
    DBusGProxy *proxy = NULL;
    GError *error = NULL;

    // initialize GObject
    g_type_init();

    // connect to D-Bus
    print_debug("Connecting to D-Bus...", debug);
    bus = dbus_g_bus_get(DBUS_BUS_SESSION, &error);
    if (error != NULL)
        handle_error("Couldn't connect to D-Bus",
                    error->message,
                    TRUE);
    print_debug_ok(debug);

    // get the proxy
    print_debug("Getting proxy...", debug);
    proxy = dbus_g_proxy_new_for_name(bus,
                                      VALUE_SERVICE_NAME,
                                      VALUE_SERVICE_OBJECT_PATH,
                                      VALUE_SERVICE_INTERFACE);
    if (proxy == NULL)
        handle_error("Couldn't get a proxy for D-Bus",
                    "Unknown(dbus_g_proxy_new_for_name)",
                    TRUE);
    print_debug_ok(debug);

    print_debug("Sending volume...", debug);
    uk_ac_cam_db538_VolumeNotification_notify(proxy, volume, muted, icon, &error);
    if (error !=  NULL) {
        handle_error("Failed to send notification", error->message, FALSE);
        g_clear_error(&error);
        return EXIT_FAILURE;
    }
    print_debug_ok(debug);

    return EXIT_SUCCESS;
}
static bool tunnel_parse_args(int argc, char* argv[], nabto_main_setup* nms) {

    const char *tunnel_port_str;

    const char x1s[] = "h";      const char* x1l[] = { "help", 0 };
    const char x2s[] = "V";      const char* x2l[] = { "version", 0 };
    const char x3s[] = "C";      const char* x3l[] = { "config", 0 };
    const char x4s[] = "S";      const char* x4l[] = { "size", 0 };
    const char x9s[] = "d";      const char* x9l[] = { "deviceName", 0 };
    const char x10s[] = "H";     const char* x10l[] = { "tunnel_default_host", 0 }; // only used together with the tunnel.
    const char x11s[] = "P";     const char* x11l[] = { "tunnel_default_port", 0 };
    const char x12s[] = "s";     const char* x12l[] = { "use_encryption", 0 };
    const char x13s[] = "k";     const char* x13l[] = { "encryption_key", 0 };
    const char x14s[] = "p";     const char* x14l[] = { "localport", 0 };
    const char x15s[] = "a";     const char* x15l[] = { "check_acl", 0 };
    const char x16s[] = "";      const char* x16l[] = { "allow_port", 0};
    const char x17s[] = "";      const char* x17l[] = { "allow_host", 0};
    const char x18s[] = "x";     const char* x18l[] = { "nice_exit", 0};
    const char x19s[] = "";      const char* x19l[] = { "allow_all_ports", 0};
    const char x20s[] = "";      const char* x20l[] = { "test_webserver", 0};
    const char x21s[] = "l";     const char* x21l[] = { "nabtolog", 0 };
    const char x22s[] = "A";     const char* x22l[] = { "controller", 0 };
    const char x23s[] = "";      const char* x23l[] = { "disable-tcp-fb", 0 };
    const char x24s[] = "";      const char* x24l[] = { "controller-port", 0 };

    const struct { int k; int f; const char *s; const char*const* l; } opts[] = {
        { 'h', GOPT_NOARG,   x1s, x1l },
        { 'V', GOPT_NOARG,   x2s, x2l },
        { 'C', GOPT_NOARG,   x3s, x3l },
        { 'S', GOPT_NOARG,   x4s, x4l },
        { 'd', GOPT_ARG,     x9s, x9l },
        { 'H', GOPT_ARG,     x10s, x10l },
        { 'P', GOPT_ARG,     x11s, x11l },
        { 's', GOPT_NOARG,   x12s, x12l },
        { 'k', GOPT_ARG,     x13s, x13l },
        { 'p', GOPT_ARG,     x14s, x14l },
        { 'a', GOPT_NOARG,   x15s, x15l },
        { ALLOW_PORT_OPTION, GOPT_REPEAT|GOPT_ARG, x16s, x16l },
        { ALLOW_HOST_OPTION, GOPT_REPEAT|GOPT_ARG, x17s, x17l },
        { 'x', GOPT_NOARG, x18s, x18l },
        { ALLOW_ALL_PORTS_OPTION, GOPT_NOARG, x19s, x19l },
        { TEST_WEBSERVER_OPTION, GOPT_ARG, x20s, x20l },
        { 'l', GOPT_REPEAT|GOPT_ARG,  x21s, x21l },
        { 'A', GOPT_ARG, x22s, x22l },
        { DISABLE_TCP_FALLBACK_OPTION, GOPT_NOARG, x23s, x23l },
        { CONTROLLER_PORT_OPTION, GOPT_ARG, x24s, x24l },
        { 0,0,0,0 }
    };

    void *options = gopt_sort( & argc, (const char**)argv, opts);

    const char * h;
    int p;
    const char* localPortStr;
    const char* optionString;
    const char* basestationAddress;
    const char* controllerPort;
    uint32_t addr;


    if (gopt(options, 'h')) {
        printf("Usage: unabto_tunnel [options] -d devicename\n");
        printf("  -h, --help                  Print this help.\n");
        printf("  -V, --version               Print version.\n");
        printf("  -C, --config                Print configuration (unabto_config.h).\n");
        printf("  -S, --size                  Print size (in bytes) of memory usage.\n");
        printf("  -l, --nabtolog              Speficy log level such as *.trace");
        printf("  -d, --deviceName            Specify name of this device.\n");
        printf("  -H, --tunnel_default_host   Set default host name for tunnel (%s).\n", DEFAULT_HOST);
        printf("  -P, --tunnel_default_port   Set default port for tunnel (%u).\n", DEFAULT_PORT);
        printf("  -s, --use_encryption        Encrypt communication (use CRYPTO).\n");
        printf("  -k, --encryption_key        Specify encryption key.\n");
        printf("  -p, --localport             Specify port for local connections.\n");
        printf("  -A, --controller            Specify controller address\n");
        printf("      --controller-port       sets the controller port number");
        printf("  -a, --check_acl             Perform ACL check when establishing connection.\n");
        printf("      --allow_all_ports       Allow connections to all port numbers.\n");
        printf("      --allow_port            Ports that are allowed. Requires -a.\n");
        printf("      --allow_host            Hostnames that are allowed. Requires -a.\n");
        printf("  -x, --nice_exit             Close the tunnels nicely when pressing Ctrl+C.\n");
#if USE_TEST_WEBSERVER
        printf("      --test_webserver        Specify port of test webserver and enable it\n");
#endif
        printf("      --disable-tcp-fb        disable tcp fallback");
        exit(0);
    }

    if (gopt(options, 'V')) {
        printf("%d.%d\n", RELEASE_MAJOR, RELEASE_MINOR);
        exit(0);
    }

    if (gopt(options, 'C')) {
        unabto_printf_unabto_config(stdout, "unabto_tunnel");
        exit(0);
    }

    if (gopt(options, 'S')) {
        unabto_printf_memory_sizes(stdout, "unabto_tunnel");
        exit(0);
    }
    
    { 
        size_t optionsLength = gopt(options, 'l');
        int i;
        if (optionsLength > 0) {
            for (i = 0; i < optionsLength; i++) {
                optionString = gopt_arg_i(options, 'l', i);
                if (!unabto_log_system_enable_stdout_pattern(optionString)) {
                    NABTO_LOG_FATAL(("Logstring %s is not a valid logsetting", optionString));
                }
            }
        } else {
            unabto_log_system_enable_stdout_pattern("*.info");
        }
        
    } 
    

    if (!gopt_arg( options, 'd', &nms->id)) {
        NABTO_LOG_FATAL(("Specify a serverId with -d. Try -h for help."));
    }

    if(gopt_arg(options, 'H', &h)) {
        tunnel_set_default_host(h);
    }

    if (gopt_arg(options, 'P', &tunnel_port_str)) {
        if(1 != sscanf(tunnel_port_str, "%d", &p)) {
            NABTO_LOG_FATAL(("Reading of port parameter failed."));
        } else {
            tunnel_set_default_port(p);
        }
    }
     
    if( gopt_arg( options, 'p', &localPortStr) ){
        int localPort = atoi(localPortStr);
        nms->localPort = localPort;
    }


    if (gopt(options, 's')) {
        const char* preSharedKey;
        uint8_t key[16];
        memset(key, 0, 16);
        if ( gopt_arg( options, 'k', &preSharedKey)) {
            size_t i;
            size_t pskLen = strlen(preSharedKey);
            // read the pre shared key as a hexadecimal string.
            for (i = 0; i < pskLen/2 && i < 16; i++) {
                sscanf(preSharedKey+(2*i), "%02hhx", &key[i]);
            }
        }
        memcpy(nms->presharedKey,key,16);
        nms->cryptoSuite = CRYPT_W_AES_CBC_HMAC_SHA256;
        nms->secureAttach = true;
        nms->secureData = true;
    }

    if (gopt(options, 'a')) {
        check_acl = true;
    }

    if( gopt_arg( options, 'A', & basestationAddress ) ){
        addr = inet_addr(basestationAddress);
        if (addr == INADDR_NONE) {
            NABTO_LOG_FATAL(("Invalid basestation address"));
        }
        nms->controllerArg.addr = htonl(addr);
    }

    if (gopt(options, 'x')) {
        nice_exit = true;
    }

    ports_length = gopt(options, ALLOW_PORT_OPTION);
    if (ports_length > 0) {
        size_t i;
        ports = (uint16_t*) malloc(ports_length*sizeof(uint16_t));
        memset(ports,0,ports_length*sizeof(uint16_t));
        for (i = 0; i < ports_length; i++) {
            const char* opt = gopt_arg_i(options, ALLOW_PORT_OPTION, i);
            ports[i] = atoi(opt);
        }
    }
    
    hosts_length = gopt(options, ALLOW_HOST_OPTION);
    if (hosts_length > 0) {
        size_t i;
        hosts = (char**) malloc(hosts_length*sizeof(char*));
        for (i = 0; i < hosts_length; i++) {
            const char* opt = gopt_arg_i(options, ALLOW_HOST_OPTION, i);
            hosts[i] = strdup(opt);
        }
    }

    if (gopt(options, ALLOW_ALL_PORTS_OPTION)) {
        allow_all_ports = true;
    }

#if USE_TEST_WEBSERVER
    if (gopt_arg(options, TEST_WEBSERVER_OPTION, &testWebserverPortStr)) {
        testWebserver = true;
    }
#endif

#if NABTO_ENABLE_TCP_FALLBACK
    if (gopt(options, DISABLE_TCP_FALLBACK_OPTION)) {
        nms->enableTcpFallback = false;
    }
#endif

    if (gopt_arg(options, CONTROLLER_PORT_OPTION, &controllerPort)) {
        nms->controllerArg.port = atoi(controllerPort);
    }

    return true;
}