Example #1
0
func main() {
	hasher := sha1.New()
	b := make([]byte, 65536)

	c := 40
	len := 344
	if len%64 < 56 {
		println(56 - len%64)
	} else {
		println(64 + 56 - len%64)
	}
	fmt.Fprintln(os.Stderr, "%v ^%v", c, ^c)

	if terminal.IsTerminal(syscall.Stdin) {
		fmt.Fprintln(os.Stderr, "Stdin must not be a tty - pipe something into the process")
		os.Exit(2)
	}

	for nb, err := os.Stdin.Read(b); err == nil; nb, err = os.Stdin.Read(b) {
		hasher.Write(b[:nb])
	}

	res := hasher.Sum(nil)
	stat, _ := os.Stdin.Stat()
	fmt.Printf("%x %s\n", res, stat.Name())
}
Example #2
0
func main() {
	if len(os.Args) < 2 {
		fmt.Printf("Error: Not enough arguments\n")
		os.Exit(2)
	}

	addr := os.Args[1]
	result, err := mcclient.ScanServer(addr)

	if err != nil {
		fmt.Printf("Error: %s\n", err.Error())
		os.Exit(1)
	}

	motd := result.MOTD

	if len(motd) > 20 {
		motd = motd[:20]
	}

	if terminal.IsTerminal(int(os.Stdout.Fd())) {
		motd = mcclient.ANSIEscapes(motd)
	} else {
		motd = mcclient.NoEscapes(motd)
	}

	fmt.Printf("(%d/%d) %s\n", result.PlayersOnline, result.PlayersMax, motd)
}
Example #3
0
func editService(service *dao.Service, editor string) error {

	serviceJson, err := json.MarshalIndent(service, " ", " ")
	if err != nil {
		glog.Fatalf("Problem marshaling service object: %s", err)
	}

	var reader io.Reader
	if terminal.IsTerminal(syscall.Stdin) {
		editorPath, err := findEditor(editor)
		if err != nil {
			fmt.Printf("%s\n", err)
			return err
		}

		f, err := ioutil.TempFile("", fmt.Sprintf("serviced_edit_%s_", service.Id))
		if err != nil {
			glog.Fatalf("Could not write tempfile: %s", err)
		}
		defer f.Close()
		defer os.Remove(f.Name())
		_, err = f.Write(serviceJson)
		if err != nil {
			glog.Fatalf("Problem writing service json to file: %s", err)
		}

		editorCmd := exec.Command(editorPath, f.Name())
		editorCmd.Stdout = os.Stdout
		editorCmd.Stdin = os.Stdin
		editorCmd.Stderr = os.Stderr
		err = editorCmd.Run()

		if err != nil {
			glog.Fatal("Editor command returned error: %s", err)
		}
		_, err = f.Seek(0, 0)
		if err != nil {
			glog.Fatal("Could not seek to begining of tempfile: %s", err)
		}
		reader = f
	} else {
		_, err = os.Stdout.Write(serviceJson)
		if err != nil {
			glog.Fatal("Could not write service to terminal's stdout: %s", err)
		}
		reader = os.Stdin
	}

	serviceJson, err = ioutil.ReadAll(reader)
	if err != nil {
		glog.Fatal("Could not read tempfile back in: %s", err)
	}
	err = json.Unmarshal(serviceJson, &service)
	if err != nil {
		glog.Fatal("Could not parse json: %s", err)
	}
	return nil
}
Example #4
0
func main() {
	termcols = getTermWidth()

	flag.Parse()
	buildPatterns()

	if len(*file) > 0 {
		f, err := os.Create(*file)
		if err != nil {
			log.Fatal("Error opening output file: "+*file, err)
		}
		outputFile = f
	}

	if *input == "auto" {
		if !terminal.IsTerminal(int(os.Stdin.Fd())) {
			*input = "stdin"
		} else {
			*input = "adb"
		}
	}

	switch *input {
	case "adb":
		testEnv()
		deviceId, err := getDeviceId()
		if err != nil {
			log.Fatal("Error: ", err)
			return
		}

		if deviceId == "????????????" {
			log.Fatal("No permissions for device")
			return
		}

		fmt.Printf("Selected device: %s\n\n", deviceId)

		getPids()

		adbReadlog(deviceId)

	case "stdin":
		fileReadlog(os.Stdin)

	default:
		file, err := os.Open(*input)
		if err != nil {
			log.Fatal("Error: ", err)
			return
		}

		fileReadlog(file)
	}

}
Example #5
0
func InvokeServerCode(entryName string, version string) {
	path := fmt.Sprintf("/apps/%s/server-code/versions/%s/%s", globalConfig.AppId, version, entryName)
	headers := globalConfig.HttpHeadersWithAuthorization("application/json")
	var b []byte
	if terminal.IsTerminal(int(os.Stdin.Fd())) {
		b = HttpPost(path, headers, strings.NewReader("{}")).Bytes()
	} else {
		b = HttpPost(path, headers, os.Stdin).Bytes()
	}
	fmt.Printf("%s\n", string(b))
}
Example #6
0
// makeSession initializes a gossh.Session connected to the invoking process's stdout/stderr/stdout.
// If the invoking session is a terminal, a TTY will be requested for the SSH session.
// It returns a gossh.Session, a finalizing function used to clean up after the session terminates,
// and any error encountered in setting up the session.
func makeSession(client *SSHForwardingClient) (session *gossh.Session, finalize func(), err error) {
	session, err = client.NewSession()
	if err != nil {
		return
	}
	if err = client.ForwardAgentAuthentication(session); err != nil {
		return
	}

	session.Stdout = os.Stdout
	session.Stderr = os.Stderr
	session.Stdin = os.Stdin

	modes := gossh.TerminalModes{
		gossh.ECHO:          1,     // enable echoing
		gossh.TTY_OP_ISPEED: 14400, // input speed = 14.4kbaud
		gossh.TTY_OP_OSPEED: 14400, // output speed = 14.4kbaud
	}

	fd := int(os.Stdin.Fd())
	if terminal.IsTerminal(fd) {

		var termWidth, termHeight int
		var oldState *terminal.State

		oldState, err = terminal.MakeRaw(fd)
		if err != nil {
			return
		}

		finalize = func() {
			session.Close()
			terminal.Restore(fd, oldState)
		}

		termWidth, termHeight, err = terminal.GetSize(fd)

		if err != nil {
			return
		}
		err = session.RequestPty("xterm-256color", termHeight, termWidth, modes)
	} else {
		finalize = func() {
			session.Close()
		}
	}

	return
}
Example #7
0
func ui(startTime time.Time, nf int, c <-chan uiMsg, done chan<- struct{}) {
	defer close(done)
	var fileDoneCount int
	var bytes, lastBytes uint64
	lastTime := startTime
	p := func(m string, nl bool) {
		if terminal.IsTerminal(syscall.Stdout) {
			width := defaultTerminalWidth
			if w, _, err := terminal.GetSize(syscall.Stdout); err == nil {
				width = w
			}
			fmt.Printf("\r%-*s\r%s", width-1, "", m)
		} else {
			fmt.Print(m)
		}
		if nl {
			fmt.Printf("\n")
		}
	}

	for msg := range c {
		now := time.Now()
		if msg.bytes != nil {
			bytes = *msg.bytes
		}
		if msg.msg != nil {
			p(*msg.msg, true)
		}
		if msg.fileDone != nil {
			if *verbose {
				p(fmt.Sprintf("Done: %q", path.Base(*msg.fileDone)), true)
			}
			fileDoneCount++
		}
		elapsed := now.Sub(startTime)
		p(fmt.Sprintf("%d/%d files. %d workers. %sB in %s = %sBps. Current: %sBps",
			fileDoneCount, nf, *numWorkers,
			humanize(float64(bytes), 3),
			roundSeconds(elapsed),
			humanize(float64(bytes)/elapsed.Seconds(), 1),
			humanize(float64(bytes-lastBytes)/now.Sub(lastTime).Seconds(), 1),
		), false)
		lastBytes = bytes
		lastTime = now
	}
	fmt.Printf("\n")
}
Example #8
0
File: main.go Project: felipeg48/jp
func main() {
	flag.Usage = func() {
		fmt.Fprintf(os.Stderr, "usage: jp [file]\n")
		flag.PrintDefaults()
	}

	isTerminal := terminal.IsTerminal(int(os.Stdout.Fd()))

	compact := flag.Bool("compact", false, "compact format")
	colors := flag.Bool("color", isTerminal, "colored format")

	flag.Parse()
	args := flag.Args()
	if len(args) < 1 {
		flag.Usage()
		os.Exit(2)
	}

	format := "pretty"
	if *compact {
		format = "compact"
	}
	if *colors {
		format += "16"
	}

	var fd *os.File
	var e error
	if args[0] == "-" {
		fd = os.Stdin
	} else {
		fd, e = os.Open(args[0])
		if e != nil {
			fmt.Fprintln(os.Stderr, "Error:", e)
			os.Exit(1)
		}
	}

	e = jp.Expand(fd, os.Stdout, format)
	if e != nil {
		fmt.Fprintln(os.Stderr, "Error:", e)
		os.Exit(1)
	}
}
Example #9
0
func main() {
	pluginPath := os.Getenv("PLUGIN_PATH")
	if pluginPath == "" {
		log.Fatal("[ERROR] Unable to locate plugins: set $PLUGIN_PATH\n")
		os.Exit(1)
	}
	if len(os.Args) < 2 {
		log.Fatal("[ERROR] Hook name argument is required\n")
		os.Exit(1)
	}
	cmds := make([]exec.Cmd, 0)
	var matches, _ = filepath.Glob(fmt.Sprintf("%s/*/%s", pluginPath, os.Args[1]))
	for _, hook := range matches {
		cmd := exec.Command(hook, os.Args[2:]...)
		cmds = append(cmds, *cmd)
	}
	done := make(chan bool, len(cmds))
	for i := len(cmds) - 1; i >= 0; i-- {
		if i == len(cmds)-1 {
			cmds[i].Stdout = os.Stdout
		}
		if i > 0 {
			stdout, err := cmds[i-1].StdoutPipe()
			if err != nil {
				log.Fatal(err)
			}
			cmds[i].Stdin = stdout
		}
		if i == 0 && !terminal.IsTerminal(syscall.Stdin) {
			cmds[i].Stdin = os.Stdin
		}
		go func(cmd exec.Cmd) {
			err := cmd.Run()
			if msg, ok := err.(*exec.ExitError); ok { // there is error code
				os.Exit(msg.Sys().(syscall.WaitStatus).ExitStatus())
			}
			done <- true
		}(cmds[i])
	}
	for i := 0; i < len(cmds); i++ {
		<-done
	}
}
Example #10
0
func passwordFromReader(reader io.Reader) (string, error) {
	var (
		password []byte
		err      error
	)
	if file, ok := reader.(*os.File); ok && terminal.IsTerminal(int(file.Fd())) {
		password, err = terminal.ReadPassword(int(file.Fd()))
		if err != nil {
			return "", err
		}
	} else {
		fmt.Fscanf(reader, "%s\n", &password)
	}
	if len(password) == 0 {
		msg := "You must provide the password!"
		return "", errors.New(msg)
	}
	return string(password), err
}
Example #11
0
// Start assigns a pseudo-terminal tty os.File to c.Stdin, c.Stdout,
// and c.Stderr, calls c.Start, and returns the File of the tty's
// corresponding pty.
func Start(c *exec.Cmd) (pty *os.File, err error) {
	pty, tty, err := Open()
	if err != nil {
		return nil, err
	}
	defer tty.Close()

	if terminal.IsTerminal(int(pty.Fd())) == false {
		return nil, ErrNotTerminal
	}

	c.Stdout = tty
	c.Stdin = tty
	c.Stderr = tty
	c.SysProcAttr = &syscall.SysProcAttr{Setctty: true, Setsid: true}
	err = c.Start()
	if err != nil {
		pty.Close()
		return nil, err
	}
	return pty, err
}
Example #12
0
// RunningOnTerminal checks whether stdout is terminal
func RunningOnTerminal() bool {
	return terminal.IsTerminal(syscall.Stdout)
}
Example #13
0
func verifyColor() bool {
	fd := os.Stdout.Fd()
	isTerm := terminal.IsTerminal(int(fd))
	return isTerm
}
Example #14
0
func (c *attachCmd) run(args []string) error {
	name := "foo"
	if len(args) > 1 {
		return errArgs
	}
	if len(args) == 1 {
		name = args[0]
	}
	config, err := flex.LoadConfig()
	if err != nil {
		return err
	}

	// NewClient will ping the server to test the connection before returning.
	d, err := flex.NewClient(config)
	if err != nil {
		return err
	}

	// TODO - random value in place of 5 :)
	secret := "5"

	l, err := d.Attach(name, "/bin/bash", secret)
	if err != nil {
		return err
	}

	cfd := syscall.Stdout
	if terminal.IsTerminal(cfd) {
		oldttystate, err := terminal.MakeRaw(cfd)
		if err != nil {
			return err
		}
		defer terminal.Restore(cfd, oldttystate)
	}

	// open a connection to l and connect stdin/stdout to it

	// connect
	conn, err := net.Dial("tcp", l)
	if err != nil {
		return err
	}
	_, err = conn.Write([]byte(secret))
	if err != nil {
		return err
	}

	go func() {
		_, err := io.Copy(conn, os.Stdin)
		if err != nil {
			fmt.Println("Stdin read error: %s", err.Error())
			return
		}
	}()
	_, err = io.Copy(os.Stdout, conn)
	if err != nil {
		fmt.Println("Connection read error: %s", err.Error())
		return err
	}

	return nil
}
Example #15
0
File: util.go Project: jingweno/gh
func isTerminal(fd uintptr) bool {
	return terminal.IsTerminal(int(fd))
}
Example #16
0
// SupportsColor inspects the file descriptor to figure out if it's attached to
// a terminal, and if so, returns true for color support. Example usage:
//
//     useColor := log.SupportsColor(os.Stdout)
func SupportsColor(f *os.File) bool {
	return terminal.IsTerminal(int(f.Fd()))
}
Example #17
0
func (sshToContainerCmd) Run(context *cmd.Context, _ *cmd.Client) error {
	serverURL, err := cmd.GetURL("/docker/ssh/" + context.Args[0])
	if err != nil {
		return err
	}
	request, err := http.NewRequest("GET", serverURL, nil)
	if err != nil {
		return err
	}
	request.Close = true
	token, err := cmd.ReadToken()
	if err == nil {
		request.Header.Set("Authorization", "bearer "+token)
	}
	parsedURL, _ := url.Parse(serverURL)
	conn, err := net.Dial("tcp", parsedURL.Host)
	if err != nil {
		return err
	}
	defer conn.Close()
	request.Write(conn)
	if stdin, ok := context.Stdin.(*os.File); ok {
		fd := int(stdin.Fd())
		if terminal.IsTerminal(fd) {
			oldState, err := terminal.MakeRaw(fd)
			if err != nil {
				return err
			}
			defer terminal.Restore(fd, oldState)
			sigChan := make(chan os.Signal, 2)
			go func(c <-chan os.Signal) {
				if _, ok := <-c; ok {
					terminal.Restore(fd, oldState)
					os.Exit(1)
				}
			}(sigChan)
			signal.Notify(sigChan, syscall.SIGINT, syscall.SIGTERM, syscall.SIGKILL, syscall.SIGQUIT)
		}
	}
	bytesLimit := 50
	var readStr string
	byteBuffer := make([]byte, 1)
	for i := 0; i < bytesLimit && byteBuffer[0] != '\n'; i++ {
		_, err := conn.Read(byteBuffer)
		if err != nil {
			break
		}
		readStr += string(byteBuffer)
	}
	matches := httpHeaderRegexp.FindAllStringSubmatch(readStr, -1)
	if len(matches) > 0 && len(matches[0]) > 1 {
		code, _ := strconv.Atoi(matches[0][1])
		return &errors.HTTP{
			Code:    code,
			Message: strings.TrimSpace(readStr),
		}
	} else {
		context.Stdout.Write([]byte(readStr))
	}
	errs := make(chan error, 2)
	quit := make(chan bool)
	go io.Copy(conn, context.Stdin)
	go func() {
		defer close(quit)
		_, err := io.Copy(context.Stdout, conn)
		if err != nil && err != io.EOF {
			errs <- err
		}
	}()
	<-quit
	close(errs)
	return <-errs
}
Example #18
0
func isTerminal() bool {
	return terminal.IsTerminal(1)
}
Example #19
0
func main() {
	var parallel = flag.Bool("p", false, "Run hooks in parallel")
	var trace = flag.Bool("x", false, "Trace mode")
	flag.Parse()

	if len(os.Getenv("PLUGINHOOK_TRACE")) > 0 {
		*trace = true
	}

	pluginPath := os.Getenv("PLUGIN_PATH")
	if pluginPath == "" {
		log.Fatal("[ERROR] Unable to locate plugins: set $PLUGIN_PATH\n")
		os.Exit(1)
	}
	if flag.NArg() < 1 {
		log.Fatal("[ERROR] Hook name argument is required\n")
		os.Exit(1)
	}
	cmds := make([]exec.Cmd, 0)
	var matches, _ = filepath.Glob(fmt.Sprintf("%s/*/%s", pluginPath, flag.Arg(0)))
	for _, hook := range matches {
		cmd := exec.Command(hook, flag.Args()[1:]...)
		cmds = append(cmds, *cmd)
	}
	for i := len(cmds) - 1; i >= 0; i-- {
		cmds[i].Stderr = os.Stderr

		if i == len(cmds)-1 {
			cmds[i].Stdout = os.Stdout
		}
		if i > 0 {
			if *parallel {
				stdout, err := cmds[i-1].StdoutPipe()
				if err != nil {
					log.Fatal(err)
				}
				cmds[i].Stdin = stdout
			} else {
				var buf bytes.Buffer
				cmds[i-1].Stdout = &buf
				cmds[i].Stdin = &buf
			}
		}
		if i == 0 && !terminal.IsTerminal(syscall.Stdin) {
			cmds[i].Stdin = os.Stdin
		}
	}

	if *parallel {
		done := make(chan bool, len(cmds))

		for i := 0; i < len(cmds); i++ {
			go func(cmd exec.Cmd, i int) {
				if *trace {
					fmt.Fprintln(os.Stderr, "+", strings.Join(cmds[i].Args, " "))
				}
				err := cmd.Run()
				if msg, ok := err.(*exec.ExitError); ok { // there is error code
					os.Exit(msg.Sys().(syscall.WaitStatus).ExitStatus())
				}
				done <- true
			}(cmds[i], i)
		}
		for i := 0; i < len(cmds); i++ {
			<-done
		}
	} else {
		for i := 0; i < len(cmds); i++ {
			if *trace {
				fmt.Fprintln(os.Stderr, "+", strings.Join(cmds[i].Args, " "))
			}
			err := cmds[i].Run()
			if msg, ok := err.(*exec.ExitError); ok { // there is error code
				os.Exit(msg.Sys().(syscall.WaitStatus).ExitStatus())
			}
		}
	}
}