gotty-client/gotty-client.go

310 lines
6.5 KiB
Go
Raw Normal View History

2015-08-25 00:48:27 +08:00
package gottyclient
import (
2015-08-25 04:53:35 +08:00
"bufio"
2015-08-26 15:29:52 +08:00
"encoding/base64"
2015-08-25 19:30:04 +08:00
"encoding/json"
2015-08-25 00:48:27 +08:00
"fmt"
2015-09-19 09:40:42 +08:00
"io/ioutil"
2015-08-25 00:48:27 +08:00
"net/http"
"net/url"
2015-08-25 04:53:35 +08:00
"os"
2015-08-25 19:30:04 +08:00
"os/signal"
2015-09-19 09:40:42 +08:00
"regexp"
2015-08-25 00:48:27 +08:00
"strings"
2015-09-30 23:17:57 +08:00
"sync"
2015-08-25 19:30:04 +08:00
"syscall"
2015-09-19 09:40:42 +08:00
"time"
2015-08-25 04:53:35 +08:00
"unicode/utf8"
2015-08-25 19:30:04 +08:00
"unsafe"
2015-08-25 00:48:27 +08:00
2015-09-28 03:49:24 +08:00
"github.com/moul/gotty-client/vendor/github.com/Sirupsen/logrus"
"github.com/moul/gotty-client/vendor/github.com/gorilla/websocket"
"github.com/moul/gotty-client/vendor/golang.org/x/crypto/ssh/terminal"
2015-08-25 00:48:27 +08:00
)
2015-09-19 09:40:42 +08:00
// GetAuthTokenURL transforms a GoTTY http URL to its AuthToken file URL
func GetAuthTokenURL(httpURL string) (*url.URL, *http.Header, error) {
header := http.Header{}
target, err := url.Parse(httpURL)
if err != nil {
return nil, nil, err
}
target.Path = strings.TrimLeft(target.Path+"auth_token.js", "/")
if target.User != nil {
header.Add("Authorization", "Basic "+base64.StdEncoding.EncodeToString([]byte(target.User.String())))
target.User = nil
}
return target, &header, nil
}
2015-09-30 23:17:57 +08:00
// GetURLQuery returns url.query
func GetURLQuery(rawurl string) (url.Values, error) {
target, err := url.Parse(rawurl)
if err != nil {
return nil, err
}
return target.Query(), nil
}
2015-08-25 00:48:27 +08:00
// GetWebsocketURL transforms a GoTTY http URL to its WebSocket URL
2015-08-26 15:29:52 +08:00
func GetWebsocketURL(httpURL string) (*url.URL, *http.Header, error) {
header := http.Header{}
2015-08-25 00:48:27 +08:00
target, err := url.Parse(httpURL)
if err != nil {
2015-08-26 15:29:52 +08:00
return nil, nil, err
2015-08-25 00:48:27 +08:00
}
if target.Scheme == "https" {
target.Scheme = "wss"
} else {
target.Scheme = "ws"
}
target.Path = strings.TrimLeft(target.Path+"ws", "/")
2015-08-26 15:29:52 +08:00
if target.User != nil {
header.Add("Authorization", "Basic "+base64.StdEncoding.EncodeToString([]byte(target.User.String())))
target.User = nil
}
return target, &header, nil
2015-08-25 00:48:27 +08:00
}
type Client struct {
2015-09-30 23:17:57 +08:00
Dialer *websocket.Dialer
Conn *websocket.Conn
URL string
Connected bool
WriteMutex *sync.Mutex
}
2015-10-13 00:07:50 +08:00
type querySingleType struct {
AuthToken string `json:"AuthToken"`
Arguments string `json:"Arguments"`
}
2015-09-30 23:17:57 +08:00
func (c *Client) write(data []byte) error {
c.WriteMutex.Lock()
defer c.WriteMutex.Unlock()
return c.Conn.WriteMessage(websocket.TextMessage, data)
2015-08-25 00:48:27 +08:00
}
2015-09-19 09:40:42 +08:00
// GetAuthToken retrieves an Auth Token from dynamic auth_token.js file
func (c *Client) GetAuthToken() (string, error) {
target, header, err := GetAuthTokenURL(c.URL)
if err != nil {
return "", err
}
2015-10-13 23:02:38 +08:00
logrus.Debugf("Fetching auth token auth-token: %q", target.String())
2015-09-19 09:40:42 +08:00
req, err := http.NewRequest("GET", target.String(), nil)
req.Header = *header
client := http.Client{}
resp, err := client.Do(req)
if err != nil {
return "", err
}
2015-10-13 22:41:37 +08:00
switch resp.StatusCode {
case 200:
// Everything is OK
default:
return "", fmt.Errorf("unknown status code: %d (%s)", resp.StatusCode, http.StatusText(resp.StatusCode))
}
2015-09-19 09:40:42 +08:00
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return "", err
}
re := regexp.MustCompile("var gotty_auth_token = '(.*)'")
output := re.FindStringSubmatch(string(body))
if len(output) == 0 {
return "", fmt.Errorf("Cannot fetch GoTTY auth-token, please upgrade your GoTTY server.")
}
return output[1], nil
2015-09-19 09:40:42 +08:00
}
2015-08-25 00:48:27 +08:00
// Connect tries to dial a websocket server
func (c *Client) Connect() error {
2015-09-19 09:40:42 +08:00
// Retrieve AuthToken
authToken, err := c.GetAuthToken()
if err != nil {
return err
}
2015-10-13 23:02:38 +08:00
logrus.Debugf("Auth-token: %q", authToken)
2015-09-19 09:40:42 +08:00
// Open WebSocket connection
target, header, err := GetWebsocketURL(c.URL)
if err != nil {
return err
}
2015-10-13 23:02:38 +08:00
logrus.Debugf("Connecting to websocket: %q", target.String())
2015-09-19 09:40:42 +08:00
conn, _, err := c.Dialer.Dial(target.String(), *header)
2015-08-25 00:48:27 +08:00
if err != nil {
return err
}
c.Conn = conn
2015-09-19 09:40:42 +08:00
2015-10-13 23:02:38 +08:00
// Pass arguments and auth-token
2015-09-30 23:17:57 +08:00
query, err := GetURLQuery(c.URL)
if err != nil {
return err
}
2015-10-13 00:07:50 +08:00
var querySingle querySingleType = querySingleType{
Arguments: "?" + query.Encode(),
AuthToken: authToken,
2015-09-30 23:17:57 +08:00
}
json, err := json.Marshal(querySingle)
if err != nil {
2015-10-13 00:07:50 +08:00
logrus.Errorf("Failed to parse init message %v", err)
2015-09-30 23:17:57 +08:00
return err
}
// Send Json
2015-10-13 23:02:38 +08:00
logrus.Debugf("Sending arguments and auth-token")
2015-09-30 23:17:57 +08:00
err = c.write(json)
2015-09-19 09:40:42 +08:00
if err != nil {
return err
}
go c.pingLoop()
2015-08-25 00:48:27 +08:00
return nil
}
2015-09-19 09:40:42 +08:00
func (c *Client) pingLoop() {
for {
2015-10-13 23:02:38 +08:00
logrus.Debugf("Sending ping")
2015-09-30 23:17:57 +08:00
c.write([]byte("1"))
2015-09-19 09:40:42 +08:00
time.Sleep(30 * time.Second)
}
}
2015-08-25 00:48:27 +08:00
// Close will nicely close the dialer
func (c *Client) Close() {
c.Conn.Close()
}
// Loop will look indefinitely for new messages
func (c *Client) Loop() error {
if !c.Connected {
err := c.Connect()
if err != nil {
return err
}
}
2015-08-25 04:53:35 +08:00
done := make(chan bool)
go c.readLoop(done)
go c.writeLoop(done)
2015-08-25 19:30:04 +08:00
go c.termsizeLoop(done)
2015-08-25 04:53:35 +08:00
<-done
return nil
}
2015-08-25 19:30:04 +08:00
type winsize struct {
Rows uint16 `json:"rows"`
Columns uint16 `json:"columns"`
// unused
x uint16
y uint16
}
func (c *Client) termsizeLoop(done chan bool) {
ch := make(chan os.Signal, 1)
signal.Notify(ch, syscall.SIGWINCH)
ws := winsize{}
for {
syscall.Syscall(syscall.SYS_IOCTL,
uintptr(0), uintptr(syscall.TIOCGWINSZ),
uintptr(unsafe.Pointer(&ws)))
b, err := json.Marshal(ws)
if err != nil {
logrus.Warnf("json.Marshal error: %v", err)
}
2015-09-30 23:17:57 +08:00
err = c.write(append([]byte("2"), b...))
2015-08-25 19:30:04 +08:00
if err != nil {
logrus.Warnf("ws.WriteMessage failed: %v", err)
}
<-ch
}
}
2015-08-25 04:53:35 +08:00
func (c *Client) writeLoop(done chan bool) {
2015-08-25 18:11:21 +08:00
oldState, err := terminal.MakeRaw(0)
if err == nil {
defer terminal.Restore(0, oldState)
}
2015-08-25 04:53:35 +08:00
reader := bufio.NewReader(os.Stdin)
for {
x, size, err := reader.ReadRune()
if size <= 0 || err != nil {
done <- true
return
}
p := make([]byte, size)
utf8.EncodeRune(p, x)
2015-09-30 23:17:57 +08:00
err = c.write(append([]byte("0"), p...))
2015-08-25 04:53:35 +08:00
if err != nil {
done <- true
return
}
}
}
func (c *Client) readLoop(done chan bool) {
2015-08-25 00:48:27 +08:00
for {
_, data, err := c.Conn.ReadMessage()
if err != nil {
2015-08-25 04:53:35 +08:00
done <- true
logrus.Warnf("c.Conn.ReadMessage: %v", err)
return
2015-08-25 00:48:27 +08:00
}
2015-09-30 23:17:57 +08:00
if len(data) == 0 {
done <- true
logrus.Warnf("An error has occured")
return
}
2015-08-25 00:48:27 +08:00
switch data[0] {
case '0': // data
2015-09-19 09:40:42 +08:00
buf, err := base64.StdEncoding.DecodeString(string(data[1:]))
if err != nil {
logrus.Warnf("Invalid base64 content: %q", data[1:])
}
fmt.Print(string(buf))
case '1': // pong
case '2': // new title
2015-08-25 04:10:19 +08:00
newTitle := string(data[1:])
fmt.Printf("\033]0;%s\007", newTitle)
2015-09-19 09:40:42 +08:00
case '3': // json prefs
2015-10-13 23:02:38 +08:00
logrus.Debugf("Unhandled protocol message: json pref: %s", string(data[1:]))
2015-09-19 09:40:42 +08:00
case '4': // autoreconnect
logrus.Debugf("Unhandled protocol message: autoreconnect: %s", string(data))
2015-08-25 00:48:27 +08:00
default:
logrus.Warnf("Unhandled protocol message: %s", string(data))
}
}
}
// NewClient returns a GoTTY client object
func NewClient(httpURL string) (*Client, error) {
return &Client{
2015-09-30 23:17:57 +08:00
Dialer: &websocket.Dialer{},
URL: httpURL,
WriteMutex: &sync.Mutex{},
2015-08-25 00:48:27 +08:00
}, nil
}