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

# set -euo pipefail              # strict mode

### 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
VRSN=-0.7                      # version number

# shellcheck disable=2120
bollux_usage() {
	cat <<END_USAGE >&2
	$PRGN ($VRSN): a bash gemini client
	usage:
		$PRGN [-h]
		$PRGN [-L LVL] [URL]
	options:
		-h	show this help
		-L LVL	set the loglevel to LVL.
			Default: $BOLLUX_LOGLEVEL
			The loglevel is between 0 and 5, with
			lower levels being more dire.
	parameters:
		URL	the URL to navigate view or download
END_USAGE
	exit "${1:-0}"
}

# 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' "$*"; }

# 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 </dev/tty -e -r -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 ###
# url functions
# normalize a path from /../ /./ /
normalize_path() { # normalize_path <<< PATH
	gawk '{
	if ($0 == "" || $0 ~ /^\/\/[^\/]/) {
		return -1
	}
	split($0, path, /\//)
	for (c in path) {
		if (path[c] == "" || path[c] == ".") {
			continue
		}
		if (path[c] == "..") {
			sub(/[^\/]+$/, "", ret)
			continue
		}
		if (! ret || match(ret, /\/$/)) {
			slash = ""
		} else {
			slash = "/"
		}
		ret = ret slash path[c]
	}
	print ret
	}'
}

# split a url into the URL array
split_url() {
	gawk '{
	if (match($0, /^[A-Za-z]+:/)) {
		arr["scheme"] = substr($0, RSTART, RLENGTH)
		$0 = substr($0, RLENGTH + 1)
	}
	if (match($0, /^\/\/[^\/?#]+?/) || (match($0, /^[^\/?#]+?/) && scheme)) {
		arr["authority"] = substr($0, RSTART, RLENGTH)
		$0 = substr($0, RLENGTH + 1)
	}
	if (match($0, /^\/?[^?#]+/)) {
		arr["path"] = substr($0, RSTART, RLENGTH)
		$0 = substr($0, RLENGTH + 1)
	}
	if (match($0, /^\?[^#]+/)) {
		arr["query"] = substr($0, RSTART, RLENGTH)
		$0 = substr($0, RLENGTH + 1)
	}
	if (match($0, /^#.*/)) {
		arr["fragment"] = substr($0, RSTART, RLENGTH)
		$0 = substr($0, RLENGTH + 1)
	}
	for (part in arr) {
		printf "URL[\"%s\"]=\"%s\"\n", part, arr[part]
	}
	}'
}

# 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")
	# use SNI
	sslcmd+=(-servername "${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 -d $'\r' -r head; do
		break # wait to read the first line
	done
	code="$(gawk '{print $1}' <<<"$head")"
	meta="$(gawk '{for(i=2;i<=NF;i++)printf "%s ",$i;printf "\n"}' <<<"$head")"

	log 5 "[$code]	$meta"

	case "$code" in
	1*) # INPUT
		log 3 "Input"
		RDRS=0 # this is not a redirect
		ask "$meta" QUERY
		bollux "$URL?$QUERY"
		;;
	2*) # SUCCESS
		log 3 "Success"
		RDRS=0 # this is not a redirect
		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"
		RDRS=0 # this is not a redirect
		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"
		RDRS=0 # this is not a redirect
		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"
		RDRS=0 # this is not a redirect
		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 META < DOCUMENT
	case "$1" in
	*\;*)
		mime="$(cut -d\; -f1 <<<"$1" | trim)"
		charset="$(cut -d\; -f2 <<<"$1" | trim)"
		;;
	*) mime="$(trim <<<"$1")" ;;
	esac
	[ -z "$mime" ] && mime="text/gemini"
	if [ -z "$charset" ]; then
		charset="utf-8"
	else
		charset="${charset#*=}"
	fi

	log 5 "mime=$mime; charset=$charset"

	case "$mime" in
	text/gemini)
		lc="/tmp/bollux-currentpage.gmi" # link copy
		lfn | typeset_gemini | tee "$lc" | less -R ||
			cat "$lc" # TODO list out links on success
		# lesskey:
		# o #> Open a link (quit 1)
		# q #> Quit (quit 0)
		# cf. also prompt & filename
		;;
	text/*) lfn ;;
	*) download "$URL" ;;
	esac
}

# normalize line endings to \n (LF)
lfn() {
	gawk 'BEGIN{RS="\n\n"}{gsub(/\r\n?/,"\n");print;print ""}'
}

# typeset text
typeset_gemini() { # typeset_gemini < INPUT
	gawk '
	BEGIN { pre = 0 }
	/^###/ { sub(/^#+[[:space:]]*/, ""); 
		printf " \033[3m%s\033[0m\n", $0
	next }
	/^##/  { sub(/^#+[[:space:]]*/, ""); 
		printf " \033[1m%s\033[0m\n", $0
	next }
	/^#/   { sub(/^#+[[:space:]]*/, ""); 
		printf " \033[1;4m%s\033[0m\n", $0
	next }
	/^=>/  { 
		sub(/=>[[:space:]]*/, "")
		url = $1; desc = ""
		for (w=2;w<=NF;w++) 
			desc = desc (desc?" ":"") $w
		printf " \033[1m[%s]\033[0m \033[4m%s\033[0m \033[36m%s\033[0m\n", 
			(++ln), desc, "(" url ")"
	next }
	# /^\*/  { sub(/\*[[:space:]]*/, ""); }
	/```/  { pre = !pre; next }
	{ sub(/^/, " "); print }
	'
}

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() {
	OPTIND=0
	process_cmdline "$@"
	shift $((OPTIND - 1))

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

	log 5 "URL : $URL"

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

process_cmdline() {
	while getopts :hL: OPT; do
		case "$OPT" in
		h) bollux_usage ;;
		L) LOGL="$OPTARG" ;;
		:) die 1 "Option -$OPTARG requires an argument" ;;
		*) die 1 "Unknown option: -$OPTARG" ;;
		esac
	done
}

bollux_setup() {
	trap bollux_cleanup INT QUIT EXIT
}

bollux_cleanup() {
	exit $?
}

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

	bollux_setup

	bollux "$@"

	bollux_cleanup
fi