c2c24a89ea53c5965a5a85b27ece5a94019e7e0f
[elpher.git] / elpher.el
1 ;;; elpher.el --- A friendly gopher and gemini client  -*- lexical-binding:t -*-
2
3 ;; Copyright (C) 2021 Jens Östlund <jostlund@gmail.com>
4 ;; Copyright (C) 2021 F. Jason Park <jp@neverwas.me>
5 ;; Copyright (C) 2021 Christopher Brannon <chris@the-brannons.com>
6 ;; Copyright (C) 2021 Omar Polo <op@omarpolo.com>
7 ;; Copyright (C) 2021 Noodles! <nnoodle@chiru.no>
8 ;; Copyright (C) 2020-2021 Alex Schroeder <alex@gnu.org>
9 ;; Copyright (C) 2020 Zhiwei Chen <chenzhiwei03@kuaishou.com>
10 ;; Copyright (C) 2020 condy0919 <condy0919@gmail.com>
11 ;; Copyright (C) 2020 Alexis <flexibeast@gmail.com>
12 ;; Copyright (C) 2020 Étienne Deparis <etienne@depar.is>
13 ;; Copyright (C) 2020 Simon Nicolussi <sinic@sinic.name>
14 ;; Copyright (C) 2020 Michel Alexandre Salim <michel@michel-slm.name>
15 ;; Copyright (C) 2020 Koushk Roy <kroy@twilio.com>
16 ;; Copyright (C) 2020 Vee <vee@vnsf.xyz>
17 ;; Copyright (C) 2020 Simon South <simon@simonsouth.net>
18 ;; Copyright (C) 2019-2020 Tim Vaughan <plugd@thelambdalab.xyz>
19
20 ;; Author: Tim Vaughan <plugd@thelambdalab.xyz>
21 ;; Created: 11 April 2019
22 ;; Version: 2.11.0
23 ;; Keywords: comm gopher
24 ;; Homepage: http://thelambdalab.xyz/elpher
25 ;; Package-Requires: ((emacs "26.2"))
26
27 ;; This file is not part of GNU Emacs.
28
29 ;; This program is free software: you can redistribute it and/or modify
30 ;; it under the terms of the GNU General Public License as published by
31 ;; the Free Software Foundation, either version 3 of the License, or
32 ;; (at your option) any later version.
33
34 ;; This program is distributed in the hope that it will be useful,
35 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
36 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
37 ;; GNU General Public License for more details.
38
39 ;; You should have received a copy of the GNU General Public License
40 ;; along with this file.  If not, see <http://www.gnu.org/licenses/>.
41
42 ;;; Commentary:
43
44 ;; Elpher aims to provide a practical and friendly gopher and gemini
45 ;; client for GNU Emacs.  It supports:
46
47 ;; - intuitive keyboard and mouse-driven browsing,
48 ;; - out-of-the-box compatibility with evil-mode,
49 ;; - clickable web and gopher links *in plain text*,
50 ;; - caching of visited sites,
51 ;; - pleasant and configurable colouring of Gopher directories,
52 ;; - direct visualisation of image files,
53 ;; - a simple bookmark management system,
54 ;; - gopher connections using TLS encryption,
55 ;; - the fledgling Gemini protocol,
56 ;; - the greybeard Finger protocol.
57
58 ;; To launch Elpher, simply use 'M-x elpher'.  This will open a start
59 ;; page containing information on key bindings and suggested starting
60 ;; points for your gopher exploration.
61
62 ;; Full instructions can be found in the Elpher info manual.
63
64 ;; Elpher is under active development.  Any suggestions for
65 ;; improvements are welcome, and can be made on the official
66 ;; project page, gopher://thelambdalab.xyz/1/projects/elpher/.
67
68 ;;; Code:
69
70 (provide 'elpher)
71
72 ;;; Dependencies
73 ;;
74
75 (require 'seq)
76 (require 'pp)
77 (require 'shr)
78 (require 'url-util)
79 (require 'subr-x)
80 (require 'dns)
81 (require 'nsm)
82 (require 'gnutls)
83 (require 'socks)
84
85 ;;; ANSI colors or XTerm colors
86
87 (or (require 'xterm-color nil t)
88     (require 'ansi-color))
89
90 (defalias 'elpher-color-filter-apply
91   (if (fboundp 'xterm-color-filter)
92       (lambda (s)
93         (let ((xterm-color-render nil))
94           (xterm-color-filter s)))
95     'ansi-color-filter-apply)
96   "A function to filter out ANSI escape sequences.")
97 (defalias 'elpher-color-apply
98   (if (fboundp 'xterm-color-filter)
99       'xterm-color-filter
100     'ansi-color-apply)
101   "A function to apply ANSI escape sequences.")
102
103 ;;; Global constants
104 ;;
105
106 (defconst elpher-version "2.10.2"
107   "Current version of elpher.")
108
109 (defconst elpher-margin-width 6
110   "Width of left-hand margin used when rendering indicies.")
111
112 (defconst elpher-type-map
113   '(((gopher ?0) elpher-get-gopher-page elpher-render-text "txt" elpher-text)
114     ((gopher ?1) elpher-get-gopher-page elpher-render-index "/" elpher-index)
115     ((gopher ?4) elpher-get-gopher-page elpher-render-download "bin" elpher-binary)
116     ((gopher ?5) elpher-get-gopher-page elpher-render-download "bin" elpher-binary)
117     ((gopher ?7) elpher-get-gopher-query-page elpher-render-index "?" elpher-search)
118     ((gopher ?9) elpher-get-gopher-page elpher-render-download "bin" elpher-binary)
119     ((gopher ?g) elpher-get-gopher-page elpher-render-image "img" elpher-image)
120     ((gopher ?p) elpher-get-gopher-page elpher-render-image "img" elpher-image)
121     ((gopher ?I) elpher-get-gopher-page elpher-render-image "img" elpher-image)
122     ((gopher ?d) elpher-get-gopher-page elpher-render-download "doc" elpher-binary)
123     ((gopher ?P) elpher-get-gopher-page elpher-render-download "doc" elpher-binary)
124     ((gopher ?s) elpher-get-gopher-page elpher-render-download "snd" elpher-binary)
125     ((gopher ?h) elpher-get-gopher-page elpher-render-html "htm" elpher-html)
126     (gemini elpher-get-gemini-page elpher-render-gemini "gem" elpher-gemini)
127     (finger elpher-get-finger-page elpher-render-text "txt" elpher-text)
128     (telnet elpher-get-telnet-page nil "tel" elpher-telnet)
129     (other-url elpher-get-other-url-page nil "url" elpher-other-url)
130     ((special bookmarks) elpher-get-bookmarks-page nil "/" elpher-index)
131     ((special start) elpher-get-start-page nil))
132   "Association list from types to getters, renderers, margin codes and index faces.")
133
134
135 ;;; Internal variables
136 ;;
137
138 (defvar elpher--gemini-page-links '()
139   "Internal variable containing list of links on page.")
140
141 (defvar elpher--gemini-page-links-cache (make-hash-table :test 'equal)
142   "Internal variable containing hash of addresses and page links.")
143
144 ;;; Customization group
145 ;;
146
147 (defgroup elpher nil
148   "A gopher and gemini client."
149   :group 'applications)
150
151 ;; General appearance and customizations
152
153 (defcustom elpher-open-urls-with-eww nil
154   "If non-nil, open URL selectors using eww.
155 Otherwise, use the system browser via the BROWSE-URL function."
156   :type '(boolean))
157
158 (defcustom elpher-use-header t
159   "If non-nil, display current page information in buffer header."
160   :type '(boolean))
161
162 (defcustom elpher-auto-disengage-TLS nil
163   "If non-nil, automatically disengage TLS following an unsuccessful connection.
164 While enabling this may seem convenient, it is also potentially dangerous as it
165 allows switching from an encrypted channel back to plain text without user input."
166   :type '(boolean))
167
168 (defcustom elpher-connection-timeout 5
169   "Specifies the number of seconds to wait for a network connection to time out."
170   :type '(integer))
171
172 (defcustom elpher-filter-ansi-from-text nil
173   "If non-nil, filter ANSI escape sequences from text.
174 The default behaviour is to use the ansi-color package to interpret these
175 sequences."
176   :type '(boolean))
177
178 (defcustom elpher-certificate-directory
179   (file-name-as-directory (locate-user-emacs-file "elpher-certificates"))
180   "Specify the name of the directory where client certificates will be stored.
181 These certificates may be used for establishing authenticated TLS connections."
182   :type '(directory))
183
184 (defcustom elpher-openssl-command "openssl"
185   "The command used to launch openssl when generating TLS client certificates."
186   :type '(file))
187
188 (defcustom elpher-default-url-type "gopher"
189   "Default URL type to assume if not explicitly given."
190   :type '(choice (const "gopher")
191                  (const "gemini")))
192
193 (defcustom elpher-gemini-TLS-cert-checks nil
194   "If non-nil, verify gemini server TLS certs using the default security level.
195 Otherwise, certificate verification is disabled.
196
197 This defaults to off because it is standard practice for Gemini servers
198 to use self-signed certificates, meaning that most servers provide what
199 EMACS considers to be an invalid certificate."
200   :type '(boolean))
201
202 (defcustom elpher-gemini-max-fill-width 80
203   "Specify the maximum default width (in columns) of text/gemini documents.
204 The actual width used is the minimum of this value and the window width at
205 the time when the text is rendered."
206   :type '(integer))
207
208 (defcustom elpher-gemini-link-string "→ "
209   "Specify the string used to indicate links when rendering gemini maps.
210 May be empty."
211   :type '(string))
212
213 (defcustom elpher-gemini-bullet-string "•"
214   "Specify the string used for bullets when rendering gemini maps."
215   :type '(string))
216
217 (defcustom elpher-bookmarks-file (locate-user-emacs-file "elpher-bookmarks")
218   "Specify the name of the file where elpher bookmarks will be saved."
219   :type '(file))
220
221 (defcustom elpher-ipv4-always nil
222   "If non-nil, elpher will always use IPv4 to establish network connections.
223 This can be useful when browsing from a computer that supports IPv6, because
224 some servers which do not support IPv6 can take a long time to time-out."
225   :type '(boolean))
226
227 (defcustom elpher-socks-always nil
228   "If non-nil, elpher will establish network connections over a SOCKS proxy.
229 Otherwise, the SOCKS proxy is only used for connections to onion services."
230   :type '(boolean))
231
232 (defcustom elpher-gemini-number-links nil
233   "If non-nil, number links in gemini pages when rendering.
234 Links can be accessed by pressing `v' ('visit') followed by the link number."
235   :type '(boolean))
236
237 ;; Face customizations
238
239 (defgroup elpher-faces nil
240   "Elpher face customizations."
241   :group 'elpher)
242
243 (defface elpher-index
244   '((t :inherit font-lock-keyword-face))
245   "Face used for directory type directory records.")
246
247 (defface elpher-text
248   '((t :inherit bold))
249   "Face used for text type directory records.")
250
251 (defface elpher-info
252   '((t :inherit default))
253   "Face used for info type directory records.")
254
255 (defface elpher-image
256   '((t :inherit font-lock-string-face))
257   "Face used for image type directory records.")
258
259 (defface elpher-search
260   '((t :inherit warning))
261   "Face used for search type directory records.")
262
263 (defface elpher-html
264   '((t :inherit font-lock-comment-face))
265   "Face used for html type directory records.")
266
267 (defface elpher-gemini
268   '((t :inherit font-lock-constant-face))
269   "Face used for Gemini type directory records.")
270
271 (defface elpher-other-url
272   '((t :inherit font-lock-comment-face))
273   "Face used for other URL type links records.")
274
275 (defface elpher-telnet
276   '((t :inherit font-lock-function-name-face))
277   "Face used for telnet type directory records.")
278
279 (defface elpher-binary
280   '((t :inherit font-lock-doc-face))
281   "Face used for binary type directory records.")
282
283 (defface elpher-unknown
284   '((t :inherit error))
285   "Face used for directory records with unknown/unsupported types.")
286
287 (defface elpher-margin-key
288   '((t :inherit bold))
289   "Face used for directory margin key.")
290
291 (defface elpher-margin-brackets
292   '((t :inherit shadow))
293   "Face used for brackets around directory margin key.")
294
295 (defface elpher-gemini-heading1
296   '((t :inherit bold :height 1.8))
297   "Face used for gemini heading level 1.")
298
299 (defface elpher-gemini-heading2
300   '((t :inherit bold :height 1.5))
301   "Face used for gemini heading level 2.")
302
303 (defface elpher-gemini-heading3
304   '((t :inherit bold :height 1.2))
305   "Face used for gemini heading level 3.")
306
307 (defface elpher-gemini-preformatted
308   '((t :inherit fixed-pitch))
309   "Face used for pre-formatted gemini text blocks.")
310
311 (defface elpher-gemini-quoted
312   '((t :inherit font-lock-doc-face))
313   "Face used for gemini quoted texts.")
314
315 ;;; Model
316 ;;
317
318 ;; Address
319
320 ;; An elpher "address" object is either a url object or a symbol.
321 ;; Symbol addresses are "special", corresponding to pages generated
322 ;; dynamically for and by elpher.  All others represent pages which
323 ;; rely on content retrieved over the network.
324
325 (defun elpher-address-from-url (url-string)
326   "Create a ADDRESS object corresponding to the given URL-STRING."
327   (let ((data (match-data))) ; Prevent parsing clobbering match data
328     (unwind-protect
329         (let ((url (url-generic-parse-url url-string)))
330           (unless (and (not (url-fullness url)) (url-type url))
331             (setf (url-fullness url) t)
332             (setf (url-filename url)
333                   (url-unhex-string (url-filename url)))
334             (unless (url-type url)
335               (setf (url-type url) elpher-default-url-type))
336             (unless (url-host url)
337               (let ((p (split-string (url-filename url) "/" nil nil)))
338                 (setf (url-host url) (car p))
339                 (setf (url-filename url)
340                       (if (cdr p)
341                           (concat "/" (mapconcat #'identity (cdr p) "/"))
342                         ""))))
343             (when (or (equal "gopher" (url-type url))
344                       (equal "gophers" (url-type url)))
345               ;; Gopher defaults
346               (when (or (equal (url-filename url) "")
347                         (equal (url-filename url) "/"))
348                 (setf (url-filename url) "/1")))
349             (when (equal "gemini" (url-type url))
350               ;; Gemini defaults
351               (if (equal (url-filename url) "")
352                   (setf (url-filename url) "/"))))
353           (elpher-remove-redundant-ports url))
354       (set-match-data data))))
355
356 (defun elpher-remove-redundant-ports (address)
357   "Remove redundant port specifiers from ADDRESS.
358 Here 'redundant' means that the specified port matches the default
359 for that protocol, eg 70 for gopher."
360   (if (and (not (elpher-address-special-p address))
361            (eq (url-portspec address) ; (url-port) is too slow!
362                (pcase (url-type address)
363                  ("gemini" 1965)
364                  ((or "gopher" "gophers") 70)
365                  ("finger" 79)
366                  (_ -1))))
367       (setf (url-portspec address) nil))
368   address)
369
370 (defun elpher-make-gopher-address (type selector host port &optional tls)
371   "Create an ADDRESS object using gopher directory record attributes.
372 The basic attributes include: TYPE, SELECTOR, HOST and PORT.
373 If the optional attribute TLS is non-nil, the address will be marked as
374 requiring gopher-over-TLS."
375   (cond
376    ((equal type ?i) nil)
377    ((and (equal type ?h)
378          (string-prefix-p "URL:" selector))
379     (elpher-address-from-url (elt (split-string selector "URL:") 1)))
380    ((equal type ?8)
381     (elpher-address-from-url
382      (concat "telnet"
383              "://" host
384              ":" (number-to-string port))))
385    (t
386     (elpher-address-from-url
387      (concat "gopher" (if tls "s" "")
388              "://" host
389              ":" (number-to-string port)
390              "/" (string type)
391              selector)))))
392
393 (defun elpher-make-special-address (type)
394   "Create an ADDRESS object corresponding to the given special address symbol TYPE."
395   type)
396
397 (defun elpher-address-to-url (address)
398   "Get string representation of ADDRESS, or nil if ADDRESS is special."
399   (if (elpher-address-special-p address)
400       nil
401     (url-encode-url (url-recreate-url address))))
402
403 (defun elpher-address-type (address)
404   "Retrieve type of ADDRESS object.
405 This is used to determine how to retrieve and render the document the
406 address refers to, via the table `elpher-type-map'."
407   (if (symbolp address)
408       (list 'special address)
409     (let ((protocol (url-type address)))
410       (cond ((or (equal protocol "gopher")
411                  (equal protocol "gophers"))
412              (list 'gopher
413                    (if (member (url-filename address) '("" "/"))
414                        ?1
415                      (string-to-char (substring (url-filename address) 1)))))
416             ((equal protocol "gemini")
417              'gemini)
418             ((equal protocol "telnet")
419              'telnet)
420             ((equal protocol "finger")
421              'finger)
422             (t 'other-url)))))
423
424 (defun elpher-address-protocol (address)
425   "Retrieve the transport protocol for ADDRESS.  This is nil for special addresses."
426   (if (symbolp address)
427       nil
428     (url-type address)))
429
430 (defun elpher-address-filename (address)
431   "Retrieve the filename component of ADDRESS.
432 For gopher addresses this is a combination of the selector type and selector."
433   (if (symbolp address)
434       nil
435     (url-filename address)))
436
437 (defun elpher-address-host (address)
438   "Retrieve host from ADDRESS object."
439   (url-host address))
440
441 (defun elpher-address-user (address)
442   "Retrieve user from ADDRESS object."
443   (url-user address))
444
445 (defun elpher-address-port (address)
446   "Retrieve port from ADDRESS object.
447 If no address is defined, returns 0.  (This is for compatibility with the URL library.)"
448   (if (symbolp address)
449       0
450     (url-port address)))
451
452 (defun elpher-address-special-p (address)
453   "Return non-nil if ADDRESS object is special (e.g. start page, bookmarks page)."
454   (symbolp address))
455
456 (defun elpher-address-gopher-p (address)
457   "Return non-nill if ADDRESS object is a gopher address."
458   (and (not (elpher-address-special-p address))
459        (member (elpher-address-protocol address) '("gopher gophers"))))
460
461 (defun elpher-gopher-address-selector (address)
462   "Retrieve gopher selector from ADDRESS object."
463   (if (member (url-filename address) '("" "/"))
464       ""
465     (url-unhex-string (substring (url-filename address) 2))))
466
467
468 ;; Cache
469
470 (defvar elpher-content-cache (make-hash-table :test 'equal))
471 (defvar elpher-pos-cache (make-hash-table :test 'equal))
472
473 (defun elpher-get-cached-content (address)
474   "Retrieve the cached content for ADDRESS, or nil if none exists."
475   (gethash address elpher-content-cache))
476
477 (defun elpher-cache-content (address content)
478   "Set the content cache for ADDRESS to CONTENT."
479   (puthash address content elpher-content-cache))
480
481 (defun elpher-get-cached-pos (address)
482   "Retrieve the cached cursor position for ADDRESS, or nil if none exists."
483   (gethash address elpher-pos-cache))
484
485 (defun elpher-cache-pos (address pos)
486   "Set the cursor position cache for ADDRESS to POS."
487   (puthash address pos elpher-pos-cache))
488
489
490 ;; Page
491
492 (defun elpher-make-page (display-string address)
493   "Create a page with DISPLAY-STRING and ADDRESS."
494   (list display-string address))
495
496 (defun elpher-page-display-string (page)
497   "Retrieve the display string corresponding to PAGE."
498   (elt page 0))
499
500 (defun elpher-page-address (page)
501   "Retrieve the address corresponding to PAGE."
502   (elt page 1))
503
504 (defun elpher-page-set-address (page new-address)
505   "Set the address corresponding to PAGE to NEW-ADDRESS."
506   (setcar (cdr page) new-address))
507
508 (defvar elpher-current-page nil)        ; buffer local
509 (defvar elpher-history nil)             ; buffer local
510
511 (defun elpher-visit-page (page &optional renderer no-history)
512   "Visit PAGE using its own renderer or RENDERER, if non-nil.
513 Additionally, push PAGE onto the stack of previously-visited pages,
514 unless NO-HISTORY is non-nil."
515   (elpher-save-pos)
516   (elpher-process-cleanup)
517   (unless (or no-history
518               (equal (elpher-page-address elpher-current-page)
519                      (elpher-page-address page)))
520     (push elpher-current-page elpher-history))
521   (setq-local elpher-current-page page)
522   (let* ((address (elpher-page-address page))
523          (type (elpher-address-type address))
524          (type-record (cdr (assoc type elpher-type-map)))
525          (page-links nil))
526     (if type-record
527         (progn
528           (funcall (car type-record)
529                    (if renderer
530                        renderer
531                      (cadr type-record)))
532           (setq page-links (gethash address elpher--gemini-page-links-cache))
533           (if page-links
534               (setq elpher--gemini-page-links page-links)))
535       (elpher-visit-previous-page)
536       (pcase type
537         (`(gopher ,type-char)
538          (error "Unsupported gopher selector type '%c' for '%s'"
539                 type-char (elpher-address-to-url address)))
540         (other
541          (error "Unsupported address type '%S' for '%s'"
542                 other (elpher-address-to-url address)))))))
543
544 (defun elpher-visit-previous-page ()
545   "Visit the previous page in the history."
546   (let ((previous-page (pop elpher-history)))
547     (if previous-page
548         (elpher-visit-page previous-page nil t)
549       (error "No previous page"))))
550
551 (defun elpher-reload-current-page ()
552   "Reload the current page, discarding any existing cached content."
553   (elpher-cache-content (elpher-page-address elpher-current-page) nil)
554   (elpher-visit-page elpher-current-page))
555
556 (defun elpher-save-pos ()
557   "Save the current position of point to the current page."
558   (when elpher-current-page
559     (elpher-cache-pos (elpher-page-address elpher-current-page) (point))))
560
561 (defun elpher-restore-pos ()
562   "Restore the position of point to that cached in the current page."
563   (let ((pos (elpher-get-cached-pos (elpher-page-address elpher-current-page))))
564     (if pos
565         (goto-char pos)
566       (goto-char (point-min)))))
567
568
569 ;;; Buffer preparation
570 ;;
571
572 (defvar elpher-buffer-name "*elpher*"
573   "The default name of the Elpher buffer.")
574
575 (defun elpher-update-header ()
576   "If `elpher-use-header' is true, display current page info in window header."
577   (if elpher-use-header
578       (let* ((display-string (elpher-page-display-string elpher-current-page))
579              (address (elpher-page-address elpher-current-page))
580              (tls-string (if (and (not (elpher-address-special-p address))
581                                   (member (elpher-address-protocol address)
582                                           '("gophers" "gemini")))
583                              " [TLS encryption]"
584                            ""))
585              (header (concat display-string
586                              (propertize tls-string 'face 'bold))))
587         (setq header-line-format header))))
588
589 (defmacro elpher-with-clean-buffer (&rest args)
590   "Evaluate ARGS with a clean *elpher* buffer as current."
591   `(with-current-buffer elpher-buffer-name
592      (unless (eq major-mode 'elpher-mode)
593        ;; avoid resetting buffer-local variables
594        (elpher-mode))
595      (let ((inhibit-read-only t))
596        (setq-local network-security-level
597                    (default-value 'network-security-level))
598        (erase-buffer)
599        (elpher-update-header)
600        ,@args)))
601
602 (defun elpher-buffer-message (string &optional line)
603   "Replace first line in elpher buffer with STRING.
604 If LINE is non-nil, replace that line instead."
605   (with-current-buffer elpher-buffer-name
606     (let ((inhibit-read-only t))
607       (goto-char (point-min))
608       (if line
609           (forward-line line))
610       (let ((data (match-data)))
611         (unwind-protect
612             (progn
613               (re-search-forward "^.*$")
614               (replace-match string))
615           (set-match-data data))))))
616
617
618 ;;; Text Processing
619 ;;
620
621 (defvar elpher-user-coding-system nil
622   "User-specified coding system to use for decoding text responses.")
623
624 (defun elpher-decode (string)
625   "Decode STRING using autodetected or user-specified coding system."
626   (decode-coding-string string
627                         (if elpher-user-coding-system
628                             elpher-user-coding-system
629                           (detect-coding-string string t))))
630
631 (defun elpher-preprocess-text-response (string)
632   "Preprocess text selector response contained in STRING.
633 This involes decoding the character representation, and clearing
634 away CRs and any terminating period."
635   (elpher-decode (replace-regexp-in-string "\n\.\n$" "\n"
636                                            (replace-regexp-in-string "\r" "" string))))
637
638
639 ;;; Network error reporting
640 ;;
641
642 (defun elpher-network-error (address error)
643   "Display ERROR message following unsuccessful negotiation with ADDRESS.
644 ERROR can be either an error object or a string."
645   (elpher-with-clean-buffer
646    (insert (propertize "\n---- ERROR -----\n\n" 'face 'error)
647            "When attempting to retrieve " (elpher-address-to-url address) ":\n"
648            (if (stringp error) error (error-message-string error)) "\n"
649            (propertize "\n----------------\n\n" 'face 'error)
650            "Press 'u' to return to the previous page.")))
651
652
653 ;;; General network communication
654 ;;
655
656 (defvar elpher-network-timer nil
657   "Timer used for network connections.")
658
659 (defvar elpher-use-tls nil
660   "If non-nil, use TLS to communicate with gopher servers.")
661
662 (defvar elpher-client-certificate nil
663   "If non-nil, contains client certificate details to use for TLS connections.")
664
665 (defun elpher-process-cleanup ()
666   "Immediately shut down any extant elpher process and timers."
667   (let ((p (get-process "elpher-process")))
668     (if p (delete-process p)))
669   (if (timerp elpher-network-timer)
670       (cancel-timer elpher-network-timer)))
671
672 (defun elpher-get-host-response (address default-port query-string response-processor
673                                          &optional use-tls force-ipv4)
674   "Generic function for retrieving data from ADDRESS.
675
676 When ADDRESS lacks a specific port, DEFAULT-PORT is used instead.
677 QUERY-STRING is a string sent to the host specified by ADDRESS to
678 illicet a response.  This response is passed as an argument to the
679 function RESPONSE-PROCESSOR.
680
681 If non-nil, USE-TLS specifies that the connection is to be made over
682 TLS.  If set to gemini, the certificate verification will be disabled
683 unless `elpher-gemini-TLS-cert-checks' is non-nil.
684
685 If non-nil, FORCE-IPV4 causes the network connection to be made over
686 ipv4 only.  (The default behaviour when this is not set depends on
687 the host operating system and the local network capabilities."
688   (if (and use-tls (not (gnutls-available-p)))
689       (error "Use of TLS requires Emacs to be compiled with GNU TLS support")
690     (unless (< (elpher-address-port address) 65536)
691       (error "Cannot establish network connection: port number > 65536"))
692     (when (and (eq use-tls 'gemini) (not elpher-gemini-TLS-cert-checks))
693       (setq-local network-security-level 'low)
694       (setq-local gnutls-verify-error nil))
695     (condition-case nil
696         (let* ((kill-buffer-query-functions nil)
697                (port (elpher-address-port address))
698                (service (if (> port 0) port default-port))
699                (host (elpher-address-host address))
700                (socks (or elpher-socks-always (string-suffix-p ".onion" host)))
701                (response-string-parts nil)
702                (bytes-received 0)
703                (hkbytes-received 0)
704                (timer (run-at-time elpher-connection-timeout nil
705                                    (lambda ()
706                                      (elpher-process-cleanup)
707                                      (cond
708                                         ; Try again with IPv4
709                                       ((not (or force-ipv4 socks))
710                                        (message "Connection timed out.  Retrying with IPv4.")
711                                        (elpher-get-host-response address default-port
712                                                                  query-string
713                                                                  response-processor
714                                                                  use-tls t))
715                                       ((and use-tls
716                                             (not (eq use-tls 'gemini))
717                                             (or elpher-auto-disengage-TLS
718                                                 (y-or-n-p
719                                                  "TLS connetion failed.  Disable TLS mode and retry? ")))
720                                        (setq elpher-use-tls nil)
721                                        (elpher-get-host-response address default-port
722                                                                  query-string
723                                                                  response-processor
724                                                                  nil force-ipv4))
725                                       (t
726                                        (elpher-network-error address "Connection time-out."))))))
727                (gnutls-params (list :type 'gnutls-x509pki :hostname host
728                                     :keylist (elpher-get-current-keylist address)))
729                (proc (if socks (socks-open-network-stream "elpher-process" nil host service)
730                        (make-network-process :name "elpher-process"
731                                              :host host
732                                              :family (and force-ipv4 'ipv4)
733                                              :service service
734                                              :buffer nil
735                                              :nowait t
736                                              :tls-parameters
737                                              (and use-tls
738                                                   (cons 'gnutls-x509pki
739                                                         (apply #'gnutls-boot-parameters
740                                                                gnutls-params)))))))
741           (setq elpher-network-timer timer)
742           (set-process-coding-system proc 'binary 'binary)
743           (set-process-query-on-exit-flag proc nil)
744           (elpher-buffer-message (concat "Connecting to " host "..."
745                                          " (press 'u' to abort)"))
746           (set-process-filter proc
747                               (lambda (_proc string)
748                                 (when timer
749                                   (cancel-timer timer)
750                                   (setq timer nil))
751                                 (setq bytes-received (+ bytes-received (length string)))
752                                 (let ((new-hkbytes-received (/ bytes-received 102400)))
753                                   (when (> new-hkbytes-received hkbytes-received)
754                                     (setq hkbytes-received new-hkbytes-received)
755                                     (elpher-buffer-message
756                                         (concat "("
757                                                 (number-to-string (/ hkbytes-received 10.0))
758                                                 " MB read)")
759                                         1)))
760                                 (setq response-string-parts
761                                       (cons string response-string-parts))))
762           (set-process-sentinel proc
763                                 (lambda (proc event)
764                                   (when timer
765                                     (cancel-timer timer))
766                                   (condition-case the-error
767                                       (cond
768                                        ((string-prefix-p "open" event)    ; request URL
769                                         (elpher-buffer-message
770                                          (concat "Connected to " host ". Receiving data..."
771                                                  " (press 'u' to abort)"))
772                                         (let ((inhibit-eol-conversion t))
773                                           (process-send-string proc query-string)))
774                                        ((string-prefix-p "deleted" event)) ; do nothing
775                                        ((and (not response-string-parts)
776                                              (not (or elpher-ipv4-always force-ipv4 socks)))
777                                         ; Try again with IPv4
778                                         (message "Connection failed. Retrying with IPv4.")
779                                         (elpher-get-host-response address default-port
780                                                                   query-string
781                                                                   response-processor
782                                                                   use-tls t))
783                                        (response-string-parts
784                                         (elpher-with-clean-buffer
785                                          (insert "Data received.  Rendering..."))
786                                         (funcall response-processor
787                                                  (apply #'concat (reverse response-string-parts)))
788                                         (elpher-restore-pos))
789                                        (t
790                                         (error "No response from server")))
791                                     (error
792                                      (elpher-network-error address the-error)))))
793           (when socks
794             (if use-tls (apply #'gnutls-negotiate :process proc gnutls-params))
795             (funcall (process-sentinel proc) proc "open\n")))
796       (error
797        (error "Error initiating connection to server")))))
798
799
800 ;;; Client-side TLS Certificate Management
801 ;;
802
803 (defun elpher-generate-certificate (common-name key-file cert-file &optional temporary)
804   "Generate a key and a self-signed client TLS certificate using openssl.
805
806 The Common Name field of the certificate is set to COMMON-NAME.  The
807 arguments KEY-FILE and CERT-FILE should contain the absolute paths of
808 the key and certificate files to write.
809
810 If TEMPORARY is non-nil, the certificate will be given an exporation
811 period of one day, and the key and certificate files will be deleted
812 when the certificate is no longer needed for the current session.
813
814 Otherwise, the certificate will be given a 100 year expiration period
815 and the files will not be deleted.
816
817 The function returns a list containing the current host name, the
818 temporary flag, and the key and cert file names in the form required
819 by `gnutls-boot-parameters`."
820   (let ((exp-key-file (expand-file-name key-file))
821         (exp-cert-file (expand-file-name cert-file)))
822     (condition-case nil
823         (progn
824           (call-process elpher-openssl-command nil nil nil
825                         "req" "-x509" "-newkey" "rsa:2048"
826                         "-days" (if temporary "1" "36500")
827                         "-nodes"
828                         "-subj" (concat "/CN=" common-name)
829                         "-keyout" exp-key-file
830                         "-out" exp-cert-file)
831           (list (elpher-address-host (elpher-page-address elpher-current-page))
832                 temporary exp-key-file exp-cert-file))
833       (error
834        (message "Check that openssl is installed, or customize `elpher-openssl-command`.")
835        (error "Program 'openssl', required for certificate generation, not found")))))
836
837 (defun elpher-generate-throwaway-certificate ()
838   "Generate and return details of a throwaway certificate.
839 The key and certificate files will be deleted when they are no
840 longer needed for this session."
841   (let* ((file-base (make-temp-name "elpher"))
842          (key-file (concat temporary-file-directory file-base ".key"))
843          (cert-file (concat temporary-file-directory file-base ".crt")))
844     (elpher-generate-certificate file-base key-file cert-file t)))
845
846 (defun elpher-generate-persistent-certificate (file-base common-name)
847   "Generate and return details of a persistent certificate.
848 The argument FILE-BASE is used as the base for the key and certificate
849 files, while COMMON-NAME specifies the common name field of the
850 certificate.
851
852 The key and certificate files are written to in `elpher-certificate-directory'."
853   (let* ((key-file (concat elpher-certificate-directory file-base ".key"))
854          (cert-file (concat elpher-certificate-directory file-base ".crt")))
855     (elpher-generate-certificate common-name key-file cert-file)))
856
857 (defun elpher-get-existing-certificate (file-base)
858   "Return a certificate object corresponding to an existing certificate.
859 It is assumed that the key files FILE-BASE.key and FILE-BASE.crt exist in
860 the directory `elpher-certificate-directory'."
861   (let* ((key-file (concat elpher-certificate-directory file-base ".key"))
862          (cert-file (concat elpher-certificate-directory file-base ".crt")))
863     (list (elpher-address-host (elpher-page-address elpher-current-page))
864           nil
865           (expand-file-name key-file)
866           (expand-file-name cert-file))))
867
868 (defun elpher-install-and-use-existing-certificate (key-file-src cert-file-src file-base)
869   "Install a key+certificate file pair in `elpher-certificate-directory'.
870 The strings KEY-FILE-SRC and CERT-FILE-SRC are the existing key and
871 certificate files to install.  The argument FILE-BASE is used as the
872 base for the installed key and certificate files."
873   (let* ((key-file (concat elpher-certificate-directory file-base ".key"))
874          (cert-file (concat elpher-certificate-directory file-base ".crt")))
875     (if (or (file-exists-p key-file)
876             (file-exists-p cert-file))
877         (error "A certificate with base name %s is already installed" file-base))
878     (copy-file key-file-src key-file)
879     (copy-file cert-file-src cert-file)
880     (list (elpher-address-host (elpher-page-address elpher-current-page))
881           nil
882           (expand-file-name key-file)
883           (expand-file-name cert-file))))
884
885 (defun elpher-list-existing-certificates ()
886   "Return a list of the persistent certificates in `elpher-certificate-directory'."
887   (unless (file-directory-p elpher-certificate-directory)
888     (make-directory elpher-certificate-directory))
889   (mapcar
890    (lambda (file)
891      (file-name-sans-extension file))
892    (directory-files elpher-certificate-directory nil "\\.key$")))
893
894 (defun elpher-forget-current-certificate ()
895   "Causes any current certificate to be forgotten.)
896 In the case of throwaway certificates, the key and certificate files
897 are also deleted."
898   (interactive)
899   (when elpher-client-certificate
900     (unless (and (called-interactively-p 'any)
901                  (not (y-or-n-p (concat "Really forget client certificate? "
902                                         "(Throwaway certificates will be deleted.)"))))
903       (when (cadr elpher-client-certificate)
904         (delete-file (elt elpher-client-certificate 2))
905         (delete-file (elt elpher-client-certificate 3)))
906       (setq elpher-client-certificate nil)
907       (if (called-interactively-p 'any)
908           (message "Client certificate forgotten.")))))
909
910 (defun elpher-get-current-keylist (address)
911   "Retrieve the `gnutls-boot-parameters'-compatable keylist.
912
913 This is obtained from the client certificate described by
914 `elpher-current-certificate', if one is available and the host for
915 that certificate matches the host in ADDRESS.
916
917 If `elpher-current-certificate' is non-nil, and its host name doesn't
918 match that of ADDRESS, the certificate is forgotten."
919   (if elpher-client-certificate
920       (if (string= (car elpher-client-certificate)
921                    (elpher-address-host address))
922           (list (cddr elpher-client-certificate))
923         (elpher-forget-current-certificate)
924         (message "Disabling client certificate for new host")
925         nil)
926     nil))
927
928
929 ;;; Gopher selector retrieval
930 ;;
931
932 (defun elpher-get-gopher-response (address renderer)
933   "Get response string from gopher server at ADDRESS and render using RENDERER."
934   (elpher-get-host-response address 70
935                             (concat (elpher-gopher-address-selector address) "\r\n")
936                             renderer
937                             (or (string= (elpher-address-protocol address) "gophers")
938                                 elpher-use-tls)))
939
940 (defun elpher-get-gopher-page (renderer)
941   "Getter function for gopher pages.
942 The RENDERER procedure is used to display the contents of the page
943 once they are retrieved from the gopher server."
944   (let* ((address (elpher-page-address elpher-current-page))
945          (content (elpher-get-cached-content address)))
946     (if (and content (funcall renderer nil))
947         (elpher-with-clean-buffer
948          (insert content)
949          (elpher-restore-pos))
950       (elpher-with-clean-buffer
951        (insert "LOADING... (use 'u' to cancel)\n"))
952       (condition-case the-error
953           (elpher-get-gopher-response address renderer)
954         (error
955          (elpher-network-error address the-error))))))
956
957 ;; Index rendering
958
959 (defun elpher-insert-index (string)
960   "Insert the index corresponding to STRING into the current buffer."
961   ;; Should be able to split directly on CRLF, but some non-conformant
962   ;; LF-only servers sadly exist, hence the following.
963   (let ((str-processed (elpher-preprocess-text-response string)))
964     (dolist (line (split-string str-processed "\n"))
965       (ignore-errors
966         (unless (= (length line) 0)
967           (let* ((type (elt line 0))
968                  (fields (split-string (substring line 1) "\t"))
969                  (display-string (elt fields 0))
970                  (selector (elt fields 1))
971                  (host (elt fields 2))
972                  (port (if (elt fields 3)
973                            (string-to-number (elt fields 3))
974                          nil))
975                  (address (elpher-make-gopher-address type selector host port)))
976             (elpher-insert-index-record display-string address)))))))
977
978 (defun elpher-insert-margin (&optional type-name)
979   "Insert index margin, optionally containing the TYPE-NAME, into the current buffer."
980   (if type-name
981       (progn
982         (insert (format (concat "%" (number-to-string (- elpher-margin-width 1)) "s")
983                         (concat
984                          (propertize "[" 'face 'elpher-margin-brackets)
985                          (propertize type-name 'face 'elpher-margin-key)
986                          (propertize "]" 'face 'elpher-margin-brackets))))
987         (insert " "))
988     (insert (make-string elpher-margin-width ?\s))))
989
990 (defun elpher--page-button-help (_window buffer pos)
991   "Function called by Emacs to generate mouse-over text.
992 The arguments specify the BUFFER and the POS within the buffer of the item
993 for which help is required.  The function returns the help to be
994 displayed.  The _WINDOW argument is currently unused."
995   (with-current-buffer buffer
996     (let ((button (button-at pos)))
997       (when button
998         (let* ((page (button-get button 'elpher-page))
999                (address (elpher-page-address page)))
1000           (format "mouse-1, RET: open '%s'" (if (elpher-address-special-p address)
1001                                                 address
1002                                               (elpher-address-to-url address))))))))
1003
1004 (defun elpher-insert-index-record (display-string &optional address)
1005   "Function to insert an index record into the current buffer.
1006 The contents of the record are dictated by DISPLAY-STRING and ADDRESS.
1007 If ADDRESS is not supplied or nil the record is rendered as an
1008 'information' line."
1009   (let* ((type (if address (elpher-address-type address) nil))
1010          (type-map-entry (cdr (assoc type elpher-type-map))))
1011     (if type-map-entry
1012         (let* ((margin-code (elt type-map-entry 2))
1013                (face (elt type-map-entry 3))
1014                (filtered-display-string (elpher-color-filter-apply display-string))
1015                (page (elpher-make-page filtered-display-string address)))
1016           (elpher-insert-margin margin-code)
1017           (insert-text-button filtered-display-string
1018                               'face face
1019                               'elpher-page page
1020                               'action #'elpher-click-link
1021                               'follow-link t
1022                               'help-echo #'elpher--page-button-help))
1023       (pcase type
1024         ('nil ;; Information
1025          (elpher-insert-margin)
1026          (let ((propertized-display-string
1027                 (propertize display-string 'face 'elpher-info)))
1028            (insert (elpher-process-text-for-display propertized-display-string))))
1029         (`(gopher ,selector-type) ;; Unknown
1030          (elpher-insert-margin (concat (char-to-string selector-type) "?"))
1031          (insert (propertize display-string
1032                              'face 'elpher-unknown)))))
1033     (insert "\n")))
1034
1035 (defun elpher-click-link (button)
1036   "Function called when the gopher link BUTTON is activated (via mouse or keypress)."
1037   (let ((page (button-get button 'elpher-page)))
1038     (elpher-visit-page page)))
1039
1040 (defun elpher-render-index (data &optional _mime-type-string)
1041   "Render DATA as an index.  MIME-TYPE-STRING is unused."
1042   (elpher-with-clean-buffer
1043    (if (not data)
1044        t
1045      (elpher-insert-index data)
1046      (elpher-cache-content (elpher-page-address elpher-current-page)
1047                            (buffer-string)))))
1048
1049 ;; Text rendering
1050
1051 (defconst elpher-url-regex
1052   "\\([a-zA-Z]+\\)://\\([a-zA-Z0-9.\-]*[a-zA-Z0-9\-]\\|\[[a-zA-Z0-9:]+\]\\)\\(:[0-9]+\\)?\\(/\\([0-9a-zA-Z\-_~?/@|:.%#=&]*[0-9a-zA-Z\-_~?/@|#]\\)?\\)?"
1053   "Regexp used to locate and buttinofy URLs in text files loaded by elpher.")
1054
1055 (defun elpher-buttonify-urls (string)
1056   "Turn substrings which look like urls in STRING into clickable buttons."
1057   (with-temp-buffer
1058     (insert string)
1059     (goto-char (point-min))
1060     (while (re-search-forward elpher-url-regex nil t)
1061       (let ((page (elpher-make-page (substring-no-properties (match-string 0))
1062                                     (elpher-address-from-url (match-string 0)))))
1063           (make-text-button (match-beginning 0)
1064                             (match-end 0)
1065                             'elpher-page  page
1066                             'action #'elpher-click-link
1067                             'follow-link t
1068                             'help-echo #'elpher--page-button-help
1069                             'face 'button)))
1070     (buffer-string)))
1071
1072 (defconst elpher-ansi-regex "\x1b\\[[^m]*m"
1073   "Wildly incomplete regexp used to strip out some troublesome ANSI escape sequences.")
1074
1075 (defun elpher-process-text-for-display (string)
1076   "Perform any desired processing of STRING prior to display as text.
1077 Currently includes buttonifying URLs and processing ANSI escape codes."
1078   (elpher-buttonify-urls (if elpher-filter-ansi-from-text
1079                              (elpher-color-filter-apply string)
1080                            (elpher-color-apply string))))
1081
1082 (defun elpher-render-text (data &optional _mime-type-string)
1083   "Render DATA as text.  MIME-TYPE-STRING is unused."
1084   (elpher-with-clean-buffer
1085    (if (not data)
1086        t
1087      (insert (elpher-process-text-for-display (elpher-preprocess-text-response data)))
1088      (elpher-cache-content
1089       (elpher-page-address elpher-current-page)
1090       (buffer-string)))))
1091
1092 ;; Image retrieval
1093
1094 (defun elpher-render-image (data &optional _mime-type-string)
1095   "Display DATA as image.  MIME-TYPE-STRING is unused."
1096   (if (not data)
1097       nil
1098     (if (display-images-p)
1099         (progn
1100           (let ((image (create-image
1101                         data
1102                         nil t)))
1103             (elpher-with-clean-buffer
1104              (insert-image image)
1105              (elpher-restore-pos))))
1106       (elpher-render-download data))))
1107
1108 ;; Search retrieval and rendering
1109
1110 (defun elpher-get-gopher-query-page (renderer)
1111   "Getter for gopher addresses requiring input.
1112 The response is rendered using the rendering function RENDERER."
1113    (let* ((address (elpher-page-address elpher-current-page))
1114           (content (elpher-get-cached-content address))
1115           (aborted t))
1116     (if (and content (funcall renderer nil))
1117         (elpher-with-clean-buffer
1118          (insert content)
1119          (elpher-restore-pos)
1120          (message "Displaying cached search results.  Reload to perform a new search."))
1121       (unwind-protect
1122           (let* ((query-string (read-string "Query: "))
1123                  (query-selector (concat (elpher-gopher-address-selector address) "\t" query-string))
1124                  (search-address (elpher-make-gopher-address ?1
1125                                                              query-selector
1126                                                              (elpher-address-host address)
1127                                                              (elpher-address-port address)
1128                                                              (equal (elpher-address-type address) "gophers"))))
1129             (setq aborted nil)
1130
1131             (elpher-with-clean-buffer
1132              (insert "LOADING RESULTS... (use 'u' to cancel)"))
1133             (elpher-get-gopher-response search-address renderer))
1134         (if aborted
1135             (elpher-visit-previous-page))))))
1136
1137 ;; Raw server response rendering
1138
1139 (defun elpher-render-raw (data &optional mime-type-string)
1140   "Display raw DATA in buffer.  MIME-TYPE-STRING is also displayed if provided."
1141   (if (not data)
1142       nil
1143     (elpher-with-clean-buffer
1144      (when mime-type-string
1145        (insert "MIME type specified by server: '" mime-type-string "'\n"))
1146      (insert data)
1147      (goto-char (point-min)))
1148     (message "Displaying raw server response.  Reload or redraw to return to standard view.")))
1149
1150 ;; File save "rendering"
1151
1152 (defun elpher-render-download (data &optional _mime-type-string)
1153   "Save DATA to file.  MIME-TYPE-STRING is unused."
1154   (if (not data)
1155       nil
1156     (let* ((address (elpher-page-address elpher-current-page))
1157            (selector (if (elpher-address-gopher-p address)
1158                          (elpher-gopher-address-selector address)
1159                        (elpher-address-filename address))))
1160       (elpher-visit-previous-page) ; Do first in case of non-local exits.
1161       (let* ((filename-proposal (file-name-nondirectory selector))
1162              (filename (read-file-name "Download complete. Save file as: "
1163                                        nil nil nil
1164                                        (if (> (length filename-proposal) 0)
1165                                            filename-proposal
1166                                          "download.file"))))
1167         (let ((coding-system-for-write 'binary))
1168           (with-temp-file filename
1169             (insert data)))
1170         (message (format "Saved to file %s." filename))))))
1171
1172 ;; HTML rendering
1173
1174 (defun elpher-render-html (data &optional _mime-type-string)
1175   "Render DATA as HTML using shr.  MIME-TYPE-STRING is unused."
1176   (elpher-with-clean-buffer
1177    (if (not data)
1178        t
1179      (let ((dom (with-temp-buffer
1180                   (insert data)
1181                   (libxml-parse-html-region (point-min) (point-max)))))
1182        (shr-insert-document dom)))))
1183
1184 ;; Gemini page retrieval
1185
1186 (defvar elpher-gemini-redirect-chain)
1187
1188 (defun elpher-get-gemini-response (address renderer)
1189   "Get response string from gemini server at ADDRESS and render using RENDERER."
1190   (elpher-get-host-response address 1965
1191                             (concat (elpher-address-to-url address) "\r\n")
1192                             (lambda (response-string)
1193                               (elpher-process-gemini-response response-string renderer))
1194                             'gemini))
1195
1196 (defun elpher-parse-gemini-response (response)
1197   "Parse the RESPONSE string and return a list of components.
1198 The list is of the form (code meta body).  A response of nil implies
1199 that the response was malformed."
1200   (let ((header-end-idx (string-match "\r\n" response)))
1201     (if header-end-idx
1202         (let ((header (string-trim (substring response 0 header-end-idx)))
1203               (body (substring response (+ header-end-idx 2))))
1204           (if (>= (length header) 2)
1205               (let ((code (substring header 0 2))
1206                     (meta (string-trim (substring header 2))))
1207                 (list code meta body))
1208             (error "Malformed response: No response status found in header %s" header)))
1209       (error "Malformed response: No CRLF-delimited header found in response %s" response))))
1210
1211 (defun elpher-process-gemini-response (response-string renderer)
1212   "Process the gemini response RESPONSE-STRING and pass the result to RENDERER."
1213   (let ((response-components (elpher-parse-gemini-response response-string)))
1214     (let ((response-code (elt response-components 0))
1215           (response-meta (elt response-components 1))
1216           (response-body (elt response-components 2)))
1217       (pcase (elt response-code 0)
1218         (?1 ; Input required
1219          (elpher-with-clean-buffer
1220           (insert "Gemini server is requesting input."))
1221          (let* ((query-string
1222                  (if (eq (elt response-code 1) ?1)
1223                      (read-passwd (concat response-meta ": "))
1224                    (read-string (concat response-meta ": "))))
1225                 (query-address (seq-copy (elpher-page-address elpher-current-page)))
1226                 (old-fname (url-filename query-address)))
1227            (setf (url-filename query-address)
1228                  (concat old-fname "?" (url-build-query-string `((,query-string)))))
1229            (elpher-get-gemini-response query-address renderer)))
1230         (?2 ; Normal response
1231          (funcall renderer response-body response-meta))
1232         (?3 ; Redirect
1233          (message "Following redirect to %s" response-meta)
1234          (if (>= (length elpher-gemini-redirect-chain) 5)
1235              (error "More than 5 consecutive redirects followed"))
1236          (let ((redirect-address (elpher-address-from-gemini-url response-meta)))
1237            (if (member redirect-address elpher-gemini-redirect-chain)
1238                (error "Redirect loop detected"))
1239            (if (not (string= (elpher-address-protocol redirect-address)
1240                              "gemini"))
1241                (error "Server tried to automatically redirect to non-gemini URL: %s"
1242                       response-meta))
1243            (elpher-page-set-address elpher-current-page redirect-address)
1244            (add-to-list 'elpher-gemini-redirect-chain redirect-address)
1245            (elpher-get-gemini-response redirect-address renderer)))
1246         (?4 ; Temporary failure
1247          (error "Gemini server reports TEMPORARY FAILURE for this request: %s %s"
1248                 response-code response-meta))
1249         (?5 ; Permanent failure
1250          (error "Gemini server reports PERMANENT FAILURE for this request: %s %s"
1251                 response-code response-meta))
1252         (?6 ; Client certificate required
1253          (elpher-with-clean-buffer
1254           (if elpher-client-certificate
1255               (insert "Gemini server does not recognise the provided TLS certificate:\n\n")
1256             (insert "Gemini server is requesting a valid TLS certificate:\n\n"))
1257           (auto-fill-mode 1)
1258           (elpher-gemini-insert-text response-meta))
1259          (let ((chosen-certificate (elpher-choose-client-certificate)))
1260            (unless chosen-certificate
1261              (error "Gemini server requires a client certificate and none was provided"))
1262            (setq elpher-client-certificate chosen-certificate))
1263          (elpher-with-clean-buffer)
1264          (elpher-get-gemini-response (elpher-page-address elpher-current-page) renderer))
1265         (_other
1266          (error "Gemini server response unknown: %s %s"
1267                 response-code response-meta))))))
1268
1269 (defun elpher-choose-client-certificate ()
1270   "Prompt for a client certificate to use to establish a TLS connection."
1271   (let* ((read-answer-short t))
1272     (pcase (read-answer "What do you want to do? "
1273                         '(("throwaway" ?t
1274                            "generate and use throw-away certificate")
1275                           ("persistent" ?p
1276                            "generate new or use existing persistent certificate")
1277                           ("abort" ?a
1278                            "stop immediately")))
1279       ("throwaway"
1280        (setq elpher-client-certificate (elpher-generate-throwaway-certificate)))
1281       ("persistent"
1282        (let* ((existing-certificates (elpher-list-existing-certificates))
1283               (file-base (completing-read
1284                           "Nickname for new or existing certificate (autocompletes, empty response aborts): "
1285                           existing-certificates)))
1286          (if (string-empty-p (string-trim file-base))
1287              nil
1288            (if (member file-base existing-certificates)
1289                (setq elpher-client-certificate
1290                      (elpher-get-existing-certificate file-base))
1291              (pcase (read-answer "Generate new certificate or install externally-generated one? "
1292                                  '(("new" ?n
1293                                     "generate new certificate")
1294                                    ("install" ?i
1295                                     "install existing certificate")
1296                                    ("abort" ?a
1297                                     "stop immediately")))
1298                ("new"
1299                 (let ((common-name (read-string "Common Name field for new certificate: "
1300                                                 file-base)))
1301                   (message "New key and self-signed certificate written to %s"
1302                            elpher-certificate-directory)
1303                   (elpher-generate-persistent-certificate file-base common-name)))
1304                ("install"
1305                 (let* ((cert-file (read-file-name "Certificate file: " nil nil t))
1306                        (key-file (read-file-name "Key file: " nil nil t)))
1307                   (message "Key and certificate installed in %s for future use"
1308                            elpher-certificate-directory)
1309                   (elpher-install-and-use-existing-certificate key-file
1310                                                                cert-file
1311                                                                file-base)))
1312                ("abort" nil))))))
1313       ("abort" nil))))
1314
1315 (defun elpher-get-gemini-page (renderer)
1316   "Getter which retrieves and renders a Gemini page and renders it using RENDERER."
1317   (let* ((address (elpher-page-address elpher-current-page))
1318          (content (elpher-get-cached-content address)))
1319     (condition-case the-error
1320         (if (and content (funcall renderer nil))
1321             (elpher-with-clean-buffer
1322               (insert content)
1323               (elpher-restore-pos))
1324           (elpher-with-clean-buffer
1325            (insert "LOADING GEMINI... (use 'u' to cancel)\n"))
1326           (setq elpher-gemini-redirect-chain nil)
1327           (elpher-get-gemini-response address renderer))
1328       (error
1329        (elpher-network-error address the-error)))))
1330
1331 (defun elpher-render-gemini (body &optional mime-type-string)
1332   "Render gemini response BODY with rendering MIME-TYPE-STRING."
1333   (if (not body)
1334       t
1335     (let* ((mime-type-string* (if (or (not mime-type-string)
1336                                       (string-empty-p mime-type-string))
1337                                   "text/gemini; charset=utf-8"
1338                                 mime-type-string))
1339            (mime-type-split (split-string mime-type-string* ";" t))
1340            (mime-type (string-trim (car mime-type-split)))
1341            (parameters (mapcar (lambda (s)
1342                                  (let ((key-val (split-string s "=")))
1343                                    (list (downcase (string-trim (car key-val)))
1344                                          (downcase (string-trim (cadr key-val))))))
1345                                (cdr mime-type-split))))
1346       (when (string-prefix-p "text/" mime-type)
1347         (setq body (decode-coding-string
1348                     body
1349                     (if (assoc "charset" parameters)
1350                         (intern (cadr (assoc "charset" parameters)))
1351                       'utf-8)))
1352         (setq body (replace-regexp-in-string "\r" "" body)))
1353       (pcase mime-type
1354         ((or "text/gemini" "")
1355          (elpher-render-gemini-map body parameters))
1356         ("text/html"
1357          (elpher-render-html body))
1358         ((pred (string-prefix-p "text/"))
1359          (elpher-render-gemini-plain-text body parameters))
1360         ((pred (string-prefix-p "image/"))
1361          (elpher-render-image body))
1362         (_other
1363          (elpher-render-download body))))))
1364
1365 (defun elpher-gemini-get-link-url (link-line)
1366   "Extract the url portion of LINK-LINE, a gemini map file link line.
1367 Returns nil in the event that the contents of the line following the
1368 => prefix are empty."
1369   (let ((l (split-string (substring link-line 2))))
1370     (if l
1371         (string-trim (elt l 0))
1372       nil)))
1373
1374 (defun elpher-gemini-get-link-display-string (link-line)
1375   "Extract the display string portion of LINK-LINE, a gemini map file link line.
1376 Returns the url portion in the event that the display-string portion is empty."
1377   (let* ((rest (string-trim (elt (split-string link-line "=>") 1)))
1378          (idx (string-match "[ \t]" rest)))
1379     (string-trim (if idx
1380                      (substring rest (+ idx 1))
1381                    rest))))
1382
1383 (defun elpher-collapse-dot-sequences (filename)
1384   "Collapse dot sequences in FILENAME.
1385 For instance, the filename /a/b/../c/./d will reduce to /a/c/d"
1386   (let* ((path (split-string filename "/"))
1387          (path-reversed-normalized
1388           (seq-reduce (lambda (a b)
1389                         (cond ((and a (equal b "..") (cdr a)))
1390                               ((and (not a) (equal b "..")) a) ;leading .. are dropped
1391                               ((equal b ".") a)
1392                               (t (cons b a))))
1393                       path nil)))
1394     (string-join (reverse path-reversed-normalized) "/")))
1395
1396 (defun elpher-address-from-gemini-url (url)
1397   "Extract address from URL with defaults as per gemini map files.
1398 While there's obviously some redundancy here between this function and
1399 `elpher-address-from-url', gemini map file URLs require enough special
1400 treatment that a separate function is warranted."
1401   (let ((address (url-generic-parse-url url))
1402         (current-address (elpher-page-address elpher-current-page)))
1403     (unless (and (url-type address) (not (url-fullness address))) ;avoid mangling mailto: urls
1404       (setf (url-fullness address) t)
1405       (if (url-host address) ;if there is an explicit host, filenames are absolute
1406           (if (string-empty-p (url-filename address))
1407               (setf (url-filename address) "/")) ;ensure empty filename is marked as absolute
1408         (setf (url-host address) (url-host current-address))
1409         (setf (url-port address) (url-port current-address))
1410         (unless (string-prefix-p "/" (url-filename address)) ;deal with relative links
1411           (setf (url-filename address)
1412                 (concat (file-name-directory (url-filename current-address))
1413                         (url-filename address)))))
1414       (unless (url-type address)
1415         (setf (url-type address) "gemini"))
1416       (when (equal (url-type address) "gemini")
1417         (setf (url-filename address)
1418               (elpher-collapse-dot-sequences (url-filename address)))))
1419     (elpher-remove-redundant-ports address)))
1420
1421 (defun elpher-gemini-insert-link (link-line)
1422   "Insert link described by LINK-LINE into a text/gemini document."
1423   (let* ((url (elpher-gemini-get-link-url link-line))
1424          (display-string (elpher-gemini-get-link-display-string link-line))
1425          (address (elpher-address-from-gemini-url url))
1426          (type (if address (elpher-address-type address) nil))
1427          (type-map-entry (cdr (assoc type elpher-type-map))))
1428     (setq elpher--gemini-page-links (append elpher--gemini-page-links `(,address)))
1429     (when display-string
1430       (insert elpher-gemini-link-string)
1431       (if type-map-entry
1432           (let* ((face (elt type-map-entry 3))
1433                  (filtered-display-string (elpher-color-filter-apply display-string))
1434                  (page (elpher-make-page filtered-display-string address)))
1435             (insert-text-button filtered-display-string
1436                                 'face face
1437                                 'elpher-page page
1438                                 'action #'elpher-click-link
1439                                 'follow-link t
1440                                 'help-echo #'elpher--page-button-help))
1441         (insert (propertize display-string 'face 'elpher-unknown)))
1442       (insert "\n"))))
1443
1444 (defun elpher-gemini-insert-header (header-line)
1445   "Insert header described by HEADER-LINE into a text/gemini document.
1446 The gemini map file line describing the header is given
1447 by HEADER-LINE."
1448   (when (string-match "^\\(#+\\)[ \t]*" header-line)
1449     (let* ((level (length (match-string 1 header-line)))
1450            (header (substring header-line (match-end 0)))
1451            (face (pcase level
1452                    (1 'elpher-gemini-heading1)
1453                    (2 'elpher-gemini-heading2)
1454                    (3 'elpher-gemini-heading3)
1455                    (_ 'default)))
1456            (fill-column (if (display-graphic-p)
1457                             (/ (* fill-column
1458                                   (font-get (font-spec :name (face-font 'default)) :size))
1459                                (font-get (font-spec :name (face-font face)) :size)) fill-column)))
1460       (unless (display-graphic-p)
1461         (insert (make-string level ?#) " "))
1462       (insert (propertize header 'face face))
1463       (newline))))
1464
1465 (defun elpher-gemini-insert-text (text-line)
1466   "Insert a plain non-preformatted TEXT-LINE into a text/gemini document.
1467 This function uses Emacs' auto-fill to wrap text sensibly to a maximum
1468 width defined by elpher-gemini-max-fill-width."
1469   (string-match "\\(^[ \t]*\\)\\(\*[ \t]+\\|>[ \t]*\\)?" text-line)
1470   (let* ((line-prefix (match-string 2 text-line))
1471          (processed-text-line
1472           (if line-prefix
1473               (cond ((string-prefix-p "*" line-prefix)
1474                      (concat
1475                       (replace-regexp-in-string "\*"
1476                                                 elpher-gemini-bullet-string
1477                                                 (match-string 0 text-line))
1478                       (substring text-line (match-end 0))))
1479                     ((string-prefix-p ">" line-prefix)
1480                      (propertize text-line 'face 'elpher-gemini-quoted))
1481                     (t text-line))
1482             text-line))
1483          (adaptive-fill-mode nil))
1484     (insert (elpher-process-text-for-display processed-text-line))
1485     (newline)))
1486
1487 (defun elpher-render-gemini-map (data _parameters)
1488   "Render DATA as a gemini map file, PARAMETERS is currently unused."
1489   (elpher-with-clean-buffer
1490    (let ((preformatted nil)
1491          (link-counter 1))
1492      (auto-fill-mode 1)
1493      (setq-local fill-column (min (window-width) elpher-gemini-max-fill-width))
1494      (setq elpher--gemini-page-links '())
1495      (dolist (line (split-string data "\n"))
1496        (cond
1497         ((string-prefix-p "```" line) (setq preformatted (not preformatted)))
1498         (preformatted (insert (elpher-process-text-for-display
1499                                (propertize line 'face 'elpher-gemini-preformatted))
1500                               "\n"))
1501         ((string-prefix-p "=>" line)
1502          (progn
1503            (if elpher-gemini-number-links
1504                (insert
1505                 (concat
1506                  "["
1507                  (number-to-string link-counter)
1508                  "] ")))
1509            (setq link-counter (1+ link-counter))
1510            (elpher-gemini-insert-link line)))
1511         ((string-prefix-p "#" line) (elpher-gemini-insert-header line))
1512         (t (elpher-gemini-insert-text line)))))
1513    (elpher-cache-content
1514     (elpher-page-address elpher-current-page)
1515     (buffer-string))
1516    (puthash
1517     (elpher-page-address elpher-current-page)
1518     elpher--gemini-page-links
1519     elpher--gemini-page-links-cache)))
1520
1521 (defun elpher-render-gemini-plain-text (data _parameters)
1522   "Render DATA as plain text file.  PARAMETERS is currently unused."
1523   (elpher-with-clean-buffer
1524    (insert (elpher-process-text-for-display data))
1525    (elpher-cache-content
1526     (elpher-page-address elpher-current-page)
1527     (buffer-string))))
1528
1529
1530 ;; Finger page connection
1531
1532 (defun elpher-get-finger-page (renderer)
1533   "Opens a finger connection to the current page address.
1534 The result is rendered using RENDERER."
1535   (let* ((address (elpher-page-address elpher-current-page))
1536          (content (elpher-get-cached-content address)))
1537     (if (and content (funcall renderer nil))
1538         (elpher-with-clean-buffer
1539          (insert content)
1540          (elpher-restore-pos))
1541       (elpher-with-clean-buffer
1542        (insert "LOADING... (use 'u' to cancel)\n"))
1543       (condition-case the-error
1544           (let* ((kill-buffer-query-functions nil)
1545                  (user (let ((filename (elpher-address-filename address)))
1546                          (if (> (length filename) 1)
1547                              (substring filename 1)
1548                            (elpher-address-user address)))))
1549             (elpher-get-host-response address 79
1550                                       (concat user "\r\n")
1551                                       renderer))
1552         (error
1553          (elpher-network-error address the-error))))))
1554
1555
1556 ;; Telnet page connection
1557
1558 (defun elpher-get-telnet-page (renderer)
1559   "Opens a telnet connection to the current page address (RENDERER must be nil)."
1560   (when renderer
1561     (elpher-visit-previous-page)
1562     (error "Command not supported for telnet URLs"))
1563   (let* ((address (elpher-page-address elpher-current-page))
1564          (host (elpher-address-host address))
1565          (port (elpher-address-port address)))
1566     (elpher-visit-previous-page)
1567     (if (> port 0)
1568         (telnet host port)
1569       (telnet host))))
1570
1571
1572 ;; Other URL page opening
1573
1574 (defun elpher-get-other-url-page (renderer)
1575   "Getter which attempts to open the URL specified by the current page (RENDERER must be nil)."
1576   (when renderer
1577     (elpher-visit-previous-page)
1578     (error "Command not supported for general URLs"))
1579   (let* ((address (elpher-page-address elpher-current-page))
1580          (url (elpher-address-to-url address)))
1581     (progn
1582       (elpher-visit-previous-page) ; Do first in case of non-local exits.
1583       (message "Opening URL...")
1584       (if elpher-open-urls-with-eww
1585           (browse-web url)
1586         (browse-url url)))))
1587
1588
1589 ;; Start page page retrieval
1590
1591 (defun elpher-get-start-page (renderer)
1592   "Getter which displays the start page (RENDERER must be nil)."
1593   (when renderer
1594     (elpher-visit-previous-page)
1595     (error "Command not supported for start page"))
1596   (elpher-with-clean-buffer
1597    (insert "     --------------------------------------------\n"
1598            "           Elpher Gopher and Gemini Client       \n"
1599            "                   version " elpher-version "\n"
1600            "     --------------------------------------------\n"
1601            "\n"
1602            "Default bindings:\n"
1603            "\n"
1604            " - TAB/Shift-TAB: next/prev item on current page\n"
1605            " - RET/mouse-1: open item under cursor\n"
1606            " - m: select an item on current page by name (autocompletes)\n"
1607            " - u/mouse-3/U: return to previous page or to the start page\n"
1608            " - o/O: visit different selector or the root menu of the current server\n"
1609            " - g: go to a particular address (gopher, gemini, finger)\n"
1610            " - v: visit a numbered link on a gemini page\n"
1611            " - d/D: download item under cursor or current page\n"
1612            " - i/I: info on item under cursor or current page\n"
1613            " - c/C: copy URL representation of item under cursor or current page\n"
1614            " - a/A: bookmark the item under cursor or current page\n"
1615            " - x/X: remove bookmark for item under cursor or current page\n"
1616            " - B: visit the bookmarks page\n"
1617            " - r: redraw current page (using cached contents if available)\n"
1618            " - R: reload current page (regenerates cache)\n"
1619            " - S: set character coding system for gopher (default is to autodetect)\n"
1620            " - T: toggle TLS gopher mode\n"
1621            " - F: forget/discard current TLS client certificate\n"
1622            " - .: display the raw server response for the current page\n"
1623            "\n"
1624            "Start your exploration of gopher space and gemini:\n")
1625    (elpher-insert-index-record "Floodgap Systems Gopher Server"
1626                                (elpher-make-gopher-address ?1 "" "gopher.floodgap.com" 70))
1627    (elpher-insert-index-record "Project Gemini home page"
1628                                (elpher-address-from-url "gemini://gemini.circumlunar.space/"))
1629    (insert "\n"
1630            "Alternatively, select a search engine and enter some search terms:\n")
1631    (elpher-insert-index-record "Gopher Search Engine (Veronica-2)"
1632                                (elpher-make-gopher-address ?7 "/v2/vs" "gopher.floodgap.com" 70))
1633    (elpher-insert-index-record "Gemini Search Engine (GUS)"
1634                                (elpher-address-from-url "gemini://gus.guru/search"))
1635    (insert "\n"
1636            "This page contains your bookmarked sites (also visit with B):\n")
1637    (elpher-insert-index-record "Your Bookmarks" 'bookmarks)
1638    (insert "\n"
1639            "For Elpher release news or to leave feedback, visit:\n")
1640    (elpher-insert-index-record "The Elpher Project Page"
1641                                (elpher-make-gopher-address ?1
1642                                                            "/projects/elpher/"
1643                                                            "thelambdalab.xyz"
1644                                                            70))
1645    (insert "\n"
1646            "** Refer to the ")
1647    (let ((help-string "RET,mouse-1: Open Elpher info manual (if available)"))
1648      (insert-text-button "Elpher info manual"
1649                          'face 'link
1650                          'action (lambda (_)
1651                                    (interactive)
1652                                    (info "(elpher)"))
1653                          'follow-link t
1654                          'help-echo help-string))
1655    (insert " for the full documentation. **\n")
1656    (insert (propertize
1657             (concat "  (This should be available if you have installed Elpher using\n"
1658                     "   MELPA. Otherwise you will have to install the manual yourself.)\n")
1659             'face 'shadow))
1660    (elpher-restore-pos)))
1661
1662 ;; Bookmarks page page retrieval
1663
1664 (defun elpher-get-bookmarks-page (renderer)
1665   "Getter to load and display the current bookmark list (RENDERER must be nil)."
1666   (when renderer
1667     (elpher-visit-previous-page)
1668     (error "Command not supported for bookmarks page"))
1669   (elpher-with-clean-buffer
1670    (insert "---- Bookmark list ----\n\n")
1671    (let ((bookmarks (elpher-load-bookmarks)))
1672      (if bookmarks
1673          (dolist (bookmark bookmarks)
1674            (let ((display-string (elpher-bookmark-display-string bookmark))
1675                  (address (elpher-address-from-url (elpher-bookmark-url bookmark))))
1676              (elpher-insert-index-record display-string address)))
1677        (insert "No bookmarks found.\n")))
1678    (insert "\n-----------------------\n"
1679            "\n"
1680            "- u: return to previous page\n"
1681            "- x: delete selected bookmark\n"
1682            "- a: rename selected bookmark\n"
1683            "\n"
1684            "Bookmarks are stored in the file ")
1685    (let ((filename elpher-bookmarks-file)
1686          (help-string "RET,mouse-1: Open bookmarks file in new buffer for editing."))
1687      (insert-text-button filename
1688                          'face 'link
1689                          'action (lambda (_)
1690                                    (interactive)
1691                                    (find-file filename))
1692                          'follow-link t
1693                          'help-echo help-string))
1694    (insert "\n")
1695    (elpher-restore-pos)))
1696
1697
1698 ;;; Bookmarks
1699 ;;
1700
1701 (defun elpher-make-bookmark (display-string url)
1702   "Make an elpher bookmark.
1703 DISPLAY-STRING determines how the bookmark will appear in the
1704 bookmark list, while URL is the url of the entry."
1705   (list display-string url))
1706
1707 (defun elpher-bookmark-display-string (bookmark)
1708   "Get the display string of BOOKMARK."
1709   (elt bookmark 0))
1710
1711 (defun elpher-set-bookmark-display-string (bookmark display-string)
1712   "Set the display string of BOOKMARK to DISPLAY-STRING."
1713   (setcar bookmark display-string))
1714
1715 (defun elpher-bookmark-url (bookmark)
1716   "Get the address for BOOKMARK."
1717   (elt bookmark 1))
1718
1719 (defun elpher-save-bookmarks (bookmarks)
1720   "Record the bookmark list BOOKMARKS to the user's bookmark file.
1721 Beware that this completely replaces the existing contents of the file."
1722   (let ((bookmark-dir (file-name-directory elpher-bookmarks-file)))
1723     (unless (file-directory-p bookmark-dir)
1724       (make-directory bookmark-dir)))
1725   (with-temp-file elpher-bookmarks-file
1726     (erase-buffer)
1727     (insert "; Elpher bookmarks file\n\n"
1728             "; Bookmarks are stored as a list of (label URL) items.\n"
1729             "; Feel free to edit by hand, but take care to ensure\n"
1730             "; the list structure remains intact.\n\n")
1731     (pp bookmarks (current-buffer))))
1732
1733 (defun elpher-load-bookmarks ()
1734   "Get the list of bookmarks from the users's bookmark file."
1735   (let ((bookmarks
1736          (with-temp-buffer
1737            (ignore-errors
1738              (insert-file-contents elpher-bookmarks-file)
1739              (goto-char (point-min))
1740              (read (current-buffer))))))
1741     (if (and bookmarks (listp (cadar bookmarks)))
1742         (progn
1743           (message "Reading old bookmark file. (Will be updated on write.)")
1744           (mapcar (lambda (old-bm)
1745                     (list (car old-bm)
1746                           (elpher-address-to-url (apply #'elpher-make-gopher-address
1747                                                         (cadr old-bm)))))
1748                   bookmarks))
1749       bookmarks)))
1750
1751 (defun elpher-add-address-bookmark (address display-string)
1752   "Save a bookmark for ADDRESS with label DISPLAY-STRING.)))
1753 If ADDRESS is already bookmarked, update the label only."
1754   (let ((bookmarks (elpher-load-bookmarks))
1755         (url (elpher-address-to-url address)))
1756     (let ((existing-bookmark (rassoc (list url) bookmarks)))
1757       (if existing-bookmark
1758           (elpher-set-bookmark-display-string existing-bookmark display-string)
1759         (push (elpher-make-bookmark display-string url) bookmarks)))
1760     (elpher-save-bookmarks bookmarks)))
1761
1762 (defun elpher-remove-address-bookmark (address)
1763   "Remove any bookmark to ADDRESS."
1764   (let ((url (elpher-address-to-url address)))
1765     (elpher-save-bookmarks
1766      (seq-filter (lambda (bookmark)
1767                    (not (equal (elpher-bookmark-url bookmark) url)))
1768                  (elpher-load-bookmarks)))))
1769
1770 ;;; Integrations
1771 ;;
1772
1773 (defun elpher-org-link-store ()
1774   "Store link to an `elpher' page in org-mode."
1775   (when (eq major-mode 'elpher-mode)
1776     (let ((link (concat "elpher:" (elpher-info-current)))
1777           (desc (car elpher-current-page)))
1778       (org-link-store-props :type "elpher"
1779                             :link link
1780                             :description desc)
1781       t)))
1782
1783 (defun elpher-org-link-follow (link _args)
1784   "Follow an `elpher' link in an `org' buffer."
1785   (require 'elpher)
1786   (message (concat "Got link: " link))
1787   (when (or
1788          (string-match-p "^gemini://.+" link)
1789          (string-match-p "^gopher://.+" link)
1790          (string-match-p "^finger://.+" link))
1791     (elpher-go (string-remove-prefix "elpher:" link))))
1792
1793 (with-eval-after-load "org"
1794   ;; Use `org-link-set-parameters' if defined (org-mode 9+)
1795   (if (fboundp 'org-link-set-parameters)
1796       (org-link-set-parameters "elpher"
1797                                :store #'elpher-org-link-store
1798                                :follow #'elpher-org-link-follow)
1799     (org-add-link-type "mu4e" 'elpher-org-link-follow)
1800     (add-hook 'org-store-link-functions 'elpher-org-link-store)))
1801
1802 (defun browse-url-elpher (url &rest _args)
1803   "Browse URL. This function is used by `browse-url'."
1804   (interactive (browse-url-interactive-arg "Elpher URL: "))
1805   (elpher-go url))
1806
1807 (with-eval-after-load "browse-url"
1808   ;; Use elpher to open gopher, finger and gemini links
1809   (when (boundp 'browse-url-default-handlers)
1810     (add-to-list 'browse-url-default-handlers
1811                  '("^\\(gopher\\|finger\\|gemini\\)://" . browse-url-elpher)))
1812   ;; Register "gemini://" as a URI scheme so `browse-url' does the right thing
1813   (add-to-list 'thing-at-point-uri-schemes "gemini://"))
1814
1815 ;;; Interactive procedures
1816 ;;
1817
1818 (defun elpher-next-link ()
1819   "Move point to the next link on the current page."
1820   (interactive)
1821   (forward-button 1))
1822
1823 (defun elpher-prev-link ()
1824   "Move point to the previous link on the current page."
1825   (interactive)
1826   (backward-button 1))
1827
1828 (defun elpher-follow-current-link ()
1829   "Open the link or url at point."
1830   (interactive)
1831   (push-button))
1832
1833 ;;;###autoload
1834 (defun elpher-go (host-or-url)
1835   "Go to a particular gopher site HOST-OR-URL.
1836 When run interactively HOST-OR-URL is read from the minibuffer."
1837   (interactive "sGopher or Gemini URL: ")
1838   (let* ((cleaned-host-or-url (string-trim host-or-url))
1839          (address (elpher-address-from-url cleaned-host-or-url))
1840          (page (elpher-make-page cleaned-host-or-url address)))
1841     (switch-to-buffer elpher-buffer-name)
1842     (elpher-visit-page page)
1843     nil))
1844
1845 (defun elpher-go-current ()
1846   "Go to a particular site read from the minibuffer, initialized with the current URL."
1847   (interactive)
1848   (let ((address (elpher-page-address elpher-current-page)))
1849     (if (elpher-address-special-p address)
1850         (error "Command invalid for this page")
1851       (let ((url (read-string "Gopher or Gemini URL: " (elpher-address-to-url address))))
1852         (elpher-visit-page (elpher-make-page url (elpher-address-from-url url)))))))
1853
1854 (defun elpher-visit-gemini-numbered-link (n)
1855   "Visit link designated by a number."
1856   (interactive "nLink number: ")
1857   (if (or (> n (length elpher--gemini-page-links))
1858           (< n 1))
1859       (user-error "Invalid link number"))
1860   (let ((address (nth (1- n) elpher--gemini-page-links)))
1861     (elpher-go (url-recreate-url address))))
1862
1863 (defun elpher-redraw ()
1864   "Redraw current page."
1865   (interactive)
1866   (elpher-visit-page elpher-current-page))
1867
1868 (defun elpher-reload ()
1869   "Reload current page."
1870   (interactive)
1871   (elpher-reload-current-page))
1872
1873 (defun elpher-toggle-tls ()
1874   "Toggle TLS encryption mode for gopher."
1875   (interactive)
1876   (setq elpher-use-tls (not elpher-use-tls))
1877   (if elpher-use-tls
1878       (if (gnutls-available-p)
1879           (message "TLS gopher mode enabled.  (Will not affect current page until reload.)")
1880         (setq elpher-use-tls nil)
1881         (error "Cannot enable TLS gopher mode: GnuTLS not available"))
1882     (message "TLS gopher mode disabled.  (Will not affect current page until reload.)")))
1883
1884 (defun elpher-view-raw ()
1885   "View raw server response for current page."
1886   (interactive)
1887   (if (elpher-address-special-p (elpher-page-address elpher-current-page))
1888       (error "This page was not generated by a server")
1889     (elpher-visit-page elpher-current-page
1890                        #'elpher-render-raw)))
1891
1892 (defun elpher-back ()
1893   "Go to previous site."
1894   (interactive)
1895   (elpher-visit-previous-page))
1896
1897 (defun elpher-back-to-start ()
1898   "Go all the way back to the start page."
1899   (interactive)
1900   (setq-local elpher-current-page nil)
1901   (setq-local elpher-history nil)
1902   (let ((start-page (elpher-make-page "Elpher Start Page"
1903                                       (elpher-make-special-address 'start))))
1904     (elpher-visit-page start-page)))
1905
1906 (defun elpher-download ()
1907   "Download the link at point."
1908   (interactive)
1909   (let ((button (button-at (point))))
1910     (if button
1911         (let ((page (button-get button 'elpher-page)))
1912           (if (elpher-address-special-p (elpher-page-address page))
1913               (error "Cannot download %s"
1914                      (elpher-page-display-string page))
1915             (elpher-visit-page (button-get button 'elpher-page)
1916                                #'elpher-render-download)))
1917       (error "No link selected"))))
1918
1919 (defun elpher-download-current ()
1920   "Download the current page."
1921   (interactive)
1922   (if (elpher-address-special-p (elpher-page-address elpher-current-page))
1923       (error "Cannot download %s"
1924              (elpher-page-display-string elpher-current-page))
1925     (elpher-visit-page (elpher-make-page
1926                         (elpher-page-display-string elpher-current-page)
1927                         (elpher-page-address elpher-current-page))
1928                        #'elpher-render-download
1929                        t)))
1930
1931 (defun elpher-build-link-map ()
1932   "Build alist mapping link names to destination pages in current buffer."
1933   (let ((link-map nil)
1934         (b (next-button (point-min) t)))
1935     (while b
1936       (push (cons (button-label b) b) link-map)
1937       (setq b (next-button (button-start b))))
1938     link-map))
1939
1940 (defun elpher-jump ()
1941   "Select a directory entry by name.  Similar to the info browser (m)enu command."
1942   (interactive)
1943   (let* ((link-map (elpher-build-link-map)))
1944     (if link-map
1945         (let ((key (let ((completion-ignore-case t))
1946                      (completing-read "Directory item/link: "
1947                                       link-map nil t))))
1948           (if (and key (> (length key) 0))
1949               (let ((b (cdr (assoc key link-map))))
1950                 (goto-char (button-start b))
1951                 (button-activate b)))))))
1952
1953 (defun elpher-root-dir ()
1954   "Visit root of current server."
1955   (interactive)
1956   (let ((address (elpher-page-address elpher-current-page)))
1957     (if (not (elpher-address-special-p address))
1958         (if (or (member (url-filename address) '("/" ""))
1959                 (and (elpher-address-gopher-p address)
1960                      (= (length (elpher-gopher-address-selector address)) 0)))
1961             (error "Already at root directory of current server")
1962           (let ((address-copy (elpher-address-from-url
1963                                (elpher-address-to-url address))))
1964             (setf (url-filename address-copy) "")
1965             (elpher-go (elpher-address-to-url address-copy))))
1966       (error "Command invalid for %s" (elpher-page-display-string elpher-current-page)))))
1967
1968 (defun elpher-bookmarks-current-p ()
1969   "Return non-nil if current page is a bookmarks page."
1970   (equal (elpher-address-type (elpher-page-address elpher-current-page))
1971          '(special bookmarks)))
1972
1973 (defun elpher-reload-bookmarks ()
1974   "Reload bookmarks if current page is a bookmarks page."
1975   (if (elpher-bookmarks-current-p)
1976       (elpher-reload-current-page)))
1977
1978 (defun elpher-bookmark-current ()
1979   "Bookmark the current page."
1980   (interactive)
1981   (let ((address (elpher-page-address elpher-current-page))
1982         (display-string (elpher-page-display-string elpher-current-page)))
1983     (if (not (elpher-address-special-p address))
1984         (let ((bookmark-display-string (read-string "Bookmark display string: "
1985                                                     display-string)))
1986           (elpher-add-address-bookmark address bookmark-display-string)
1987           (message "Bookmark added."))
1988       (error "Cannot bookmark %s" display-string))))
1989
1990 (defun elpher-bookmark-link ()
1991   "Bookmark the link at point."
1992   (interactive)
1993   (let ((button (button-at (point))))
1994     (if button
1995         (let* ((page (button-get button 'elpher-page))
1996                (address (elpher-page-address page))
1997                (display-string (elpher-page-display-string page)))
1998           (if (not (elpher-address-special-p address))
1999               (let ((bookmark-display-string (read-string "Bookmark display string: "
2000                                                           display-string)))
2001                 (elpher-add-address-bookmark address bookmark-display-string)
2002                 (elpher-reload-bookmarks)
2003                 (message "Bookmark added."))
2004             (error "Cannot bookmark %s" display-string)))
2005       (error "No link selected"))))
2006
2007 (defun elpher-unbookmark-current ()
2008   "Remove bookmark for the current page."
2009   (interactive)
2010   (let ((address (elpher-page-address elpher-current-page)))
2011     (when (and (not (elpher-address-special-p address))
2012                (y-or-n-p "Really remove bookmark for the current page? "))
2013       (elpher-remove-address-bookmark address)
2014       (message "Bookmark removed."))))
2015
2016 (defun elpher-unbookmark-link ()
2017   "Remove bookmark for the link at point."
2018   (interactive)
2019   (let ((button (button-at (point))))
2020     (if button
2021         (when (y-or-n-p "Really remove bookmark for this link? ")
2022           (let ((page (button-get button 'elpher-page)))
2023             (elpher-remove-address-bookmark (elpher-page-address page))
2024             (elpher-reload-bookmarks)
2025             (message "Bookmark removed.")))
2026       (error "No link selected"))))
2027
2028 ;;;###autoload
2029 (defun elpher-bookmarks ()
2030   "Visit bookmarks page."
2031   (interactive)
2032   (switch-to-buffer elpher-buffer-name)
2033   (elpher-visit-page
2034    (elpher-make-page "Bookmarks Page" (elpher-make-special-address 'bookmarks))))
2035
2036 (defun elpher-info-page (page)
2037   "Display information on PAGE."
2038   (let ((display-string (elpher-page-display-string page))
2039         (address (elpher-page-address page)))
2040     (if (elpher-address-special-p address)
2041         (message "Special page: %s" display-string)
2042       (message "%s" (elpher-address-to-url address)))))
2043
2044 (defun elpher-info-link ()
2045   "Display information on page corresponding to link at point."
2046   (interactive)
2047   (let ((button (button-at (point))))
2048     (if button
2049         (elpher-info-page (button-get button 'elpher-page))
2050       (error "No item selected"))))
2051
2052 (defun elpher-info-current ()
2053   "Display information on current page."
2054   (interactive)
2055   (elpher-info-page elpher-current-page))
2056
2057 (defun elpher-copy-page-url (page)
2058   "Copy URL representation of address of PAGE to `kill-ring'."
2059   (let ((address (elpher-page-address page)))
2060     (if (elpher-address-special-p address)
2061         (error (format "Cannot represent %s as URL" (elpher-page-display-string page)))
2062       (let ((url (elpher-address-to-url address)))
2063         (message "Copied \"%s\" to kill-ring/clipboard." url)
2064         (kill-new url)))))
2065
2066 (defun elpher-copy-link-url ()
2067   "Copy URL of item at point to `kill-ring'."
2068   (interactive)
2069   (let ((button (button-at (point))))
2070     (if button
2071         (elpher-copy-page-url (button-get button 'elpher-page))
2072       (error "No item selected"))))
2073
2074 (defun elpher-copy-current-url ()
2075   "Copy URL of current page to `kill-ring'."
2076   (interactive)
2077   (elpher-copy-page-url elpher-current-page))
2078
2079 (defun elpher-set-gopher-coding-system ()
2080   "Specify an explicit character coding system for gopher selectors."
2081   (interactive)
2082   (let ((system (read-coding-system "Set coding system to use for gopher (default is to autodetect): " nil)))
2083     (setq elpher-user-coding-system system)
2084     (if system
2085         (message "Gopher coding system fixed to %s. (Reload to see effect)." system)
2086       (message "Gopher coding system set to autodetect. (Reload to see effect)."))))
2087
2088
2089 ;;; Mode and keymap
2090 ;;
2091
2092 (defvar elpher-mode-map
2093   (let ((map (make-sparse-keymap)))
2094     (define-key map (kbd "TAB") 'elpher-next-link)
2095     (define-key map (kbd "<backtab>") 'elpher-prev-link)
2096     (define-key map (kbd "C-M-i") 'elpher-prev-link)
2097     (define-key map (kbd "u") 'elpher-back)
2098     (define-key map (kbd "U") 'elpher-back-to-start)
2099     (define-key map [mouse-3] 'elpher-back)
2100     (define-key map (kbd "O") 'elpher-root-dir)
2101     (define-key map (kbd "g") 'elpher-go)
2102     (define-key map (kbd "o") 'elpher-go-current)
2103     (define-key map (kbd "r") 'elpher-redraw)
2104     (define-key map (kbd "R") 'elpher-reload)
2105     (define-key map (kbd "T") 'elpher-toggle-tls)
2106     (define-key map (kbd ".") 'elpher-view-raw)
2107     (define-key map (kbd "d") 'elpher-download)
2108     (define-key map (kbd "D") 'elpher-download-current)
2109     (define-key map (kbd "m") 'elpher-jump)
2110     (define-key map (kbd "i") 'elpher-info-link)
2111     (define-key map (kbd "I") 'elpher-info-current)
2112     (define-key map (kbd "c") 'elpher-copy-link-url)
2113     (define-key map (kbd "C") 'elpher-copy-current-url)
2114     (define-key map (kbd "a") 'elpher-bookmark-link)
2115     (define-key map (kbd "A") 'elpher-bookmark-current)
2116     (define-key map (kbd "x") 'elpher-unbookmark-link)
2117     (define-key map (kbd "X") 'elpher-unbookmark-current)
2118     (define-key map (kbd "B") 'elpher-bookmarks)
2119     (define-key map (kbd "S") 'elpher-set-gopher-coding-system)
2120     (define-key map (kbd "F") 'elpher-forget-current-certificate)
2121     (define-key map (kbd "v") 'elpher-visit-gemini-numbered-link)
2122     (when (fboundp 'evil-define-key*)
2123       (evil-define-key* 'motion map
2124         (kbd "TAB") 'elpher-next-link
2125         (kbd "C-") 'elpher-follow-current-link
2126         (kbd "C-t") 'elpher-back
2127         (kbd "u") 'elpher-back
2128         (kbd "-") 'elpher-back
2129         (kbd "^") 'elpher-back
2130         (kbd "U") 'elpher-back-to-start
2131         [mouse-3] 'elpher-back
2132         (kbd "o") 'elpher-go
2133         (kbd "O") 'elpher-go-current
2134         (kbd "r") 'elpher-redraw
2135         (kbd "R") 'elpher-reload
2136         (kbd "T") 'elpher-toggle-tls
2137         (kbd ".") 'elpher-view-raw
2138         (kbd "d") 'elpher-download
2139         (kbd "D") 'elpher-download-current
2140         (kbd "J") 'elpher-jump
2141         (kbd "i") 'elpher-info-link
2142         (kbd "I") 'elpher-info-current
2143         (kbd "c") 'elpher-copy-link-url
2144         (kbd "C") 'elpher-copy-current-url
2145         (kbd "a") 'elpher-bookmark-link
2146         (kbd "A") 'elpher-bookmark-current
2147         (kbd "x") 'elpher-unbookmark-link
2148         (kbd "X") 'elpher-unbookmark-current
2149         (kbd "B") 'elpher-bookmarks
2150         (kbd "S") 'elpher-set-gopher-coding-system
2151         (kbd "F") 'elpher-forget-current-certificate
2152         (kbd "v") 'elpher-visit-gemini-numbered-link))
2153     map)
2154   "Keymap for gopher client.")
2155
2156 (define-derived-mode elpher-mode special-mode "elpher"
2157   "Major mode for elpher, an elisp gopher client.
2158
2159 This mode is automatically enabled by the interactive
2160 functions which initialize the gopher client, namely
2161 `elpher', `elpher-go' and `elpher-bookmarks'."
2162   (setq-local elpher-current-page nil)
2163   (setq-local elpher-history nil)
2164   (setq-local elpher-buffer-name (buffer-name)))
2165
2166 (when (fboundp 'evil-set-initial-state)
2167   (evil-set-initial-state 'elpher-mode 'motion))
2168
2169
2170 ;;; Main start procedure
2171 ;;
2172
2173 ;;;###autoload
2174 (defun elpher (&optional arg)
2175   "Start elpher with default landing page.
2176 The buffer used for Elpher sessions is determined by the value of
2177 ‘elpher-buffer-name’.  If there is already an Elpher session active in
2178 that buffer, Emacs will simply switch to it.  Otherwise, a new session
2179 will begin.  A numeric prefix arg (as in ‘C-u 42 M-x elpher RET’)
2180 switches to the session with that number, creating it if necessary.  A
2181 nonnumeric prefix arg means to create a new session.  Returns the
2182 buffer selected (or created)."
2183   (interactive "P")
2184   (let* ((name (default-value 'elpher-buffer-name))
2185          (buf (cond ((numberp arg)
2186                      (get-buffer-create (format "%s<%d>" name arg)))
2187                     (arg
2188                      (generate-new-buffer name))
2189                     (t
2190                      (get-buffer-create name)))))
2191     (pop-to-buffer-same-window buf)
2192     (unless (buffer-modified-p)
2193       (elpher-mode)
2194       (let ((start-page (elpher-make-page "Elpher Start Page"
2195                                           (elpher-make-special-address 'start))))
2196         (elpher-visit-page start-page))
2197       "Started Elpher."))); Otherwise (elpher) evaluates to start page string.
2198
2199 ;;; elpher.el ends here