go-gemini/examples/client.go

101 lines
2.1 KiB
Go
Raw Normal View History

2020-10-12 20:34:52 +00:00
// +build ignore
2020-09-21 21:23:51 +00:00
package main
import (
"bufio"
2020-11-01 02:50:42 +00:00
"crypto/x509"
2020-12-18 00:50:26 +00:00
"errors"
2020-09-21 21:23:51 +00:00
"fmt"
2020-10-27 23:16:55 +00:00
"io/ioutil"
"log"
2020-09-21 21:23:51 +00:00
"os"
2020-11-09 17:04:53 +00:00
"path/filepath"
2020-09-28 03:49:41 +00:00
"time"
2020-10-28 02:12:10 +00:00
"git.sr.ht/~adnano/go-gemini"
2020-11-09 17:04:53 +00:00
"git.sr.ht/~adnano/go-xdg"
2020-09-21 21:23:51 +00:00
)
const trustPrompt = `The certificate offered by %s is of unknown trust. Its fingerprint is:
%s
If you knew the fingerprint to expect in advance, verify that this matches.
Otherwise, this should be safe to trust.
[t]rust always; trust [o]nce; [a]bort
=> `
2020-12-18 00:50:26 +00:00
func main() {
if len(os.Args) < 2 {
fmt.Printf("usage: %s <url> [host]", os.Args[0])
os.Exit(1)
}
// Load known hosts file
var knownHosts gemini.KnownHostsFile
if err := knownHosts.Load(filepath.Join(xdg.DataHome(), "gemini", "known_hosts")); err != nil {
log.Println(err)
}
scanner := bufio.NewScanner(os.Stdin)
var client gemini.Client
client.TrustCertificate = func(hostname string, cert *x509.Certificate) error {
knownHost, ok := knownHosts.Lookup(hostname)
if ok && time.Now().Before(knownHost.Expires) {
// Certificate is in known hosts file and is not expired
return nil
}
2020-09-21 21:23:51 +00:00
2020-11-09 17:04:53 +00:00
fingerprint := gemini.NewFingerprint(cert.Raw, cert.NotAfter)
2020-11-05 20:27:12 +00:00
fmt.Printf(trustPrompt, hostname, fingerprint.Hex)
2020-11-01 02:50:42 +00:00
scanner.Scan()
switch scanner.Text() {
case "t":
2020-12-18 00:50:26 +00:00
knownHosts.Add(hostname, fingerprint)
knownHosts.Write(hostname, fingerprint)
return nil
2020-11-01 02:50:42 +00:00
case "o":
2020-12-18 00:50:26 +00:00
knownHosts.Add(hostname, fingerprint)
return nil
2020-11-01 02:50:42 +00:00
default:
2020-12-18 00:50:26 +00:00
return errors.New("certificate not trusted")
2020-11-01 02:50:42 +00:00
}
}
client.GetInput = func(prompt string, sensitive bool) (string, bool) {
2020-12-18 00:50:26 +00:00
fmt.Printf("%s ", prompt)
scanner.Scan()
return scanner.Text(), true
}
2020-09-27 23:45:48 +00:00
2020-12-18 00:50:26 +00:00
// Do the request
2020-09-27 23:45:48 +00:00
url := os.Args[1]
2020-10-28 02:12:10 +00:00
req, err := gemini.NewRequest(url)
2020-09-27 23:45:48 +00:00
if err != nil {
fmt.Println(err)
os.Exit(1)
}
if len(os.Args) == 3 {
req.Host = os.Args[2]
}
resp, err := client.Do(req)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
2020-12-18 00:50:26 +00:00
// Handle response
if resp.Status.Class() == gemini.StatusClassSuccess {
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Fatal(err)
}
fmt.Print(string(body))
} else {
2020-12-18 00:50:26 +00:00
fmt.Printf("%d %s: %s\n", resp.Status, resp.Status.Message(), resp.Meta)
os.Exit(1)
2020-09-21 21:23:51 +00:00
}
}