gotty-client/gotty-client.go

360 lines
7.6 KiB
Go
Raw Normal View History

2015-08-25 00:48:27 +08:00
package gottyclient
import (
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-10-23 21:16:42 +08:00
"io"
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 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"
2015-10-23 21:16:42 +08:00
"github.com/moul/gotty-client/vendor/github.com/creack/goselect"
2015-09-28 03:49:24 +08:00
"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-22 23:35:05 +08:00
querySingle := querySingleType{
2015-10-13 00:07:50 +08:00
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-10-23 21:16:42 +08:00
var wg sync.WaitGroup
quit := make(chan struct{})
2015-08-25 04:53:35 +08:00
done := make(chan bool)
2015-10-23 21:16:42 +08:00
wg.Add(1)
go c.termsizeLoop(quit, &wg)
wg.Add(1)
go c.readLoop(done, quit, &wg)
wg.Add(1)
go c.writeLoop(done, quit, &wg)
2015-08-25 04:53:35 +08:00
<-done
2015-10-23 21:16:42 +08:00
close(quit)
wg.Wait()
2015-08-25 04:53:35 +08:00
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
}
2015-10-23 21:16:42 +08:00
func (c *Client) termsizeLoop(quit chan struct{}, wg *sync.WaitGroup) {
defer wg.Done()
2015-08-25 19:30:04 +08:00
ch := make(chan os.Signal, 1)
signal.Notify(ch, syscall.SIGWINCH)
2015-10-23 21:16:42 +08:00
defer signal.Reset(syscall.SIGWINCH)
2015-08-25 19:30:04 +08:00
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)
}
2015-10-23 21:16:42 +08:00
select {
case <-quit:
return
case <-ch:
}
2015-08-25 19:30:04 +08:00
}
}
2015-10-23 21:16:42 +08:00
type exposeFd interface {
Fd() uintptr
}
func (c *Client) writeLoop(done chan bool, quit chan struct{}, wg *sync.WaitGroup) {
defer wg.Done()
buff := make([]byte, 128)
2015-08-25 18:11:21 +08:00
oldState, err := terminal.MakeRaw(0)
if err == nil {
defer terminal.Restore(0, oldState)
}
2015-10-23 21:16:42 +08:00
rdfs := &goselect.FDSet{}
reader := io.Reader(os.Stdin)
2015-08-25 04:53:35 +08:00
for {
2015-10-23 21:16:42 +08:00
rdfs.Zero()
rdfs.Set(reader.(exposeFd).Fd())
err := goselect.Select(1, rdfs, nil, nil, 50*time.Millisecond)
if err != nil {
2015-08-25 04:53:35 +08:00
done <- true
return
}
2015-10-23 21:16:42 +08:00
if rdfs.IsSet(reader.(exposeFd).Fd()) {
size, err := reader.Read(buff)
if size <= 0 || err != nil {
done <- true
return
}
data := buff[:size]
err = c.write(append([]byte("0"), data...))
if err != nil {
done <- true
return
}
}
select {
case <-quit:
2015-08-25 04:53:35 +08:00
return
2015-10-23 21:16:42 +08:00
default:
break
2015-08-25 04:53:35 +08:00
}
}
}
2015-10-23 21:16:42 +08:00
func (c *Client) readLoop(done chan bool, quit chan struct{}, wg *sync.WaitGroup) {
defer wg.Done()
type MessageNonBlocking struct {
Data []byte
Err error
}
msgChan := make(chan MessageNonBlocking)
2015-08-25 00:48:27 +08:00
for {
2015-10-23 21:16:42 +08:00
go func() {
_, data, err := c.Conn.ReadMessage()
msgChan <- MessageNonBlocking{Data: data, Err: err}
}()
select {
case <-quit:
2015-09-30 23:17:57 +08:00
return
2015-10-23 21:16:42 +08:00
case msg := <-msgChan:
if msg.Err != nil {
done <- true
logrus.Warnf("c.Conn.ReadMessage: %v", msg.Err)
return
}
if len(msg.Data) == 0 {
done <- true
logrus.Warnf("An error has occured")
return
}
switch msg.Data[0] {
case '0': // data
buf, err := base64.StdEncoding.DecodeString(string(msg.Data[1:]))
if err != nil {
logrus.Warnf("Invalid base64 content: %q", msg.Data[1:])
}
fmt.Print(string(buf))
case '1': // pong
case '2': // new title
newTitle := string(msg.Data[1:])
fmt.Printf("\033]0;%s\007", newTitle)
case '3': // json prefs
logrus.Debugf("Unhandled protocol message: json pref: %s", string(msg.Data[1:]))
case '4': // autoreconnect
logrus.Debugf("Unhandled protocol message: autoreconnect: %s", string(msg.Data))
default:
logrus.Warnf("Unhandled protocol message: %s", string(msg.Data))
2015-09-19 09:40:42 +08:00
}
2015-08-25 00:48:27 +08:00
}
}
}
// 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
}