oficina / meet Public

Clone
git clone https://amadan.net/oficina/meet

Plain git — no account needed to clone.

Download

Download this file

1// Package callscore is the shared, UI-free Go client for Calls. It owns signaling
2// and room state plus browser sign-in handoff; the host owns browser launch,
3// credential storage and media.
4package callscore
5
6import (
7 "bufio"
8 "bytes"
9 "context"
10 "encoding/base64"
11 "encoding/json"
12 "errors"
13 "fmt"
14 "io"
15 "net/http"
16 "net/url"
17 "strconv"
18 "strings"
19 "time"
20
21 "amadan.net/oficina/calls/protocol"
22)
23
24const maxResponse = 128 * 1024
25
26// HTTPError intentionally excludes response bodies and URLs: those may contain
27// session material, meeting names, or peer-supplied payloads.
28type HTTPError struct {
29 Status int
30 Reason string
31 RetryAfter time.Duration
32}
33
34func (e *HTTPError) Error() string { return fmt.Sprintf("Calls request refused (%d)", e.Status) }
35
36type transport struct {
37 origin string
38 room string
39 http *http.Client
40}
41
42// checkOrigin is the one place an origin is judged, so a request made
43// outside a transport — StartMeeting is the only one — cannot reach a
44// server this package would otherwise refuse. It answers the origin
45// without its trailing slash, which is also the value the Origin header
46// has to carry for csrf.Protect to recognise it.
47func checkOrigin(origin string) (string, error) {
48 u, err := url.Parse(origin)
49 if err != nil || u.Host == "" || u.User != nil || u.RawQuery != "" || u.Fragment != "" || (u.Path != "" && u.Path != "/") {
50 return "", errors.New("enter a Calls server origin")
51 }
52 if u.Scheme != "https" && !(u.Scheme == "http" && (u.Hostname() == "127.0.0.1" || u.Hostname() == "localhost" || u.Hostname() == "::1")) {
53 return "", errors.New("Calls requires HTTPS (HTTP is allowed only on loopback)")
54 }
55 return strings.TrimSuffix(origin, "/"), nil
56}
57
58// validRoom is the meeting identifier's shape, checked both on the way
59// in from a person and on the way back from the server: a sqid this app
60// cannot open is a bad answer, not a meeting.
61func validRoom(room string) bool {
62 return room != "" && len(room) <= 32 && strings.IndexFunc(room, func(r rune) bool {
63 return !(r >= 'a' && r <= 'z' || r >= 'A' && r <= 'Z' || r >= '0' && r <= '9')
64 }) < 0
65}
66
67// safeClient wraps the caller's client for every request this package
68// makes. Never follow a redirect with a credential or accidentally decode a
69// sign-in page as protocol JSON. The caller's transport and cookie jar are
70// retained.
71func safeClient(client *http.Client) (*http.Client, error) {
72 if client == nil {
73 return nil, errors.New("an authenticated HTTP client is required")
74 }
75 safe := *client
76 if safe.Transport == nil {
77 // The default transport, with a deadline on the response's
78 // headers. A process that has replaced it (internal/callstest's
79 // TestMain installs keymailtest's, which answers DNS in-process)
80 // keeps its own: asserting *http.Transport panicked there.
81 if base, ok := http.DefaultTransport.(*http.Transport); ok {
82 transport := base.Clone()
83 transport.ResponseHeaderTimeout = 15 * time.Second
84 safe.Transport = transport
85 } else {
86 safe.Transport = http.DefaultTransport
87 }
88 }
89 safe.CheckRedirect = func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }
90 safe.Timeout = 0 // streams live for five minutes; individual calls have deadlines
91 return &safe, nil
92}
93
94func newTransport(origin, room string, client *http.Client) (*transport, error) {
95 trimmed, err := checkOrigin(origin)
96 if err != nil {
97 return nil, err
98 }
99 if !validRoom(room) {
100 return nil, errors.New("invalid meeting identifier")
101 }
102 safe, err := safeClient(client)
103 if err != nil {
104 return nil, err
105 }
106 return &transport{trimmed, room, safe}, nil
107}
108
109func (t *transport) request(ctx context.Context, method, endpoint string, q url.Values, body []byte) (*http.Response, error) {
110 path := t.origin + "/m/" + t.room + "/" + endpoint
111 if len(q) > 0 {
112 path += "?" + q.Encode()
113 }
114 req, err := http.NewRequestWithContext(ctx, method, path, bytes.NewReader(body))
115 if err != nil {
116 return nil, errors.New("cannot build Calls request")
117 }
118 req.Header.Set("Accept", "application/json")
119 if endpoint == "stream" {
120 req.Header.Set("Accept", "text/event-stream")
121 }
122 if method == http.MethodPost {
123 req.Header.Set("Content-Type", "application/json")
124 req.Header.Set("Origin", t.origin)
125 }
126 if c := ClientLabel(); c != "" {
127 req.Header.Set(protocol.ClientHeader, c)
128 }
129 res, err := t.http.Do(req)
130 if err != nil {
131 return nil, errors.New("cannot reach Calls")
132 }
133 if res.StatusCode >= 200 && res.StatusCode < 300 {
134 return res, nil
135 }
136 defer res.Body.Close()
137 var b struct {
138 Reason string `json:"reason"`
139 }
140 _ = json.NewDecoder(io.LimitReader(res.Body, maxResponse)).Decode(&b)
141 // Only protocol-defined terminal reasons may reach the UI.
142 switch b.Reason {
143 case "replaced", "removed", "expired", "standing", "ended":
144 default:
145 b.Reason = ""
146 }
147 retry := time.Second
148 if n, err := strconv.Atoi(res.Header.Get("Retry-After")); err == nil && n > 0 {
149 retry = min(time.Duration(n)*time.Second, 30*time.Second)
150 }
151 return nil, &HTTPError{res.StatusCode, b.Reason, retry}
152}
153
154func (t *transport) post(ctx context.Context, s protocol.Signal) error {
155 b, err := json.Marshal(s)
156 if err != nil || len(b) > 64*1024 {
157 return errors.New("signal exceeds Calls' message limit")
158 }
159 ctx, cancel := context.WithTimeout(ctx, 10*time.Second)
160 defer cancel()
161 res, err := t.request(ctx, http.MethodPost, "signal", nil, b)
162 if err != nil {
163 return err
164 }
165 defer res.Body.Close()
166 _, err = io.Copy(io.Discard, io.LimitReader(res.Body, maxResponse))
167 return err
168}
169
170// readEvents bounds both individual lines and complete events, accepts SSE
171// comments and multiline data, and never dispatches an incomplete final event.
172func readEvents(r io.Reader, receive func(protocol.Message) error) error {
173 scanner := bufio.NewScanner(r)
174 scanner.Buffer(make([]byte, 4096), maxResponse)
175 var data []string
176 size := 0
177 for scanner.Scan() {
178 line := scanner.Text()
179 if line == "" {
180 if len(data) > 0 {
181 var m protocol.Message
182 if err := json.Unmarshal([]byte(strings.Join(data, "\n")), &m); err != nil {
183 return errors.New("invalid Calls event")
184 }
185 if err := receive(m); err != nil {
186 return err
187 }
188 }
189 data = nil
190 size = 0
191 continue
192 }
193 if strings.HasPrefix(line, "data:") {
194 value := strings.TrimPrefix(strings.TrimPrefix(line, "data:"), " ")
195 size += len(value) + 1
196 if size > maxResponse {
197 return errors.New("Calls event exceeds limit")
198 }
199 data = append(data, value)
200 }
201 }
202 if err := scanner.Err(); err != nil {
203 return errors.New("Calls event stream interrupted")
204 }
205 return io.EOF
206}
207
208// ICEServers is the server's short-lived TURN credential response. It stays in
209// memory and must never be logged or persisted by a native host.
210type ICEServers struct {
211 Servers []ICEServer `json:"iceServers"`
212 ExpiresAt int64 `json:"expiresAt"`
213 RenewAt int64 `json:"renewAt"`
214}
215type ICEServer struct {
216 URLs []string `json:"urls"`
217 Username string `json:"username,omitempty"`
218 Credential string `json:"credential,omitempty"`
219}
220
221func (t *transport) ice(ctx context.Context, peer protocol.PeerID) (ICEServers, error) {
222 ctx, cancel := context.WithTimeout(ctx, 10*time.Second)
223 defer cancel()
224 res, err := t.request(ctx, http.MethodGet, "ice", url.Values{"peer": {string(peer)}}, nil)
225 if err != nil {
226 return ICEServers{}, err
227 }
228 defer res.Body.Close()
229 var ice ICEServers
230 if err := json.NewDecoder(io.LimitReader(res.Body, maxResponse)).Decode(&ice); err != nil {
231 return ice, errors.New("invalid Calls ICE response")
232 }
233 return ice, nil
234}
235
236// Info is the same metadata the server renders on the holding screen.
237type Info struct {
238 Title string `json:"title"`
239 // Named is a title someone chose rather than one Calls wrote ("Call,
240 // 2 Oct 15:40"): the apps show it over the call. A server from before
241 // 0.4.7 does not say, so its titles are left off — the default for
242 // every call now.
243 Named bool `json:"named"`
244 Name string `json:"name"`
245 Standing string `json:"standing"`
246 Floor bool `json:"floor"`
247}
248
249func (t *transport) info(ctx context.Context) (Info, error) {
250 ctx, cancel := context.WithTimeout(ctx, 10*time.Second)
251 defer cancel()
252 res, err := t.request(ctx, http.MethodGet, "info", nil, nil)
253 if err != nil {
254 return Info{}, err
255 }
256 defer res.Body.Close()
257 var info Info
258 if err := json.NewDecoder(io.LimitReader(res.Body, maxResponse)).Decode(&info); err != nil {
259 return info, errors.New("invalid meeting information")
260 }
261 return info, nil
262}
263
264// takeover ends this session's own live participation in the room — the
265// web's "Use this tab" (POST /m/{sqid}/takeover), which answers 303 back
266// to the room when it has done so. Any other answer, a redirect to
267// sign-in among them, is a refusal.
268func (t *transport) takeover(ctx context.Context) error {
269 ctx, cancel := context.WithTimeout(ctx, 10*time.Second)
270 defer cancel()
271 room := "/m/" + t.room
272 req, err := http.NewRequestWithContext(ctx, http.MethodPost, t.origin+room+"/takeover", nil)
273 if err != nil {
274 return errors.New("cannot build Calls request")
275 }
276 req.Header.Set("Origin", t.origin)
277 res, err := t.http.Do(req)
278 if err != nil {
279 return errors.New("cannot reach Calls")
280 }
281 defer res.Body.Close()
282 _, _ = io.Copy(io.Discard, io.LimitReader(res.Body, maxResponse))
283 if res.StatusCode != http.StatusSeeOther {
284 return &HTTPError{Status: res.StatusCode}
285 }
286 if u, err := url.Parse(res.Header.Get("Location")); err != nil || u.Path != room {
287 return &HTTPError{Status: res.StatusCode}
288 }
289 return nil
290}
291
292func (t *transport) shareLink(ctx context.Context) (string, error) {
293 ctx, cancel := context.WithTimeout(ctx, 10*time.Second)
294 defer cancel()
295 res, err := t.request(ctx, http.MethodPost, "share", nil, []byte(`{}`))
296 if err != nil {
297 return "", err
298 }
299 defer res.Body.Close()
300 var result struct {
301 URL string `json:"url"`
302 }
303 if err := json.NewDecoder(io.LimitReader(res.Body, maxResponse)).Decode(&result); err != nil {
304 return "", errors.New("invalid meeting invitation")
305 }
306 prefix := t.origin + "/j/"
307 if !strings.HasPrefix(result.URL, prefix) {
308 return "", errors.New("invalid meeting invitation")
309 }
310 token := strings.TrimPrefix(result.URL, prefix)
311 decoded, err := base64.RawURLEncoding.DecodeString(token)
312 if err != nil || len(decoded) != 32 || base64.RawURLEncoding.EncodeToString(decoded) != token {
313 return "", errors.New("invalid meeting invitation")
314 }
315 return result.URL, nil
316}
317