~adnano/astronaut

ref: 72ba913688a9d2dafb0bfdf11a5cee16685ce98a astronaut/tab.go -rw-r--r-- 10.1 KiB
72ba9136Adnan Maolood Use scfg to configure settings 4 months ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
package main

import (
	"astronaut/styles"
	"astronaut/ui"
	"bytes"
	"context"
	"crypto/tls"
	"crypto/x509"
	"io"
	"net/url"
	"sync"
	"sync/atomic"
	"time"

	"git.sr.ht/~adnano/go-gemini"
	"git.sr.ht/~adnano/go-gemini/certificate"
	"git.sr.ht/~adnano/go-gemini/tofu"
	"github.com/gdamore/tcell/v2"
)

// Tab represents a browser tab.
type Tab struct {
	view    *ui.View
	busy    int32
	mu      sync.RWMutex
	buf     bytes.Buffer
	status  *ui.StatusLine
	browser *Browser
	pages   []Page // navigation history
	page    int
	cancel  func()
}

func (t *Tab) URL() string {
	t.mu.RLock()
	defer t.mu.RUnlock()
	if len(t.pages) == 0 {
		return ""
	}
	return t.pages[t.page].URL
}

func (t *Tab) MediaType() string {
	t.mu.RLock()
	defer t.mu.RUnlock()
	if len(t.pages) == 0 {
		return ""
	}
	return t.pages[t.page].MediaType
}

func (t *Tab) content() Content {
	t.mu.RLock()
	defer t.mu.RUnlock()
	if len(t.pages) == 0 {
		return nil
	}
	// Show previous page's content if there is no content to show
	if atomic.LoadInt32(&t.busy) != 0 && t.page > 0 && t.pages[t.page].Content == nil {
		return t.pages[t.page-1].Content
	}
	return t.pages[t.page].Content
}

func (t *Tab) setContent(content Content) {
	t.mu.Lock()
	defer t.mu.Unlock()
	page := &t.pages[t.page]
	if page.Content != nil {
		page.Content.Close()
	}
	page.Content = content
}

// Page represents a page.
type Page struct {
	URL       string
	MediaType string
	Content   Content
	Scroll    ui.ScrollState
}

// Clone returns a new tab with the same URL and navigation history.
func (t *Tab) Clone() *Tab {
	t.mu.RLock()
	defer t.mu.RUnlock()
	clone := &Tab{}
	clone.pages = make([]Page, len(t.pages))
	copy(clone.pages, t.pages)
	clone.page = t.page
	clone.status = t.status
	clone.browser = t.browser
	return clone
}

func (t *Tab) Busy() bool {
	if atomic.LoadInt32(&t.busy) != 0 {
		return true
	}

	content := t.content()
	return content != nil && !content.Done()
}

// Draw draws the tab.
func (t *Tab) Draw() {
	t.view.Fill(' ', styles.Default)
	content := t.content()
	if content != nil {
		content.Draw()
	}
}

// Title returns the tab title.
func (t *Tab) Title() string {
	content := t.content()
	if content == nil {
		return t.URL()
	}
	title := content.Title()
	if title == "" {
		title = t.URL()
	}
	return title
}

// Event handles events.
func (t *Tab) Event(event tcell.Event) bool {
	content := t.content()
	if content != nil && content.Event(event) {
		return true
	}
	return false
}

// Reload reloads the tab.
func (t *Tab) Reload() {
	t.Get(t.URL())
}

// Cancel cancels the current request.
func (t *Tab) Cancel() {
	t.mu.Lock()
	defer t.mu.Unlock()
	if t.cancel != nil {
		t.cancel()
		t.cancel = nil
	}
}

// Back moves back in history.
func (t *Tab) Back() {
	t.mu.Lock()
	defer t.mu.Unlock()
	t.saveScroll()
	if t.page > 0 {
		t.page--
		t.restoreScroll()
	} else {
		t.status.Info("Already at beginning of history")
	}
}

// Forward moves forward in history.
func (t *Tab) Forward() {
	t.mu.Lock()
	defer t.mu.Unlock()
	t.saveScroll()
	if t.page < len(t.pages)-1 {
		t.page++
		t.restoreScroll()
	} else {
		t.status.Info("Already at end of history")
	}
}

func (t *Tab) saveScroll() {
	if len(t.pages) == 0 {
		return
	}
	t.pages[t.page].Scroll = t.view.ScrollState
}

func (t *Tab) restoreScroll() {
	t.view.ScrollState = t.pages[t.page].Scroll
	t.view.Invalidate()
}

func (t *Tab) resetScroll() {
	t.mu.Lock()
	defer t.mu.Unlock()
	t.saveScroll()
	t.view.ScrollState = ui.ScrollState{}
}

func (t *Tab) Error(err error) {
	t.mu.Lock()
	t.status.SetStyle(styles.Error)
	t.mu.Unlock()

	var buf bytes.Buffer
	templates.ExecuteTemplate(&buf, "error.tmpl", err)
	t.setContent(NewParsedGemText(t.view, t, io.NopCloser(&buf)))
	t.view.Invalidate()
}

// Get makes a request for the given raw URL.
// It resets the history going forward.
func (t *Tab) Get(rawurl string) {
	url, err := url.Parse(rawurl)
	if err != nil {
		t.Error(err)
		return
	}
	t.GetURL(url)
}

func (t *Tab) ResolveReference(rawurl string) (*url.URL, error) {
	url, err := url.Parse(rawurl)
	if err != nil {
		return nil, err
	}
	rel, err := url.Parse(t.URL())
	if err != nil {
		return nil, err
	}
	return rel.ResolveReference(url), nil
}

// GetURL makes a request for the given URL.
func (t *Tab) GetURL(url *url.URL) {
	req := &gemini.Request{URL: url}
	go t.Do(req)
}

// Do performs the provided request.
func (t *Tab) Do(req *gemini.Request) {
	// Don't perform a request if one is underway
	if !atomic.CompareAndSwapInt32(&t.busy, 0, 1) {
		return
	}
	defer atomic.StoreInt32(&t.busy, 0)

	ctx, cancel := context.WithCancel(context.Background())
	t.mu.Lock()
	t.cancel = cancel
	t.mu.Unlock()

	t.resetScroll()

	// Get certificate
	hostname := req.URL.Hostname()
	if cert, ok := t.browser.certs.Lookup(hostname); ok {
		req.Certificate = &cert
	}

	t.newPage(req)
	err := t.do(ctx, req, nil)
	if err != nil {
		t.Error(err)
	}
}

// do performs the request.
func (t *Tab) do(ctx context.Context, req *gemini.Request, via []*gemini.Request) error {
	t.updatePage(req)

	resp, err := t.doRequest(ctx, req)
	if err != nil {
		return err
	}

	// Create a certificate if necessary
	if resp.Status == gemini.StatusCertificateRequired && req.Certificate == nil {
		cert, ok := t.createCertificate(req.URL.Hostname())
		if !ok {
			return nil
		}
		req.Certificate = &cert
		return t.do(ctx, req, via)
	}

	switch resp.Status.Class() {
	case gemini.StatusInput:
		sensitive := resp.Status == gemini.StatusSensitiveInput
		input, ok := t.browser.getInput(resp.Meta, sensitive)
		if !ok {
			return nil
		}
		req.URL.ForceQuery = true
		req.URL.RawQuery = gemini.QueryEscape(input)
		return t.do(ctx, req, via)

	case gemini.StatusRedirect:
		target, err := url.Parse(resp.Meta)
		if err != nil {
			return err
		}
		redirect := *req
		redirect.URL = req.URL.ResolveReference(target)

		via = append(via, req)
		if len(via) > 5 {
			return &ErrTooManyRedirects{
				Req: &redirect,
				Via: via,
			}
		}
		if t.shouldRedirect(&redirect, via) {
			return t.do(ctx, &redirect, via)
		} else {
			t.setContent(nil)
			return nil
		}

	case gemini.StatusSuccess:
		t.buf.Reset()
		resp.Body = &teeReader{resp.Body, &t.buf}
		return t.handle(req, resp)

	default:
		return &ErrUnsuccessful{
			Status: resp.Status,
			Meta:   resp.Meta,
		}
	}
}

func (t *Tab) doRequest(ctx context.Context, req *gemini.Request) (resp *gemini.Response, err error) {
	switch req.URL.Scheme {
	case "about":
		var w ResponseWriter
		t.handleAbout(&w, req)
		resp = w.Response()
	case "file":
		var w ResponseWriter
		handleFile(&w, req)
		resp = w.Response()
	case "gemini":
		client := &gemini.Client{
			TrustCertificate: t.trustCertificate,
		}
		resp, err = client.Do(ctx, req)

	default:
		err = ErrUnsupportedScheme{}
	}
	return
}

// createCertificate is called when the server requests a certificate.
func (t *Tab) createCertificate(hostname string) (tls.Certificate, bool) {
	b := t.browser
	if cert, ok := b.certs.Lookup(hostname); ok {
		return cert, true
	}

	b.mu.Lock()
	b.status.Info("Creating a certificate for " + hostname)
	b.input.Prompt("Duration: ")
	b.mu.Unlock()

	ch := b.Inputch()
	input, ok := <-ch
	if !ok {
		return tls.Certificate{}, false
	}
	duration, err := time.ParseDuration(input)
	if err != nil {
		b.tabs[b.tab].Error(err)
		return tls.Certificate{}, false
	}
	cert, err := certificate.Create(certificate.CreateOptions{
		Duration: duration,
	})
	if err != nil {
		b.tabs[b.tab].Error(err)
		return cert, false
	}

	if err := b.certs.Add(hostname, cert); err != nil {
		b.tabs[b.tab].Error(err)
		return cert, false
	}
	return cert, true
}

// trustCertificate is called to determine if the client trusts the certificate.
func (t *Tab) trustCertificate(hostname string, cert *x509.Certificate) error {
	b := t.browser
	// Check the known hosts
	host := tofu.NewHost(hostname, cert.Raw)
	knownHost, ok := b.hosts.Lookup(hostname)
	if ok {
		// Check fingerprint
		if host.Fingerprint != knownHost.Fingerprint {
			return &ErrFingerprintMismatch{
				Expected: knownHost,
				Got:      host,
			}
		}
		return nil
	}

	ch := make(chan int)
	const (
		trustAlways = iota + 1
		trustOnce
	)

	{
		b.status.SetStyle(styles.Warning)

		var buf bytes.Buffer
		templates.ExecuteTemplate(&buf, "trust.tmpl", host)
		gem := NewParsedGemText(b.tabView, b.tabs[b.tab], io.NopCloser(&buf))
		gem.action = func(action string) {
			switch action {
			case "trust-always":
				ch <- trustAlways
			case "trust-once":
				ch <- trustOnce
			default:
				close(ch)
			}
		}
		t.setContent(gem)
	}

	select {
	case trust := <-ch:
		switch trust {
		case trustAlways:
			b.hosts.Add(host)
			if b.hostsFile != nil {
				b.hostsFile.WriteHost(host)
			}
			return nil
		case trustOnce:
			b.hosts.Add(host)
			return nil
		}
	}

	return ErrNotTrusted
}

// shouldRedirect is called to determine whether we should redirect.
func (t *Tab) shouldRedirect(req *gemini.Request, via []*gemini.Request) bool {
	if !t.shouldPromptRedirect(req, via[len(via)-1]) {
		return true
	}

	ch := make(chan bool)

	{
		t.mu.Lock()
		t.status.SetStyle(styles.Warning)
		t.mu.Unlock()

		ctx := struct {
			Req *gemini.Request
			Via []*gemini.Request
		}{req, via}

		var buf bytes.Buffer
		templates.ExecuteTemplate(&buf, "redirect.tmpl", ctx)
		gem := NewParsedGemText(t.view, t, io.NopCloser(&buf))
		gem.action = func(action string) {
			switch action {
			case "proceed":
				ch <- true
			default:
				close(ch)
			}
		}
		t.setContent(gem)
	}

	select {
	case b := <-ch:
		return b
	}
	return false
}

func (t *Tab) shouldPromptRedirect(req *gemini.Request, via *gemini.Request) bool {
	external := req.URL.Host != via.URL.Host
	nonGemini := via.URL.Scheme == "gemini" && req.URL.Scheme != "gemini"
	return external || nonGemini
}

func (t *Tab) newPage(req *gemini.Request) {
	t.mu.Lock()
	defer t.mu.Unlock()

	if len(t.pages) != 0 {
		if t.page != len(t.pages)-1 {
			if req.URL.String() != t.pages[t.page+1].URL {
				// Truncate history going forward
				t.pages = t.pages[:t.page+1]
			} else {
				// Refresh existing content
				t.pages[t.page+1].Content = nil
			}
		}
		t.page++
	}

	t.pages = append(t.pages, Page{})
}

func (t *Tab) updatePage(req *gemini.Request) {
	t.mu.Lock()
	defer t.mu.Unlock()
	t.pages[t.page].URL = req.URL.String()
}