int main(int argc, char **argv) { sxc_client_t *sx; sxc_logger_t log; struct gengetopt_args_info args; char file[1024]; const char *filter_dir; if(cmdline_parser(argc, argv, &args)) return 1; if(args.version_given) { printf("%s %s\n", CMDLINE_PARSER_PACKAGE, SRC_VERSION); cmdline_parser_free(&args); return 0; } if(args.output_given) snprintf(file, sizeof(file), "%s", args.output_arg); else snprintf(file, sizeof(file), "sxreport-client-%ld.log", (long)time(NULL)); umask(077); if(!(sx = sxc_init(SRC_VERSION, sxc_file_logger(&log, argv[0], file, 1), NULL, NULL))) { cmdline_parser_free(&args); return 1; } if(args.config_dir_given && sxc_set_confdir(sx, args.config_dir_arg)) { cmdline_parser_free(&args); sxc_shutdown(sx, 0); return 1; } sxc_set_verbose(sx, 1); filter_dir = get_filter_dir(sx, args.filter_dir_arg); if(sxc_filter_loadall(sx, filter_dir)) { cmdline_parser_free(&args); sxc_shutdown(sx, 0); return 1; } sxi_report_build_info(sx); #define INFO_PKGCONFIG "" #define INFO_PKGCONFIG_LIBDIR "" #define INFO_PKGCONFIG_PATH "" sxi_report_build_flags(sx); sxi_report_library_versions(sx, SRC_VERSION); sxi_report_system_info(sx); sxi_report_limits(sx); sxi_report_section(sx, "Filters"); sxi_info(sx,"Default filter directory: %s\n", SX_FILTER_DIR); sxi_info(sx,"Current filter directory: %s\n", filter_dir); filter_list(sx); sxi_report_configuration(sx, args.config_dir_arg); printf("Report stored in %s\n", file); printf("You can attach it to a bugreport at %s\n", PACKAGE_BUGREPORT); cmdline_parser_free(&args); sxc_shutdown(sx, 0); return 0; }
int main(int argc, char ** argv) { int result = EXIT_FAILURE; struct gengetopt_args_info ai; Options options = { .IPAddress = NULL, .InterfaceName = NULL, .AddressFamily = AF_UNSPEC, .CoapPort = 0, .IpcPort = 0, .ContentType = 0, .Secure = false, .ObjDefsFiles = {0}, .NumObjDefsFiles = 0, .Daemonise = false, .Verbose = false, .LogFile = NULL, .Version = false, }; if (ParseOptions(argc, argv, &ai, &options) == EXIT_SUCCESS) { result = Lwm2mServer_Start(&options); } cmdline_parser_free(&ai); exit(result); }
int main(int argc, char ** argv) { int result = EXIT_FAILURE; struct gengetopt_args_info ai; Options options = { .CoapPort = 0, .AddressFamily = AF_UNSPEC, .IpcPort = 0, .EndPointName = NULL, .BootStrap = NULL, .PskIdentity = NULL, .PskKey = NULL, .CertificateFile = NULL, .FactoryBootstrapFile = NULL, .DefaultContentType = AwaContentType_ApplicationPlainText, .ObjDefsFiles = {0}, .NumObjDefsFiles = 0, .Daemonise = false, .Verbose = false, .LogFile = NULL, .Version = false, }; if (ParseOptions(argc, argv, &ai, &options) == EXIT_SUCCESS) { result = Lwm2mClient_Start(&options); } cmdline_parser_free(&ai); exit(result); }
int main(int argc, char *argv[]) { static char dflt_fmt[] = "%Y-%m-%d\n\0H:%M:%S %Z\n"; struct gengetopt_args_info argi[1]; char *outfmt = dflt_fmt; char **infmt; size_t ninfmt; char **input; size_t ninput; int quietp; int res = 0; if (cmdline_parser(argc, argv, argi)) { res = 1; goto out; } if (argi->format_given) { outfmt = argi->format_arg; /* unescape sequences, maybe */ if (argi->backslash_escapes_given) { dt_io_unescape(outfmt); } } else if (argi->time_given) { outfmt[8] = ' '; outfmt[9] = '%'; } if (!argi->input_format_given) { infmt = argi->inputs; ninfmt = argi->inputs_num; input = NULL; ninput = 0; } else { infmt = argi->input_format_arg; ninfmt = argi->input_format_given; input = argi->inputs; ninput = argi->inputs_num; } /* get quiet predicate */ quietp = argi->quiet_given; /* get lines one by one, apply format string and print date/time */ if (ninput == 0) { /* read from stdin */ proc_lines((const char*const*)infmt, ninfmt, outfmt, quietp); } else { const char *const *cinfmt = (const char*const*)infmt; for (size_t i = 0; i < ninput; i++) { proc_line(input[i], cinfmt, ninfmt, outfmt, quietp); } } out: cmdline_parser_free(argi); return res; }
int main(int argc, char *argv[]) { int fail = 1; unsigned char *cvc_data = NULL, *desc_data = NULL, *csr_data = NULL; size_t cvc_len = 0, desc_len = 0, csr_len = 0; struct gengetopt_args_info cmdline; /* Parse command line */ if (cmdline_parser (argc, argv, &cmdline) != 0) { return fail; } if (cmdline.cvc_arg) { fail = read_file(cmdline.cvc_arg, &cvc_data, &cvc_len); if (fail) { fprintf(stderr, "failed to read %s\n", cmdline.cvc_arg); goto err; } } if (cmdline.description_arg) { fail = read_file(cmdline.description_arg, &desc_data, &desc_len); if (fail) { fprintf(stderr, "failed to read %s\n", cmdline.description_arg); goto err; } } if (cmdline.csr_arg) { fail = read_file(cmdline.csr_arg, &csr_data, &csr_len); if (fail) { fprintf(stderr, "failed to read %s\n", cmdline.csr_arg); goto err; } } EAC_init(); fail = print_cvc(cvc_data, cvc_len, desc_data, desc_len, csr_data, csr_len); err: cmdline_parser_free (&cmdline); free(cvc_data); free(desc_data); EAC_cleanup(); return fail; }
int main(int argc, char **argv) { struct gengetopt_args_info cmdline; if (cmdline_parser(argc, argv, &cmdline) != 0) return 1; const char *module_path = cmdline.module_arg; if (!cmdline.module_given) module_path = default_pkcs11_provider; #ifdef _WIN32 DWORD expanded_len; char module_path_expanded[PATH_MAX], default_expanded[PATH_MAX], onepin_expanded[PATH_MAX]; expand(module_path, module_path_expanded, expanded_len); expand(default_pkcs11_provider, default_expanded, expanded_len); expand(default_onepin_pkcs11_provider, onepin_expanded, expanded_len); #endif const char *module_name = get_module_name(module_path); if (!module_name) { fprintf(stderr, "Could not load initialize %s\n", module_path); return 1; } if (!cmdline.skip_chrome_flag) add_module_chrome(module_path, module_name); if (!cmdline.skip_firefox_flag) add_module_firefox(module_path, module_name); if (!cmdline.skip_thunderbird_flag) add_module_thunderbird(module_path, module_name); if (!cmdline.skip_seamonkey_flag) add_module_seamonkey(module_path, module_name); cmdline_parser_free (&cmdline); return 0; }
static void handle_oor_command_line(int argc, char **argv) { struct gengetopt_args_info args_info; if (cmdline_parser(argc, argv, &args_info) != 0) { exit_cleanup(); } if (args_info.daemonize_given) { daemonize = TRUE; } if (args_info.config_file_given) { config_file = strdup(args_info.config_file_arg); } if (args_info.debug_given) { debug_level = args_info.debug_arg; } if (args_info.afi_given) { switch (args_info.afi_arg) { case 0: /* afi given = 4 */ default_rloc_afi = AF_INET; break; case 1: /* afi given = 6 */ default_rloc_afi = AF_INET6; break; default: OOR_LOG(LINF, "AFI must be IPv4 (-a 4) or IPv6 (-a 6)\n"); break; } } else { default_rloc_afi = AF_UNSPEC; } cmdline_parser_free(&args_info); }
int main(int argc, char **argv) { struct gengetopt_args_info args_info; struct hostent *host; char hostname[USERURLSIZE]; int numargs; int ret = -1; int i; options_init(); memset(&args_info, 0, sizeof(args_info)); if (cmdline_parser2(argc, argv, &args_info, 1, 1, 1) != 0) { log_err(0, "Failed to parse command line options"); goto end_processing; } if (args_info.version_given) { options_print_version(); exit(2); } if (args_info.help_given) { options_print_help(); exit(2); } if (cmdline_parser_configfile(args_info.conf_arg ? args_info.conf_arg : DEFCHILLICONF, &args_info, 0, 0, 0)) { log_err(0, "Failed to parse configuration file: %s!", args_info.conf_arg); if (!args_info.forgiving_flag) goto end_processing; } /* Get the system default DNS entries */ if (res_init()) { log_err(0, "Failed to update system DNS settings (res_init()!"); goto end_processing; } /* Handle each option */ _options.initialized = 1; if (args_info.debug_flag) _options.debug = args_info.debugfacility_arg; else _options.debug = 0; /* pass-throughs */ memset(_options.pass_throughs, 0, sizeof(_options.pass_throughs)); _options.num_pass_throughs = 0; /** simple configuration parameters **/ _options.layer3 = args_info.layer3_flag; #if(_debug_ && !defined(ENABLE_LAYER3)) if (_options.layer3) log_warn(0, "layer3 not implemented. build with --enable-layer3"); #endif _options.uid = args_info.uid_arg; _options.gid = args_info.gid_arg; _options.mtu = args_info.mtu_arg; _options.usetap = args_info.usetap_flag; _options.noarpentries = args_info.noarpentries_flag; #if(_debug_ && !defined(ENABLE_TAP)) if (_options.noarpentries) log_warn(0, "tap not implemented. build with --enable-tap"); #endif #if(_debug_ && !defined(ENABLE_TAP)) if (_options.usetap) log_warn(0, "tap not implemented. build with --enable-tap"); #endif _options.foreground = args_info.fg_flag; _options.interval = args_info.interval_arg; _options.lease = args_info.lease_arg; _options.leaseplus = args_info.leaseplus_arg; _options.dhcpstart = args_info.dhcpstart_arg; _options.dhcpend = args_info.dhcpend_arg; _options.eapolenable = args_info.eapolenable_flag; #if(_debug_ && !defined(ENABLE_EAPOL)) if (_options.eapolenable) log_warn(0, "EAPOL not implemented. build with --enable-eapol"); #endif _options.swapoctets = args_info.swapoctets_flag; _options.logfacility = args_info.logfacility_arg; _options.chillixml = args_info.chillixml_flag; _options.macauth = args_info.macauth_flag; _options.macreauth = args_info.macreauth_flag; _options.macauthdeny = args_info.macauthdeny_flag; _options.uamport = args_info.uamport_arg; #ifdef ENABLE_UAMUIPORT _options.uamuiport = args_info.uamuiport_arg; #endif _options.macallowlocal = args_info.macallowlocal_flag; _options.strictmacauth = args_info.strictmacauth_flag; _options.strictdhcp = args_info.strictdhcp_flag; _options.no_wispr1 = args_info.nowispr1_flag; _options.no_wispr2 = args_info.nowispr2_flag; _options.wpaguests = args_info.wpaguests_flag; _options.openidauth = args_info.openidauth_flag; _options.challengetimeout = args_info.challengetimeout_arg; _options.challengetimeout2 = args_info.challengetimeout2_arg; _options.defsessiontimeout = args_info.defsessiontimeout_arg; _options.definteriminterval = args_info.definteriminterval_arg; _options.defbandwidthmaxdown = args_info.defbandwidthmaxdown_arg; _options.defbandwidthmaxup = args_info.defbandwidthmaxup_arg; _options.defidletimeout = args_info.defidletimeout_arg; _options.radiusnasporttype = args_info.radiusnasporttype_arg; _options.radiusauthport = args_info.radiusauthport_arg; _options.radiusacctport = args_info.radiusacctport_arg; _options.coaport = args_info.coaport_arg; _options.coanoipcheck = args_info.coanoipcheck_flag; _options.radiustimeout = args_info.radiustimeout_arg; _options.radiusretry = args_info.radiusretry_arg; _options.radiusretrysec = args_info.radiusretrysec_arg; #ifdef ENABLE_RADPROXY _options.proxyport = args_info.proxyport_arg; _options.proxymacaccept = args_info.proxymacaccept_flag; _options.proxyonacct = args_info.proxyonacct_flag; #endif #if(_debug_ && !defined(ENABLE_RADPROXY)) if (args_info.proxyport_arg) log_err(0,"radproxy not implemented. build with --enable-radproxy"); #endif _options.txqlen = args_info.txqlen_arg; _options.ringsize = args_info.ringsize_arg; _options.sndbuf = args_info.sndbuf_arg; _options.rcvbuf = args_info.rcvbuf_arg; _options.childmax = args_info.childmax_arg; _options.postauth_proxyport = args_info.postauthproxyport_arg; _options.pap_always_ok = args_info.papalwaysok_flag; _options.mschapv2 = args_info.mschapv2_flag; _options.acct_update = args_info.acctupdate_flag; _options.dhcpradius = args_info.dhcpradius_flag; _options.dhcp_broadcast = args_info.dhcpbroadcast_flag; _options.dhcpgwport = args_info.dhcpgatewayport_arg; _options.noc2c = args_info.noc2c_flag; _options.tcpwin = args_info.tcpwin_arg; _options.tcpmss = args_info.tcpmss_arg; _options.max_clients = args_info.maxclients_arg; _options.radiusqsize = args_info.radiusqsize_arg; _options.dhcphashsize = args_info.dhcphashsize_arg; _options.uamdomain_ttl = args_info.uamdomainttl_arg; _options.seskeepalive = args_info.seskeepalive_flag; _options.uamallowpost = args_info.uamallowpost_flag; _options.redir = args_info.redir_flag; _options.redirurl = args_info.redirurl_flag; _options.statusfilesave = args_info.statusfilesave_flag; _options.dhcpnotidle = args_info.dhcpnotidle_flag; #if(_debug_ && !defined(ENABLE_CHILLIREDIR)) if (_options.redir) log_err(0, "chilli_redir not implemented. build with --enable-chilliredir"); #endif _options.redirssl = args_info.redirssl_flag; _options.uamuissl = args_info.uamuissl_flag; _options.domaindnslocal = args_info.domaindnslocal_flag; _options.framedservice = args_info.framedservice_flag; _options.radsec = args_info.radsec_flag; #if(_debug_ && !defined(ENABLE_CHILLIRADSEC)) if (_options.radsec) log_err(0, "chilli_radsec not implemented. build with --enable-chilliradsec"); #endif _options.noradallow = args_info.noradallow_flag; _options.peerid = args_info.peerid_arg; #if(_debug_ && !defined(ENABLE_CLUSTER)) if (_options.peerid) log_err(0, "clustering not implemented. build with --enable-cluster"); #endif _options.redirdnsreq = args_info.redirdnsreq_flag; #if(_debug_ && !defined(ENABLE_REDIRDNSREQ)) if (_options.redirdnsreq) log_err(0, "redirdnsreq not implemented. build with --enable-redirdnsreq"); #endif #ifdef ENABLE_IPV6 _options.ipv6 = args_info.ipv6_flag; _options.ipv6only = args_info.ipv6only_flag; #endif #ifdef ENABLE_LEAKYBUCKET _options.scalewin = args_info.scalewin_flag; _options.bwbucketupsize = args_info.bwbucketupsize_arg; _options.bwbucketdnsize = args_info.bwbucketdnsize_arg; _options.bwbucketminsize = args_info.bwbucketminsize_arg; #endif #ifdef ENABLE_PROXYVSA _options.vlanlocation = args_info.vlanlocation_flag; _options.location_stop_start = args_info.locationstopstart_flag; _options.location_copy_called = args_info.locationcopycalled_flag; _options.location_immediate_update = args_info.locationimmediateupdate_flag; _options.location_option_82 = args_info.locationopt82_flag; if (args_info.proxylocattr_given) { for (numargs = 0; numargs < args_info.proxylocattr_given && numargs < PROXYVSA_ATTR_CNT; ++numargs) { unsigned int i[2]; switch (sscanf(args_info.proxylocattr_arg[numargs], "%u,%u", &i[0], &i[1])) { case 0: log_err(0, "invalid input %s", args_info.proxylocattr_arg[numargs]); break; case 1: _options.proxy_loc[numargs].attr = i[0]; break; case 2: _options.proxy_loc[numargs].attr_vsa = i[0]; _options.proxy_loc[numargs].attr = i[1]; break; } log_dbg("Proxy location attr %d %d", (int)_options.proxy_loc[numargs].attr_vsa, (int)_options.proxy_loc[numargs].attr); } } #endif if (args_info.dhcpgateway_arg && !inet_aton(args_info.dhcpgateway_arg, &_options.dhcpgwip)) { log_err(0, "Invalid DHCP gateway IP address: %s!", args_info.dhcpgateway_arg); if (!args_info.forgiving_flag) goto end_processing; } if (args_info.dhcprelayagent_arg && !inet_aton(args_info.dhcprelayagent_arg, &_options.dhcprelayip)) { log_err(0, "Invalid DHCP gateway relay IP address: %s!", args_info.dhcprelayagent_arg); if (!args_info.forgiving_flag) goto end_processing; } _options.dhcpif = STRDUP(args_info.dhcpif_arg); #ifdef ENABLE_MULTILAN for (numargs = 0; numargs < args_info.moreif_given && numargs < MAX_MOREIF; ++numargs) { char *nif = STRDUP(args_info.moreif_arg[numargs]); char *vln = strchr(nif, '/'); _options.moreif[numargs].dhcpif = nif; if (vln) { if (strlen(vln) > 1) _options.moreif[numargs].vlan = vln + 1; *vln = 0; } else { vln = strchr(nif, '.'); if (vln && strlen(vln) > 1) _options.moreif[numargs].vlan = vln + 1; } } #endif if (!args_info.radiussecret_arg) { log_err(0, "radiussecret must be specified!"); if (!args_info.forgiving_flag) goto end_processing; } if (!args_info.nexthop_arg) { memset(_options.nexthop, 0, PKT_ETH_ALEN); _options.has_nexthop = 0; } else { unsigned int temp[PKT_ETH_ALEN]; char macstr[RADIUS_ATTR_VLEN]; int macstrlen; int i; if ((macstrlen = strlen(args_info.nexthop_arg)) >= (RADIUS_ATTR_VLEN-1)) { log_err(0, "MAC address too long"); if (!args_info.forgiving_flag) goto end_processing; } memcpy(macstr, args_info.nexthop_arg, macstrlen); macstr[macstrlen] = 0; /* Replace anything but hex with space */ for (i=0; i<macstrlen; i++) if (!isxdigit((int) macstr[i])) macstr[i] = 0x20; if (sscanf (macstr, "%2x %2x %2x %2x %2x %2x", &temp[0], &temp[1], &temp[2], &temp[3], &temp[4], &temp[5]) != 6) { log_err(0, "MAC conversion failed!"); return -1; } for (i = 0; i < PKT_ETH_ALEN; i++) _options.nexthop[i] = temp[i]; _options.has_nexthop = 1; } if (!args_info.dhcpmac_arg) { memset(_options.dhcpmac, 0, PKT_ETH_ALEN); _options.dhcpusemac = 0; _options.dhcpmacset = 0; } else { unsigned int temp[PKT_ETH_ALEN]; char macstr[RADIUS_ATTR_VLEN]; int macstrlen; int i; if ((macstrlen = strlen(args_info.dhcpmac_arg)) >= (RADIUS_ATTR_VLEN-1)) { log_err(0, "MAC address too long"); if (!args_info.forgiving_flag) goto end_processing; } memcpy(macstr, args_info.dhcpmac_arg, macstrlen); macstr[macstrlen] = 0; /* Replace anything but hex with space */ for (i=0; i<macstrlen; i++) if (!isxdigit((int) macstr[i])) macstr[i] = 0x20; if (sscanf (macstr, "%2x %2x %2x %2x %2x %2x", &temp[0], &temp[1], &temp[2], &temp[3], &temp[4], &temp[5]) != 6) { log_err(0, "MAC conversion failed!"); return -1; } for (i = 0; i < PKT_ETH_ALEN; i++) _options.dhcpmac[i] = temp[i]; _options.dhcpusemac = 1; _options.dhcpmacset = args_info.dhcpmacset_flag; } if (args_info.net_arg) { if (option_aton(&_options.net, &_options.mask, args_info.net_arg, 0)) { log_err(0, "Invalid network address: %s!", args_info.net_arg); if (!args_info.forgiving_flag) goto end_processing; } if (!args_info.uamlisten_arg) { _options.uamlisten.s_addr = htonl(ntohl(_options.net.s_addr)+1); } else if (!inet_aton(args_info.uamlisten_arg, &_options.uamlisten)) { log_err(0, "Invalid UAM IP address: %s!", args_info.uamlisten_arg); if (!args_info.forgiving_flag) goto end_processing; } if (!args_info.dhcplisten_arg) { _options.dhcplisten.s_addr = _options.uamlisten.s_addr; } else if (!inet_aton(args_info.dhcplisten_arg, &_options.dhcplisten)) { log_err(0, "Invalid DHCP IP address: %s!", args_info.dhcplisten_arg); if (!args_info.forgiving_flag) goto end_processing; } } else { log_err(0, "Network address must be specified ('net' parameter)!"); if (!args_info.forgiving_flag) goto end_processing; } log_dbg("DHCP Listen: %s", inet_ntoa(_options.dhcplisten)); log_dbg("UAM Listen: %s", inet_ntoa(_options.uamlisten)); if (!args_info.uamserver_arg) { log_err(0, "WARNING: No uamserver defiend!"); } if (args_info.uamserver_arg) { int uamserverport=80; if (_options.debug & DEBUG_CONF) { log_dbg("Uamserver: %s\n", args_info.uamserver_arg); } if (get_urlparts(args_info.uamserver_arg, hostname, USERURLSIZE, &uamserverport, 0)) { log_err(0, "Failed to parse uamserver: %s!", args_info.uamserver_arg); if (!args_info.forgiving_flag) goto end_processing; } if (!args_info.uamaliasname_arg || strncmp(args_info.uamaliasname_arg, hostname, strlen(args_info.uamaliasname_arg))) { if (!(host = gethostbyname(hostname))) { log_err(0, "Could not resolve IP address of uamserver: %s!", args_info.uamserver_arg); } else { int j = 0; pass_through pt; memset(&pt, 0, sizeof(pt)); pt.port = uamserverport; pt.mask.s_addr = ~0; while (host->h_addr_list[j] != NULL) { if (_options.debug & DEBUG_CONF) { log_dbg("Uamserver IP address #%d: %s\n", j, inet_ntoa(*(struct in_addr*) host->h_addr_list[j])); } pt.host.s_addr = ((struct in_addr*) host->h_addr_list[j++])->s_addr; if (pass_through_add(_options.pass_throughs, MAX_PASS_THROUGHS, &_options.num_pass_throughs, &pt, 0 #ifdef HAVE_PATRICIA , 0 #endif )) log_err(0, "Too many pass-throughs! skipped %s:%d", inet_ntoa(pt.host), pt.port); } } } } _options.uamanydns = args_info.uamanydns_flag; #ifdef ENABLE_UAMANYIP _options.uamanyip = args_info.uamanyip_flag; _options.uamnatanyip = args_info.uamnatanyip_flag; #endif _options.dnsparanoia = args_info.dnsparanoia_flag; _options.radiusoriginalurl = args_info.radiusoriginalurl_flag; _options.routeonetone = args_info.routeonetone_flag; #ifdef HAVE_PATRICIA _options.patricia = args_info.patricia_flag; #endif #ifdef ENABLE_GARDENACCOUNTING _options.nousergardendata = args_info.nousergardendata_flag; _options.uamgardendata = args_info.uamgardendata_flag; _options.uamotherdata = args_info.uamotherdata_flag; #endif for (numargs = 0; numargs < args_info.uamallowed_given; ++numargs) { pass_throughs_from_string(_options.pass_throughs, MAX_PASS_THROUGHS, &_options.num_pass_throughs, args_info.uamallowed_arg[numargs], 0, 0 #ifdef HAVE_PATRICIA , 0 #endif ); } #ifdef ENABLE_DHCPOPT _options.dhcp_options_len = 0; for (numargs = 0; numargs < args_info.dhcpopt_given; ++numargs) { unsigned char binopt[128]; int hex_length = strlen(args_info.dhcpopt_arg[numargs]); int bin_length = hex_length / 2; if (hex_length > 0 && (bin_length * 2) == hex_length && bin_length < sizeof(binopt)) { log_dbg("DHCP Options %s", args_info.dhcpopt_arg[numargs]); if (redir_hextochar((unsigned char *)args_info.dhcpopt_arg[numargs], hex_length, binopt, bin_length) == 0) { if (_options.dhcp_options_len + bin_length < sizeof(_options.dhcp_options)) { memcpy(_options.dhcp_options + _options.dhcp_options_len, binopt, bin_length); _options.dhcp_options_len += bin_length; } else { log_dbg("No room for DHCP option %d", (int)binopt[0]); } } else { log_dbg("Bad DHCP option hex encoding"); } } else { log_dbg("DHCP options are hex encoded binary"); } } #endif #ifdef ENABLE_MODULES memset(_options.modules, 0, sizeof(_options.modules)); for (numargs = 0; numargs < args_info.module_given; ++numargs) { if (numargs < MAX_MODULES) { char *n, *sc; int len, nlen; n = args_info.module_arg[numargs]; len = strlen(n); sc = strchr(n, ';'); if (!sc) sc = strchr(n, ':'); nlen = sc ? (sc - n) : len; safe_snprintf(_options.modules[numargs].name, sizeof(_options.modules[numargs].name), "%.*s", nlen, n); if (sc && len > (nlen + 1)) { safe_snprintf(_options.modules[numargs].conf, sizeof(_options.modules[numargs].conf), "%.*s", len - nlen - 1, sc + 1); } } } #endif #ifdef ENABLE_CHILLIREDIR /* for (numargs = 0; numargs < MAX_REGEX_PASS_THROUGHS; ++numargs) { if (_options.regex_pass_throughs[numargs].re_host.allocated) regfree(&_options.regex_pass_throughs[numargs].re_host); if (_options.regex_pass_throughs[numargs].re_path.allocated) regfree(&_options.regex_pass_throughs[numargs].re_path); if (_options.regex_pass_throughs[numargs].re_qs.allocated) regfree(&_options.regex_pass_throughs[numargs].re_qs); } */ memset(_options.regex_pass_throughs, 0, sizeof(_options.regex_pass_throughs)); _options.regex_num_pass_throughs = 0; for (numargs = 0; numargs < args_info.uamregex_given; ++numargs) { regex_pass_throughs_from_string(_options.regex_pass_throughs, MAX_REGEX_PASS_THROUGHS, &_options.regex_num_pass_throughs, args_info.uamregex_arg[numargs], 0); } #endif for (numargs = 0; numargs < MAX_UAM_DOMAINS; ++numargs) { if (_options.uamdomains[numargs]) free(_options.uamdomains[numargs]); _options.uamdomains[numargs] = 0; } if (args_info.uamdomain_given) { for (numargs = 0, i=0; numargs < args_info.uamdomain_given && i < MAX_UAM_DOMAINS; ++numargs) { char *tb = args_info.uamdomain_arg[numargs]; char *tok, *str, *ptr; for (str = tb ; i < MAX_UAM_DOMAINS; str = NULL) { tok = strtok_r(str, ",", &ptr); if (!tok) break; log_dbg("uamdomain %s", tok); _options.uamdomains[i++] = STRDUP(tok); } } } _options.allowdyn = 1; #ifdef ENABLE_UAMANYIP _options.autostatip = args_info.autostatip_arg; if (_options.autostatip) _options.uamanyip = 1; #endif if (args_info.nodynip_flag) { _options.allowdyn = 0; } else { if (!args_info.dynip_arg) { _options.dynip = STRDUP(args_info.net_arg); } else { struct in_addr addr; struct in_addr mask; _options.dynip = STRDUP(args_info.dynip_arg); if (option_aton(&addr, &mask, _options.dynip, 0)) { log_err(0, "Failed to parse dynamic IP address pool!"); if (!args_info.forgiving_flag) goto end_processing; } } } /* statip */ if (args_info.statip_arg) { struct in_addr addr; struct in_addr mask; _options.statip = STRDUP(args_info.statip_arg); if (option_aton(&addr, &mask, _options.statip, 0)) { log_err(0, "Failed to parse static IP address pool!"); return -1; } _options.allowstat = 1; } else { _options.allowstat = 0; } #ifdef ENABLE_UAMANYIP if (args_info.uamnatanyipex_arg) { if (option_aton(&_options.uamnatanyipex_addr, &_options.uamnatanyipex_mask, args_info.uamnatanyipex_arg, 0)) { log_err(0, "Failed to parse uamnatanyipex network!"); return -1; } } if (args_info.uamanyipex_arg) { if (option_aton(&_options.uamanyipex_addr, &_options.uamanyipex_mask, args_info.uamanyipex_arg, 0)) { log_err(0, "Failed to parse uamanyipex network!"); return -1; } } #endif if (args_info.dns1_arg) { if (!inet_aton(args_info.dns1_arg, &_options.dns1)) { log_err(0,"Invalid primary DNS address: %s!", args_info.dns1_arg); if (!args_info.forgiving_flag) goto end_processing; } } else if (_res.nscount >= 1) { _options.dns1 = _res.nsaddr_list[0].sin_addr; } else { _options.dns1.s_addr = 0; } if (args_info.dns2_arg) { if (!inet_aton(args_info.dns2_arg, &_options.dns2)) { log_err(0,"Invalid secondary DNS address: %s!", args_info.dns1_arg); if (!args_info.forgiving_flag) goto end_processing; } } else if (_res.nscount >= 2) { _options.dns2 = _res.nsaddr_list[1].sin_addr; } else { _options.dns2.s_addr = _options.dns1.s_addr; } /* If no listen option is specified listen to any local port */ /* Do hostname lookup to translate hostname to IP address */ if (args_info.radiuslisten_arg) { if (!(host = gethostbyname(args_info.radiuslisten_arg))) { log_err(0, "Invalid listening address: %s! [%s]", args_info.radiuslisten_arg, strerror(errno)); if (!args_info.forgiving_flag) goto end_processing; } else { memcpy(&_options.radiuslisten.s_addr, host->h_addr, host->h_length); } } else { _options.radiuslisten.s_addr = htonl(INADDR_ANY); } #ifdef ENABLE_NETNAT if (args_info.natip_arg) { if (!(host = gethostbyname(args_info.natip_arg))) { log_warn(0, "Invalid natip address: %s! [%s]", args_info.natip_arg, strerror(errno)); } else { memcpy(&_options.natip.s_addr, host->h_addr, host->h_length); } } #endif if (args_info.uamlogoutip_arg) { if (!(host = gethostbyname(args_info.uamlogoutip_arg))) { log_warn(0, "Invalid uamlogoutup address: %s! [%s]", args_info.uamlogoutip_arg, strerror(errno)); } else { memcpy(&_options.uamlogout.s_addr, host->h_addr, host->h_length); } } if (args_info.uamaliasip_arg) { if (!(host = gethostbyname(args_info.uamaliasip_arg))) { log_warn(0, "Invalid uamaliasip address: %s! [%s]", args_info.uamlogoutip_arg, strerror(errno)); } else { memcpy(&_options.uamalias.s_addr, host->h_addr, host->h_length); } } if (args_info.postauthproxy_arg) { if (!(host = gethostbyname(args_info.postauthproxy_arg))) { log_warn(0, "Invalid postauthproxy address: %s! [%s]", args_info.postauthproxy_arg, strerror(errno)); } else { memcpy(&_options.postauth_proxyip.s_addr, host->h_addr, host->h_length); } } /* If no option is specified terminate */ /* Do hostname lookup to translate hostname to IP address */ if (args_info.radiusserver1_arg) { if (!(host = gethostbyname(args_info.radiusserver1_arg))) { log_err(0, "Invalid radiusserver1 address: %s! [%s]", args_info.radiusserver1_arg, strerror(errno)); if (!args_info.forgiving_flag) goto end_processing; } else { memcpy(&_options.radiusserver1.s_addr, host->h_addr, host->h_length); } } else { log_err(0,"No radiusserver1 address given!"); if (!args_info.forgiving_flag) goto end_processing; } /* radiusserver2 */ /* If no option is specified terminate */ /* Do hostname lookup to translate hostname to IP address */ if (args_info.radiusserver2_arg) { if (!(host = gethostbyname(args_info.radiusserver2_arg))) { log_err(0, "Invalid radiusserver2 address: %s! [%s]", args_info.radiusserver2_arg, strerror(errno)); if (!args_info.forgiving_flag) goto end_processing; } else { memcpy(&_options.radiusserver2.s_addr, host->h_addr, host->h_length); } } else { _options.radiusserver2.s_addr = 0; } /* If no listen option is specified listen to any local port */ /* Do hostname lookup to translate hostname to IP address */ if (args_info.proxylisten_arg) { #ifdef ENABLE_RADPROXY if (!(host = gethostbyname(args_info.proxylisten_arg))) { log_err(0, "Invalid listening address: %s! [%s]", args_info.proxylisten_arg, strerror(errno)); if (!args_info.forgiving_flag) goto end_processing; } else { memcpy(&_options.proxylisten.s_addr, host->h_addr, host->h_length); } } else { _options.proxylisten.s_addr = htonl(INADDR_ANY); #elif (_debug_) log_warn(0,"radproxy not implemented. build with --enable-radproxy"); #endif } /* Store proxyclient as in_addr net and mask */ if (args_info.proxyclient_arg) { #ifdef ENABLE_RADPROXY if(option_aton(&_options.proxyaddr, &_options.proxymask, args_info.proxyclient_arg, 0)) { log_err(0,"Invalid proxy client address: %s!", args_info.proxyclient_arg); if (!args_info.forgiving_flag) goto end_processing; } } else { _options.proxyaddr.s_addr = ~0; /* Let nobody through */ _options.proxymask.s_addr = 0; #elif (_debug_) log_warn(0,"radproxy not implemented. build with --enable-radproxy"); #endif } memset(_options.macok, 0, sizeof(_options.macok)); _options.macoklen = 0; for (numargs = 0; numargs < args_info.macallowed_given; ++numargs) { char *p1 = NULL; char *p2 = NULL; char *p3 = malloc(strlen(args_info.macallowed_arg[numargs])+1); int i; unsigned int mac[6]; log_dbg("Macallowed #%d: %s", numargs, args_info.macallowed_arg[numargs]); strcpy(p3, args_info.macallowed_arg[numargs]); p1 = p3; if ((p2 = strchr(p1, ','))) { *p2 = '\0'; } while (p1) { if (_options.macoklen>=MACOK_MAX) { log_err(0,"Too many addresses in macallowed %s!", args_info.macallowed_arg); } else { /* Replace anything but hex and comma with space */ for (i=0; i<strlen(p1); i++) if (!isxdigit((int) p1[i])) p1[i] = 0x20; if (sscanf (p1, "%2x %2x %2x %2x %2x %2x", &mac[0], &mac[1], &mac[2], &mac[3], &mac[4], &mac[5]) != 6) { log_err(0, "Failed to convert macallowed option to MAC Address"); } else { log_dbg("Macallowed address #%d: %.2X-%.2X-%.2X-%.2X-%.2X-%.2X", _options.macoklen, mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]); for (i = 0; i < 6; i++) _options.macok[_options.macoklen][i] = (unsigned char) mac[i]; _options.macoklen++; } } if (p2) { p1 = p2+1; if ((p2 = strchr(p1, ','))) { *p2 = 0; } } else { p1 = NULL; } } free(p3); } /** string parameters **/ #ifdef HAVE_SSL _options.sslkeyfile = STRDUP(args_info.sslkeyfile_arg); _options.sslkeypass = STRDUP(args_info.sslkeypass_arg); _options.sslcertfile = STRDUP(args_info.sslcertfile_arg); _options.sslcafile = STRDUP(args_info.sslcafile_arg); #endif #ifdef USING_IPC_UNIX _options.unixipc = STRDUP(args_info.unixipc_arg); #endif #ifdef HAVE_NETFILTER_COOVA _options.kname = STRDUP(args_info.kname_arg); #endif #ifdef ENABLE_DNSLOG _options.dnslog = STRDUP(args_info.dnslog_arg); #else if (args_info.dnslog_arg) log_err(0, "option dnslog given when no support built-in"); #endif #ifdef ENABLE_IPWHITELIST _options.ipwhitelist = STRDUP(args_info.ipwhitelist_arg); #else if (args_info.ipwhitelist_arg) log_err(0, "option ipwhitelist given when no support built-in"); #endif #ifdef ENABLE_UAMDOMAINFILE _options.uamdomainfile = STRDUP(args_info.uamdomainfile_arg); #else if (args_info.uamdomainfile_arg) log_err(0, "option uamdomainfile given when no support built-in"); #endif #ifdef ENABLE_MODULES _options.moddir = STRDUP(args_info.moddir_arg); #else if (args_info.moddir_arg) log_err(0, "option moddir given when no support built-in"); #endif #ifdef ENABLE_RADPROXY if (!args_info.proxysecret_arg) { _options.proxysecret = STRDUP(args_info.radiussecret_arg); } else { _options.proxysecret = STRDUP(args_info.proxysecret_arg); } #endif #ifdef ENABLE_REDIRINJECT _options.inject = STRDUP(args_info.inject_arg); _options.inject_ext = STRDUP(args_info.injectext_arg); _options.inject_wispr = args_info.injectwispr_flag; #endif #ifdef ENABLE_EXTADMVSA if (args_info.extadmvsa_given) { for (numargs = 0; numargs < args_info.extadmvsa_given && numargs < EXTADMVSA_ATTR_CNT; ++numargs) { int len = strlen(args_info.extadmvsa_arg[numargs]); if (len > 0 && len < 256) { unsigned int i[2]; char s[256]; if (sscanf(args_info.extadmvsa_arg[numargs], "%u,%u:%s", &i[0], &i[1], s) == 3) { char *idx = strchr(s, ':'); _options.extadmvsa[numargs].attr_vsa = i[0]; _options.extadmvsa[numargs].attr = i[1]; if (idx) *idx = 0; safe_strncpy(_options.extadmvsa[numargs].script, s, sizeof(_options.extadmvsa[numargs].script)-1); if (idx) { safe_strncpy(_options.extadmvsa[numargs].data, idx + 1, sizeof(_options.extadmvsa[numargs].data)-1); } } else if (sscanf(args_info.extadmvsa_arg[numargs], "%u:%s", &i[0], s) == 2) { char *idx = strchr(s, ':'); _options.extadmvsa[numargs].attr = i[0]; if (idx) *idx = 0; safe_strncpy(_options.extadmvsa[numargs].script, s, sizeof(_options.extadmvsa[numargs].script)-1); if (idx) { safe_strncpy(_options.extadmvsa[numargs].data, idx + 1, sizeof(_options.extadmvsa[numargs].data)-1); } } else { log_err(0, "invalid input %s", args_info.extadmvsa_arg[numargs]); } } log_dbg("Extended admin-user attr (%d/%d) data=%s script=%s", (int)_options.extadmvsa[numargs].attr_vsa, (int)_options.extadmvsa[numargs].attr, _options.extadmvsa[numargs].data, _options.extadmvsa[numargs].script); } } #endif _options.peerkey = STRDUP(args_info.peerkey_arg); _options.routeif = STRDUP(args_info.routeif_arg); _options.wwwdir = STRDUP(args_info.wwwdir_arg); _options.wwwbin = STRDUP(args_info.wwwbin_arg); _options.uamui = STRDUP(args_info.uamui_arg); _options.localusers = STRDUP(args_info.localusers_arg); _options.uamurl = STRDUP(args_info.uamserver_arg); _options.uamaaaurl = STRDUP(args_info.uamaaaurl_arg); _options.uamhomepage = STRDUP(args_info.uamhomepage_arg); _options.wisprlogin = STRDUP(args_info.wisprlogin_arg); _options.uamsecret = STRDUP(args_info.uamsecret_arg); _options.macsuffix = STRDUP(args_info.macsuffix_arg); _options.macpasswd = STRDUP(args_info.macpasswd_arg); _options.adminuser = STRDUP(args_info.adminuser_arg); _options.adminpasswd = STRDUP(args_info.adminpasswd_arg); _options.adminupdatefile = STRDUP(args_info.adminupdatefile_arg); _options.rtmonfile = STRDUP(args_info.rtmonfile_arg); _options.ssid = STRDUP(args_info.ssid_arg); _options.vlan = STRDUP(args_info.vlan_arg); _options.nasmac = STRDUP(args_info.nasmac_arg); _options.nasip = STRDUP(args_info.nasip_arg); _options.tundev = STRDUP(args_info.tundev_arg); _options.radiusnasid = STRDUP(args_info.radiusnasid_arg); _options.radiuslocationid = STRDUP(args_info.radiuslocationid_arg); _options.radiuslocationname = STRDUP(args_info.radiuslocationname_arg); _options.locationname = STRDUP(args_info.locationname_arg); _options.radiussecret = STRDUP(args_info.radiussecret_arg); #ifdef ENABLE_LARGELIMITS /*_options.radiusacctsecret = STRDUP(args_info.radiusacctsecret_arg); _options.radiusadmsecret = STRDUP(args_info.radiusadmsecret_arg);*/ #endif _options.cmdsocket = STRDUP(args_info.cmdsocket_arg); _options.cmdsocketport = args_info.cmdsocketport_arg; _options.domain = STRDUP(args_info.domain_arg); _options.ipup = STRDUP(args_info.ipup_arg); _options.ipdown = STRDUP(args_info.ipdown_arg); _options.conup = STRDUP(args_info.conup_arg); _options.condown = STRDUP(args_info.condown_arg); _options.macup = STRDUP(args_info.macup_arg); _options.macdown = STRDUP(args_info.macdown_arg); _options.pidfile = STRDUP(args_info.pidfile_arg); _options.statedir = STRDUP(args_info.statedir_arg); _options.usestatusfile = STRDUP(args_info.usestatusfile_arg); _options.uamaliasname = STRDUP(args_info.uamaliasname_arg); _options.uamhostname = STRDUP(args_info.uamhostname_arg); _options.binconfig = STRDUP(args_info.bin_arg); _options.ethers = STRDUP(args_info.ethers_arg); #ifdef ENABLE_IEEE8021Q _options.ieee8021q = args_info.ieee8021q_flag; _options.ieee8021q_only = args_info.only8021q_flag; _options.vlanupdate = STRDUP(args_info.vlanupdate_arg); #endif #ifdef ENABLE_PROXYVSA _options.locationupdate = STRDUP(args_info.locationupdate_arg); #endif #ifdef EX_OPT_MAIN #include EX_OPT_MAIN #endif ret = 0; if (_options.binconfig) { /* save out the configuration */ bstring bt = bfromcstr(""); int ok = options_save(_options.binconfig, bt); if (!ok) log_err(0, "could not save configuration options!"); bdestroy(bt); } if (args_info.reload_flag) { if (execl(SBINDIR "/chilli_query", "chilli_query", args_info.cmdsocket_arg, "reload", (char *) 0) != 0) { log_err(errno, "execl() did not return 0!"); exit(2); } } end_processing: cmdline_parser_free (&args_info); return ret; }
static void gengetopt_free() { cmdline_parser_free( &args_info ); }
int main(int argc, char ** argv) { int result = 0; struct gengetopt_args_info ai; AwaClientSession * session = NULL; AwaClientDeleteOperation * operation = NULL; if (cmdline_parser(argc, argv, &ai) != 0) { exit(1); } g_logLevel = ai.debug_given ? 2 : (ai.verbose_given ? 1 : 0); AwaLog_SetLevel(ai.debug_given ? AwaLogLevel_Debug : (ai.verbose_given ? AwaLogLevel_Verbose : AwaLogLevel_Warning)); if (ai.inputs_num == 0) { printf("Specify one or more resource paths.\n"); result = 1; goto cleanup; } session = Client_EstablishSession(ai.ipcAddress_arg, ai.ipcPort_arg); if (session != NULL) { // Create delete operation operation = AwaClientDeleteOperation_New(session); if (operation == NULL) { Error("AwaClientDeleteOperation_New failed\n"); result = 1; goto cleanup; } int i = 0; for (i = 0; i < ai.inputs_num; ++i) { Target * target = CreateTarget(ai.inputs[i]); if (target != NULL) { AddTarget(operation, target); FreeTarget(&target); } } } else { Error("Failed to establish Awa Session\n"); result = 1; goto cleanup; } result = ProcessDeleteOperation(operation); cleanup: if (session != NULL) { Client_ReleaseSession(&session); } cmdline_parser_free(&ai); return result; }
int main( int argc, char** argv ) { // First parse any options and the filename we need. gengetopt_args_info options; int err = cmdline_parser( argc, argv, &options ); if ( err ) { return err; } // Then set up the x interface. err = xengine->init( options.xdisplay_arg ); if ( err ) { fprintf( stderr, "Failed to grab X display!\n" ); return err; } // Then the imlib2 interface err = imengine->init(); if ( err ) { fprintf( stderr, "Failed to initialize imlib2!\n" ); return err; } float delay = atof( options.delay_arg ); if ( !options.windowid_given ) { options.windowid_arg = None; } std::string file = ""; // If we don't have a file, default to writing to the home directory. if ( options.inputs_num <= 0 ) { char currentdir[MAXPATHLEN]; // FIXME: getcwd is fundamentally broken, switch it with a C++ equivalent that won't ever have // buffer sizing issues. char* error = getcwd( currentdir, MAXPATHLEN ); if ( error == NULL ) { fprintf( stderr, "Failed to get current working directory!\n" ); return errno; } file = currentdir; // Get unix timestamp std::stringstream result; result << (int)time( NULL ); file += "/" + result.str() + ".png"; printf( "No file specified, using %s\n", file.c_str() ); } else if ( options.inputs_num == 1 ) { file = options.inputs[ 0 ]; } else { fprintf( stderr, "Unexpected number of output files! There should only be one.\n" ); cmdline_parser_free( &options ); return 1; } // Check if we were asked to prompt for selection: if ( options.select_flag ) { // Execute slop with any options given. std::string result; std::stringstream slopcommand; slopcommand << "slop "; slopcommand << options.nokeyboard_flag ? "--nokeyboard" : ""; slopcommand << " -b " << options.bordersize_arg; slopcommand << " -p " << options.padding_arg; slopcommand << " -t " << options.tolerance_arg; slopcommand << " -g " << options.gracetime_arg; slopcommand << " -c " << options.color_arg; slopcommand << options.nodecorations_flag ? "-n" : ""; slopcommand << " --min=" << options.min_arg; slopcommand << " --max=" << options.max_arg; slopcommand << options.highlight_flag ? "-l" : ""; err = exec( slopcommand.str(), &result ); if ( err ) { fprintf( stderr, "slop failed to run, canceling screenshot. Is slop installed?\n" ); cmdline_parser_free( &options ); return 1; } // from here we'll just be parsing the output of slop. // Replace all ='s with spaces in the result, this is so sscanf works properly. int find = result.find( "=" ); while( find != result.npos ) { result.at( find ) = ' '; find = result.find( "=" ); } int x, y, w, h; int num = sscanf( result.c_str(), "X %d\n Y %d\n W %d\n H %d\n%*s", &x, &y, &w, &h ); if ( num == 4 && ( w > 0 && h > 0 ) ) { bool mask = checkMask( options.mask_arg, x, y, w, h, options.windowid_arg ); // Wait the designated amount of time before taking the screenshot. // 1000000 microseconds = 1 second usleep( (unsigned int)(delay * 1000000.f) ); err = imengine->screenshot( file, x, y, w, h, options.hidecursor_flag, options.windowid_arg, mask ); cmdline_parser_free( &options ); if ( err ) { return err; } return 0; } fprintf( stderr, "Either the user canceled the query for selection, or slop failed to run properly. Canceling screenshot.\n" ); cmdline_parser_free( &options ); return 1; } if ( options.x_given && options.y_given && options.w_given && options.h_given ) { options.geometry_given = true; char temp[128]; sprintf( temp, "%ix%i+%i+%i\0", options.w_arg, options.h_arg, options.x_arg, options.y_arg ); options.geometry_arg = temp; } else if ( ( options.x_given || options.y_given || options.w_given || options.h_given ) && !options.geometry_given ) { fprintf( stderr, "Partial geometry arguments were set, but it isn't enough data to take a screenshot!" ); fprintf( stderr, "Either give the geometry arugment, or give ALL of the following arguments: x, y, w, h," ); fprintf( stderr, " or don't give any of them." ); cmdline_parser_free( &options ); return 1; } // Just take a full screen shot if we didn't get any geometry. if ( !options.geometry_given ) { // Wait the designated amount of time before taking the screenshot. // 1000000 microseconds = 1 second usleep( (unsigned int)(delay * 1000000.f) ); err = imengine->screenshot( file, options.hidecursor_flag, options.windowid_arg, strcmp( options.mask_arg, "off" ) ? true : false ); cmdline_parser_free( &options ); if ( err ) { return err; } return 0; } // Otherwise take a screen shot of the supplied region. int x, y, w, h; parseGeometry( options.geometry_arg, &x, &y, &w, &h ); bool mask = checkMask( options.mask_arg, x, y, w, h, options.windowid_arg ); usleep( (unsigned int)(delay * 1000000.f) ); err = imengine->screenshot( file, x, y, w, h, options.hidecursor_flag, options.windowid_arg, mask ); cmdline_parser_free( &options ); if ( err ) { return err; } return 0; }
int main(int argc, char *argv[]) { struct gengetopt_args_info argi[1]; const char *ofmt; char **fmt; size_t nfmt; int res = 0; zif_t fromz = NULL; zif_t z = NULL; if (cmdline_parser(argc, argv, argi)) { res = 1; goto out; } /* init and unescape sequences, maybe */ ofmt = argi->format_arg; fmt = argi->input_format_arg; nfmt = argi->input_format_given; if (argi->backslash_escapes_given) { dt_io_unescape(argi->format_arg); for (size_t i = 0; i < nfmt; i++) { dt_io_unescape(fmt[i]); } } /* try and read the from and to time zones */ if (argi->from_zone_given) { fromz = zif_open(argi->from_zone_arg); } if (argi->zone_given) { z = zif_open(argi->zone_arg); } if (argi->default_given) { struct dt_dt_s dflt = dt_strpdt(argi->default_arg, NULL, NULL); dt_set_default(dflt); } if (argi->inputs_num) { for (size_t i = 0; i < argi->inputs_num; i++) { const char *inp = argi->inputs[i]; struct dt_dt_s d = dt_io_strpdt(inp, fmt, nfmt, fromz); if (!dt_unk_p(d)) { dt_io_write(d, ofmt, z, '\n'); } else if (!argi->quiet_given) { dt_io_warn_strpdt(inp); } } } else { /* read from stdin */ size_t lno = 0; struct grep_atom_s __nstk[16], *needle = __nstk; size_t nneedle = countof(__nstk); struct grep_atom_soa_s ndlsoa; void *pctx; struct prln_ctx_s prln = { .ndl = &ndlsoa, .ofmt = ofmt, .fromz = fromz, .outz = z, .sed_mode_p = argi->sed_mode_given, .quietp = argi->quiet_given, }; /* no threads reading this stream */ __io_setlocking_bycaller(stdout); /* lest we overflow the stack */ if (nfmt >= nneedle) { /* round to the nearest 8-multiple */ nneedle = (nfmt | 7) + 1; needle = calloc(nneedle, sizeof(*needle)); } /* and now build the needles */ ndlsoa = build_needle(needle, nneedle, fmt, nfmt); /* using the prchunk reader now */ if ((pctx = init_prchunk(STDIN_FILENO)) == NULL) { error(errno, "Error: could not open stdin"); goto ndl_free; } while (prchunk_fill(pctx) >= 0) { for (char *line; prchunk_haslinep(pctx); lno++) { size_t llen = prchunk_getline(pctx, &line); proc_line(prln, line, llen); } } /* get rid of resources */ free_prchunk(pctx); ndl_free: if (needle != __nstk) { free(needle); } } if (argi->from_zone_given) { zif_close(fromz); } if (argi->zone_given) { zif_close(z); } out: cmdline_parser_free(argi); return res; }
int main(int argc, char *argv[]) { char *modelDir=NULL; /* Directory with model files */ struct svm_model* decision_model; /* SVM classification model */ /* Command line options */ int reverse=0; /* Scan reverse complement */ int showVersion=0; /* Shows version and exits */ int showHelp=0; /* Show short help and exits */ int from=-1; /* Scan slice from-to */ int to=-1; FILE *clust_file=stdin; /* Input file */ FILE *out=stdout; /* Output file */ struct aln *AS[MAX_NUM_NAMES]; struct aln *window[MAX_NUM_NAMES]; char *tmpAln[MAX_NUM_NAMES]; int n_seq; /* number of input sequences */ int length; /* length of alignment/window */ int z_score_type; int decision_model_type; char *structure=NULL; char *singleStruc,*gapStruc, *output,*woGapsSeq; char strand[8]; char warningString[2000]; char warningString_regression[2000]; char *string=NULL; double singleMFE,sumMFE,singleZ,sumZ,z,sci,id,decValue,prob,comb,entropy,GC; double min_en, real_en; int i,j,k,l,ll,r,countAln,nonGaps,singleGC; int (*readFunction)(FILE *clust,struct aln *alignedSeqs[]); char** lines=NULL; int directions[3]={FORWARD,0,0}; int currDirection; struct gengetopt_args_info args; double meanMFE_fwd=0; double consensusMFE_fwd=0; double sci_fwd=0; double z_fwd=0; int strandGuess; int avoid_shuffle=0; double strandProb,strandDec; if (cmdline_parser (argc, argv, &args) != 0){ usage(); exit(EXIT_FAILURE); } if (args.help_given){ help(); exit(EXIT_SUCCESS); } if (args.version_given){ version(); exit(EXIT_SUCCESS); } if (args.outfile_given){ out = fopen(args.outfile_arg, "w"); if (out == NULL){ fprintf(stderr, "ERROR: Can't open output file %s\n", args.outfile_arg); exit(1); } } /* Strand prediction implies both strands scored */ if (args.predict_strand_flag){ args.both_strands_flag=1; } if (args.forward_flag && !args.reverse_flag){ directions[0]=FORWARD; directions[1]=directions[2]=0; } if (!args.forward_flag && args.reverse_flag){ directions[0]=REVERSE; directions[1]=directions[2]=0; } if ((args.forward_flag && args.reverse_flag) || args.both_strands_flag){ directions[0]=FORWARD; directions[1]=REVERSE; } if (args.window_given){ if (sscanf(args.window_arg,"%d-%d",&from,&to)!=2){ nrerror("ERROR: Invalid --window/-w command. " "Use it like '--window 100-200'\n"); } printf("from:%d,to:%d\n",from,to); } if (args.inputs_num>=1){ clust_file = fopen(args.inputs[0], "r"); if (clust_file == NULL){ fprintf(stderr, "ERROR: Can't open input file %s\n", args.inputs[0]); exit(1); } } /* Global RNA package variables */ do_backtrack = 1; dangles=2; switch(checkFormat(clust_file)){ case CLUSTAL: readFunction=&read_clustal; break; case MAF: readFunction=&read_maf; break; case 0: nrerror("ERROR: Unknown alignment file format. Use Clustal W or MAF format.\n"); } /* Set z-score type (mono/dinucleotide) here */ z_score_type = 2; if (args.mononucleotide_given) z_score_type = 0; /* now let's decide which decision model to take */ /* decision_model_type = 1 for normal model used in RNAz 1.0 */ /* decision_model_type = 2 for normal model using dinucelotide background */ /* decision_model_type = 3 for structural model using dinucelotide background */ decision_model_type = 2; if (args.mononucleotide_given) decision_model_type = 1; if (args.locarnate_given) decision_model_type = 3; if ((args.mononucleotide_given) && args.locarnate_given){ z_score_type=2; nrerror("ERROR: Structural decision model only trained with dinucleotide background model.\n"); } if (args.no_shuffle_given) avoid_shuffle = 1; decision_model=get_decision_model(NULL, decision_model_type); /* Initialize Regression Models for mononucleotide */ /* Not needed if we score with dinucleotides */ if (z_score_type == 0) regression_svm_init(); countAln=0; while ((n_seq=readFunction(clust_file, AS))!=0){ if (n_seq ==1){ nrerror("ERROR: You need at least two sequences in the alignment.\n"); } countAln++; length = (int) strlen(AS[0]->seq); /* if a slice is specified by the user */ if ((from!=-1 || to!=-1) && (countAln==1)){ if ((from>=to)||(from<=0)||(to>length)){ nrerror("ERROR: Invalid window range given.\n"); } sliceAln((const struct aln**)AS, (struct aln **)window, from, to); length=to-from+1; } else { /* take complete alignment */ /* window=AS does not work..., deep copy seems not necessary here*/ from=1; to=length; sliceAln((const struct aln **)AS, (struct aln **)window, 1, length); } /* Convert all Us to Ts for RNAalifold. There is a slight difference in the results. During training we used alignments with Ts, so we use Ts here as well. */ for (i=0;i<n_seq;i++){ j=0; while (window[i]->seq[j]){ window[i]->seq[j]=toupper(window[i]->seq[j]); if (window[i]->seq[j]=='U') window[i]->seq[j]='T'; ++j; } } k=0; while ((currDirection=directions[k++])!=0){ if (currDirection==REVERSE){ revAln((struct aln **)window); strcpy(strand,"reverse"); } else { strcpy(strand,"forward"); } structure = (char *) space((unsigned) length+1); for (i=0;window[i]!=NULL;i++){ tmpAln[i]=window[i]->seq; } tmpAln[i]=NULL; min_en = alifold(tmpAln, structure); free_alifold_arrays(); comb=combPerPair(window,structure); sumZ=0.0; sumMFE=0.0; GC=0.0; output=(char *)space(sizeof(char)*(length+160)*(n_seq+1)*3); strcpy(warningString,""); strcpy(warningString_regression,""); for (i=0;i<n_seq;i++){ singleStruc = space(strlen(window[i]->seq)+1); woGapsSeq = space(strlen(window[i]->seq)+1); j=0; nonGaps=0; singleGC=0; while (window[i]->seq[j]){ /* Convert all Ts to Us for RNAfold. There is a difference between the results. With U in the function call, we get the results as RNAfold gives on the command line. Since this variant was also used during training, we use it here as well. */ if (window[i]->seq[j]=='T') window[i]->seq[j]='U'; if (window[i]->seq[j]=='C') singleGC++; if (window[i]->seq[j]=='G') singleGC++; if (window[i]->seq[j]!='-'){ nonGaps++; woGapsSeq[strlen(woGapsSeq)]=window[i]->seq[j]; woGapsSeq[strlen(woGapsSeq)]='\0'; } ++j; } /* z-score is calculated here! */ singleMFE = fold(woGapsSeq, singleStruc); free_arrays(); /* z-score type may be overwritten. If it is out of training bounds, we switch to shuffling if allowed (avoid_shuffle). */ int z_score_type_orig = z_score_type; singleZ=mfe_zscore(woGapsSeq,singleMFE, &z_score_type, avoid_shuffle, warningString_regression); GC+=(double) singleGC/nonGaps; sumZ+=singleZ; sumMFE+=singleMFE; if (window[1]->strand!='?' && !args.window_given){ sprintf(output+strlen(output), ">%s %d %d %c %d\n", window[i]->name,window[i]->start, window[i]->length,window[i]->strand, window[i]->fullLength); } else { sprintf(output+strlen(output),">%s\n",window[i]->name); } gapStruc= (char *) space(sizeof(char)*(strlen(window[i]->seq)+1)); l=ll=0; while (window[i]->seq[l]!='\0'){ if (window[i]->seq[l]!='-'){ gapStruc[l]=singleStruc[ll]; l++; ll++; } else { gapStruc[l]='-'; l++; } } char ch; ch = 'R'; if (z_score_type == 1 || z_score_type == 3) ch = 'S'; sprintf(output+strlen(output),"%s\n%s ( %6.2f, z-score = %6.2f, %c)\n", window[i]->seq,gapStruc,singleMFE,singleZ,ch); z_score_type = z_score_type_orig; free(woGapsSeq); free(singleStruc); } { int i; double s=0; extern int eos_debug; eos_debug=-1; /* shut off warnings about nonstandard pairs */ for (i=0; window[i]!=NULL; i++) s += energy_of_struct(window[i]->seq, structure); real_en = s/i; } string = consensus((const struct aln**) window); sprintf(output+strlen(output), ">consensus\n%s\n%s (%6.2f = %6.2f + %6.2f) \n", string, structure, min_en, real_en, min_en-real_en ); free(string); id=meanPairID((const struct aln**)window); entropy=NormShannonEntropy((const struct aln**)window); z=sumZ/n_seq; GC=(double)GC/n_seq; if (sumMFE==0){ /*Set SCI to 0 in the weird case of no structure in single sequences*/ sci=0; } else { sci=min_en/(sumMFE/n_seq); } decValue=999; prob=0; classify(&prob,&decValue,decision_model,id,n_seq,z,sci,entropy,decision_model_type); if (args.cutoff_given){ if (prob<args.cutoff_arg){ continue; } } warning(warningString,id,n_seq,z,sci,entropy,(struct aln **)window,decision_model_type); fprintf(out,"\n############################ RNAz "PACKAGE_VERSION" ##############################\n\n"); fprintf(out," Sequences: %u\n", n_seq); if (args.window_given){ fprintf(out," Slice: %u to %u\n",from,to); } fprintf(out," Columns: %u\n",length); fprintf(out," Reading direction: %s\n",strand); fprintf(out," Mean pairwise identity: %6.2f\n", id); fprintf(out," Shannon entropy: %2.5f\n", entropy); fprintf(out," G+C content: %2.5f\n", GC); fprintf(out," Mean single sequence MFE: %6.2f\n", sumMFE/n_seq); fprintf(out," Consensus MFE: %6.2f\n",min_en); fprintf(out," Energy contribution: %6.2f\n",real_en); fprintf(out," Covariance contribution: %6.2f\n",min_en-real_en); fprintf(out," Combinations/Pair: %6.2f\n",comb); fprintf(out," Mean z-score: %6.2f\n",z); fprintf(out," Structure conservation index: %6.2f\n",sci); if (decision_model_type == 1) { fprintf(out," Background model: mononucleotide\n"); fprintf(out," Decision model: sequence based alignment quality\n"); } if (decision_model_type == 2) { fprintf(out," Background model: dinucleotide\n"); fprintf(out," Decision model: sequence based alignment quality\n"); } if (decision_model_type == 3) { fprintf(out," Background model: dinucleotide\n"); fprintf(out," Decision model: structural RNA alignment quality\n"); } fprintf(out," SVM decision value: %6.2f\n",decValue); fprintf(out," SVM RNA-class probability: %6f\n",prob); if (prob>0.5){ fprintf(out," Prediction: RNA\n"); } else { fprintf(out," Prediction: OTHER\n"); } fprintf(out,"%s",warningString_regression); fprintf(out,"%s",warningString); fprintf(out,"\n######################################################################\n\n"); fprintf(out,"%s",output); fflush(out); free(structure); free(output); if (currDirection==FORWARD && args.predict_strand_flag){ meanMFE_fwd=sumMFE/n_seq; consensusMFE_fwd=min_en; sci_fwd=sci; z_fwd=z; } if (currDirection==REVERSE && args.predict_strand_flag){ if (predict_strand(sci_fwd-sci, meanMFE_fwd-(sumMFE/n_seq), consensusMFE_fwd-min_en, z_fwd-z, n_seq, id, &strandGuess, &strandProb, &strandDec, NULL)){ if (strandGuess==1){ fprintf(out, "\n# Strand winner: forward (%.2f)\n",strandProb); } else { fprintf(out, "\n# Strand winner: reverse (%.2f)\n",1-strandProb); } } else { fprintf(out, "\n# WARNING: No strand prediction (values out of range)\n"); } } } freeAln((struct aln **)AS); freeAln((struct aln **)window); } if (args.inputs_num>=1){ fclose(clust_file); } cmdline_parser_free (&args); if (countAln==0){ nrerror("ERROR: Empty alignment file\n"); } svm_destroy_model(decision_model); regression_svm_free(); return 0; }
void free_gengetopt() { cmdline_parser_free(&args_info); }
int main (int argc, char **argv) { /*printf("%s:%d\n", __FILE__, __LINE__);*/ int fd, c, i; struct gengetopt_args_info cmdline; /* Parse command line */ if (cmdline_parser (argc, argv, &cmdline) != 0) exit(1); doiintf = cmdline.interface_arg; productid = cmdline.product_arg; vendorid = cmdline.vendor_arg; verbose = cmdline.verbose_given; doint = cmdline.interrupt_flag; gadgetfs = cmdline.gadgetfs_arg; if (cmdline.info_flag) return print_avail(verbose); if (ccid_initialize(cmdline.reader_arg, verbose) < 0) { fprintf (stderr, "Can't initialize ccid\n"); return 1; } if (chdir (gadgetfs) < 0) { fprintf (stderr, "Error changing directory to %s\n", gadgetfs); return 1; } if (strncmp(cmdline.serial_arg, "random", strlen("random")) == 0) { /* random initial serial number */ srand ((int) time (0)); for (i = 0; i < sizeof serial - 1; ) { c = rand () % 127; if ((('a' <= c && c <= 'z') || ('0' <= c && c <= '9'))) serial [i++] = c; } if (verbose) fprintf (stderr, "serial=\"%s\"\n", serial); } else { for (i=0; i<sizeof stringtab/sizeof(struct usb_string); i++) { if (stringtab[i].id == STRINGID_SERIAL) { stringtab[i].s = cmdline.serial_arg; break; } } if (verbose) fprintf (stderr, "serial=\"%s\"\n", cmdline.serial_arg); } if (doiintf) { for (i=0; i<sizeof stringtab/sizeof(struct usb_string); i++) { if (stringtab[i].id == STRINGID_INTERFACE) { stringtab[i].s = doiintf; break; } } } fd = init_device (); if (fd < 0) return 1; if (debug) fprintf (stderr, "%s%s ep0 configured\n", gadgetfs, DEVNAME); fflush (stdout); fflush (stderr); (void) ep0_thread (&fd); cmdline_parser_free(&cmdline); return 0; }
int main(int argc, char ** argv) { int result = 0; AwaClientSubscribeOperation * operation; struct gengetopt_args_info ai; AwaClientSession * session = NULL; // Catch CTRL-C to ensure clean-up signal(SIGINT, INThandler); if (cmdline_parser(argc, argv, &ai) != 0) { exit(1); } g_logLevel = ai.debug_given ? 2 : (ai.verbose_given ? 1 : 0); AwaLog_SetLevel(ai.debug_given ? AwaLogLevel_Debug : (ai.verbose_given ? AwaLogLevel_Verbose : AwaLogLevel_Warning)); if (ai.inputs_num == 0) { Error("Specify one or more resource paths.\n"); result = 1; goto cleanup; } session = Client_EstablishSession(ai.ipcAddress_arg, ai.ipcPort_arg); if (session != NULL) { operation = AwaClientSubscribeOperation_New(session); if (operation == NULL) { Error("Failed to create subscribe operation\n"); exit(1); } void * context = &ai.quiet_given; // pass the quiet parameter as our context int count = 0; int i = 0; for (i = 0; i < ai.inputs_num; ++i) { Target * target = CreateTarget(ai.inputs[i]); if (target != NULL) { count = SubscribeToTarget(session, operation, target, context) ? count + 1 : count; FreeTarget(&target); } } if (AwaClientSubscribeOperation_Perform(operation, OPERATION_PERFORM_TIMEOUT) != AwaError_Success) { Error("Failed to perform subscribe operation\n"); goto cleanup; } int validCount = count; const AwaClientSubscribeResponse * response = AwaClientSubscribeOperation_GetResponse(operation); SubscriptionNode * currentSubscription = g_subscriptionListHead; SubscriptionNode * nextSubscription; while (currentSubscription != NULL) { nextSubscription = currentSubscription->next; const AwaPathResult * pathResult = NULL; const char * path = NULL; switch (currentSubscription->type) { case AwaSubscribeType_Change: { AwaClientChangeSubscription * subscription = (AwaClientChangeSubscription *)(currentSubscription->subscription); path = AwaClientChangeSubscription_GetPath(subscription); break; } case AwaSubscribeType_Execute: { AwaClientExecuteSubscription * subscription = (AwaClientExecuteSubscription *)(currentSubscription->subscription); path = AwaClientExecuteSubscription_GetPath(subscription); break; } default: Error("Unsupported subscribe type: %d for path %s\n", currentSubscription->type, path); break; } pathResult = AwaClientSubscribeResponse_GetPathResult(response, path); if (AwaPathResult_GetError(pathResult) != AwaError_Success) { Error("Failed to subscribe to %s: %s\n", path, AwaError_ToString(AwaPathResult_GetError(pathResult))); validCount--; } currentSubscription = nextSubscription; } AwaClientSubscribeOperation_Free(&operation); Debug("count %d\n", count); // Wait if there's something to wait for if (count > 0) { if (validCount > 0) { Wait(session, ai.waitTime_arg, ai.waitCount_arg); } UnsubscribeFromTargets(session); } } else { Error("Failed to establish Awa Session\n"); result = 1; } cleanup: if (session) { FreeSubscriptionList(); Client_ReleaseSession(&session); } cmdline_parser_free(&ai); return result; }
static void process_options_gg (int argc, char *argv[]) { struct gengetopt_args_info args_info; if (cmdline_parser (argc, argv, &args_info) != 0) exit(1) ; if (args_info.help_given) cmdline_parser_print_help(); if (args_info.full_help_given) cmdline_parser_print_full_help(); GTV.dangle = args_info.dangle_arg; GSV.Temp = args_info.Temp_arg; strncpy(GAV.ParamFile,255,args_info.Par_arg); GTV.Par = args_info.Par_given; GTV.logML = args_info.logML_flag; GTV.noShift = args_info.noShift_flag; GTV.noLP = args_info.noLP_flag; GTV.start= args_info.start_flag; GTV.stop = args_info.stop_flag; GTV.mc = args_info.met_flag; GTV.lmin = args_info.lmin_flag; GTV.verbose = args_info.verbose_flag; GTV.silent = (GTV.verbose==0)? args_info.silent_flag : 0; if (args_info.seed_given) if (sscanf(args_info.seed_arg, "%hu=%hu=%hu", &GAV.subi[0], &GAV.subi[1], &GAV.subi[2]) != 3) usage(EXIT_FAILURE); else GTV.seed = 1; /* laplace stuff */ if (args_info.phi_given) { if (args_info.phi_arg>0) { GTV.phi = 1; GSV.phi = args_info.phi_arg; } else { fprintf(stderr, "Value of --phi must be > 0 >%lf<\n", args_info.phi_arg); exit(EXIT_FAILURE); } } if (args_info.pbounds_given) { if (sscanf(args_info.pbounds_arg, "%g=%g=%g", &GAV.phi_bounds[0], &GAV.phi_bounds[1], &GAV.phi_bounds[2]) == 0) usage(EXIT_FAILURE); else GTV.phi = 1; /* check if values are proper */ if (GAV.phi_bounds[0] > GAV.phi_bounds[2] || GAV.phi_bounds[1] > GAV.phi_bounds[2]) { fprintf(stderr, "Unmet requirements for pbounds:\n" "phi_min < phi_max && phi_inc < phi_max\n" "phi_min: %g phi_inc: %g phi_max: %g\n", GAV.phi_bounds[0], GAV.phi_bounds[1], GAV.phi_bounds[2]); exit(EXIT_FAILURE); } } GSV.time = args_info.time_arg; GSV.num = args_info.num_arg; strncpy(GAV.BaseName, args_info.log_arg, 255); GSV.cut = args_info.cut_arg; GSV.grow = args_info.grow_arg; GSV.glen = args_info.glen_arg; GTV.lmin = args_info.lmin_flag; GTV.fpt = args_info.fpt_flag; cmdline_parser_free(&args_info); }
int app( int argc, char** argv ) { // First parse any options and the filename we need. gengetopt_args_info options; int err = cmdline_parser( argc, argv, &options ); if ( err != EXIT_SUCCESS ) { return EXIT_FAILURE; } maim::IMEngine* imengine = new maim::IMEngine(options); // Then set up the x interface. if ( options.xdisplay_given ) { err = xengine->init( options.xdisplay_arg ); } else { // If we weren't specifically given a xdisplay, we try // to parse it from environment variables char* display = getenv( "DISPLAY" ); if ( display ) { err = xengine->init( display ); } else { fprintf( stderr, "Warning: Failed to parse environment variable: DISPLAY. Using \":0\" instead.\n" ); err = xengine->init( ":0" ); } } if ( err != EXIT_SUCCESS ) { fprintf( stderr, "Failed to grab X display!\n" ); return EXIT_FAILURE; } // Then the imlib2 interface err = imengine->init(); if ( err != EXIT_SUCCESS ) { fprintf( stderr, "Failed to initialize imlib2!\n" ); return EXIT_FAILURE; } // Grab all of our variables from the options. bool gotGeometry = false; bool gotSelectFlag = options.select_flag; int x, y, w, h; float delay; err = sscanf( options.delay_arg, "%f", &delay ); if ( err != 1 ) { fprintf( stderr, "Failed to parse %s as a float for delay!\n", options.delay_arg ); return EXIT_FAILURE; } struct timespec delayTime; delayTime.tv_sec = delay; delayTime.tv_nsec = 0; // Get our geometry if we have any. if ( options.x_given && options.y_given && options.w_given && options.h_given && !options.geometry_given ) { x = options.x_arg; y = options.y_arg; w = options.w_arg; h = options.h_arg; gotGeometry = true; } else if ( ( options.x_given || options.y_given || options.w_given || options.h_given ) && !options.geometry_given ) { fprintf( stderr, "Partial geometry arguments were set, but it isn't enough data to take a screenshot!\n" ); fprintf( stderr, "Please give the geometry argument or give ALL of the following arguments: x, y, w, h.\n" ); cmdline_parser_free( &options ); return EXIT_FAILURE; } else if ( options.geometry_given ) { err = parseGeometry( options, &x, &y, &w, &h ); if ( err != EXIT_SUCCESS ) { fprintf( stderr, "Failed to parse geometry %s, should be in format WxH+X+Y!\n", options.geometry_orig ); cmdline_parser_free( &options ); return EXIT_FAILURE; } gotGeometry = true; } // Get our window if we have one, default to the root window. Window window = xengine->m_root; if ( options.windowid_given ) { window = (Window)options.windowid_arg; } // Get our file name std::string file = ""; // If we don't have a file, default to writing to the home directory. if ( options.inputs_num == 0 ) { // Try as hard as we can to get the current directory. int trycount = 0; char* home_env = getenv("HOME"); int length = MAXPATHLEN; char* currentdir = new char[ length ]; char* error = getcwd( currentdir, length ); while ( error == NULL ) { delete[] currentdir; length *= 2; currentdir = new char[ length ]; error = getcwd( currentdir, length ); trycount++; // Ok someone's trying to be whacky with the current directory if we're going 8 times over // the max path length. if ( trycount > 3 ) { fprintf( stderr, "Failed to grab the current directory!" ); // Try to HOME later if ( home_env == NULL ) { fprintf( stderr, "Failed to get HOME environment variable, no where left to save!" ); cmdline_parser_free( &options ); delete [] currentdir; return EXIT_FAILURE; } } } if ( is_valid_directory ( currentdir ) == EXIT_SUCCESS ) { file = currentdir; } else { file = home_env; } // Get unix timestamp std::stringstream result; result << (int)time( NULL ); file += "/" + result.str() + ".png"; printf( "No file specified, using %s\n", file.c_str() ); delete [] currentdir; } else if ( options.inputs_num == 1 ) { file = options.inputs[ 0 ]; } else { fprintf( stderr, "Unexpected number of output files! There should only be one.\n" ); cmdline_parser_free( &options ); return EXIT_FAILURE; } // Finally we have all our information, now to use it. if ( gotSelectFlag ) { err = slop( options, &x, &y, &w, &h, &window ); if ( err != EXIT_SUCCESS ) { fprintf( stderr, "Selection was cancelled or slop failed to run. Make sure it's installed!\n" ); cmdline_parser_free( &options ); return EXIT_FAILURE; } err = nanosleep( &delayTime, NULL ); if ( err != EXIT_SUCCESS ) { fprintf( stderr, "Warning: Failed to delay the screenshot. Continuing anyway..." ); } err = imengine->screenshot( window, x, y, w, h ); if ( err != EXIT_SUCCESS ) { fprintf( stderr, "Failed to take screenshot.\n" ); return EXIT_FAILURE; } if ( options.showcursor_flag ) { imengine->blendCursor( window, x, y ); } if ( checkMask( options.mask_arg, x, y, w, h, window ) ) { imengine->mask( x, y, w, h ); } err = imengine->save( file, options.format_arg ); cmdline_parser_free( &options ); if ( err != EXIT_SUCCESS ) { fprintf( stderr, "Failed to take screenshot.\n" ); return EXIT_FAILURE; } return EXIT_SUCCESS; } if ( gotGeometry ) { err = nanosleep( &delayTime, NULL ); if ( err != EXIT_SUCCESS ) { fprintf( stderr, "Warning: Failed to delay the screenshot. Continuing anyway..." ); } err = imengine->screenshot( window, x, y, w, h ); if ( err != EXIT_SUCCESS ) { fprintf( stderr, "Failed to take screenshot.\n" ); return EXIT_FAILURE; } if ( options.showcursor_flag ) { imengine->blendCursor( window, x, y ); } if ( checkMask( options.mask_arg, x, y, w, h, window ) ) { imengine->mask( x, y, w, h ); } err = imengine->save( file, options.format_arg ); cmdline_parser_free( &options ); if ( err != EXIT_SUCCESS ) { fprintf( stderr, "Failed to take screenshot.\n" ); return EXIT_FAILURE; } return EXIT_SUCCESS; } // If we didn't get any special options, just screenshot the specified window // (Which defaults to the whole screen). err = nanosleep( &delayTime, NULL ); if ( err != EXIT_SUCCESS ) { fprintf( stderr, "Warning: Failed to delay the screenshot. Continuing anyway..." ); } err = imengine->screenshot( window ); if ( err != EXIT_SUCCESS ) { fprintf( stderr, "Failed to take screenshot.\n" ); return EXIT_FAILURE; } if ( options.showcursor_flag ) { imengine->blendCursor( window ); } if ( checkMask( options.mask_arg, 0, 0, WidthOfScreen( xengine->m_screen ), HeightOfScreen( xengine->m_screen ), window ) ) { imengine->mask(); } err = imengine->save( file, options.format_arg ); cmdline_parser_free( &options ); if ( err != EXIT_SUCCESS ) { fprintf( stderr, "Failed to take screenshot.\n" ); return EXIT_FAILURE; } return EXIT_SUCCESS; }
int main(int argc, char ** argv) { int result = 1; struct gengetopt_args_info ai; AwaServerSession * session = NULL; AwaServerWriteOperation * operation = NULL; char address[128]; unsigned int port; if (cmdline_parser(argc, argv, &ai) != 0) { result = 1; goto cleanup; } g_logLevel = ai.debug_given ? 2 : (ai.verbose_given ? 1 : 0); AwaLog_SetLevel(ai.debug_given ? AwaLogLevel_Debug : (ai.verbose_given ? AwaLogLevel_Verbose : AwaLogLevel_Warning)); if (ai.inputs_num == 0 && ai.create_given == 0) { Error("Specify one or more resource paths.\n"); result = 1; goto cleanup; } port = ai.ipcPort_arg; strncpy(address, ai.ipcAddress_arg, strlen(ai.ipcAddress_arg)+1); // Establish Awa Session with the daemon session = Server_EstablishSession(address, port); if (session == NULL) { Error("Failed to establish Awa Session\n"); result = 1; goto cleanup; } AwaWriteMode mode = AwaWriteMode_Update; if (ai.replace_given) mode = AwaWriteMode_Replace; operation = AwaServerWriteOperation_New(session, mode); if (operation == NULL) { Error("AwaServerWriteOperation_New failed\n"); Server_ReleaseSession(&session); result = 1; goto cleanup; } // Add create directives first int count = 0; count = CreateTargets(session, operation, ai.clientID_arg, ai.create_arg, ai.create_given); // Add target paths and values from the command line int i = 0; for (i = 0; i < ai.inputs_num; ++i) { Target * target = CreateTarget(ai.inputs[i]); if (target != NULL) { char * value = Server_GetValue(session, target, ai.inputs[i]); if (value != NULL) { if (AddTargetWithValue(session, operation, target, value) == 0) { ++count; } free(value); value = NULL; } FreeTarget(&target); } } if (count > 0) { result = ProcessWriteOperation(operation, ai.clientID_arg); } cleanup: if (operation) { AwaServerWriteOperation_Free(&operation); } if (session) { Server_ReleaseSession(&session); } cmdline_parser_free(&ai); return result; }
int main(int argc, char **argv) { /* gengeopt declarations */ struct gengetopt_args_info args_info; struct hostent *host; /* Handle keyboard interrupt SIGINT */ struct sigaction s; s.sa_handler = (void *) signal_handler; if ((0 != sigemptyset( &s.sa_mask )) && debug) printf("sigemptyset failed.\n"); s.sa_flags = SA_RESETHAND; if ((sigaction(SIGINT, &s, NULL) != 0) && debug) printf("Could not register SIGINT signal handler.\n"); fd_set fds; /* For select() */ struct timeval idleTime; /* How long to select() */ int timelimit; /* Number of seconds to be connected */ int starttime; /* Time program was started */ /* open a connection to the syslog daemon */ /*openlog(PACKAGE, LOG_PID, LOG_DAEMON);*/ /* TODO: Only use LOG__PERROR for linux */ #ifdef __linux__ openlog(PACKAGE, (LOG_PID | LOG_PERROR), LOG_DAEMON); #else openlog(PACKAGE, (LOG_PID), LOG_DAEMON); #endif if (cmdline_parser (argc, argv, &args_info) != 0) exit(1); if (args_info.debug_flag) { printf("listen: %s\n", args_info.listen_arg); if (args_info.conf_arg) printf("conf: %s\n", args_info.conf_arg); printf("fg: %d\n", args_info.fg_flag); printf("debug: %d\n", args_info.debug_flag); printf("qos: %#08x\n", args_info.qos_arg); if (args_info.apn_arg) printf("apn: %s\n", args_info.apn_arg); if (args_info.net_arg) printf("net: %s\n", args_info.net_arg); if (args_info.dynip_arg) printf("dynip: %s\n", args_info.dynip_arg); if (args_info.statip_arg) printf("statip: %s\n", args_info.statip_arg); if (args_info.ipup_arg) printf("ipup: %s\n", args_info.ipup_arg); if (args_info.ipdown_arg) printf("ipdown: %s\n", args_info.ipdown_arg); if (args_info.pidfile_arg) printf("pidfile: %s\n", args_info.pidfile_arg); if (args_info.statedir_arg) printf("statedir: %s\n", args_info.statedir_arg); printf("timelimit: %d\n", args_info.timelimit_arg); } /* Try out our new parser */ if (cmdline_parser_configfile (args_info.conf_arg, &args_info, 0, 0, 0) != 0) exit(1); if (args_info.debug_flag) { printf("cmdline_parser_configfile\n"); printf("listen: %s\n", args_info.listen_arg); printf("conf: %s\n", args_info.conf_arg); printf("fg: %d\n", args_info.fg_flag); printf("debug: %d\n", args_info.debug_flag); printf("qos: %#08x\n", args_info.qos_arg); if (args_info.apn_arg) printf("apn: %s\n", args_info.apn_arg); if (args_info.net_arg) printf("net: %s\n", args_info.net_arg); if (args_info.dynip_arg) printf("dynip: %s\n", args_info.dynip_arg); if (args_info.statip_arg) printf("statip: %s\n", args_info.statip_arg); if (args_info.ipup_arg) printf("ipup: %s\n", args_info.ipup_arg); if (args_info.ipdown_arg) printf("ipdown: %s\n", args_info.ipdown_arg); if (args_info.pidfile_arg) printf("pidfile: %s\n", args_info.pidfile_arg); if (args_info.statedir_arg) printf("statedir: %s\n", args_info.statedir_arg); printf("timelimit: %d\n", args_info.timelimit_arg); } /* Handle each option */ /* debug */ debug = args_info.debug_flag; /* listen */ /* Do hostname lookup to translate hostname to IP address */ /* Any port listening is not possible as a valid address is */ /* required for create_pdp_context_response messages */ if (args_info.listen_arg) { if (!(host = gethostbyname(args_info.listen_arg))) { sys_err(LOG_ERR, __FILE__, __LINE__, 0, "Invalid listening address: %s!", args_info.listen_arg); exit(1); } else { memcpy(&listen_.s_addr, host->h_addr, host->h_length); } } else { sys_err(LOG_ERR, __FILE__, __LINE__, 0, "Listening address must be specified! " "Please use command line option --listen or " "edit %s configuration file\n", args_info.conf_arg); exit(1); } /* net */ /* Store net as in_addr net and mask */ if (args_info.net_arg) { if(ippool_aton(&net, &mask, args_info.net_arg, 0)) { sys_err(LOG_ERR, __FILE__, __LINE__, 0, "Invalid network address: %s!", args_info.net_arg); exit(1); } netaddr.s_addr = htonl(ntohl(net.s_addr) + 1); destaddr.s_addr = htonl(ntohl(net.s_addr) + 1); } else { sys_err(LOG_ERR, __FILE__, __LINE__, 0, "Network address must be specified: %s!", args_info.net_arg); exit(1); } /* dynip */ if (!args_info.dynip_arg) { if (ippool_new(&ippool, args_info.net_arg, NULL, 1, 0, IPPOOL_NONETWORK | IPPOOL_NOGATEWAY | IPPOOL_NOBROADCAST)) { sys_err(LOG_ERR, __FILE__, __LINE__, 0, "Failed to allocate IP pool!"); exit(1); } } else { if (ippool_new(&ippool, args_info.dynip_arg, NULL, 1 ,0, IPPOOL_NONETWORK | IPPOOL_NOGATEWAY | IPPOOL_NOBROADCAST)) { sys_err(LOG_ERR, __FILE__, __LINE__, 0, "Failed to allocate IP pool!"); exit(1); } } /* DNS1 and DNS2 */ #ifdef HAVE_INET_ATON dns1.s_addr = 0; if (args_info.pcodns1_arg) { if (0 == inet_aton(args_info.pcodns1_arg, &dns1)) { sys_err(LOG_ERR, __FILE__, __LINE__, 0, "Failed to convert pcodns1!"); exit(1); } } dns2.s_addr = 0; if (args_info.pcodns2_arg) { if (0 == inet_aton(args_info.pcodns2_arg, &dns2)) { sys_err(LOG_ERR, __FILE__, __LINE__, 0, "Failed to convert pcodns2!"); exit(1); } } #else dns1.s_addr = 0; if (args_info.pcodns1_arg) { dns1.s_addr = inet_addr(args_info.pcodns1_arg); if (dns1.s_addr == -1) { sys_err(LOG_ERR, __FILE__, __LINE__, 0, "Failed to convert pcodns1!"); exit(1); } } dns2.s_addr = 0; if (args_info.pcodns2_arg) { dns2.s_addr = inet_addr(args_info.pcodns2_arg); if (dns2.s_addr == -1) { sys_err(LOG_ERR, __FILE__, __LINE__, 0, "Failed to convert pcodns2!"); exit(1); } } #endif pco.l = 20; pco.v[0] = 0x80; /* x0000yyy x=1, yyy=000: PPP */ pco.v[1] = 0x80; /* IPCP */ pco.v[2] = 0x21; pco.v[3] = 0x10; /* Length of contents */ pco.v[4] = 0x02; /* ACK */ pco.v[5] = 0x00; /* ID: Need to match request */ pco.v[6] = 0x00; /* Length */ pco.v[7] = 0x10; pco.v[8] = 0x81; /* DNS 1 */ pco.v[9] = 0x06; memcpy(&pco.v[10], &dns1, sizeof(dns1)); pco.v[14] = 0x83; pco.v[15] = 0x06; /* DNS 2 */ memcpy(&pco.v[16], &dns2, sizeof(dns2)); /* ipup */ ipup = args_info.ipup_arg; /* ipdown */ ipdown = args_info.ipdown_arg; /* Timelimit */ timelimit = args_info.timelimit_arg; starttime = time(NULL); /* qos */ qos.l = 3; qos.v[2] = (args_info.qos_arg) & 0xff; qos.v[1] = ((args_info.qos_arg) >> 8) & 0xff; qos.v[0] = ((args_info.qos_arg) >> 16) & 0xff; /* apn */ if (strlen(args_info.apn_arg) > (sizeof(apn.v)-1)) { printf("Invalid APN\n"); return -1; } apn.l = strlen(args_info.apn_arg) + 1; apn.v[0] = (char) strlen(args_info.apn_arg); strncpy((char *) &apn.v[1], args_info.apn_arg, sizeof(apn.v)-1); /* foreground */ /* If flag not given run as a daemon */ if (!args_info.fg_flag) { closelog(); /* Close the standard file descriptors. */ /* Is this really needed ? */ freopen("/dev/null", "w", stdout); freopen("/dev/null", "w", stderr); freopen("/dev/null", "r", stdin); daemon(0, 0); /* Open log again. This time with new pid */ openlog(PACKAGE, LOG_PID, LOG_DAEMON); } /* pidfile */ /* This has to be done after we have our final pid */ if (args_info.pidfile_arg) { log_pid(args_info.pidfile_arg); } if (debug) printf("gtpclient: Initialising GTP tunnel\n"); if (gtp_new(&gsn, args_info.statedir_arg, &listen_, GTP_MODE_GGSN)) { sys_err(LOG_ERR, __FILE__, __LINE__, 0, "Failed to create gtp"); exit(1); } if (gsn->fd0 > maxfd) maxfd = gsn->fd0; if (gsn->fd1c > maxfd) maxfd = gsn->fd1c; if (gsn->fd1u > maxfd) maxfd = gsn->fd1u; gtp_set_cb_data_ind(gsn, encaps_tun); gtp_set_cb_delete_context(gsn, delete_context); gtp_set_cb_create_context_ind(gsn, create_context_ind); /* Create a tunnel interface */ if (debug) printf("Creating tun interface\n"); if (tun_new((struct tun_t**) &tun)) { sys_err(LOG_ERR, __FILE__, __LINE__, 0, "Failed to create tun"); if (debug) printf("Failed to create tun\n"); exit(1); } if (debug) printf("Setting tun IP address\n"); if (tun_setaddr(tun, &netaddr, &destaddr, &mask)) { sys_err(LOG_ERR, __FILE__, __LINE__, 0, "Failed to set tun IP address"); if (debug) printf("Failed to set tun IP address\n"); exit(1); } tun_set_cb_ind(tun, cb_tun_ind); if (tun->fd > maxfd) maxfd = tun->fd; if (ipup) tun_runscript(tun, ipup); /******************************************************************/ /* Main select loop */ /******************************************************************/ while ((((starttime + timelimit) > time(NULL)) || (0 == timelimit)) && (!end)) { FD_ZERO(&fds); if (tun) FD_SET(tun->fd, &fds); FD_SET(gsn->fd0, &fds); FD_SET(gsn->fd1c, &fds); FD_SET(gsn->fd1u, &fds); gtp_retranstimeout(gsn, &idleTime); switch (select(maxfd + 1, &fds, NULL, NULL, &idleTime)) { case -1: /* errno == EINTR : unblocked signal */ sys_err(LOG_ERR, __FILE__, __LINE__, 0, "select() returned -1"); /* On error, select returns without modifying fds */ FD_ZERO(&fds); break; case 0: /* printf("Select returned 0\n"); */ gtp_retrans(gsn); /* Only retransmit if nothing else */ break; default: break; } if (tun->fd != -1 && FD_ISSET(tun->fd, &fds) && tun_decaps(tun) < 0) { sys_err(LOG_ERR, __FILE__, __LINE__, 0, "TUN read failed (fd)=(%d)", tun->fd); } if (FD_ISSET(gsn->fd0, &fds)) gtp_decaps0(gsn); if (FD_ISSET(gsn->fd1c, &fds)) gtp_decaps1c(gsn); if (FD_ISSET(gsn->fd1u, &fds)) gtp_decaps1u(gsn); } cmdline_parser_free(&args_info); ippool_free(ippool); gtp_free(gsn); tun_free(tun); return 1; }
int main(int argc, char *argv[]) { double time_spent; clock_t begin, end; begin = clock(); install_signal_handler(); struct gengetopt_args_info args_info; cod_t cod_struct; dict_t dict_struct; int parser_ret; parser_ret = cmdline_parser(argc, argv, &args_info); /** parse the user given parameters with gengetopt */ if (parser_ret != 0) { fprintf(stderr, "[ERROR] while calling cmdline_parser\n"); exit(1); } /**Missing Arguments or incorrect arguments ate least one argument must be provided*/ if (argc < 2) { printf("===================== HELP: Some Arguments Avaiable: =====================\n\n"); printf("--encode --> use this to encode an image file, don't forget to supply the file to encode\n"); printf("--parallel-encode --> use this to encode an image file with threads, don't forget to supply the file to encode and the number of threads\n"); printf("--decode --> use this to decode an image file, don't forget to supply the file to decode\n"); printf("--decode-dir --> use this to decode images in a given directory, suply the directory path\n"); printf("--PSNR --> use this to calculate .... between the original and decoded file, must supply both files as arguments\n"); printf("--dict --> use this to suply the dictionary file while encoding or decoding images\n"); printf("--about --> use this to know about the this app programmers\n"); printf("--help --> to know all the arguments avaiable\n\n"); printf("================================================================================\n"); exit(1); } /** About the authors */ if (args_info.about_given){ about(); } /** Decode the given file*/ if (args_info.decode_given){ cod_struct = read_cod_file(args_info.decode_arg); dict_struct = read_dictionary (args_info.dict_arg); decode_pgm(cod_struct, dict_struct, args_info.decode_arg); } /** Calculate PSNR */ if(args_info.PSNR_given){ char *token; char delim[2] = ","; char *original_filename; char *decoded_filename; token = strtok (args_info.PSNR_arg,delim); //point to 1 filename (before delimiter) original_filename = token; token = strtok (NULL, delim); //point to 2 filename (after delimiter) decoded_filename = token; DEBUG("%s", original_filename); DEBUG("%s", decoded_filename); calculatePSNR (original_filename, decoded_filename); } /** ------------------- Project Delivery II ------------------------- */ /** --encode argument given*/ if(args_info.encode_given){ printf("\n[TO BE DONE] option not implemented yet!!!\n"); } /** --parallel-encode argument given*/ if(args_info.parallel_encode_given){ /** --threads argument not given*/ if(!args_info.threads_given) { fprintf(stderr, "[ERROR] --threads <nthreads> parameter is mandatory with --parallel-enconde\n"); exit(1); }else { if(args_info.threads_arg > 1) { printf("\n[TO BE DONE] option not implemented yet!!!\n"); }else { fprintf(stderr, "[ERROR] The threads number must be more than 1\n"); exit(1); } } } if (args_info.decode_dir_given) { printf("\nOption not full implemented yet!!!\n"); } if (args_info.dict_given == 1) { validate_extension(args_info.dict_arg, ".dic"); } /** free the memory allocated by gengetop */ cmdline_parser_free (&args_info); end = clock(); time_spent = (double)(end - begin) / CLOCKS_PER_SEC; printf ("Excution Time: %.3f s\n", time_spent); return 0; }
int main(int argc, char ** argv) { int result = 0; AwaServerSession * session = NULL; AwaServerExecuteOperation * operation = NULL; struct gengetopt_args_info ai; if (cmdline_parser(argc, argv, &ai) != 0) { result = 1; goto cleanup; } g_logLevel = ai.debug_given ? 2 : (ai.verbose_given ? 1 : 0); AwaLog_SetLevel(ai.debug_given ? AwaLogLevel_Debug : (ai.verbose_given ? AwaLogLevel_Verbose : AwaLogLevel_Warning)); if (ai.inputs_num == 0) { Error("Specify one or more resource paths.\n"); result = 1; goto cleanup; } // Create Session session = Server_EstablishSession(ai.ipcAddress_arg, ai.ipcPort_arg); if (session == NULL) { Error("EstablishSession failed\n"); result = 1; goto cleanup; } operation = AwaServerExecuteOperation_New(session); if (operation == NULL) { Error("AwaServerExecuteOperation_New failed\n"); result = 1; goto cleanup; } AwaExecuteArguments arguments = { .Data = NULL, .Size = 0 }; if (ai.stdin_given) { char buf[BUFSIZ]; int numBytes = 0; while (fread(buf+numBytes, 1, 1, stdin) == 1) { numBytes++; } arguments.Data = buf; arguments.Size = numBytes; Verbose("Read payload from stdin: %s [%zu bytes]\n", buf, arguments.Size); } else { Verbose("No payload specified.\n"); } int i = 0; for (i = 0; i < ai.inputs_num; ++i) { Target * target = CreateTarget(ai.inputs[i]); if (target != NULL) { AddTarget(operation, ai.clientID_arg, target, &arguments); FreeTarget(&target); } } result = ProcessExecuteOperation(session, operation, ai.clientID_arg); cleanup: if (session) { Server_ReleaseSession(&session); } if (operation) { AwaServerExecuteOperation_Free(&operation); } cmdline_parser_free(&ai); return result; }
int main(int argc, char *argv[]) { int rc, sync[2]; pid_t pid = -1; siginfo_t status; struct mount *mounts = NULL; struct netif *netifs = NULL; struct cgroup *cgroups = NULL; struct user *users = NULL; #if HAVE_LIBCAP_NG struct capability *caps = NULL; #endif char *master; _close_ int master_fd = -1; char ephemeral_dir[] = "/tmp/pflask-ephemeral-XXXXXX"; int clone_flags = CLONE_NEWNS | CLONE_NEWIPC | CLONE_NEWPID | #ifdef CLONE_NEWCGROUP CLONE_NEWCGROUP | #endif CLONE_NEWUTS; struct gengetopt_args_info args; if (cmdline_parser(argc, argv, &args) != 0) return 1; for (unsigned int i = 0; i < args.mount_given; i++) { validate_optlist("--mount", args.mount_arg[i]); mount_add_from_spec(&mounts, args.mount_arg[i]); } for (unsigned int i = 0; i < args.netif_given; i++) { clone_flags |= CLONE_NEWNET; if (args.netif_arg != NULL) { validate_optlist("--netif", args.netif_arg[i]); netif_add_from_spec(&netifs, args.netif_arg[i]); } } if (args.user_given && !args.user_map_given) { uid_t uid; gid_t gid; clone_flags |= CLONE_NEWUSER; if (user_get_uid_gid(args.user_arg, &uid, &gid)) { user_add_map(&users, 'u', uid, uid, 1); user_add_map(&users, 'g', gid, gid, 1); } } for (unsigned int i = 0; i < args.user_map_given; i++) { size_t count; uid_t id, host_id; char *start = args.user_map_arg[i], *end = NULL; validate_optlist("--user-map", args.user_map_arg[i]); clone_flags |= CLONE_NEWUSER; id = strtoul(start, &end, 10); if (*end != ':') fail_printf("Invalid value '%s' for --user-map", args.user_map_arg[i]); start = end + 1; host_id = strtoul(start, &end, 10); if (*end != ':') fail_printf("Invalid value '%s' for --user-map", args.user_map_arg[i]); start = end + 1; count = strtoul(start, &end, 10); if (*end != '\0') fail_printf("Invalid value '%s' for --user-map", args.user_map_arg[i]); user_add_map(&users, 'u', id, host_id, count); user_add_map(&users, 'g', id, host_id, count); } for (unsigned int i = 0; i < args.cgroup_given; i++) cgroup_add(&cgroups, args.cgroup_arg[i]); #if HAVE_LIBCAP_NG for (unsigned int i = 0; i < args.caps_given; i++) capability_add(&caps, args.caps_arg[i]); #endif if (args.no_userns_flag) clone_flags &= ~(CLONE_NEWUSER); if (args.no_mountns_flag) clone_flags &= ~(CLONE_NEWNS); if (args.no_netns_flag) clone_flags &= ~(CLONE_NEWNET); if (args.no_ipcns_flag) clone_flags &= ~(CLONE_NEWIPC); if (args.no_utsns_flag) clone_flags &= ~(CLONE_NEWUTS); if (args.no_pidns_flag) clone_flags &= ~(CLONE_NEWPID); if (args.attach_given) { master_fd = recv_pty(args.attach_arg); fail_if(master_fd < 0, "Invalid PID '%u'", args.attach_arg); process_pty(master_fd); return 0; } open_master_pty(&master_fd, &master); if (args.detach_flag) do_daemonize(); sync_init(sync); if (args.ephemeral_flag) { if (!mkdtemp(ephemeral_dir)) sysf_printf("mkdtemp()"); } pid = do_clone(&clone_flags); if (!pid) { closep(&master_fd); rc = prctl(PR_SET_PDEATHSIG, SIGKILL); sys_fail_if(rc < 0, "prctl(PR_SET_PDEATHSIG)"); rc = setsid(); sys_fail_if(rc < 0, "setsid()"); sync_barrier_parent(sync, SYNC_START); sync_close(sync); open_slave_pty(master); setup_user(args.user_arg); if (args.hostname_given) { rc = sethostname(args.hostname_arg, strlen(args.hostname_arg)); sys_fail_if(rc < 0, "Error setting hostname"); } setup_mount(mounts, args.chroot_arg, args.ephemeral_flag ? ephemeral_dir : NULL); if (args.chroot_given) { setup_nodes(args.chroot_arg); setup_ptmx(args.chroot_arg); setup_symlinks(args.chroot_arg); setup_console(args.chroot_arg, master); do_chroot(args.chroot_arg); } if (clone_flags & CLONE_NEWNET) config_netif(); umask(0022); #if HAVE_LIBCAP_NG setup_capabilities(caps); #endif if (args.chdir_given) { rc = chdir(args.chdir_arg); sys_fail_if(rc < 0, "Error changing cwd"); } if (args.chroot_given) { char *term = getenv("TERM"); if (!args.keepenv_flag) clearenv(); setenv("PATH", "/usr/sbin:/usr/bin:/sbin:/bin", 1); setenv("USER", args.user_arg, 1); setenv("LOGNAME", args.user_arg, 1); if (term) setenv("TERM", term, 1); } for (unsigned int i = 0; i < args.setenv_given; i++) { rc = putenv(strdup(args.setenv_arg[i])); sys_fail_if(rc != 0, "Error setting environment"); } setenv("container", "pflask", 1); if (argc > optind) rc = execvpe(argv[optind], argv + optind, environ); else rc = execle("/bin/bash", "-bash", NULL, environ); sys_fail_if(rc < 0, "Error executing command"); } sync_wait_child(sync, SYNC_START); if (args.chroot_given && (clone_flags & CLONE_NEWUSER)) setup_console_owner(master, users); setup_cgroup(cgroups, pid); setup_netif(netifs, pid); #ifdef HAVE_DBUS register_machine(pid, args.chroot_given ? args.chroot_arg : ""); #endif if (clone_flags & CLONE_NEWUSER) setup_user_map(users, pid); sync_wake_child(sync, SYNC_DONE); sync_close(sync); if (args.detach_flag) serve_pty(master_fd); else process_pty(master_fd); kill(pid, SIGKILL); rc = waitid(P_PID, pid, &status, WEXITED); sys_fail_if(rc < 0, "Error waiting for child"); switch (status.si_code) { case CLD_EXITED: if (status.si_status != 0) err_printf("Child failed with code '%d'", status.si_status); else ok_printf("Child exited"); break; case CLD_KILLED: err_printf("Child was terminated by signal '%d'", status.si_status); break; default: err_printf("Child failed"); break; } sync_close(sync); clean_cgroup(cgroups); if (args.ephemeral_flag) { rc = rmdir(ephemeral_dir); sys_fail_if(rc != 0, "Error deleting ephemeral directory: %s", ephemeral_dir); } cmdline_parser_free(&args); return status.si_status; }
int main(int argc, char ** argv) { int result = 0; struct gengetopt_args_info ai; AwaClientSession * session = NULL; AwaClientSetOperation * operation = NULL; if (cmdline_parser(argc, argv, &ai) != 0) { exit(1); } g_logLevel = ai.debug_given ? 2 : (ai.verbose_given ? 1 : 0); AwaLog_SetLevel(ai.debug_given ? AwaLogLevel_Debug : (ai.verbose_given ? AwaLogLevel_Verbose : AwaLogLevel_Warning)); if ((ai.inputs_num == 0) && (ai.create_given == 0)) { Error("Specify one or more resource paths.\n"); result = 1; goto cleanup; } session = Client_EstablishSession(ai.ipcAddress_arg, ai.ipcPort_arg); if (session != NULL) { // Create Set operation operation = AwaClientSetOperation_New(session); if (operation != NULL) { // Add create directives first int count = 0; count = CreateTargets(session, operation, ai.create_arg, ai.create_given); // Add target paths and values from the command line int i = 0; for (i = 0; i < ai.inputs_num; ++i) { Target * target = CreateTarget(ai.inputs[i]); if (target != NULL) { char * value = Client_GetValue(session, target, ai.inputs[i]); if (value != NULL) { if (AddTargetWithValue(session, operation, target, value) == 0) { ++count; } free(value); value = NULL; } FreeTarget(&target); } } if (count > 0) { // Process Set operation result = ProcessSetOperation(operation); } } else { Error("Failed to create Set operation\n"); result = 1; } } else { Error("Failed to establish Awa Session\n"); result = 1; } cleanup: if (operation) { AwaClientSetOperation_Free(&operation); } if (session) { Client_ReleaseSession(&session); } cmdline_parser_free(&ai); return result; }
/*============================*/ int main (int argc, char *argv[]) { int tmp; char *line; loc_min *LM; int *tm; int i; char signal[100]="", what[100]="", stuff[100]=""; /* Parse command line */ program_name = argv[0]; opt.kT = -300; opt.MOVESET = ""; opt.minh = 0.0000001; opt.label = 0; /* normally, use numbers for minima */ GRAPH = NULL; /* Try to parse head to determine graph-type */ decode_switches (argc, argv); if (args_info.inputs_num > 0) { opt.INFILE = fopen(args_info.inputs[0], "r"); if (opt.INFILE==NULL) nrerror("can't open file"); } else { opt.INFILE = stdin; } line = get_line(opt.INFILE); if (line == NULL) { fprintf(stderr,"Error in input file\n"); exit(123); } opt.seq = (char *) space(strlen(line) + 1); sscanf(line,"%s %d %99s %99s %99s", opt.seq, &tmp, signal, what, stuff); if(strcmp(stuff, "\0")!=0 && strncmp(what, "Q", 1)==0) { /* lattice proteins*/ memset(opt.seq, 0, strlen(line)+1); strcpy(opt.seq, stuff); } if ((!opt.poset)&&(strcmp(signal,"::")!=0)) { int r, dim; /* in this case we have a poset file !!!! */ r=sscanf(signal,"P:%d",&dim); if(r<1) { fprintf(stderr, "Warning: obscure headline in input file\n"); dim = 0; } if(dim>0) opt.poset = dim; } if (opt.poset) { /* in this case we have a poset file !!!! */ fprintf(stderr, "!!! Input data are a poset with %d objective functions\n", opt.poset); /* we have a SECIS design file */ if ( ((GRAPH != NULL) && (strstr(GRAPH, "SECIS") != NULL)) ||(strncmp(what, "SECIS", 5) == 0) ) { #if HAVE_SECIS_EXTENSION int len, max_m, min_as; char *sec_structure, *protein_sequence; if (sscanf(what,"SECIS,%d,%d", &max_m, &min_as) < 2) { fprintf(stderr, "Error in input format for SECIS design !" "expected format: SECIS,INT,INT\n" "got: `%s'", what); exit(EXIT_FAILURE); } free(line); line = get_line(opt.INFILE); len = strlen(line); sec_structure = (char*)calloc(len+1, sizeof(char)); protein_sequence = (char*)calloc(len+1, sizeof(char)); sscanf(line,"%s %s", sec_structure, protein_sequence); if (opt.want_verbose) fprintf(stderr, "\nGraph is SECIS design with the following parameters:\n" "Structure: %s\n" "Constraints: %s\n" "Protein sequence: %s\n" "Max. number of mutations : %d\n" "Min. alignment score (aa): %d\n\n", sec_structure, opt.seq, protein_sequence, max_m, min_as); initialize_SECIS(opt.seq, sec_structure, protein_sequence, max_m, min_as); free(sec_structure); free(protein_sequence); #else fprintf(stderr, "You need to reconfigure barriers with the --with-secis" " option\nto use barriers SECIS design extension\n"); exit(EXIT_FAILURE); #endif } } free(line); if (GRAPH==NULL) if(strlen(what)) GRAPH = what; if (GRAPH==NULL) GRAPH="RNA"; opt.GRAPH=GRAPH; LM = barriers(opt); if (opt.INFILE != stdin) fclose(opt.INFILE); tm = make_truemin(LM); if(opt.poset) mark_global(LM); print_results(LM,tm,opt.seq); fflush(stdout); if (!opt.want_quiet) ps_tree(LM,tm,0); if (opt.rates || opt.microrates) { compute_rates(tm,opt.seq); if (!opt.want_quiet) ps_tree(LM,tm,1); print_rates(tm[0], "rates.out"); } if (opt.poset) mark_global(LM); for (i = 0; i < args_info.path_given; ++i) { int L1, L2; sscanf(args_info.path_arg[i], "%d=%d", &L1, &L2); if ((L1>0) && (L2>0)) { FILE *PATH = NULL; char tmp[30]; path_entry *path; path = backtrack_path(L1, L2, LM, tm); (void) sprintf(tmp, "path.%03d.%03d.txt", L1, L2); PATH = fopen (tmp, "w"); if (PATH == NULL) nrerror("couldn't open path file"); print_path(PATH, path, tm); /* fprintf(stderr, "%llu %llu\n", 0, MAXIMUM); */ fclose (PATH); fprintf (stderr, "wrote file %s\n", tmp); free (path); } } /* memory cleanup */ free(opt.seq); free(LM); free(tm); #if WITH_DMALLOC kill_hash(); /* freeing the hash takes unacceptably long */ #endif cmdline_parser_free(&args_info); exit(0); }
int app( int argc, char** argv ) { gengetopt_args_info options; int err = cmdline_parser( argc, argv, &options ); if ( err != EXIT_SUCCESS ) { return EXIT_FAILURE; } int state = 0; bool running = true; bool opengl = options.opengl_flag; slop::SelectRectangle* selection = NULL; Window window = None; Window windowmemory = None; std::string xdisplay; if ( options.xdisplay_given ) { xdisplay = options.xdisplay_arg; } else { // If we weren't specifically given a xdisplay, we try // to parse it from environment variables char* display = getenv( "DISPLAY" ); if ( display ) { xdisplay = display; } else { fprintf( stderr, "Warning: Failed to parse environment variable: DISPLAY. Using \":0\" instead.\n" ); xdisplay = ":0"; } } int padding = options.padding_arg; int borderSize = options.bordersize_arg; int tolerance = options.tolerance_arg; float r, g, b, a; err = parseColor( options.color_arg, &r, &g, &b, &a ); if ( err != EXIT_SUCCESS ) { fprintf( stderr, "Error parsing color %s\n", options.color_arg ); return EXIT_FAILURE; } float gracetime; err = sscanf( options.gracetime_arg, "%f", &gracetime ); if ( err != 1 ) { fprintf( stderr, "Error parsing %s as a float for gracetime!\n", options.gracetime_arg ); return EXIT_FAILURE; } bool highlight = options.highlight_flag; bool keyboard = !options.nokeyboard_flag; bool decorations = !options.nodecorations_flag; bool themeon = (bool)options.theme_given; std::string theme = options.theme_arg; #ifdef OPENGL_ENABLED bool shadergiven = (bool)options.shader_given; #endif std::string shader = options.shader_arg; struct timespec start, time; int xoffset = 0; int yoffset = 0; int cx = 0; int cy = 0; int xmem = 0; int ymem = 0; int wmem = 0; int hmem = 0; int minimumsize = options.min_arg; int maximumsize = options.max_arg; bool pressedMemory[4]; double pressedTime[4]; for ( int i=0;i<4;i++ ) { pressedMemory[ i ] = false; pressedTime[ i ] = 0; } std::string format = options.format_arg; bool magenabled = options.magnify_flag; #ifdef OPENGL_ENABLED float magstrength = options.magstrength_arg; if ( options.magpixels_arg < 0 ) { fprintf( stderr, "Error: --magpixels < 0, it's an unsigned integer you twat. Stop trying to underflow me!\n" ); return EXIT_FAILURE; } unsigned int magpixels = (unsigned int)options.magpixels_arg; #endif cmdline_parser_free( &options ); #ifndef OPENGL_ENABLED if ( opengl || themeon || magenabled ) { throw std::runtime_error( "Slop wasn't compiled with OpenGL support, so themes, magnifications, and shaders are disabled! Try compiling it with the CMAKE_OPENGL_SUPPORT set to true." ); } #else // OPENGL_ENABLED if ( ( themeon || magenabled || shadergiven ) && !opengl ) { throw std::runtime_error( "Slop needs --opengl enabled to use themes, shaders, or magnifications." ); } #endif // First we set up the x interface and grab the mouse, // if we fail for either we exit immediately. err = xengine->init( xdisplay.c_str() ); if ( err != EXIT_SUCCESS ) { printSelection( format, true, 0, 0, 0, 0, None ); return EXIT_FAILURE; } if ( !slop::isSelectRectangleSupported() ) { fprintf( stderr, "Error: Your X server doesn't support the XShape extension. There's nothing slop can do about this!\n" ); fprintf( stderr, " Try updating X and making sure you have XExtensions installed. (/usr/lib/libXext.so, /usr/include/X11/extensions/shape.h)\n" ); return EXIT_FAILURE; } err = xengine->grabCursor( slop::Cross, gracetime ); if ( err != EXIT_SUCCESS ) { printSelection( format, true, 0, 0, 0, 0, None ); return EXIT_FAILURE; } if ( keyboard ) { err = xengine->grabKeyboard(); if ( err ) { fprintf( stderr, "Warning: Failed to grab the keyboard. This is non-fatal, keyboard presses might fall through to other applications.\n" ); } } current_utc_time( &start ); double deltatime = 0; double curtime = double( start.tv_sec*1000000000L + start.tv_nsec )/1000000000.f; while ( running ) { current_utc_time( &time ); // "ticking" the xengine makes it process all queued events. xengine->tick(); // If the user presses any key on the keyboard, exit the application. // Make sure at least gracetime has passed before allowing canceling double newtime = double( time.tv_sec*1000000000L + time.tv_nsec )/1000000000.f; deltatime = newtime-curtime; curtime = newtime; double starttime = double( start.tv_sec*1000000000L + start.tv_nsec )/1000000000.f; if ( curtime - starttime > gracetime ) { if ( keyRepeat( XK_Up, curtime, 0.5, &pressedTime[ 0 ], &pressedMemory[ 0 ] ) ) { yoffset -= 1; } if ( keyRepeat( XK_Down, curtime, 0.5, &pressedTime[ 1 ], &pressedMemory[ 1 ] ) ) { yoffset += 1; } if ( keyRepeat( XK_Left, curtime, 0.5, &pressedTime[ 2 ], &pressedMemory[ 2 ] ) ) { xoffset -= 1; } if ( keyRepeat( XK_Right, curtime, 0.5, &pressedTime[ 3 ], &pressedMemory[ 3 ] ) ) { xoffset += 1; } // If we pressed enter we move the state onward. if ( xengine->keyPressed( XK_Return ) ) { // If we're highlight windows, just select the active window. if ( state == 0 ) { state = 1; // If we're making a custom selection, select the custom selection. } else if ( state == 2 ) { state = 3; } } // If we press any key other than the arrow keys or enter key, we shut down! if ( !( xengine->keyPressed( XK_Up ) || xengine->keyPressed( XK_Down ) || xengine->keyPressed( XK_Left ) || xengine->keyPressed( XK_Right ) ) && !( xengine->keyPressed( XK_Return ) ) && ( ( xengine->anyKeyPressed() && keyboard ) || xengine->mouseDown( 3 ) ) ) { printSelection( format, true, 0, 0, 0, 0, None ); fprintf( stderr, "User pressed key. Canceled selection.\n" ); state = -1; running = false; } } // Our adorable little state manager will handle what state we're in. switch ( state ) { default: { break; } case 0: { // If xengine has found a window we're hovering over (or if it changed) // create a rectangle around it so the user knows he/she can click on it. // --but only if the user wants us to if ( window != xengine->m_hoverWindow && tolerance > 0 ) { slop::WindowRectangle t; t.setGeometry( xengine->m_hoverWindow, decorations ); t.applyPadding( padding ); t.applyMinMaxSize( minimumsize, maximumsize ); // Make sure we only apply offsets to windows that we've forcibly removed decorations on. if ( !selection ) { #ifdef OPENGL_ENABLED if ( opengl ) { selection = new slop::GLSelectRectangle( t.m_x, t.m_y, t.m_x + t.m_width, t.m_y + t.m_height, borderSize, highlight, r, g, b, a ); // Haha why is this so hard to cast? ((slop::GLSelectRectangle*)(selection))->setMagnifySettings( magenabled, magstrength, magpixels ); ((slop::GLSelectRectangle*)(selection))->setTheme( themeon, theme ); ((slop::GLSelectRectangle*)(selection))->setShader( shader ); } else { #endif // OPENGL_ENABLED selection = new slop::XSelectRectangle( t.m_x, t.m_y, t.m_x + t.m_width, t.m_y + t.m_height, borderSize, highlight, r, g, b, a ); #ifdef OPENGL_ENABLED } #endif // OPENGL_ENABLED } else { selection->setGeo( t.m_x, t.m_y, t.m_x + t.m_width, t.m_y + t.m_height ); } //window = xengine->m_hoverWindow; // Since WindowRectangle can select different windows depending on click location... window = t.getWindow(); } if ( selection ) { selection->update( deltatime ); } // If the user clicked we move on to the next state. if ( xengine->mouseDown( 1 ) ) { state++; } break; } case 1: { // Set the mouse position of where we clicked, used so that click tolerance doesn't affect the rectangle's position. cx = xengine->m_mousex; cy = xengine->m_mousey; // Make sure we don't have un-seen applied offsets. xoffset = 0; yoffset = 0; // Also remember where the original selection was if ( selection ) { xmem = selection->m_x; ymem = selection->m_y; wmem = selection->m_width; hmem = selection->m_height; } else { xmem = cx; ymem = cy; } state++; break; } case 2: { // It's possible that our selection doesn't exist still, lets make sure it actually gets created here. if ( !selection ) { int sx, sy, ex, ey; constrain( cx, cy, xengine->m_mousex, xengine->m_mousey, padding, minimumsize, maximumsize, &sx, &sy, &ex, &ey ); #ifdef OPENGL_ENABLED if ( opengl ) { selection = new slop::GLSelectRectangle( sx, sy, ex, ey, borderSize, highlight, r, g, b, a ); // Haha why is this so hard to cast? ((slop::GLSelectRectangle*)(selection))->setMagnifySettings( magenabled, magstrength, magpixels ); ((slop::GLSelectRectangle*)(selection))->setTheme( themeon, theme ); ((slop::GLSelectRectangle*)(selection))->setShader( shader ); } else { #endif // OPENGL_ENABLED selection = new slop::XSelectRectangle( sx, sy, ex, ey, borderSize, highlight, r, g, b, a ); #ifdef OPENGL_ENABLED } #endif // OPENGL_ENABLED } windowmemory = window; // If the user has let go of the mouse button, we'll just // continue to the next state. if ( !xengine->mouseDown( 1 ) ) { state++; break; } // Check to make sure the user actually wants to drag for a selection before moving things around. int w = xengine->m_mousex - cx; int h = xengine->m_mousey - cy; if ( ( std::abs( w ) < tolerance && std::abs( h ) < tolerance ) ) { // We make sure the selection rectangle stays on the window we had selected selection->setGeo( xmem, ymem, xmem + wmem, ymem + hmem ); selection->update( deltatime ); xengine->setCursor( slop::Left ); // Make sure window = windowmemory; continue; } // If we're not selecting a window. windowmemory = window; window = None; // We also detect which way the user is pulling and set the mouse icon accordingly. bool x = cx > xengine->m_mousex; bool y = cy > xengine->m_mousey; if ( ( selection->m_width <= 1 && selection->m_height <= 1 ) || ( minimumsize == maximumsize && minimumsize != 0 && maximumsize != 0 ) ) { xengine->setCursor( slop::Cross ); } else if ( !x && !y ) { xengine->setCursor( slop::LowerRightCorner ); } else if ( x && !y ) { xengine->setCursor( slop::LowerLeftCorner ); } else if ( !x && y ) { xengine->setCursor( slop::UpperRightCorner ); } else if ( x && y ) { xengine->setCursor( slop::UpperLeftCorner ); } // Apply padding and minimum size adjustments. int sx, sy, ex, ey; constrain( cx, cy, xengine->m_mousex, xengine->m_mousey, padding, minimumsize, maximumsize, &sx, &sy, &ex, &ey ); // Set the selection rectangle's dimensions to mouse movement. selection->setGeo( sx + xoffset, sy + yoffset, ex, ey ); selection->update( deltatime ); break; } case 3: { int x, y, w, h; // Exit the utility after this state runs once. running = false; // We pull the dimensions and positions from the selection rectangle. // The selection rectangle automatically converts the positions and // dimensions to absolute coordinates when we set them earilier. x = selection->m_x; y = selection->m_y; w = selection->m_width; h = selection->m_height; // Delete the rectangle, which will remove it from the screen. delete selection; // Make sure if no window was specifically specified, that we output the root window. Window temp = window; if ( temp == None ) { temp = xengine->m_root; } // Print the selection :) printSelection( format, false, x, y, w, h, temp ); break; } } // This sleep is required because drawing the rectangles is a very expensive task that acts really weird with Xorg when called as fast as possible. // 0.01 seconds usleep( 10000 ); } xengine->releaseCursor(); xengine->releaseKeyboard(); // Try to process any last-second requests. //xengine->tick(); // Clean up global classes. delete xengine; // Sleep for 0.05 seconds to ensure everything was cleaned up. (Without this, slop's window often shows up in screenshots.) usleep( 50000 ); // If we canceled the selection, return error. if ( state == -1 ) { return EXIT_FAILURE; } return EXIT_SUCCESS; }
//Main program int main(int argc, char *argv[]) { INT4 ii, jj; //counter variables //Turn off gsl error handler gsl_set_error_handler_off(); //Initiate command line interpreter and config file loader struct gengetopt_args_info args_info; struct cmdline_parser_params *configparams; configparams = cmdline_parser_params_create(); //initialize parameters structure configparams->check_required = 0; //don't check for required values at the step if ( cmdline_parser_ext(argc, argv, &args_info, configparams) ) { fprintf(stderr, "%s: cmdline_parser_ext() failed.\n", __func__); XLAL_ERROR(XLAL_FAILURE); } configparams->initialize = 0; //don't reinitialize the parameters structure if ( args_info.config_given && cmdline_parser_config_file(args_info.config_arg, &args_info, configparams) ) { fprintf(stderr, "%s: cmdline_parser_config_file() failed.\n", __func__); XLAL_ERROR(XLAL_FAILURE); } //Check required if ( cmdline_parser_required(&args_info, argv[0]) ) { fprintf(stderr, "%s: cmdline_parser_required() failed.\n", __func__); XLAL_ERROR(XLAL_FAILURE); } //Set lalDebugLevel to user input or 0 if no input //Allocate input parameters structure memory inputParamsStruct *inputParams = new_inputParams(args_info.IFO_given); if (inputParams==NULL) { fprintf(stderr, "%s: new_inputParams() failed.\n", __func__); XLAL_ERROR(XLAL_EFUNC); } //Read TwoSpect input parameters if ( (readTwoSpectInputParams(inputParams, args_info)) != 0 ) { fprintf(stderr, "%s: readTwoSpectInputParams() failed.\n", __func__); XLAL_ERROR(XLAL_EFUNC); } //Initialize ephemeris data structure EphemerisData *edat = XLALInitBarycenter(earth_ephemeris, sun_ephemeris); if (edat==NULL) { fprintf(stderr, "%s: XLALInitBarycenter() failed.\n", __func__); XLAL_ERROR(XLAL_EFUNC); } //Maximum detector velocity in units of c from start of observation time - Tcoh to end of observation + Tcoh REAL4 detectorVmax = CompDetectorVmax(inputParams->searchstarttime-inputParams->Tcoh, inputParams->Tcoh, inputParams->SFToverlap, inputParams->Tobs+2.0*inputParams->Tcoh, inputParams->det[0], edat); if (xlalErrno!=0) { fprintf(stderr, "%s: CompDetectorVmax() failed.\n", __func__); XLAL_ERROR(XLAL_EFUNC); } //Assume maximum bin shift possible inputParams->maxbinshift = (INT4)round(detectorVmax * (inputParams->fmin+0.5*inputParams->fspan) * inputParams->Tcoh)+1; //Read in the T-F data from SFTs fprintf(stderr, "Loading in SFTs... "); REAL8 tfnormalization = 2.0/inputParams->Tcoh/(args_info.avesqrtSh_arg*args_info.avesqrtSh_arg); REAL4Vector *tfdata = readInSFTs(inputParams, &(tfnormalization)); if (tfdata==NULL) { fprintf(stderr, "\n%s: readInSFTs() failed.\n", __func__); XLAL_ERROR(XLAL_EFUNC); } fprintf(stderr, "done\n"); //Removing bad SFTs using K-S test and Kuiper's test if (inputParams->markBadSFTs!=0 && inputParams->signalOnly==0) { fprintf(stderr, "Marking and removing bad SFTs... "); INT4 numffts = (INT4)floor(inputParams->Tobs/(inputParams->Tcoh-inputParams->SFToverlap)-1); //Number of FFTs INT4 numfbins = (INT4)(round(inputParams->fspan*inputParams->Tcoh+2.0*inputParams->dfmax*inputParams->Tcoh)+12+1)+2*inputParams->maxbinshift+inputParams->blksize-1; //Number of frequency bins REAL4Vector *tempvect = XLALCreateREAL4Vector(numfbins); if (tempvect==NULL) { fprintf(stderr, "%s: XLALCreateREAL4Vector(%d) failed.\n", __func__, numfbins); XLAL_ERROR(XLAL_EFUNC); } REAL8 ksthreshold = 1.358/(sqrt(numfbins)+0.12+0.11/sqrt(numfbins)); REAL8 kuiperthreshold = 1.747/(sqrt(numfbins)+0.155+0.24/sqrt(numfbins)); //fprintf(stderr, "%f %f\n", ksthreshold, kuiperthreshold); INT4 badsfts = 0, badsfts0 = 0, kuiperoverlap1 = 0, kuiperoverlap2 = 0, totalsfts = 0; FILE *OUTPUT = fopen("./output/kskoutput.dat","a"); for (ii=0; ii<numffts; ii++) { if (tfdata->data[ii*numfbins]!=0.0) { totalsfts++; memcpy(tempvect->data, &(tfdata->data[ii*numfbins]), sizeof(REAL4)*tempvect->length); qsort(tempvect->data, tempvect->length, sizeof(REAL4), qsort_REAL4_compar); REAL4 vector_median = 0.0; if (tempvect->length % 2 != 1) vector_median = 0.5*(tempvect->data[(INT4)(0.5*tempvect->length)-1] + tempvect->data[(INT4)(0.5*tempvect->length)]); else vector_median = tempvect->data[(INT4)(0.5*tempvect->length)]; REAL4 vector_mean = (REAL4)(vector_median/LAL_LN2); REAL8 ksvalue = 0.0, testval1, testval2, testval; REAL8 oneoverlength = 1.0/tempvect->length; for (jj=0; jj<(INT4)tempvect->length; jj++) { testval1 = fabs((1.0+jj)*oneoverlength - gsl_cdf_exponential_P(tempvect->data[jj], vector_mean)); testval2 = fabs(jj*oneoverlength - gsl_cdf_exponential_P(tempvect->data[jj], vector_mean)); testval = fmax(testval1, testval2); if (testval>ksvalue) ksvalue = testval; } REAL8 loval = 0.0, hival = 0.0; for (jj=0; jj<(INT4)tempvect->length; jj++) { testval1 = (1.0+jj)*oneoverlength - gsl_cdf_exponential_P(tempvect->data[jj], vector_mean); testval2 = jj*oneoverlength - gsl_cdf_exponential_P(tempvect->data[jj], vector_mean); if (hival<testval1) hival = testval1; if (loval<testval2) loval = testval2; } REAL8 kuiperval1 = hival + loval; loval = -1.0, hival = -1.0; for (jj=0; jj<(INT4)tempvect->length; jj++) { testval1 = (1.0+jj)*oneoverlength - gsl_cdf_exponential_P(tempvect->data[jj], vector_mean); testval2 = jj*oneoverlength - gsl_cdf_exponential_P(tempvect->data[jj], vector_mean); if (hival<testval1) hival = testval1; if (hival<testval2) hival = testval2; if (loval<-testval1) loval = -testval1; if (loval<-testval2) loval = -testval2; } REAL8 kuiperval = hival + loval; //fprintf(OUTPUT, "%g %g %g\n", ksvalue, kuiperval1, kuiperval); if (ksvalue>ksthreshold || kuiperval1>kuiperthreshold) badsfts0++; if (ksvalue>ksthreshold || kuiperval>kuiperthreshold) badsfts++; if (kuiperval1>kuiperthreshold && kuiperval>kuiperthreshold) kuiperoverlap1++; if (kuiperval1>kuiperthreshold || kuiperval>kuiperthreshold) kuiperoverlap2++; } } fprintf(OUTPUT, "%f %d %d %d %d\n", inputParams->fmin, badsfts0, badsfts, kuiperoverlap1, kuiperoverlap2); fclose(OUTPUT); fprintf(stderr, "Fraction excluded in K-S and Kuiper's tests = %f\n", (REAL4)badsfts/(REAL4)totalsfts); XLALDestroyREAL4Vector(tempvect); } XLALDestroyREAL4Vector(tfdata); XLALDestroyEphemerisData(edat); cmdline_parser_free(&args_info); free_inputParams(inputParams); return 0; }
int main(int argc, char ** argv) { int result = 0; AwaServerObserveOperation * operation; struct gengetopt_args_info ai; AwaServerSession * session = NULL; Target ** targets = NULL; // Catch CTRL-C to ensure clean-up signal(SIGINT, INThandler); if (cmdline_parser(argc, argv, &ai) != 0) { exit(1); } g_logLevel = ai.debug_given ? 2 : (ai.verbose_given ? 1 : 0); AwaLog_SetLevel(ai.debug_given ? AwaLogLevel_Debug : (ai.verbose_given ? AwaLogLevel_Verbose : AwaLogLevel_Warning)); if (ai.inputs_num == 0) { Error("Specify one or more resource paths.\n"); result = 1; goto cleanup; } session = Server_EstablishSession(ai.ipcAddress_arg, ai.ipcPort_arg); if (session != NULL) { operation = AwaServerObserveOperation_New(session); if (operation == NULL) { Error("Failed to create observe operation\n"); exit(1); } targets = malloc(ai.inputs_num * sizeof(Target *)); ObserveContext observeContext; observeContext.targets = targets; observeContext.numTargets = ai.inputs_num; observeContext.quiet = ai.quiet_given; // pass the quiet parameter as our context int count = 0; int i = 0; for (i = 0; i < ai.inputs_num; ++i) { targets[i] = CreateTarget(ai.inputs[i]); if (targets[i] != NULL) { count = ObserveTarget(operation, ai.clientID_arg, targets[i], &observeContext) ? count + 1 : count; } } if (AwaServerObserveOperation_Perform(operation, OPERATION_PERFORM_TIMEOUT) != AwaError_Success) { Error("Failed to perform observe operation\n"); goto cleanup; } int validCount = count; const AwaServerObserveResponse * response = AwaServerObserveOperation_GetResponse(operation, ai.clientID_arg); ObservationNode * currentObservation = g_observationListHead; ObservationNode * nextObservation; while (currentObservation != NULL) { nextObservation = currentObservation->next; const AwaPathResult * pathResult = NULL; AwaServerObservation * observation = (AwaServerObservation *)(currentObservation->observation); const char * path = AwaServerObservation_GetPath(observation); pathResult = AwaServerObserveResponse_GetPathResult(response, path); if (AwaPathResult_GetError(pathResult) != AwaError_Success) { Error("Failed to observe to %s: %s\n", path, AwaError_ToString(AwaPathResult_GetError(pathResult))); validCount--; } currentObservation = nextObservation; } AwaServerObserveOperation_Free(&operation); // Wait if there's something to wait for Debug("count %d\n", count); if (count > 0) { if (validCount > 0) { Wait(session, ai.waitTime_arg, ai.waitCount_arg); } CancelObservationFromTargets(session, ai.clientID_arg); } } else { Error("Failed to establish Awa Session\n"); result = 1; } cleanup: if (session) { FreeObservationList(); Server_ReleaseSession(&session); } if (targets) { int i; for (i = 0; i < ai.inputs_num; ++i) { if (targets[i] != NULL) { FreeTarget(&targets[i]); } } free(targets); } cmdline_parser_free(&ai); return result; }
int main (int argc, char **argv) { CHandle handle = 0; CResult res = C_SUCCESS; // Parse the command line if(cmdline_parser(argc, argv, &args_info) != 0) exit(1); // Display help if no arguments were specified if(argc == 1) { cmdline_parser_print_help(); exit(0); } res = c_init(); if(res) goto done; // Open the device if (!args_info.list_given && (!args_info.import_given || args_info.device_given)) { handle = c_open_device(args_info.device_arg); if(!handle) { print_error("Unable to open device", -1); res = C_INVALID_DEVICE; goto done; } } // List devices if(args_info.list_given) { res = list_devices(); goto done; } // Import dynamic controls from XML file else if(args_info.import_given) { res = add_control_mappings(handle, args_info.import_arg); goto done; } // Import dynamic controls from XML files at default location if(args_info.addctrl_given) { // list all xml files at default data/vid dir int nf=0; char vid[5]; char pid[5]; short pid_set = 0; if(fnmatch("[[:xdigit:]][[:xdigit:]][[:xdigit:]][[:xdigit:]]:[[:xdigit:]][[:xdigit:]][[:xdigit:]][[:xdigit:]]", args_info.addctrl_arg, 0)) { if(fnmatch("[[:xdigit:]][[:xdigit:]][[:xdigit:]][[:xdigit:]]", args_info.addctrl_arg, 0)) { printf("%s invalid: set at least a valid vid value, :pid is optional\n", args_info.addctrl_arg); goto done; } else { /*extract vid and reset pid*/ int c = 0; for (c = 0; c < 4; c++) { vid[c] = args_info.addctrl_arg[c]; pid[c] = 0; } vid[4] = '\0'; pid[4] = '\0'; } } else { /*extract vid and pid*/ int c = 0; for (c = 0; c < 4; c++) { vid[c] = args_info.addctrl_arg[c]; pid[c] = args_info.addctrl_arg[c+5]; } vid[4] = '\0'; pid[4] = '\0'; pid_set = 1; /*flag pid.xml check*/ //printf("vid:%s pid:%s\n", vid, pid); } /* get xml file list from DATA_DIR/vid/ */ char **xml_files = get_filename (DATA_DIR, vid); /*check for pid.xml*/ char fname[9]; strcpy(fname, pid); strcat(fname,".xml"); if(pid_set) { pid_set = 0; /*reset*/ nf=0; while (xml_files[nf] != NULL) { if ( strcasecmp(fname, xml_files[nf]) == 0) pid_set = 1; /*file exists so flag it*/ nf++; } } /*parse xml files*/ nf = 0; while (xml_files[nf] != NULL) { /* if pid was set and pid.xml exists parse it*/ if(pid_set) { if ((strcasecmp(fname, xml_files[nf]) == 0)) { printf ( "Parsing: %s \n", xml_files[nf]); res = add_control_mappings(handle, xml_files[nf]); } } else /* parse all xml files inside vid dir */ { printf ( "Parsing: %s \n", xml_files[nf]); res = add_control_mappings(handle, xml_files[nf]); } free(xml_files[nf]); xml_files[nf]=NULL; nf++; } free(xml_files); goto done; } // List frame formats if(args_info.formats_given) { printf("Listing available frame formats for device %s:\n", args_info.device_arg); res = list_frame_formats(handle); } // List controls else if(args_info.clist_given) { printf("Listing available controls for device %s:\n", args_info.device_arg); res = list_controls(handle); } // Retrieve control value else if(args_info.get_given) { CControlValue value; // Resolve the control Id CControlId controlId = get_control_id(handle, args_info.get_arg); if(!controlId) { res = 1; print_handle_error(handle, "Unknown control specified", -1); goto done; } // Retrieve the control value res = c_get_control(handle, controlId, &value); if(res) { print_handle_error(handle, "Unable to retrieve control value", res); goto done; } printf("%d\n", value.value); } // Retrieve raw control value else if(args_info.get_raw_given) { //scan input uint16_t unit_id; unsigned char selector; sscanf(args_info.get_raw_arg, "%hu:%hhu", &unit_id, &selector); CControlValue value; value.type = CC_TYPE_RAW; // the entity is only used for the generating a control name //TODO: pass the guid through cmdline (optional) unsigned char entity[] = {0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00}; res = c_read_xu_control(handle, entity, unit_id, selector, &value); if(res) { print_handle_error(handle, "Unable to retrieve control value", res); goto done; } //print the raw value uint8_t * val = value.raw.data; int i=0; printf("query current value of: (LE)0x"); for(i=0; i<value.raw.size; i++) { printf("%.2x", val[i]); } printf(" (BE)0x"); for(i=value.raw.size-1; i >=0; i--) { printf("%.2x", val[i]); } printf("\n"); //free the raw value alocation if(value.raw.data) free(value.raw.data); } else if(args_info.set_given) { CControlValue value; // Parse the control value if(args_info.inputs_num < 1) { res = 3; print_error("No control value specified", -1); goto done; } if(parse_control_value(args_info.inputs[0], &value)) { res = 2; print_error("Invalid control value specified", -1); goto done; } // Resolve the control Id CControlId controlId = get_control_id(handle, args_info.set_arg); if(!controlId) { res = 1; print_handle_error(handle, "Unknown control specified", -1); goto done; } // Set the new control value res = c_set_control(handle, controlId, &value); if(res) { print_handle_error(handle, "Unable to set new control value", res); goto done; } } // Set the raw control value else if(args_info.set_raw_given) { CControlValue value; // Parse the control value if(args_info.inputs_num < 1) { res = 3; print_error("No raw control value specified", -1); goto done; } uint16_t unit_id; unsigned char selector; sscanf(args_info.set_raw_arg, "%hu:%hhu", &unit_id, &selector); parse_raw_control_value (args_info.inputs[0], &value); // the entity is only used for the generating a control name //TODO: pass the guid through cmdline (optional) unsigned char entity[] = {0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00}; res = c_write_xu_control(handle, entity, unit_id, selector, &value); if(res) { print_handle_error(handle, "Unable to set the control value", res); goto done; } //print the raw value le and be format uint8_t * val = value.raw.data; int i=0; printf("set value of : (LE)0x"); for(i=0; i<value.raw.size; i++) { printf("%.2x", val[i]); } printf(" (BE)0x"); for(i=value.raw.size-1; i >=0; i--) { printf("%.2x", val[i]); } printf("\n"); //free the raw value alocation if(value.raw.data) free(value.raw.data); } else if(args_info.save_ctrl_given) { res = save_controls( handle, args_info.save_ctrl_arg); } else if(args_info.load_ctrl_given) { res = load_controls( handle, args_info.load_ctrl_arg); } // Clean up done: if(handle) c_close_device(handle); c_cleanup(); cmdline_parser_free(&args_info); return res; }
int main (int argc, char **argv) { CHandle handle = 0; CResult res = C_SUCCESS; // Parse the command line if(cmdline_parser(argc, argv, &args_info) != 0) exit(1); // Display help if no arguments were specified if(argc == 1) { cmdline_parser_print_help(); exit(0); } res = c_init(); if(res) goto done; // List devices if(args_info.list_given) { res = list_devices(); goto done; } // Import dynamic controls from XML file else if(args_info.import_given) { res = add_control_mappings(args_info.import_arg); goto done; } // Open the device handle = c_open_device(args_info.device_arg); if(!handle) { print_error("Unable to open device", -1); res = C_INVALID_DEVICE; goto done; } // List frame formats if(args_info.formats_given) { printf("Listing available frame formats for device %s:\n", args_info.device_arg); res = list_frame_formats(handle); } // List controls else if(args_info.clist_given) { printf("Listing available controls for device %s:\n", args_info.device_arg); res = list_controls(handle); } // Retrieve control value else if(args_info.get_given) { CControlValue value; // Resolve the control Id CControlId controlId = get_control_id(handle, args_info.get_arg); if(!controlId) { print_handle_error(handle, "Unknown control specified", -1); goto done; } // Retrieve the control value res = c_get_control(handle, controlId, &value); if(res) { print_handle_error(handle, "Unable to retrieve control value", res); goto done; } printf("%d\n", value.value); } else if(args_info.set_given) { CControlValue value; // Parse the control value if(args_info.inputs_num < 1) { print_error("No control value specified", -1); goto done; } if(parse_control_value(args_info.inputs[0], &value)) { print_error("Invalid control value specified", -1); goto done; } // Resolve the control Id CControlId controlId = get_control_id(handle, args_info.set_arg); if(!controlId) { print_handle_error(handle, "Unknown control specified", -1); goto done; } // Set the new control value res = c_set_control(handle, controlId, &value); if(res) { print_handle_error(handle, "Unable to set new control value", res); goto done; } } // Clean up done: if(handle) c_close_device(handle); c_cleanup(); cmdline_parser_free(&args_info); return res; }