summaryrefslogtreecommitdiff
path: root/tools/sw-fetch/main.go
blob: 76e414cd1c2831ba2f5e239efc755b2ac4663367 (plain)
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
package main

import (
	"context"
	"crypto/tls"
	"fmt"
	"io"
	"net/http"
	"net/url"
	"os"
	"time"

	"tildegit.org/tjp/sliderule"
	"tildegit.org/tjp/sliderule/gemini"
	"tildegit.org/tjp/sliderule/spartan"
)

const usage = `Resource fetcher for the small web.

Usage:
  sw-fetch (-h | --help)
  sw-fetch
	[-v | --verbose]
	[-o PATH | --output PATH]
	[-k | --keyfile PATH]
	[ -c | --certfile PATH ]
	[ -s | --skip-verify ]
	[ -t | --timeout TIMEOUT ]
	[ -u | --upload ]
	URL

Options:
  -h --help             Show this screen.
  -v --verbose          Display more diagnostic information on standard error.
  -o --output PATH      Send the fetched resource to PATH instead of standard out.
  -k --keyfile PATH     Path to the TLS key file to use.
  -c --certfile PATH    Path to the TLS certificate file to use.
  -s --skip-verify      Don't verify server TLS certificates.
  -t --timeout TIMEOUT  Fail after the given timeout (like "15s").
  -u --upload           Use stdin as the request body on supported protocols and don't follow redirects.
`

func main() {
	conf := configure()
	cl := sliderule.NewClient(conf.clientTLS)

	ctx := context.Background()
	if conf.timeout != 0 {
		var cancel context.CancelFunc
		ctx, cancel = context.WithTimeout(ctx, conf.timeout)
		defer cancel()
	}

	var response *sliderule.Response
	var err error

	if conf.upload {
		response, err = cl.Upload(ctx, conf.url.String(), os.Stdin)
	} else {
		response, err = cl.Fetch(ctx, conf.url.String())
	}
	if err != nil {
		fail(err.Error() + "\n")
	}
	defer func() {
		_ = response.Close()
		_ = conf.output.Close()
	}()

	success := printResponse(response, conf)
	if !success {
		os.Exit(1)
	}
}

type config struct {
	verbose   bool
	upload    bool
	output    io.WriteCloser
	url       *url.URL
	clientTLS *tls.Config
	timeout   time.Duration
}

func configure() config {
	if len(os.Args) == 1 {
		fail(usage)
	}

	conf := config{output: os.Stdout}
	key := ""
	cert := ""
	verify := true
	var err error

	for i := 1; i <= len(os.Args)-1; i += 1 {
		switch os.Args[i] {
		case "-h", "--help":
			os.Stdout.WriteString(usage)
			os.Exit(0)
		case "-v", "--verbose":
			conf.verbose = true
		case "-o", "--output":
			if i+1 == len(os.Args)-1 {
				fail(usage)
			}

			out := os.Args[i+1]
			if out != "-" {
				conf.output, err = os.OpenFile(out, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0o644)
				if err != nil {
					fmt.Println(err.Error())
					failf("'%s' is not a valid path\n", out)
				}
			}

			i += 1
		case "-k", "--keyfile":
			if i+1 == len(os.Args)-1 {
				fail(usage)
			}

			i += 1
			key = os.Args[i]
		case "-c", "--certfile":
			if i+1 == len(os.Args)-1 {
				fail(usage)
			}

			i += 1
			cert = os.Args[i]
		case "-s", "--skip-verify":
			verify = false
		case "-t", "--timeout":
			if i+1 == len(os.Args)-1 {
				fail(usage)
			}

			i += 1
			conf.timeout, err = time.ParseDuration(os.Args[i])
			if err != nil {
				fail(err.Error())
			}
		case "-u", "--upload":
			conf.upload = true
		}
	}

	conf.clientTLS = &tls.Config{}
	if key != "" || cert != "" {
		if key == "" || cert == "" {
			fail("-k|--keyfile and -c|--certfile must both be present, or neither\n")
		}
		tlsConf, err := gemini.FileTLS(cert, key)
		if err != nil {
			failf("failed to load TLS key pair: %s", err.Error())
		}
		conf.clientTLS = tlsConf
	}
	conf.clientTLS.InsecureSkipVerify = !verify

	u, err := url.Parse(os.Args[len(os.Args)-1])
	if err != nil || u.Scheme == "" {
		fail(usage)
	}
	conf.url = u

	return conf
}

func fail(msg string) {
	os.Stderr.WriteString(msg)
	os.Exit(1)
}

func failf(msg string, args ...any) {
	fmt.Fprintf(os.Stderr, msg, args...)
	os.Exit(1)
}

func printResponse(response *sliderule.Response, conf config) bool {
	success := true

	switch conf.url.Scheme {
	case "http", "https":
		switch int(response.Status) / 100 {
		case 4, 5:
			fmt.Fprintf(os.Stderr, "http %d: %s\n", response.Status, http.StatusText(int(response.Status)))
			success = false
		}
	case "gemini": //, "titan"
		switch gemini.ResponseCategoryForStatus(response.Status) {
		case gemini.ResponseCategoryTemporaryFailure, gemini.ResponseCategoryPermanentFailure, gemini.ResponseCategoryCertificateRequired:
			fmt.Fprintf(os.Stderr, "gemini %d: %s\n", response.Status, response.Meta.(string))
			success = false
		}
	case "spartan":
		switch response.Status {
		case spartan.StatusClientError, spartan.StatusServerError:
			fmt.Fprintf(os.Stderr, "spartan %d: %s\n", response.Status, response.Meta.(string))
			success = false
		}
	}

	if _, err := io.Copy(conf.output, response.Body); err != nil {
		fail(err.Error())
	}

	return success
}