/*------------------------------------------------------------------------ * void process_options(); * * Processes the command-line options and sets the protocol parameters * as appropriate. *------------------------------------------------------------------------*/ func ProcessOptions() *Parameter { parameter := NewParameter() opt.BoolVarLong(¶meter.verbose, "verbose", 'v', "turns on verbose output mode, deafult off") opt.BoolVarLong(¶meter.transcript, "transcript", 't', "turns on transcript mode for statistics recording, deafult off") opt.BoolVarLong(¶meter.ipv6, "v6", '6', "operates using IPv6 instead of (not in addition to!) IPv4") deafultHelp := fmt.Sprintf( "specifies which TCP port on which to listen to incoming connections, default %d", tsunami.TS_TCP_PORT) port := opt.Uint16Long("port", 'p', tsunami.TS_TCP_PORT, deafultHelp) secret := opt.StringLong("secret", 's', tsunami.DEFAULT_SECRET, "specifies the shared secret for the client and server") deafultHelp = fmt.Sprintf( "specifies the desired size for UDP socket send buffer (in bytes), default %d", DEFAULT_UDP_BUFFER) buffer := opt.Uint32Long("buffer", 'b', DEFAULT_UDP_BUFFER, deafultHelp) deafultHelp = fmt.Sprintf( "specifies the timeout in seconds for disconnect after client heartbeat lost, default %d", DEFAULT_HEARTBEAT_TIMEOUT) hbtimeout := opt.Uint16Long("hbtimeout", 'h', DEFAULT_HEARTBEAT_TIMEOUT, deafultHelp) opt.StringVarLong(¶meter.client, "client", 'c', "specifies an alternate client IP or host where to send data") opt.StringVarLong(¶meter.finishhook, "finishhook", 'f', "run command on transfer completion, file name is appended automatically") opt.StringVarLong(¶meter.allhook, "allhook", 'a', "run command on 'get *' to produce a custom file list for client downloads") opt.Parse() parameter.tcp_port = *port parameter.secret = *secret parameter.udp_buffer = *buffer parameter.hb_timeout = *hbtimeout files := opt.Args() parameter.file_names = files parameter.file_sizes = make([]uint64, len(files)) parameter.total_files = uint16(len(files)) for i, v := range files { stat, err := os.Stat(v) if err != nil { fmt.Fprintln(os.Stderr, v, err) } else { size := stat.Size() parameter.file_sizes[i] = uint64(size) fmt.Fprintf(os.Stderr, " %3d) %-20s %d bytes\n", i+1, v, size) } } parameter.VerboseArg("") return parameter }
func main() { getopt.ListVarLong(&configPaths, "config", 'c', "REQUIRED: Path to configuration file (can be used multiple times)", "PATH") getopt.BoolVarLong(&verbose, "verbose", 'v', "Verbose progress indicators and messages") help := getopt.BoolLong("help", 'h', "Show this help message and exit") getopt.SetParameters("") getopt.Parse() if *help { getopt.Usage() os.Exit(0) } if len(configPaths) == 0 { log.Printf("no configuration (-c/--config) found") getopt.Usage() os.Exit(1) } log.SetFlags(log.Ldate | log.Ltime | log.Lshortfile) // set parallelism (automatic in Go 1.6+) if runtime.GOMAXPROCS(0) < runtime.NumCPU() { runtime.GOMAXPROCS(runtime.NumCPU()) log.Printf("setting GOMAXPROCS = NumCPU = %d\n", runtime.NumCPU()) } for _, configPath := range configPaths { cfg, err := config.NewConfiguration(configPath) if err != nil { log.Fatal(err) continue } idx, err := index.NewIndex(cfg) if err != nil { log.Print(err) return } if err := idx.Update(); err != nil { log.Print(err) return } if err := idx.WriteOut(); err != nil { log.Print(err) return } } }
func main() { var ( justVersion bool logLevel = "info" c = proxy.Config{ListenAddrs: defaultListenAddrs} ) c.Version = version getopt.BoolVarLong(&justVersion, "version", 0, "print version and exit") getopt.StringVarLong(&logLevel, "log-level", 0, "logging level (debug, info, warning, error)", "info") getopt.ListVar(&c.ListenAddrs, 'H', fmt.Sprintf("address on which to listen (default %s)", defaultListenAddrs)) getopt.BoolVarLong(&c.NoDefaultIPAM, "no-default-ipalloc", 0, "do not automatically allocate addresses for containers without a WEAVE_CIDR") getopt.BoolVarLong(&c.NoDefaultIPAM, "no-default-ipam", 0, "do not automatically allocate addresses for containers without a WEAVE_CIDR (deprecated; please use --no-default-ipalloc") getopt.StringVarLong(&c.TLSConfig.CACert, "tlscacert", 0, "Trust certs signed only by this CA") getopt.StringVarLong(&c.TLSConfig.Cert, "tlscert", 0, "Path to TLS certificate file") getopt.BoolVarLong(&c.TLSConfig.Enabled, "tls", 0, "Use TLS; implied by --tlsverify") getopt.StringVarLong(&c.TLSConfig.Key, "tlskey", 0, "Path to TLS key file") getopt.BoolVarLong(&c.TLSConfig.Verify, "tlsverify", 0, "Use TLS and verify the remote") getopt.BoolVarLong(&c.WithDNS, "with-dns", 'w', "instruct created containers to always use weaveDNS as their nameserver") getopt.BoolVarLong(&c.WithoutDNS, "without-dns", 0, "instruct created containers to never use weaveDNS as their nameserver") getopt.Parse() if justVersion { fmt.Printf("weave proxy %s\n", version) os.Exit(0) } if c.WithDNS && c.WithoutDNS { Log.Fatalf("Cannot use both '--with-dns' and '--without-dns' flags") } SetLogLevel(logLevel) Log.Infoln("weave proxy", version) Log.Infoln("Command line arguments:", strings.Join(os.Args[1:], " ")) p, err := proxy.NewProxy(c) if err != nil { Log.Fatalf("Could not start proxy: %s", err) } p.ListenAndServe() }
func main() { var ( format string t *oauth.Credential help bool ini bool yaml bool array bool assoc bool json bool env bool xauth bool oauth_ bool ck string cs string sn string pw string app string ) util := utility.NewUtil() prompter := prompt.NewPrompter() getopt.BoolVarLong(&help, "help", 'h') getopt.BoolVarLong(&ini, "ini", 'i') getopt.BoolVarLong(&yaml, "yaml", 'y') getopt.BoolVarLong(&array, "array", 'a') getopt.BoolVarLong(&assoc, "assoc", 'A') getopt.BoolVarLong(&json, "json", 'j') getopt.BoolVarLong(&env, "env", 'e') getopt.BoolVarLong(&oauth_, "oauth", 'o') getopt.BoolVarLong(&xauth, "xauth", 'x') getopt.StringVarLong(&ck, "ck", 0, "") getopt.StringVarLong(&cs, "cs", 0, "") getopt.StringVarLong(&sn, "sn", 0, "") getopt.StringVarLong(&pw, "pw", 0, "") getopt.StringVarLong(&app, "app", 0, "") getopt.SetUsage(util.Usage) getopt.CommandLine.Parse(os.Args) if help { util.Usage() os.Exit(0) } if ck == "" && cs == "" && app != "" { appks, ok := util.Apps[app] if !ok { log.Fatalln("Application not found: " + app) } ck = (*appks)[0] cs = (*appks)[1] } if ck == "" { ck = prompter.PromptTrimmed("consumer_key: ") } if cs == "" { cs = prompter.PromptTrimmed("consumer_secret: ") } if xauth || !oauth_ { if sn == "" { sn = prompter.PromptTrimmed("screen_name: ") } if pw == "" { pw = prompter.PromptMasked("password: "******"", ""}).RenewWithAccessToken(map[string]string{ "x_auth_mode": "client_auth", "x_auth_username": sn, "x_auth_password": pw, }, nil) } else { t = (&oauth.Credential{ck, cs, "", ""}).RenewWithRequestToken() sess := session.NewSession() uri := "https://api.twitter.com/oauth/authorize?force_login=1&oauth_token=" + t.OAuthToken { expr := `<input name="authenticity_token" type="hidden" value="([^"]+)">` matches := regexp.MustCompile(expr).FindSubmatch(sess.Get(uri)) if matches == nil { log.Fatalln("Could not find authenticity_token") } sess.SetAuthenticityToken(string(matches[1])) } { expr := `<code>([^<]+)</code>` matches := regexp.MustCompile(expr).FindSubmatch(sess.Post(uri, &url.Values{ "session[username_or_email]": {sn}, "session[password]": {pw}, })) if matches == nil { log.Fatalln("Wrong username or password. Otherwise, you may have to verify your email address.") } verifier := string(matches[1]) t = t.RenewWithAccessToken(map[string]string{}, &verifier) } } } else { t = (&oauth.Credential{ck, cs, "", ""}).RenewWithRequestToken() uri := "https://api.twitter.com/oauth/authorize?force_login=1&oauth_token=" + t.OAuthToken os.Stderr.WriteString("Access here for authorization: " + uri + "\n") verifier := prompter.PromptTrimmed("PIN: ") t = t.RenewWithAccessToken(map[string]string{}, &verifier) } if ini { format = `consumer_key = "%s" consumer_secret = "%s" access_token = "%s" access_token_secret = "%s" ` } else if yaml { format = `consumer_key: "%s" consumer_secret: "%s" access_token: "%s" access_token_secret: "%s" ` } else if array { format = `[ "%s", "%s", "%s", "%s" ] ` } else if assoc { format = `[ "consumer_key" => "%s", "consumer_secret" => "%s", "access_token" => "%s", "access_token_secret" => "%s", ] ` } else if json { format = `{ "consumer_key": "%s", "consumer_secret": "%s", "access_token": "%s", "access_token_secret": "%s" } ` } else if env { format = `CONSUMER_KEY="%s" CONSUMER_SECRET="%s" ACCESS_TOKEN="%s" ACCESS_TOKEN_SECRET="%s" ` } else { format = `%s %s %s %s ` } fmt.Printf(format, t.ConsumerKey, t.ConsumerSecret, t.OAuthToken, t.OAuthTokenSecret) }
func main() { // Uncomment the following lines if you need to time the options parsing //log.SetFlags(log.Ldate | log.Ltime | log.Lmicroseconds) //log.Println(": Program started") // Configure Command Line Options var useUDP, quiet, debug bool var maxRTT time.Duration var numPing int getopt.BoolVarLong(&useUDP, "udp", 'u', "use UDP instead of ICMP") getopt.BoolVarLong(&quiet, "quiet", 'q', "only display host data") getopt.BoolVarLong(&debug, "debug", 'v', "print additional messages") maxRTT = defaultMaxRTT getopt.DurationVarLong(&maxRTT, "rtt", 't', "max RTT for each ping") numPing = defaultPingCount getopt.IntVarLong(&numPing, "count", 'n', "max number of pings per target") getopt.SetParameters("startIP endIP") getopt.Parse() // Verify arguments if getopt.NArgs() != 2 { log.Println("Incorrect number of arguments!") getopt.PrintUsage(os.Stderr) os.Exit(1) } startIPString := getopt.Arg(0) endIPString := getopt.Arg(1) // Test for incompatible options if quiet && debug { log.Println("`quiet` and `debug` are incompatible") getopt.PrintUsage(os.Stderr) os.Exit(1) } if debug { log.SetFlags(log.Ldate | log.Ltime | log.Lmicroseconds) log.Println(": Command Line Parsing complete") } // Convert to IP object startIP := net.ParseIP(startIPString) if startIP == nil { log.Fatal("Start IP,", startIPString, ", is not a valid IP address") } if debug { log.Println(": Start IP\t", startIPString) } endIP := net.ParseIP(endIPString) if endIP == nil { log.Fatal("End IP,", endIPString, ", is not a valid IP address") } if debug { log.Println(": End IP \t", endIPString) } netProto := "ip4:icmp" if strings.Index(startIPString, ":") != -1 { netProto = "ip6:ipv6-icmp" } p := fastping.NewPinger() p.MaxRTT = maxRTT p.OnRecv = func(addr *net.IPAddr, rtt time.Duration) { var device resultData device.PingResult = addr.String() + "\t" + roundDuration(baseRTT+rtt, time.Millisecond).String() ips = append(ips, device) p.RemoveIPAddr(addr) } currentIP := make(net.IP, len(startIP)) for copy(currentIP, startIP); bytes.Compare(currentIP, endIP) <= 0; inc(currentIP) { ra, err := net.ResolveIPAddr(netProto, currentIP.String()) if err != nil { log.Fatal(err) } p.AddIPAddr(ra) } if useUDP { p.Network("udp") } if debug { log.Println(": Start Scan") } for index := 0; index < numPing; index++ { baseRTT = time.Duration(index) * maxRTT err := p.Run() if err != nil { log.Fatal("Pinger returns error: ", err) } } if debug { log.Println(": Scan complete") } if !quiet { fmt.Println() fmt.Printf("%d devices found\n", len(ips)) fmt.Println() } if debug { log.Println(": Start Host Lookup") } // Query DNS for the name of each device found by the ping scan var ipAndTime []string var hostname string var wg sync.WaitGroup for index, ip := range ips { ipAndTime = strings.SplitN(ip.PingResult, "\t", 2) wg.Add(1) go func(ipString string, localIndex int) { hosts, err := net.LookupAddr(ipString) if err != nil { hostname = "Error: " + err.Error() } else { hostname = strings.Join(hosts, ", ") } ips[localIndex].HostResult = hostname wg.Done() }(ipAndTime[0], index) } wg.Wait() if debug { log.Println(": DNS complete") } sort.Sort(byIP(ips)) if debug { log.Println(": Sort complete") } for _, ip := range ips { fmt.Printf("%-25s\t--> %s\n", ip.PingResult, ip.HostResult) } if !quiet { fmt.Println() } if debug { log.Println(": Program complete") } }