about summary refs log tree commit diff stats
path: root/bollux
blob: 05c916b0468e3978e6cbd3a362e48c1cccec2265 (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
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
#!/usr/bin/env bash
# bollux: a bash gemini client or whatever
# Author: Case Duckworth <acdw@acdw.net>
# License: MIT
# Version: -0.7

### constants ###
PRGN="${0##*/}"                # program name
DLDR="${BOLLUX_DOWNDIR:-.}"    # where to download
LOGL="${BOLLUX_LOGLEVEL:-3}"   # log level
MAXR="${BOLLUX_MAXREDIR:-5}"   # max redirects
PORT="${BOLLUX_PORT:-1965}"    # port number
PROT="${BOLLUX_PROTO:-gemini}" # protocol
RDRS=0                         # redirects

# LOGLEVELS:
# 0 - application fatal error
# 1 - application warning
# 2 - response error
# 3 - response logging
# 4 - application logging
# 5 - diagnostic

### utility functions ###
# a better echo
put() { printf '%s\n' "$*" >&3; }

# conditionally log events to stderr
# lower = more important
log() { # log [LEVEL] [<] MESSAGE
	case "$1" in
	-)
		lvl="-1"
		shift
		;;
	[0-5])
		lvl="$1"
		shift
		;;
	*) lvl=4 ;;
	esac

	output="$*"
	if ((lvl < LOGL)); then
		if (($# == 0)); then
			while IFS= read -r line; do
				output="$output${output:+$'\n'}$line"
			done
		fi
		printf '\e[34m%s\e[0m:\t%s\n' "$PRGN" "$output" >&2
	fi
}

# halt and catch fire
die() { # die [EXIT-CODE] MESSAGE
	case "$1" in
	[0-9]*)
		ec="$1"
		shift
		;;
	*) ec=1 ;;
	esac

	log 0 "$*"
	exit "$ec"
}

# ask the user for input
ask() { # ask PROMPT [READ_OPT...]
	prompt="$1"
	shift
	read -e -r -u 3 -p "$prompt> " "$@"
}

# fail if something isn't installed
require() { hash "$1" 2>/dev/null || die 127 "Requirement '$1' not found."; }

# trim a string
trim() { sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//'; }

# stubs for when things aren't implemented (fully)
NOT_IMPLEMENTED() { die 200 "NOT IMPLEMENTED!!!"; }
NOT_FULLY_IMPLEMENTED() { log 1 "NOT FULLY IMPLEMENTED!!!"; }

### gemini ###
# normalize a gemini address
# example.com => gemini://example.com/
_address() { # _address URL
	addr="$1"

	[[ "$addr" != *://* ]] && addr="$PROT://$addr"
	trim <<<"$addr"
}

# return only the server part from an address, with the port added
# gemini://example.com/path/to/file => example.com:1965
_server() {
	serv="$(_address "$1")" # normalize first
	serv="${serv#*://}"
	serv="${serv%%/*}"
	if [[ "$serv" != *:* ]]; then
		serv="$serv:$PORT"
	fi
	trim <<<"$serv"
}

# request a gemini page
# by default, extract the server from the url
request() { # request [-s SERVER] URL
	case "$1" in
	-s)
		serv="$(_server "$2")"
		addr="$(_address "$3")"
		;;
	*)
		serv="$(_server "$1")"
		addr="$(_address "$1")"
		;;
	esac

	log 5 "serv: $serv"
	log 5 "addr: $addr"

	sslcmd=(openssl s_client -crlf -ign_eof -quiet -connect "$serv")
	log "${sslcmd[@]}"
	"${sslcmd[@]}" <<<"$addr" 2>/dev/null
}

# handle the response
# cf. gemini://gemini.circumlunar.space/docs/spec-spec.txt
handle() { # handle URL < RESPONSE
	URL="$1"
	while read -r head; do
		break # wait to read the first line
	done
	code="$(awk '{print $1}' <<<"$head")"
	meta="$(awk '{for(i=2;i<=NF;i++)printf "%s ",$i;printf "\n"}' <<<"$head")"

	log 5 "[$code]	$meta"

	case "$code" in
	1*) # INPUT
		log 3 "Input"
		put "$meta"
		ask "?"
		bollux "$URL?$REPLY"
		;;
	2*) # SUCCESS
		log 3 "Success"
		case "$code" in
		20) log 5 "- OK" ;;
		21) log 5 "- End of client certificate session" ;;
		*) log 2 "- Unknown response code: '$code'." ;;
		esac
		display "$meta"
		;;
	3*) # REDIRECT
		log 3 "Redirecting"
		case "$code" in
		30) log 5 "- Temporary" ;;
		31) log 5 "- Permanent" ;;
		*) log 2 "- Unknown response code: '$code'." ;;
		esac
		((RDRS += 1))
		((RDRS > MAXR)) && die "$code" "Too many redirects!"
		bollux "$meta"
		;;
	4*) # TEMPORARY FAILURE
		log 2 "Temporary failure"
		case "$code" in
		41) log 5 "- Server unavailable" ;;
		42) log 5 "- CGI error" ;;
		43) log 5 "- Proxy error" ;;
		44) log 5 "- Rate limited" ;;
		*) log 2 "- Unknown response code: '$code'." ;;
		esac
		exit "$code"
		;;
	5*) # PERMANENT FAILURE
		log 2 "Permanent failure"
		case "$code" in
		51) log 5 "- Not found" ;;
		52) log 5 "- No longer available" ;;
		53) log 5 "- Proxy request refused" ;;
		59) log 5 "- Bad request" ;;
		*) log 2 "- Unknown response code: '$code'." ;;
		esac
		exit "$code"
		;;
	6*) # CLIENT CERT REQUIRED
		log 2 "Client certificate required"
		case "$code" in
		61) log 5 "- Transient cert requested" ;;
		62) log 5 "- Authorized cert required" ;;
		63) log 5 "- Cert not accepted" ;;
		64) log 5 "- Future cert rejected" ;;
		65) log 5 "- Expired cert rejected" ;;
		*) log 2 "- Unknown response code: '$code'." ;;
		esac
		exit "$code"
		;;
	*) # ???
		die "$code" "Unknown response code: '$code'."
		;;
	esac
}

# display the page
display() { # display MIMETYPE < DOCUMENT
	mimetype="$1"
	case "$mimetype" in
	text/*)
		# normalize line endings to "\n"
		# awk 'BEGIN{RS=""}{gsub(/\r\n?/,"\n");print}'
		cat
		# TODO: use less with linking and stuff
		# less -R -p'^=>' +g
		# lesskey:
		# l /=>\n # highlight links
		# o pipe \n open_url # open the link on the top line
		# u shell select_url % # shows a selection prompt for all urls (on screen? file?)
		# Q exit 1  # for one of these, show a selection prompt for urls
		# q exit 0  # for the other, just quit
		###
		# also look into the prompt, the filename, and input preprocessor
		# ($LESSOPEN, $LESSCLOSE)
		;;
	*)
		download "$URL"
		;;
	esac
}

download() { # download URL < FILE
	tn="$(mktemp)"
	dd status=progress >"$tn"
	fn="$DLDR/${URL##*/}"
	if [[ -f "$fn" ]]; then
		log - "Saved '$tn'."
	else
		if mv "$tn" "$fn"; then
			log - "Saved '$fn'."
		else
			log 0 "Error saving '$fn'."
			log - "Saved '$tn'."
		fi
	fi
}

### main entry point ###
bollux() {
	# use &3 for user input
	exec 3<>/dev/tty

	if (($# == 1)); then
		URL="$1"
	else
		ask GO URL
	fi

	log 5 "URL : $URL"

	request "$URL" | handle "$URL"
}

bollux_setup() {
	mkfifo .resource
	trap bollux_cleanup INT QUIT TERM EXIT
}

bollux_cleanup() {
	echo
	rm -f .resource
}

if [[ "${BASH_SOURCE[0]}" == "$0" ]]; then
	set -euo pipefail # strict mode
	# requirements here -- so they're only checked once
	require awk
	require dd
	require mv
	require openssl
	require sed

	bollux "$@"
	echo
fi