| 1 | package mobilelink |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "context" |
| 6 | "crypto/sha256" |
| 7 | "crypto/tls" |
| 8 | "encoding/base64" |
| 9 | "encoding/hex" |
| 10 | "encoding/json" |
| 11 | "errors" |
| 12 | "fmt" |
| 13 | "io" |
| 14 | "log" |
| 15 | "net/http" |
| 16 | "net/url" |
| 17 | "strings" |
| 18 | "time" |
| 19 | |
| 20 | "github.com/gorilla/websocket" |
| 21 | "github.com/sylvinus/agent-vm/internal/relay" |
| 22 | "github.com/sylvinus/agent-vm/internal/remotelink" |
| 23 | "golang.org/x/net/http2" |
| 24 | ) |
| 25 | |
| 26 | const OfficialRelay = "https://43.142.88.90" |
| 27 | |
| 28 | func relayOrigin(base string) (*url.URL, error) { |
| 29 | u, err := url.Parse(base) |
| 30 | if err != nil || u.Hostname() == "" || u.User != nil || u.Path != "" || |
| 31 | u.RawQuery != "" || u.ForceQuery || u.Fragment != "" || |
| 32 | (u.Scheme != "https" && (u.Scheme != "http" || !loopback(u.Hostname()))) { |
| 33 | return nil, errors.New("relay must use an HTTPS origin or a local loopback HTTP origin") |
| 34 | } |
| 35 | return u, nil |
| 36 | } |
| 37 | |
| 38 | func validCapability(value string) bool { |
| 39 | b, err := base64.RawURLEncoding.DecodeString(value) |
| 40 | return err == nil && len(b) == 32 && base64.RawURLEncoding.EncodeToString(b) == value |
| 41 | } |
| 42 | |
| 43 | |
| 44 | func ValidRelayOrigin(base string) bool { |
| 45 | _, err := relayOrigin(base) |
| 46 | return err == nil |
| 47 | } |
| 48 | |
| 49 | |
| 50 | |
| 51 | type retryableError struct{ error } |
| 52 | |
| 53 | |
| 54 | var ErrNoInvitation = errors.New("no available room for the saved device") |
| 55 | |
| 56 | func Retryable(err error) bool { |
| 57 | var transient retryableError |
| 58 | return errors.As(err, &transient) |
| 59 | } |
| 60 | |
| 61 | func relayNetworkError(ctx context.Context, err error) error { |
| 62 | if ctx.Err() != nil { |
| 63 | if errors.Is(ctx.Err(), context.DeadlineExceeded) { |
| 64 | return retryableError{errors.New("relay request timed out")} |
| 65 | } |
| 66 | return ctx.Err() |
| 67 | } |
| 68 | var trust *tls.CertificateVerificationError |
| 69 | if errors.As(err, &trust) { |
| 70 | return errors.New("relay HTTPS certificate verification failed") |
| 71 | } |
| 72 | return retryableError{errors.New("could not connect to relay")} |
| 73 | } |
| 74 | |
| 75 | func relayHTTPError(status int, missingIsTransient bool) error { |
| 76 | err := fmt.Errorf("relay returned HTTP %d", status) |
| 77 | if status == http.StatusConflict || status == http.StatusTooManyRequests || status == http.StatusRequestTimeout || |
| 78 | status >= 500 || (missingIsTransient && status == http.StatusNotFound) { |
| 79 | return retryableError{err} |
| 80 | } |
| 81 | return err |
| 82 | } |
| 83 | |
| 84 | type ClientInvitation struct { |
| 85 | ID string `json:"id"` |
| 86 | ClientToken string `json:"client_token"` |
| 87 | ExpiresAt time.Time `json:"expires_at"` |
| 88 | } |
| 89 | |
| 90 | func relayRequest(ctx context.Context, base, method, path, token string, payload []byte, want int) ([]byte, error) { |
| 91 | if _, err := relayOrigin(base); err != nil { |
| 92 | return nil, err |
| 93 | } |
| 94 | ctx, cancel := context.WithTimeout(ctx, 10*time.Second) |
| 95 | defer cancel() |
| 96 | req, err := http.NewRequestWithContext(ctx, method, base+path, bytes.NewReader(payload)) |
| 97 | if err != nil { |
| 98 | return nil, errors.New("invalid relay origin") |
| 99 | } |
| 100 | req.GetBody = nil |
| 101 | if token != "" { |
| 102 | req.Header.Set("Authorization", "Bearer "+token) |
| 103 | } |
| 104 | if len(payload) != 0 { |
| 105 | req.Header.Set("Content-Type", "application/json") |
| 106 | } |
| 107 | transport := &http.Transport{Proxy: nil, DisableKeepAlives: true} |
| 108 | defer transport.CloseIdleConnections() |
| 109 | res, err := transport.RoundTrip(req) |
| 110 | if err != nil { |
| 111 | return nil, relayNetworkError(ctx, err) |
| 112 | } |
| 113 | defer res.Body.Close() |
| 114 | if res.StatusCode != want { |
| 115 | if path == "/v1/invitation" && res.StatusCode == http.StatusNotFound { |
| 116 | return nil, ErrNoInvitation |
| 117 | } |
| 118 | return nil, relayHTTPError(res.StatusCode, path == "/v1/invitation") |
| 119 | } |
| 120 | return limited(res.Body, 4096) |
| 121 | } |
| 122 | |
| 123 | |
| 124 | |
| 125 | func CreateRoom(ctx context.Context, base, admin string) (relay.Invitation, error) { |
| 126 | return createRoom(ctx, base, admin, nil) |
| 127 | } |
| 128 | |
| 129 | |
| 130 | |
| 131 | func CreateDiscoverableRoom(ctx context.Context, base, admin, lookupToken string) (relay.Invitation, error) { |
| 132 | if !validCapability(lookupToken) { |
| 133 | return relay.Invitation{}, errors.New("invalid saved connection token") |
| 134 | } |
| 135 | raw, _ := base64.RawURLEncoding.DecodeString(lookupToken) |
| 136 | digest := sha256.Sum256(raw) |
| 137 | clear(raw) |
| 138 | payload, _ := json.Marshal(map[string]string{"lookup_hash": hex.EncodeToString(digest[:])}) |
| 139 | return createRoom(ctx, base, admin, payload) |
| 140 | } |
| 141 | |
| 142 | func createRoom(ctx context.Context, base, admin string, payload []byte) (relay.Invitation, error) { |
| 143 | var invite relay.Invitation |
| 144 | if (admin != "" && len(admin) < 32) || len(admin) > 4096 || strings.ContainsAny(admin, " \t\r\n") { |
| 145 | return invite, errors.New("invalid relay administration token") |
| 146 | } |
| 147 | data, err := relayRequest(ctx, base, http.MethodPost, "/v1/rooms", admin, payload, http.StatusCreated) |
| 148 | if err != nil { |
| 149 | return invite, err |
| 150 | } |
| 151 | defer clear(data) |
| 152 | if err != nil || json.Unmarshal(data, &invite) != nil || !validCapability(invite.ID) || |
| 153 | !validCapability(invite.HostToken) || !validCapability(invite.ClientToken) || !invite.ExpiresAt.After(time.Now()) { |
| 154 | return relay.Invitation{}, errors.New("invalid relay invitation") |
| 155 | } |
| 156 | return invite, nil |
| 157 | } |
| 158 | |
| 159 | |
| 160 | |
| 161 | func LookupRoom(ctx context.Context, base, lookupToken string) (ClientInvitation, error) { |
| 162 | var room ClientInvitation |
| 163 | if !validCapability(lookupToken) { |
| 164 | return room, errors.New("invalid saved connection token") |
| 165 | } |
| 166 | data, err := relayRequest(ctx, base, http.MethodGet, "/v1/invitation", lookupToken, nil, http.StatusOK) |
| 167 | if err != nil { |
| 168 | return room, err |
| 169 | } |
| 170 | defer clear(data) |
| 171 | dec := json.NewDecoder(bytes.NewReader(data)) |
| 172 | dec.DisallowUnknownFields() |
| 173 | if dec.Decode(&room) != nil || dec.Decode(new(any)) != io.EOF || !validCapability(room.ID) || !validCapability(room.ClientToken) || !room.ExpiresAt.After(time.Now()) { |
| 174 | return ClientInvitation{}, errors.New("invalid saved connection invitation") |
| 175 | } |
| 176 | return room, nil |
| 177 | } |
| 178 | |
| 179 | func join(ctx context.Context, base, roomID, role, token string) (*websocket.Conn, error) { |
| 180 | u, err := relayOrigin(base) |
| 181 | if err != nil { |
| 182 | return nil, err |
| 183 | } |
| 184 | if !validCapability(roomID) || !validCapability(token) { |
| 185 | return nil, errors.New("invalid relay room credentials") |
| 186 | } |
| 187 | if u.Scheme == "https" { |
| 188 | u.Scheme = "wss" |
| 189 | } else { |
| 190 | u.Scheme = "ws" |
| 191 | } |
| 192 | u.Path = "/v1/rooms/" + roomID + "/" + role |
| 193 | dialer := websocket.Dialer{HandshakeTimeout: 10 * time.Second} |
| 194 | socket, res, err := dialer.DialContext(ctx, u.String(), http.Header{"Authorization": {"Bearer " + token}}) |
| 195 | if err != nil { |
| 196 | if res != nil { |
| 197 | res.Body.Close() |
| 198 | return nil, relayHTTPError(res.StatusCode, true) |
| 199 | } |
| 200 | return nil, relayNetworkError(ctx, err) |
| 201 | } |
| 202 | return socket, nil |
| 203 | } |
| 204 | |
| 205 | |
| 206 | |
| 207 | func ServeHost(ctx context.Context, base, roomID, hostToken string, identity *remotelink.Identity, expectedPin string, b *Workbench) error { |
| 208 | if b == nil { |
| 209 | return errors.New("local workbench session required") |
| 210 | } |
| 211 | ws, err := join(ctx, base, roomID, "host", hostToken) |
| 212 | if err != nil { |
| 213 | return err |
| 214 | } |
| 215 | conn, err := remotelink.ServerAfterJoin(ctx, ws, identity, expectedPin) |
| 216 | if err != nil { |
| 217 | if ctx.Err() != nil { |
| 218 | return ctx.Err() |
| 219 | } |
| 220 | return retryableError{errors.New("room expired, disconnected, or peer authentication failed")} |
| 221 | } |
| 222 | stop := context.AfterFunc(ctx, func() { _ = conn.NetConn().Close() }) |
| 223 | defer stop() |
| 224 | defer conn.NetConn().Close() |
| 225 | hostHandler := b.handler() |
| 226 | server := &http2.Server{MaxConcurrentStreams: 16} |
| 227 | server.ServeConn(conn, &http2.ServeConnOpts{Context: ctx, BaseConfig: &http.Server{ |
| 228 | MaxHeaderBytes: 16 << 10, IdleTimeout: 5 * time.Minute, ErrorLog: log.New(io.Discard, "", 0), |
| 229 | }, Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 230 | if r.Host != "cage-mobile.invalid" { |
| 231 | http.Error(w, "invalid mobile authority", http.StatusForbidden) |
| 232 | return |
| 233 | } |
| 234 | hostHandler.ServeHTTP(w, r) |
| 235 | })}) |
| 236 | return ctx.Err() |
| 237 | } |
| 238 | |
| 239 | type Client struct { |
| 240 | session *http2.ClientConn |
| 241 | conn *tls.Conn |
| 242 | } |
| 243 | |
| 244 | |
| 245 | |
| 246 | func ConnectClient(ctx context.Context, base, roomID, clientToken string, identity *remotelink.Identity, expectedPin string) (*Client, error) { |
| 247 | ws, err := join(ctx, base, roomID, "client", clientToken) |
| 248 | if err != nil { |
| 249 | return nil, err |
| 250 | } |
| 251 | conn, err := remotelink.Client(ctx, ws, identity, expectedPin) |
| 252 | if err != nil { |
| 253 | return nil, errors.New("paired host authentication failed") |
| 254 | } |
| 255 | transport := &http2.Transport{MaxHeaderListSize: 16 << 10, ReadIdleTimeout: 15 * time.Second, PingTimeout: 8 * time.Second} |
| 256 | session, err := transport.NewClientConn(conn) |
| 257 | if err != nil { |
| 258 | conn.NetConn().Close() |
| 259 | return nil, errors.New("mobile protocol initialization failed") |
| 260 | } |
| 261 | return &Client{session: session, conn: conn}, nil |
| 262 | } |
| 263 | |
| 264 | func (c *Client) Do(ctx context.Context, method, path string, body []byte) (*Reply, error) { |
| 265 | return request(ctx, c.session, linkOrigin, method, path, body, false) |
| 266 | } |
| 267 | |
| 268 | |
| 269 | func (c *Client) Disconnected() bool { |
| 270 | state := c.session.State() |
| 271 | return state.Closed || state.Closing |
| 272 | } |
| 273 | |
| 274 | func (c *Client) Close() error { |
| 275 | _ = c.conn.NetConn().Close() |
| 276 | return c.session.Close() |
| 277 | } |