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