Exemplo n.º 1
1
func main() {
	certpath := flag.String("cert", "", "The path to a PEM certificate")
	keypath := flag.String("key", "", "The path to a PEM key")
	flag.Parse()
	if len(*certpath) == 0 || len(*keypath) == 0 {
		flag.PrintDefaults()
		return
	}
	ctx := gossl.NewContext(gossl.SSLv3Method())
	ctx.SetOptions(gossl.OpNoCompression)
	err := ctx.UsePrivateKeyFile(*keypath, gossl.FileTypePem)
	if err != nil {
		panic(err)
	}
	ctx.UseCertificateFile(*certpath, gossl.FileTypePem)
	if err != nil {
		panic(err)
	}
	l, err := net.Listen("tcp", ":8000")
	if err != nil {
		panic(err)
	}
	l, err = gossl.NewListener(l, ctx)
	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		fmt.Fprintf(w, "Hello, %q\n", html.EscapeString(r.URL.Path))
	})
	http.Serve(l, nil)

}
Exemplo n.º 2
0
func main() {
	detector := flag.Bool("detector", false, "start detector")
	// webapp := flag.Bool("webapp", false, "start webapp")
	// alerter := flag.Bool("alerter", false, "start alerter")
	fileName := flag.String("config", "", "config path")
	version := flag.Bool("version", false, "show version")
	flag.Parse()
	if *version {
		fmt.Fprintln(os.Stderr, VERSION)
		os.Exit(1)
	}
	if flag.NFlag() != 2 {
		flag.PrintDefaults()
		os.Exit(1)
	}
	cfg, err := config.NewWithJsonFile(*fileName)
	if err != nil {
		log.Fatalf("failed to read %s: %v", *fileName, err)
	}
	switch {
	case *detector:
		StartDetector(cfg.Detector)
	default:
		flag.PrintDefaults()
		os.Exit(1)
	}
}
Exemplo n.º 3
0
func init() {
	flag.StringVar(&address, "address", "localhost:28015", "The address to connect to a RethinkDB instance.")
	flag.StringVar(&db, "database", "", "The RethinkDB database to use.")
	flag.StringVar(&table, "table", "", "The RethinkDB database table to use.")
	flag.Parse()

	if len(db) == 0 {
		fmt.Println("You must pass the name of a database to use.\n")
		flag.PrintDefaults()
		os.Exit(1)
	}

	if len(table) == 0 {
		fmt.Println("You must pass the name of database table to use.\n")
		flag.PrintDefaults()
		os.Exit(1)
	}

	//session, err := r.Connect(r.ConnectOpts{
	//	Address:  address,
	//	Database: db,
	//	MaxIdle:  10,
	//	MaxOpen:  10,
	//})
	//if err != nil {
	//	log.Fatalln(err.Error())
	//}
}
Exemplo n.º 4
0
Arquivo: main.go Projeto: kitech/toxsh
func main() {
	flag.Parse()
	if len(config_file) > 0 {
		config = NewTunnelConfig(config_file)
		info.Println(config)
	}

	argv := flag.Args()
	argc := len(argv)

	mode := ""
	if argc > 0 {
		mode = argv[argc-1]
	}

	go NewStatServer().serve()
	appevt.Trigger("appmode", mode)

	switch mode {
	case "client":
		if config == nil {
			flag.PrintDefaults()
			os.Exit(-1)
		}
		tc := NewTunnelc()
		tc.serve()
	case "server":
		td := NewTunneld()
		td.serve()
	default:
		log.Println("Invalid mode")
		flag.PrintDefaults()
	}

}
Exemplo n.º 5
0
Arquivo: main.go Projeto: cj123/rover
func init() {
	flag.StringVar(&sourceURL, "u", "", "the url you wish to download from")
	flag.StringVar(&remoteFile, "r", "", "the remote filename to download")
	flag.StringVar(&localFile, "o", "", "the output filename")
	flag.IntVar(&timeout, "t", 5, "timeout, in seconds")
	flag.BoolVar(&verbose, "v", false, "verbose")
	flag.BoolVar(&showFiles, "l", false, "list files in zip")
	flag.Uint64Var(&limitBytes, "b", 0, "limit filesize downloaded (in bytes)")

	flag.Parse()

	if sourceURL == "" {
		fmt.Println("You must specify a URL")
		flag.PrintDefaults()
		os.Exit(1)
	}

	if !showFiles {
		if remoteFile == "" {
			fmt.Println("You must specify a remote filename")
			flag.PrintDefaults()
			os.Exit(1)
		}

		if localFile == "" {
			_, localFile = filepath.Split(remoteFile)
		}
	}
}
Exemplo n.º 6
0
/**
* Our main entry point.
* @return{struct} Our config structure populated with configuration info.
 */
func Main() Config {

	config := Config{}
	flag.IntVar(&config.Num_messages, "num-messages", 1,
		"How many messages to send?")
	flag.IntVar(&config.Message_size, "message-size", 1,
		"How many bytes in each message?")
	flag.IntVar(&config.Num_cores, "num-cores", 1,
		"How many cores to use? (Max:"+strconv.Itoa(runtime.NumCPU())+")")
	flag.IntVar(&config.Buffer_size, "buffer-size", 0,
		"Buffer size for our channel?")
	flag.IntVar(&config.Num_goroutines, "num-goroutines", 1,
		"How many goroutines to run?")
	flag.IntVar(&config.Num_goroutine_work, "num-goroutine-work", 1,
		"How much work to do in each goroutine?")

	var h = flag.Bool("h", false, "Print this help")
	var help = flag.Bool("help", false, "Print this help")

	flag.Parse()

	if *h || *help {
		flag.PrintDefaults()
		panic("Bailing out due to asking for help")

	} else if config.Num_goroutine_work < 1 {
		flag.PrintDefaults()
		panic("Goroutine work must be >= 1")

	}

	return (config)

} // End of Main()
Exemplo n.º 7
0
func main() {
	flag.Parse()
	block, err := hex.DecodeString(*hexBlock)
	if err != nil {
		log.Println(err)
		flag.PrintDefaults()
		return
	} else if len(block) != 16 {
		log.Println("Block must be 128 bits.")
		flag.PrintDefaults()
		return
	}

	// Read construction from disk and parse it into something usable.
	data, err := ioutil.ReadFile("./constr.txt")
	if err != nil {
		log.Fatal(err)
	}
	constr, err := full.Parse(data)
	if err != nil {
		log.Fatal(err)
	}

	// Encrypt block in-place, and print as hex.
	constr.Encrypt(block, block)
	fmt.Printf("%x\n", block)
}
Exemplo n.º 8
0
func main() {
	flag.Float64Var(&samplingProbability, "p", 0.0, "Sample lines at probability p in [0, 1].")
	flag.UintVar(&reservoirSize, "r", 0, "Sample exactly k lines.")
	flag.StringVar(&splitStr, "s", "", "Split the input into n random subsets. Delimit weights with commas, e.g. 8,1,1. Weights will be normalized to sum to 1.")
	flag.StringVar(&outputFilename, "o", "", "Output file(s). If not specified, write to stdout. Required and used as a basename for splitting. The basename will be appended with _1, _2, etc.")
	flag.Parse()

	rand.Seed(time.Now().UnixNano())

	if reservoirSize > 0 && samplingProbability > 0.0 {
		fmt.Println("You can specify either -p or -r, but not both.")
		flag.PrintDefaults()
		return
	}

	input := inputReader(flag.Args())

	if splitStr != "" {
		if outputFilename == "" {
			fmt.Println("To split input, you must specify an output base filename with -o.")
			flag.PrintDefaults()
			return
		}
		Split(input)
	} else if samplingProbability > 0.0 {
		sampleAtRate(input, samplingProbability, os.Stdout)
	} else if reservoirSize > 0 {
		lines := reservoirSample(input, reservoirSize)

		for _, line := range lines {
			fmt.Print(line)
		}
	}
}
Exemplo n.º 9
0
func main() {
	flag.StringVar(&presently.Dir, "d", "", "Directory of the repository")
	flag.StringVar(&presently.DeployDir, "o", "", "Directory of the deployment")
	flag.StringVar(&presently.Port, "p", "", "Port to listen")
	flag.Parse()
	args := flag.Args()

	if presently.Dir == "" {
		if len(args) == 0 {
			fmt.Println("You need to specify -d")
			flag.PrintDefaults()
			os.Exit(0)
		} else {
			presently.Dir = args[0]
		}
	}

	if presently.DeployDir == "" {
		fmt.Println("You need to specify -o")
		flag.PrintDefaults()
		os.Exit(0)
	}

	presently.Deploy()
}
Exemplo n.º 10
0
func main() {
	// redefine the flags function
	flag.Usage = func() {
		// print defaults of fatbin only if it's named fatbin
		if filepath.Base(os.Args[0]) == "fatbin" {
			flag.PrintDefaults()
			return
		}
	}

	// read the flags

	err := parseFlags()
	if err != nil {
		fmt.Println(err)
		flag.PrintDefaults()
		return
	}

	// compress mode
	if len(flags.Directory) > 0 && len(flags.Executable) > 0 {
		build()
		return
	}

	run()
}
Exemplo n.º 11
0
func main() {
	flag.Parse()
	if *help {
		fmt.Println(useage)
		flag.PrintDefaults()
		return
	}

	if *dbname == "" {
		fmt.Println(useage)
		flag.PrintDefaults()
		return
	}

	if *source == "" {
		fmt.Println(useage)
		flag.PrintDefaults()
		return
	}

	if *path == "" {
		fmt.Println(useage)
		flag.PrintDefaults()
		return
	}

	sync := db.CreateSyncDB(*dbname, *source)
	sync.SyncDB(*path, *drop, *role)

}
Exemplo n.º 12
0
func main() {
	flag.Parse()

	if *apiKey == "" || *host == "" {
		flag.PrintDefaults()
		os.Exit(1)
	}
	if *serviceAccount == "" && *echo == "" {
		fmt.Fprint(os.Stderr, "Provide one of -echo or -service-account.")
		flag.PrintDefaults()
		os.Exit(1)
	}
	if *serviceAccount != "" && *echo != "" {
		fmt.Fprint(os.Stderr, "Provide only one of -echo or -service-account.")
		flag.PrintDefaults()
		os.Exit(1)
	}

	var resp *http.Response
	var err error
	if *echo != "" {
		resp, err = doEcho()
	} else if *serviceAccount != "" {
		resp, err = doJWT()
	}
	if err != nil {
		log.Fatal(err)
	}
	b, err := httputil.DumpResponse(resp, true)
	if err != nil {
		log.Fatal(err)
	}
	os.Stdout.Write(b)
}
Exemplo n.º 13
0
func main() {
	flag.Parse()
	if !flag.Parsed() {
		fmt.Fprintf(os.Stderr, "Invalid command line!\n")
		flag.PrintDefaults()
		return
	}

	if len(flag.Args()) < 1 {
		fmt.Fprintf(os.Stderr, "No file is specified\n")
		flag.PrintDefaults()
		return
	}

	filename := flag.Arg(0)

	file, err := NewLogFile(filename)
	if err != nil {
		fmt.Fprintf(os.Stderr, "NewLogFile() failed! %s\n", err)
		panic(err)
	}
	defer file.Close()

	err = file.Monitor(*linesToPrint)
	if err != nil {
		fmt.Fprintf(os.Stderr, "Monitor() failed! %s\n", err)
		panic(err)
	}

	shutdown := make(chan bool)
	<-shutdown
}
Exemplo n.º 14
0
func main() {
	var defaultMaxprocs int
	var err error
	if defaultMaxprocs, err = strconv.Atoi(os.Getenv("GOMAXPROCS")); err != nil {
		defaultMaxprocs = runtime.NumCPU() * 2
	}
	var mode, dir string
	var port, maxprocs int
	flag.StringVar(&mode, "mode", "", "[v1|v2|v3|bench|durable-bench|example]")
	flag.StringVar(&dir, "dir", "", "database directory")
	flag.IntVar(&port, "port", 0, "listening port number")
	flag.IntVar(&maxprocs, "gomaxprocs", defaultMaxprocs, "GOMAXPROCS")
	flag.Parse()

	if mode == "" {
		flag.PrintDefaults()
		return
	}

	runtime.GOMAXPROCS(maxprocs)
	log.Printf("GOMAXPROCS is set to %d", maxprocs)

	if maxprocs < runtime.NumCPU() {
		log.Printf("GOMAXPROCS (%d) is less than number of CPUs (%d), this may affect performance. You can change it via environment variable GOMAXPROCS or by passing CLI parameter -gomaxprocs", maxprocs, runtime.NumCPU())
	}

	switch mode {
	case "v1":
		fallthrough
	case "v2":
		fallthrough
	case "v3":
		if dir == "" {
			log.Fatal("Please specify database directory, for example -dir=/tmp/db")
		}
		if port == 0 {
			log.Fatal("Please specify port number, for example -port=8080")
		}
		db, err := db.OpenDB(dir)
		if err != nil {
			log.Fatal(err)
		}
		if mode == "v1" {
			v1.Start(db, port)
		} else if mode == "v2" {
			v2.Start(db, port)
		} else if mode == "v3" {
			v3.Start(db, port)
		}
	case "bench":
		benchmark()
	case "durable-bench":
		durableBenchmark()
	case "example":
		embeddedExample()
	default:
		flag.PrintDefaults()
		return
	}
}
Exemplo n.º 15
0
func main() {
	aspong := flag.Bool("asPong", false, "Starts Pong service")
	asping := flag.Bool("asPing", false, "Starts Ping service")
	port := flag.Int("port", 8080, "Sets the port")
	ponghost := flag.String("pongHost", "localhost", "Host (valid DNS name or IP) of the pong service")
	pongport := flag.Int("pongPort", 8080, "Port of the pong service")
	flag.Parse()

	if *aspong && *asping {
		fmt.Println("You can only start ping or pong service, not both with the same command.")
		flag.PrintDefaults()
		os.Exit(1)
	}

	if *aspong {
		pong.Start(*port)
		os.Exit(0)
	}

	if *asping {
		ping.Start(*port, *ponghost, *pongport)
		os.Exit(0)
	}

	flag.PrintDefaults()
}
Exemplo n.º 16
0
func Main() {
	// Parse commandline
	opts := &http.Options{}
	var fork bool
	flag.BoolVar(&fork, "fork", false, "fork into the background")
	flag.StringVar(&opts.ListenAddr, "listenaddr", "0.0.0.0", "address of interface to listen on")
	flag.IntVar(&opts.ListenPort, "listenport", 6558, "port to listen on")
	flag.BoolVar(&opts.Xinetd, "xinetd", false, "service is running under xinetd")
	flag.StringVar(&opts.LivestatusSocket, "livestatus-socket", "", "path to Livestatus UNIX socket")
	flag.StringVar(&opts.LivestatusAddress, "livestatus-address", "", "address (host:port) of livestatus TCP endpoint")
	flag.Parse()

	if opts.Xinetd && fork {
		fmt.Println("You cannot specify both 'fork' and 'xinetd' options at the same time\n")
		flag.PrintDefaults()
		os.Exit(1)
	}

	if opts.LivestatusSocket == "" && opts.LivestatusAddress == "" {
		fmt.Println("You must specify the livestatus endpoint information\n")
		flag.PrintDefaults()
		os.Exit(1)
	}

	err := http.Start(opts)
	if err != nil {
		fmt.Printf("Error: %s\n\n", err)
		os.Exit(1)
	}
}
Exemplo n.º 17
0
func main() {
	// Initialise our configuration from flags

	var nodeName = flag.String("name", REQUIRED, "Node network name and port, e.g. localhost:3000")
	var gobName = flag.String("gob", "", "Alternative gob network name and port for clients, allowing clients to connect over a different physical interface to nodes.")
	var httpName = flag.String("http", "", "Network name and port for the http ExpVar to listen on.")
	var cborName = flag.String("cbor", "", "Network name and port for the CBOR RPC interface to listen on.")
	var nodePath = flag.String("path", REQUIRED, "Node root path for configuration and log files")
	var clusterID = flag.String("id", "", "Cluster ID that this node is part of")

	flag.Parse()

	if flag.Lookup("help") != nil || flag.Lookup("h") != nil {
		flag.PrintDefaults()
		return
	}

	if *nodeName == REQUIRED {
		log.Printf("name missing.\n")
		flag.PrintDefaults()
		return
	}

	if *nodePath == REQUIRED {
		log.Printf("path missing.\n")
		flag.PrintDefaults()
		return
	}

	// Create our server
	serverNode, err := server.NewServerNode(*nodeName, *gobName, *httpName, *cborName, *nodePath, *clusterID)

	if err != nil {
		log.Fatalf("Unable to start server due to errors.\n")
	}

	expvar.Publish("node", expvar.Func(serverNode.ExpVar))

	//dataLog := &memlog.MemoryLog{}

	// Start a listener to handle incoming requests from other peers
	err = serverNode.ListenConnections()
	if err != nil {
		log.Fatalf("Error starting listener: %v\n", err)
	}

	// Setup signal handling to catch interrupts.
	sigc := make(chan os.Signal, 1)
	signal.Notify(sigc,
		os.Interrupt,
		os.Kill)
	go func() {
		<-sigc
		serverNode.RequestShutdown("Request to terminate process detected.")
	}()

	serverNode.WaitForShutdown()

}
Exemplo n.º 18
0
// main is the entry point of the program.
func main() {
	log.SetFlags(log.Ldate | log.Ltime)

	// command line arguments.
	configPath := flag.String("config-file", "",
		"Path to a configuration file.")
	logPath := flag.String("log-file", "",
		"Path to a log file.")
	flag.Parse()
	// config file is required.
	if len(*configPath) == 0 {
		log.Print("You must specify a configuration file.")
		flag.PrintDefaults()
		os.Exit(1)
	}
	if len(*logPath) == 0 {
		log.Print("You must specify a log file.")
		flag.PrintDefaults()
		os.Exit(1)
	}

	// open log file.
	// don't use os.Create() because that truncates.
	logFh, err := os.OpenFile(*logPath, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0644)
	if err != nil {
		log.Printf("Failed to open log file: %s: %s", *logPath, err.Error())
		os.Exit(1)
	}
	log.SetOutput(logFh)

	// load up our settings.
	var settings Config
	err = config.GetConfig(*configPath, &settings)
	if err != nil {
		log.Printf("Failed to retrieve config: %s", err.Error())
		os.Exit(1)
	}

	// start listening.
	var listenHostPort = fmt.Sprintf("%s:%d", settings.ListenHost,
		settings.ListenPort)
	listener, err := net.Listen("tcp", listenHostPort)
	if err != nil {
		log.Print("Failed to open port: " + err.Error())
		os.Exit(1)
	}

	httpHandler := HttpHandler{settings: &settings}

	// XXX: this will serve requests forever - should we have a signal
	//   or a method to cause this to gracefully stop?
	log.Print("Starting to serve requests.")
	err = fcgi.Serve(listener, httpHandler)
	if err != nil {
		log.Print("Failed to start serving HTTP: " + err.Error())
		os.Exit(1)
	}
}
Exemplo n.º 19
0
func main() {
	// parse command line
	flag.Parse()

	// help?
	if *help {
		flag.PrintDefaults()
		os.Exit(0)
	}

	p := sudoku.NewPuzzle()
	if flag.NFlag() == 0 {
		// load from stdin
		if err := p.Load(); err != nil {
			log.Fatalf("Error processing puzzle:%v", err)
		}
	} else {
		// load from input file
		// must have an input argument
		if *input == "" {
			flag.PrintDefaults()
			os.Exit(0)
		}
		fpuz, err := ioutil.ReadFile(*input)
		if err != nil {
			log.Fatalf("Cannot read %v, err=%v", *input, err)
		}
		if err = p.Fload(fpuz); err != nil {
			log.Fatalf("Error processing puzzle:%v", err)
		}
	}
	var w *os.File
	w = os.Stdout
	if *otput != "" {
		var err error
		if w, err = os.Create(*otput); err != nil {
			log.Fatalf("Error opening output %v was:%v\n",
				*otput, err)
		}
	}

	// now that we have the puzzle constructed,
	// set the pencil marks and set any cells to those with
	// only one pencil mark possible
	p.SetPencilMarks()
	p.SetSingleMarks()

	sudoku.Solve(p)
	solutions := sudoku.GetSolutions()
	//number_solutions := len(solutions)
	//fmt.Printf("Number of solutions is:%v\n",number_solutions)
	for _, s := range solutions {
		fmt.Fprintf(w, "%v", s)
	}
	if *rate {
		fmt.Fprintf(os.Stderr, "Rating:%v\n", sudoku.Counter)
	}
}
Exemplo n.º 20
0
func main() {
	fConfig := flag.String("config", "", "Configuration file to load")
	fHelp := flag.Bool("help", false, "Print this help")
	fNodes := flag.String("nodes", "", "Number of nodes making chef-client runs")
	fRuns := flag.String("runs", "", "Number of chef-client runs each node should make, 0 value will make infinite runs")
	fSampleConfig := flag.Bool("sample-config", false, "Print out full sample configuration")
	fVersion := flag.Bool("version", false, "Print chef-load version")
	flag.Parse()

	if *fHelp {
		fmt.Println("Usage of chef-load:")
		flag.PrintDefaults()
		os.Exit(0)
	}

	if *fVersion {
		fmt.Println("chef-load", AppVersion)
		os.Exit(0)
	}

	if *fSampleConfig {
		printSampleConfig()
		os.Exit(0)
	}

	var (
		config *chefLoadConfig
		err    error
	)

	if *fConfig != "" {
		config, err = loadConfig(*fConfig)
		if err != nil {
			log.Fatal(err)
		}
	} else {
		fmt.Println("Usage of chef-load:")
		flag.PrintDefaults()
		return
	}

	if *fNodes != "" {
		config.Nodes, _ = strconv.Atoi(*fNodes)
	}

	if *fRuns != "" {
		config.Runs, _ = strconv.Atoi(*fRuns)
	}

	numNodes := config.Nodes
	for i := 0; i < numNodes; i++ {
		nodeName := config.NodeNamePrefix + "-" + strconv.Itoa(i)
		go startNode(nodeName, *config)
	}
	for i := 0; i < numNodes; i++ {
		<-quit // Wait to be told to exit.
	}
}
Exemplo n.º 21
0
func main() {

	flag.Parse()
	args := flag.Args()
	fmt.Fprintf(os.Stderr, "\n")

	availableCommands := "Available commands:\n\n maketorrent\n info"

	if len(args) > 0 {
		switch args[0] {
		case "maketorrent":
			name := flag.String("name", "", "Torrent name, defaults to [file]+.torrent")
			announce := flag.String("announce", "udp://tracker.publicbt.com:80", "Tracker url")
			announceList := flag.String("announceList", "", "Comma seperated tracker urls")
			comment := flag.String("comment", "", "Optional comment")
			createdBy := flag.String("createdBy", "Tulva", "Author")
			encoding := flag.String("encoding", "UTF-8", "Encoding")

			flag.Parse()
			args = flag.Args()

			if len(args) == 1 {
				fmt.Fprintf(os.Stderr, "Usage: maketorrent [options] File\n\n")
				flag.PrintDefaults()
			} else if len(args) == 2 {
				clf := &CLFlags{
					Name:         *name,
					Announce:     *announce,
					AnnounceList: *announceList,
					Comment:      *comment,
					CreatedBy:    *createdBy,
					Encoding:     *encoding,
				}
				t := MakeTorrentFile(args[1], clf)
				fmt.Fprintf(os.Stderr, "Made torrent File: %s", t.Name())
			}
		case "info":
			name := flag.Bool("name", true, "Torrent name")
			if len(args) == 1 {
				fmt.Fprintf(os.Stderr, "Usage: info [options] File\n\n")
				flag.PrintDefaults()
			} else if len(args) == 2 {
				metaInfo := TorrentInfo(args[1])
				fmt.Fprintf(os.Stderr, "Info:\n\n")
				if *name {
					fmt.Fprintf(os.Stderr, "\tName: %s", metaInfo.info.name)
				}
			}
		default:
			fmt.Fprintf(os.Stderr, availableCommands)
		}
	} else {
		fmt.Fprintf(os.Stderr, availableCommands)
	}
	fmt.Fprintf(os.Stderr, "\n\n")
}
Exemplo n.º 22
0
func main() {
	if cmdTarget == "" || cmdOidMid == "" {
		flag.PrintDefaults()
		return
	}
	if cmdBulkSize > 255 {
		fmt.Println("Bulk size should not > 255. ")
		flag.PrintDefaults()
		return
	}

	s, err := gosnmp.NewGoSNMP(cmdTarget, cmdCommunity, gosnmp.Version2c, cmdTimeout)
	if cmdDebug == true {
		s.SetDebug(true)
		s.SetVerbose(true)
	}
	if err != nil {
		fmt.Printf("Error creating SNMP instance: %s\n", err.Error())
		return
	}
	//	s.SetTimeout(cmdTimeout)
	s.SetTimeoutMs(cmdTimeout)

	cmd_oid := cmdOidMid[:]
	if cmdLookUp {
		if _oid, err := MibLookup(cmd_oid); err == nil {
			fmt.Printf("Lookup(%v) => %v\n", cmdOidMid, _oid.String())
			cmd_oid = _oid.String()
		} else {
			fmt.Printf("Failed to Lookup mib: err: %v, mib: %v\n", err, cmd_oid)
			os.Exit(2)
		}
	}

	// build caches from all mibs will take longer
	//	if files, err := ioutil.ReadDir("/usr/share/snmp/mibs"); err == nil {
	//		for _, fi := range files {
	//			BuildIdentifierCaches([]string{path.Join("/usr/share/snmp/mibs", fi.Name())})
	//		}
	//	} else {
	//		BuildIdentifierCaches([]string{"NS-MIB-smiv2.mib", "/usr/share/snmp/mibs/IPV6-MIB.txt"})
	//	}
	BuildIdentifierCaches([]string{"NS-MIB-smiv2.mib", "/usr/share/snmp/mibs/IPV6-MIB.txt"})
	//	return
	if cmdBulkWalk {
		if cmdStream {
			methodStreamBulkWalk(s, cmd_oid)
		} else {
			methodBulkWalk(s, cmd_oid)
		}
	} else {
		methodStreamWalk(s, cmd_oid)
	}
}
Exemplo n.º 23
0
func main() {
	flag.Parse()
	block, err := hex.DecodeString(*hexBlock)
	if err != nil {
		log.Println(err)
		flag.PrintDefaults()
		return
	} else if len(block) != 16 {
		log.Println("Block must be 128 bits.")
		flag.PrintDefaults()
		return
	}

	// Read key from disk and parse it.
	data, err := ioutil.ReadFile("./constr.key")
	if err != nil {
		log.Fatal(err)
	} else if len(data) != keySize {
		log.Fatalf("key wrong size: %v (should be %v)", len(data), keySize)
	}

	var key []byte
	inputLinear, outputLinear := matrix.Matrix{}, matrix.Matrix{}
	inputConst, outputConst := [16]byte{}, [16]byte{}

	key, data = data[:16], data[16:]
	for i := 0; i < 128; i++ {
		inputLinear, data = append(inputLinear, data[:16]), data[16:]
	}
	copy(inputConst[:], data)
	data = data[16:]
	for i := 0; i < 128; i++ {
		outputLinear, data = append(outputLinear, data[:16]), data[16:]
	}
	copy(outputConst[:], data)

	inputMask := encoding.NewBlockAffine(inputLinear, inputConst)
	outputMask := encoding.NewBlockAffine(outputLinear, outputConst)

	// Decrypt block and print as hex.
	temp := [16]byte{}
	copy(temp[:], block)

	temp = outputMask.Decode(temp)

	c, err := aes.NewCipher(key)
	if err != nil {
		log.Fatal(err)
	}
	c.Decrypt(temp[:], temp[:])

	temp = inputMask.Decode(temp)
	fmt.Printf("%x\n", temp)
}
Exemplo n.º 24
0
func main() {

	log.Println(os.Args)

	flag.Usage = func() {
		flag.PrintDefaults()
	}
	flag.Parse()

	if *showHelp {
		flag.PrintDefaults()
		os.Exit(0)
	}

	if *streamNameCode == "" {
		flag.PrintDefaults()
		log.Fatal("specify the stream name")
	}

	inputFs = getInputFs()

	l := rtmpLog.NewLogger("", "", nil, 60, 3600*24, true)
	rtmp.InitLogger(l)
	defer l.Close()
	createStreamChan = make(chan rtmp.OutboundStream)
	connHandler := &ConnHandler{}
	log.Println("Dialing")
	var err error
	obConn, err = rtmp.Dial(*url, connHandler, 100)
	if err != nil {
		log.Fatal("Dial error", err)
	}
	defer obConn.Close()
	log.Println("Connecting")
	err = obConn.Connect()
	if err != nil {
		log.Fatalf("Connect error: %s", err.Error())
	}
	for {
		select {
		case stream := <-createStreamChan:
			stream.Attach(connHandler)
			err = stream.Publish(*streamNameCode, "live")
			if err != nil {
				log.Fatalf("Publish error: %s", err.Error())
			}

		case <-time.After(5 * time.Second):
			log.Printf("Audio size: %d bytes; Vedio size: %d bytes; Current tag index: %d\n", audioDataSize, videoDataSize, input.curPos)
		}
	}
}
Exemplo n.º 25
0
func main() {
	if *version {
		AppVersion()
		os.Exit(0)
	}

	validModes := []string{"monitor", "events"}
	foundMode := false

	for _, v := range validModes {
		if v == *mode {
			foundMode = true
		}
	}

	if !foundMode {
		fmt.Printf("Invalid mode: %s\n", *mode)
		flag.PrintDefaults()
		os.Exit(-1)
	}

	if *cfgPath == "" {
		fmt.Println("Error: --config must be set.")
		flag.PrintDefaults()
		os.Exit(-1)
	}

	cfg, err := configurate.New(*cfgPath, logger)
	if err != nil {
		logger.Print(err)
		os.Exit(-1)
	}

	logger.Println("Done reading config.")
	if !cfg.Valid() {
		logger.Println("Something is wrong with the config file.")
		os.Exit(-1)
	}

	switch *mode {
	case "events":
		events.Run(cfg, logger)
	case "monitor":
		monitor.Run(cfg, logger)
	default:
		fmt.Println("Bad mode! Bad! Look what you did!")
		flag.PrintDefaults()
		os.Exit(-1)
	}
}
Exemplo n.º 26
0
Arquivo: hello.go Projeto: skey/hello
func main() {
	flag.Usage = func() { flag.PrintDefaults() }
	flag.Parse()
	if file == "" {
		flag.PrintDefaults()
		os.Exit(0)
	}
	ch = make(chan int, limit)
	for _, addr := range getAddrs(file) {
		wg.Add(1)
		go work(addr)
	}
	wg.Wait()
}
Exemplo n.º 27
0
func main() {
	optHost := flag.String("hostname", "localhost", "Hostname to login to")
	optPort := flag.String("port", "5432", "Database port")
	optUser := flag.String("user", "", "Postgres User")
	optDatabase := flag.String("database", "", "Database name")
	optPass := flag.String("password", "", "Postgres Password")
	optSSLmode := flag.String("sslmode", "disable", "Whether or not to use SSL")
	optConnectTimeout := flag.Int("connect_timeout", 5, "Maximum wait for connection, in seconds.")
	optTempfile := flag.String("tempfile", "", "Temp file name")
	flag.Parse()

	if *optUser == "" {
		logger.Warningf("user is required")
		flag.PrintDefaults()
		os.Exit(1)
	}
	if *optPass == "" {
		logger.Warningf("password is required")
		flag.PrintDefaults()
		os.Exit(1)
	}
	option := ""
	if *optDatabase != "" {
		option = fmt.Sprintf("dbname=%s", *optDatabase)
	}

	var postgres PostgresPlugin
	postgres.Host = *optHost
	postgres.Port = *optPort
	postgres.Username = *optUser
	postgres.Password = *optPass
	postgres.SSLmode = *optSSLmode
	postgres.Timeout = *optConnectTimeout
	postgres.Option = option

	helper := mp.NewMackerelPlugin(postgres)

	if *optTempfile != "" {
		helper.Tempfile = *optTempfile
	} else {
		helper.Tempfile = fmt.Sprintf("/tmp/mackerel-plugin-postgres-%s-%s", *optHost, *optPort)
	}

	if os.Getenv("MACKEREL_AGENT_PLUGIN_META") != "" {
		helper.OutputDefinitions()
	} else {
		helper.OutputValues()
	}
}
Exemplo n.º 28
0
func main() {
	dnssec := flag.Bool("dnssec", false, "Request DNSSEC records")
	port := flag.String("port", "53", "Set the query port")
	flag.Usage = func() {
		fmt.Fprintf(os.Stderr, "Usage: %s [OPTIONS] [name ...]\n", os.Args[0])
		flag.PrintDefaults()
	}

	flag.Parse()

	fmt.Println("dnssec: ", *dnssec)
	fmt.Println("port: ", *port)
	flag.PrintDefaults()

	cmd := exec.Command("/bin/ls", "-l")
	buf1, err := cmd.Output()
	if err != nil {
		return
	}
	fmt.Println("output is : %s ", string(buf1))

	r1, err := http.Get("http://www.google.com/robots.txt")
	if err != nil {
		fmt.Printf("%s\n", err.Error())
		return
	}
	b, err := ioutil.ReadAll(r1.Body)
	r1.Body.Close()
	if err == nil {
		fmt.Printf("%s", string(b))
	}

	return

	buf := make([]byte, 1024)
	f, _ := os.Open("/etc/passwd")
	defer f.Close()
	r := bufio.NewReader(f)
	w := bufio.NewWriter(os.Stdout)
	defer w.Flush()
	for {
		n, _ := r.Read(buf)
		if n == 0 {
			break
		}
		w.Write(buf[:n])
	}
}
Exemplo n.º 29
0
func printUsageErrorAndExit(message string) {
	fmt.Fprintln(os.Stderr, "ERROR:", message)
	fmt.Fprintln(os.Stderr)
	fmt.Fprintln(os.Stderr, "Available command line options:")
	flag.PrintDefaults()
	os.Exit(64)
}
Exemplo n.º 30
0
func Init() {
	flag.Usage = func() {
		fmt.Fprintf(os.Stderr, "%s [options] [filename]:\noptions precedence: default < config file < environment variables < command line\n", os.Args[0])
		flag.PrintDefaults()
	}

	flag.StringVar(&Identifier, "id", "", "Custom client identifier")
	flag.StringVar(&KeyRing, "keyring", "", "identifier for keyring to use")
	flag.StringVar(&KeyStore, "keystore", "db", "system to store keyrings: db|file (db)")
	flag.StringVar(&OutboundPort, "port", "30303", "listening port")
	flag.BoolVar(&UseUPnP, "upnp", false, "enable UPnP support")
	flag.IntVar(&MaxPeer, "maxpeer", 10, "maximum desired peers")
	flag.IntVar(&RpcPort, "rpcport", 8080, "port to start json-rpc server on")
	flag.BoolVar(&StartRpc, "rpc", false, "start rpc server")
	flag.BoolVar(&NonInteractive, "y", false, "non-interactive mode (say yes to confirmations)")
	flag.BoolVar(&UseSeed, "seed", true, "seed peers")
	flag.BoolVar(&GenAddr, "genaddr", false, "create a new priv/pub key")
	flag.StringVar(&SecretFile, "import", "", "imports the file given (hex or mnemonic formats)")
	flag.StringVar(&ExportDir, "export", "", "exports the session keyring to files in the directory given")
	flag.StringVar(&LogFile, "logfile", "", "log file (defaults to standard output)")
	flag.StringVar(&Datadir, "datadir", defaultDataDir(), "specifies the datadir to use")
	flag.StringVar(&ConfigFile, "conf", defaultConfigFile, "config file")
	flag.StringVar(&DebugFile, "debug", "", "debug file (no debugging if not set)")
	flag.IntVar(&LogLevel, "loglevel", int(ethlog.InfoLevel), "loglevel: 0-5: silent,error,warn,info,debug,debug detail)")
	flag.BoolVar(&DiffTool, "difftool", false, "creates output for diff'ing. Sets LogLevel=0")
	flag.StringVar(&DiffType, "diff", "all", "sets the level of diff output [vm, all]. Has no effect if difftool=false")

	flag.BoolVar(&StartMining, "mine", false, "start dagger mining")
	flag.BoolVar(&StartJsConsole, "js", false, "launches javascript console")

	flag.Parse()

	InputFile = flag.Arg(0)
}