Change browse-url advice for older releases
[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 (unless (fboundp 'read-answer)
1275   (defun read-answer (question answers)
1276     "Backfill for the new read-answer code."
1277     (completing-read question (mapcar 'identity answers))))
1278
1279 (defun elpher-choose-client-certificate ()
1280   "Prompt for a client certificate to use to establish a TLS connection."
1281   (let* ((read-answer-short t))
1282     (pcase (read-answer "What do you want to do? "
1283                         '(("throwaway" ?t
1284                            "generate and use throw-away certificate")
1285                           ("persistent" ?p
1286                            "generate new or use existing persistent certificate")
1287                           ("abort" ?a
1288                            "stop immediately")))
1289       ("throwaway"
1290        (setq elpher-client-certificate (elpher-generate-throwaway-certificate)))
1291       ("persistent"
1292        (let* ((existing-certificates (elpher-list-existing-certificates))
1293               (file-base (completing-read
1294                           "Nickname for new or existing certificate (autocompletes, empty response aborts): "
1295                           existing-certificates)))
1296          (if (string-empty-p (string-trim file-base))
1297              nil
1298            (if (member file-base existing-certificates)
1299                (setq elpher-client-certificate
1300                      (elpher-get-existing-certificate file-base))
1301              (pcase (read-answer "Generate new certificate or install externally-generated one? "
1302                                  '(("new" ?n
1303                                     "generate new certificate")
1304                                    ("install" ?i
1305                                     "install existing certificate")
1306                                    ("abort" ?a
1307                                     "stop immediately")))
1308                ("new"
1309                 (let ((common-name (read-string "Common Name field for new certificate: "
1310                                                 file-base)))
1311                   (message "New key and self-signed certificate written to %s"
1312                            elpher-certificate-directory)
1313                   (elpher-generate-persistent-certificate file-base common-name)))
1314                ("install"
1315                 (let* ((cert-file (read-file-name "Certificate file: " nil nil t))
1316                        (key-file (read-file-name "Key file: " nil nil t)))
1317                   (message "Key and certificate installed in %s for future use"
1318                            elpher-certificate-directory)
1319                   (elpher-install-and-use-existing-certificate key-file
1320                                                                cert-file
1321                                                                file-base)))
1322                ("abort" nil))))))
1323       ("abort" nil))))
1324
1325 (defun elpher-get-gemini-page (renderer)
1326   "Getter which retrieves and renders a Gemini page and renders it using RENDERER."
1327   (let* ((address (elpher-page-address elpher-current-page))
1328          (content (elpher-get-cached-content address)))
1329     (condition-case the-error
1330         (if (and content (funcall renderer nil))
1331             (elpher-with-clean-buffer
1332              (insert content)
1333              (elpher-restore-pos))
1334           (elpher-with-clean-buffer
1335            (insert "LOADING GEMINI... (use 'u' to cancel)\n"))
1336           (setq elpher-gemini-redirect-chain nil)
1337           (elpher-get-gemini-response address renderer))
1338       (error
1339        (elpher-network-error address the-error)))))
1340
1341 (defun elpher-render-gemini (body &optional mime-type-string)
1342   "Render gemini response BODY with rendering MIME-TYPE-STRING."
1343   (if (not body)
1344       t
1345     (let* ((mime-type-string* (if (or (not mime-type-string)
1346                                       (string-empty-p mime-type-string))
1347                                   "text/gemini; charset=utf-8"
1348                                 mime-type-string))
1349            (mime-type-split (split-string mime-type-string* ";" t))
1350            (mime-type (string-trim (car mime-type-split)))
1351            (parameters (mapcar (lambda (s)
1352                                  (let ((key-val (split-string s "=")))
1353                                    (list (downcase (string-trim (car key-val)))
1354                                          (downcase (string-trim (cadr key-val))))))
1355                                (cdr mime-type-split))))
1356       (when (string-prefix-p "text/" mime-type)
1357         (setq body (decode-coding-string
1358                     body
1359                     (if (assoc "charset" parameters)
1360                         (intern (cadr (assoc "charset" parameters)))
1361                       'utf-8)))
1362         (setq body (replace-regexp-in-string "\r" "" body)))
1363       (pcase mime-type
1364         ((or "text/gemini" "")
1365          (elpher-render-gemini-map body parameters))
1366         ("text/html"
1367          (elpher-render-html body))
1368         ((pred (string-prefix-p "text/"))
1369          (elpher-render-gemini-plain-text body parameters))
1370         ((pred (string-prefix-p "image/"))
1371          (elpher-render-image body))
1372         (_other
1373          (elpher-render-download body))))))
1374
1375 (defun elpher-gemini-get-link-url (link-line)
1376   "Extract the url portion of LINK-LINE, a gemini map file link line.
1377 Returns nil in the event that the contents of the line following the
1378 => prefix are empty."
1379   (let ((l (split-string (substring link-line 2))))
1380     (if l
1381         (string-trim (elt l 0))
1382       nil)))
1383
1384 (defun elpher-gemini-get-link-display-string (link-line)
1385   "Extract the display string portion of LINK-LINE, a gemini map file link line.
1386 Returns the url portion in the event that the display-string portion is empty."
1387   (let* ((rest (string-trim (elt (split-string link-line "=>") 1)))
1388          (idx (string-match "[ \t]" rest)))
1389     (string-trim (if idx
1390                      (substring rest (+ idx 1))
1391                    rest))))
1392
1393 (defun elpher-collapse-dot-sequences (filename)
1394   "Collapse dot sequences in FILENAME.
1395 For instance, the filename /a/b/../c/./d will reduce to /a/c/d"
1396   (let* ((path (split-string filename "/"))
1397          (path-reversed-normalized
1398           (seq-reduce (lambda (a b)
1399                         (cond ((and a (equal b "..") (cdr a)))
1400                               ((and (not a) (equal b "..")) a) ;leading .. are dropped
1401                               ((equal b ".") a)
1402                               (t (cons b a))))
1403                       path nil)))
1404     (string-join (reverse path-reversed-normalized) "/")))
1405
1406 (defun elpher-address-from-gemini-url (url)
1407   "Extract address from URL with defaults as per gemini map files.
1408 While there's obviously some redundancy here between this function and
1409 `elpher-address-from-url', gemini map file URLs require enough special
1410 treatment that a separate function is warranted."
1411   (let ((address (url-generic-parse-url url))
1412         (current-address (elpher-page-address elpher-current-page)))
1413     (unless (and (url-type address) (not (url-fullness address))) ;avoid mangling mailto: urls
1414       (setf (url-fullness address) t)
1415       (if (url-host address) ;if there is an explicit host, filenames are absolute
1416           (if (string-empty-p (url-filename address))
1417               (setf (url-filename address) "/")) ;ensure empty filename is marked as absolute
1418         (setf (url-host address) (url-host current-address))
1419         (setf (url-port address) (url-port current-address))
1420         (unless (string-prefix-p "/" (url-filename address)) ;deal with relative links
1421           (setf (url-filename address)
1422                 (concat (file-name-directory (url-filename current-address))
1423                         (url-filename address)))))
1424       (unless (url-type address)
1425         (setf (url-type address) "gemini"))
1426       (when (equal (url-type address) "gemini")
1427         (setf (url-filename address)
1428               (elpher-collapse-dot-sequences (url-filename address)))))
1429     (elpher-remove-redundant-ports address)))
1430
1431 (defun elpher-gemini-insert-link (link-line)
1432   "Insert link described by LINK-LINE into a text/gemini document."
1433   (let* ((url (elpher-gemini-get-link-url link-line))
1434          (display-string (elpher-gemini-get-link-display-string link-line))
1435          (address (elpher-address-from-gemini-url url))
1436          (type (if address (elpher-address-type address) nil))
1437          (type-map-entry (cdr (assoc type elpher-type-map))))
1438     (setq elpher--gemini-page-links (append elpher--gemini-page-links `(,address)))
1439     (when display-string
1440       (insert elpher-gemini-link-string)
1441       (if type-map-entry
1442           (let* ((face (elt type-map-entry 3))
1443                  (filtered-display-string (elpher-color-filter-apply display-string))
1444                  (page (elpher-make-page filtered-display-string address)))
1445             (insert-text-button filtered-display-string
1446                                 'face face
1447                                 'elpher-page page
1448                                 'action #'elpher-click-link
1449                                 'follow-link t
1450                                 'help-echo #'elpher--page-button-help))
1451         (insert (propertize display-string 'face 'elpher-unknown)))
1452       (insert "\n"))))
1453
1454 (defun elpher-gemini-insert-header (header-line)
1455   "Insert header described by HEADER-LINE into a text/gemini document.
1456 The gemini map file line describing the header is given
1457 by HEADER-LINE."
1458   (when (string-match "^\\(#+\\)[ \t]*" header-line)
1459     (let* ((level (length (match-string 1 header-line)))
1460            (header (substring header-line (match-end 0)))
1461            (face (pcase level
1462                    (1 'elpher-gemini-heading1)
1463                    (2 'elpher-gemini-heading2)
1464                    (3 'elpher-gemini-heading3)
1465                    (_ 'default)))
1466            (fill-column (if (display-graphic-p)
1467                             (/ (* fill-column
1468                                   (font-get (font-spec :name (face-font 'default)) :size))
1469                                (font-get (font-spec :name (face-font face)) :size)) fill-column)))
1470       (setq elpher--gemini-page-headings (cons (cons header (point))
1471                                                elpher--gemini-page-headings))
1472       (unless (display-graphic-p)
1473         (insert (make-string level ?#) " "))
1474       (insert (propertize header 'face face))
1475       (newline))))
1476
1477 (defun elpher-gemini-insert-text (text-line)
1478   "Insert a plain non-preformatted TEXT-LINE into a text/gemini document.
1479 This function uses Emacs' auto-fill to wrap text sensibly to a maximum
1480 width defined by `elpher-gemini-max-fill-width'."
1481   (string-match "\\(^[ \t]*\\)\\(\\*[ \t]+\\|>[ \t]*\\)?" text-line)
1482   (let* ((line-prefix (match-string 2 text-line))
1483          (processed-text-line
1484           (if line-prefix
1485               (cond ((string-prefix-p "*" line-prefix)
1486                      (concat
1487                       (replace-regexp-in-string "\\*"
1488                                                 elpher-gemini-bullet-string
1489                                                 (match-string 0 text-line))
1490                       (substring text-line (match-end 0))))
1491                     ((string-prefix-p ">" line-prefix)
1492                      (propertize text-line 'face 'elpher-gemini-quoted))
1493                     (t text-line))
1494             text-line))
1495          (adaptive-fill-mode t))
1496     (insert (elpher-process-text-for-display processed-text-line))
1497     (newline)))
1498
1499 (defun elpher-render-gemini-map (data _parameters)
1500   "Render DATA as a gemini map file, PARAMETERS is currently unused."
1501   (elpher-with-clean-buffer
1502    (setq elpher--gemini-page-headings nil)
1503    (let ((preformatted nil)
1504          (link-counter 1))
1505      (auto-fill-mode 1)
1506      (setq-local fill-column (min (window-width) elpher-gemini-max-fill-width))
1507      (setq elpher--gemini-page-links '())
1508      (dolist (line (split-string data "\n"))
1509        (cond
1510         ((string-prefix-p "```" line) (setq preformatted (not preformatted)))
1511         (preformatted (insert (elpher-process-text-for-display
1512                                (propertize line 'face 'elpher-gemini-preformatted))
1513                               "\n"))
1514         ((string-prefix-p "=>" line)
1515          (progn
1516            (if elpher-gemini-number-links
1517                (insert
1518                 (concat
1519                  "["
1520                  (number-to-string link-counter)
1521                  "] ")))
1522            (setq link-counter (1+ link-counter))
1523            (elpher-gemini-insert-link line)))
1524         ((string-prefix-p "#" line) (elpher-gemini-insert-header line))
1525         (t (elpher-gemini-insert-text line)))))
1526    (setq elpher--gemini-page-headings (nreverse elpher--gemini-page-headings))
1527    (elpher-cache-content
1528     (elpher-page-address elpher-current-page)
1529     (buffer-string))
1530    (puthash
1531     (elpher-page-address elpher-current-page)
1532     elpher--gemini-page-links
1533     elpher--gemini-page-links-cache)))
1534
1535 (defun elpher-render-gemini-plain-text (data _parameters)
1536   "Render DATA as plain text file.  PARAMETERS is currently unused."
1537   (elpher-with-clean-buffer
1538    (insert (elpher-process-text-for-display data))
1539    (elpher-cache-content
1540     (elpher-page-address elpher-current-page)
1541     (buffer-string))))
1542
1543
1544 ;; Finger page connection
1545
1546 (defun elpher-get-finger-page (renderer)
1547   "Opens a finger connection to the current page address.
1548 The result is rendered using RENDERER."
1549   (let* ((address (elpher-page-address elpher-current-page))
1550          (content (elpher-get-cached-content address)))
1551     (if (and content (funcall renderer nil))
1552         (elpher-with-clean-buffer
1553          (insert content)
1554          (elpher-restore-pos))
1555       (elpher-with-clean-buffer
1556        (insert "LOADING... (use 'u' to cancel)\n"))
1557       (condition-case the-error
1558           (let* ((kill-buffer-query-functions nil)
1559                  (user (let ((filename (elpher-address-filename address)))
1560                          (if (> (length filename) 1)
1561                              (substring filename 1)
1562                            (elpher-address-user address)))))
1563             (elpher-get-host-response address 79
1564                                       (concat user "\r\n")
1565                                       renderer))
1566         (error
1567          (elpher-network-error address the-error))))))
1568
1569
1570 ;; Telnet page connection
1571
1572 (defun elpher-get-telnet-page (renderer)
1573   "Opens a telnet connection to the current page address (RENDERER must be nil)."
1574   (when renderer
1575     (elpher-visit-previous-page)
1576     (error "Command not supported for telnet URLs"))
1577   (let* ((address (elpher-page-address elpher-current-page))
1578          (host (elpher-address-host address))
1579          (port (elpher-address-port address)))
1580     (elpher-visit-previous-page)
1581     (if (> port 0)
1582         (telnet host port)
1583       (telnet host))))
1584
1585
1586 ;; Other URL page opening
1587
1588 (defun elpher-get-other-url-page (renderer)
1589   "Getter which attempts to open the URL specified by the current page (RENDERER must be nil)."
1590   (when renderer
1591     (elpher-visit-previous-page)
1592     (error "Command not supported for general URLs"))
1593   (let* ((address (elpher-page-address elpher-current-page))
1594          (url (elpher-address-to-url address)))
1595     (progn
1596       (elpher-visit-previous-page) ; Do first in case of non-local exits.
1597       (message "Opening URL...")
1598       (if elpher-open-urls-with-eww
1599           (browse-web url)
1600         (browse-url url)))))
1601
1602
1603 ;; Start page page retrieval
1604
1605 (defun elpher-get-start-page (renderer)
1606   "Getter which displays the start page (RENDERER must be nil)."
1607   (when renderer
1608     (elpher-visit-previous-page)
1609     (error "Command not supported for start page"))
1610   (elpher-with-clean-buffer
1611    (insert "     --------------------------------------------\n"
1612            "           Elpher Gopher and Gemini Client       \n"
1613            "                   version " elpher-version "\n"
1614            "     --------------------------------------------\n"
1615            "\n"
1616            "Default bindings:\n"
1617            "\n"
1618            " - TAB/Shift-TAB: next/prev item on current page\n"
1619            " - RET/mouse-1: open item under cursor\n"
1620            " - m: select an item on current page by name (autocompletes)\n"
1621            " - u/mouse-3/U: return to previous page or to the start page\n"
1622            " - o/O: visit different selector or the root menu of the current server\n"
1623            " - g: go to a particular address (gopher, gemini, finger)\n"
1624            " - v: visit a numbered link on a gemini page\n"
1625            " - d/D: download item under cursor or current page\n"
1626            " - i/I: info on item under cursor or current page\n"
1627            " - c/C: copy URL representation of item under cursor or current page\n"
1628            " - a/A: bookmark the item under cursor or current page\n"
1629            " - x/X: remove bookmark for item under cursor or current page\n"
1630            " - B: visit the bookmarks page\n"
1631            " - r: redraw current page (using cached contents if available)\n"
1632            " - R: reload current page (regenerates cache)\n"
1633            " - S: set character coding system for gopher (default is to autodetect)\n"
1634            " - T: toggle TLS gopher mode\n"
1635            " - F: forget/discard current TLS client certificate\n"
1636            " - .: display the raw server response for the current page\n"
1637            "\n"
1638            "Start your exploration of gopher space and gemini:\n")
1639    (elpher-insert-index-record "Floodgap Systems Gopher Server"
1640                                (elpher-make-gopher-address ?1 "" "gopher.floodgap.com" 70))
1641    (elpher-insert-index-record "Project Gemini home page"
1642                                (elpher-address-from-url "gemini://gemini.circumlunar.space/"))
1643    (insert "\n"
1644            "Alternatively, select a search engine and enter some search terms:\n")
1645    (elpher-insert-index-record "Gopher Search Engine (Veronica-2)"
1646                                (elpher-make-gopher-address ?7 "/v2/vs" "gopher.floodgap.com" 70))
1647    (elpher-insert-index-record "Gemini Search Engine (geminispace.info)"
1648                                (elpher-address-from-url "gemini://geminispace.info/search"))
1649    (insert "\n"
1650            "This page contains your bookmarked sites (also visit with B):\n")
1651    (elpher-insert-index-record "Your Bookmarks" 'bookmarks)
1652    (insert "\n"
1653            "For Elpher release news or to leave feedback, visit:\n")
1654    (elpher-insert-index-record "The Elpher Project Page"
1655                                (elpher-make-gopher-address ?1
1656                                                            "/projects/elpher/"
1657                                                            "thelambdalab.xyz"
1658                                                            70))
1659    (insert "\n"
1660            "** Refer to the ")
1661    (let ((help-string "RET,mouse-1: Open Elpher info manual (if available)"))
1662      (insert-text-button "Elpher info manual"
1663                          'face 'link
1664                          'action (lambda (_)
1665                                    (interactive)
1666                                    (info "(elpher)"))
1667                          'follow-link t
1668                          'help-echo help-string))
1669    (insert " for the full documentation. **\n")
1670    (insert (propertize
1671             (concat "  (This should be available if you have installed Elpher using\n"
1672                     "   MELPA. Otherwise you will have to install the manual yourself.)\n")
1673             'face 'shadow))
1674    (elpher-restore-pos)))
1675
1676 ;; Bookmarks page page retrieval
1677
1678 (defun elpher-get-bookmarks-page (renderer)
1679   "Getter to load and display the current bookmark list (RENDERER must be nil)."
1680   (when renderer
1681     (elpher-visit-previous-page)
1682     (error "Command not supported for bookmarks page"))
1683   (elpher-with-clean-buffer
1684    (insert "---- Bookmark list ----\n\n")
1685    (let ((bookmarks (elpher-load-bookmarks)))
1686      (if bookmarks
1687          (dolist (bookmark bookmarks)
1688            (let ((display-string (elpher-bookmark-display-string bookmark))
1689                  (address (elpher-address-from-url (elpher-bookmark-url bookmark))))
1690              (elpher-insert-index-record display-string address)))
1691        (insert "No bookmarks found.\n")))
1692    (insert "\n-----------------------\n"
1693            "\n"
1694            "- u: return to previous page\n"
1695            "- x: delete selected bookmark\n"
1696            "- a: rename selected bookmark\n"
1697            "\n"
1698            "Bookmarks are stored in the file ")
1699    (let ((filename elpher-bookmarks-file)
1700          (help-string "RET,mouse-1: Open bookmarks file in new buffer for editing."))
1701      (insert-text-button filename
1702                          'face 'link
1703                          'action (lambda (_)
1704                                    (interactive)
1705                                    (find-file filename))
1706                          'follow-link t
1707                          'help-echo help-string))
1708    (insert "\n")
1709    (elpher-restore-pos)))
1710
1711
1712 ;;; Bookmarks
1713 ;;
1714
1715 (defun elpher-make-bookmark (display-string url)
1716   "Make an elpher bookmark.
1717 DISPLAY-STRING determines how the bookmark will appear in the
1718 bookmark list, while URL is the url of the entry."
1719   (list display-string url))
1720
1721 (defun elpher-bookmark-display-string (bookmark)
1722   "Get the display string of BOOKMARK."
1723   (elt bookmark 0))
1724
1725 (defun elpher-set-bookmark-display-string (bookmark display-string)
1726   "Set the display string of BOOKMARK to DISPLAY-STRING."
1727   (setcar bookmark display-string))
1728
1729 (defun elpher-bookmark-url (bookmark)
1730   "Get the address for BOOKMARK."
1731   (elt bookmark 1))
1732
1733 (defun elpher-save-bookmarks (bookmarks)
1734   "Record the bookmark list BOOKMARKS to the user's bookmark file.
1735 Beware that this completely replaces the existing contents of the file."
1736   (let ((bookmark-dir (file-name-directory elpher-bookmarks-file)))
1737     (unless (file-directory-p bookmark-dir)
1738       (make-directory bookmark-dir)))
1739   (with-temp-file elpher-bookmarks-file
1740     (erase-buffer)
1741     (insert "; Elpher bookmarks file\n\n"
1742             "; Bookmarks are stored as a list of (label URL) items.\n"
1743             "; Feel free to edit by hand, but take care to ensure\n"
1744             "; the list structure remains intact.\n\n")
1745     (pp bookmarks (current-buffer))))
1746
1747 (defun elpher-load-bookmarks ()
1748   "Get the list of bookmarks from the users's bookmark file."
1749   (let ((bookmarks
1750          (with-temp-buffer
1751            (ignore-errors
1752              (insert-file-contents elpher-bookmarks-file)
1753              (goto-char (point-min))
1754              (read (current-buffer))))))
1755     (if (and bookmarks (listp (cadar bookmarks)))
1756         (progn
1757           (message "Reading old bookmark file. (Will be updated on write.)")
1758           (mapcar (lambda (old-bm)
1759                     (list (car old-bm)
1760                           (elpher-address-to-url (apply #'elpher-make-gopher-address
1761                                                         (cadr old-bm)))))
1762                   bookmarks))
1763       bookmarks)))
1764
1765 (defun elpher-add-address-bookmark (address display-string)
1766   "Save a bookmark for ADDRESS with label DISPLAY-STRING.)))
1767 If ADDRESS is already bookmarked, update the label only."
1768   (let ((bookmarks (elpher-load-bookmarks))
1769         (url (elpher-address-to-url address)))
1770     (let ((existing-bookmark (rassoc (list url) bookmarks)))
1771       (if existing-bookmark
1772           (elpher-set-bookmark-display-string existing-bookmark display-string)
1773         (push (elpher-make-bookmark display-string url) bookmarks)))
1774     (elpher-save-bookmarks bookmarks)))
1775
1776 (defun elpher-remove-address-bookmark (address)
1777   "Remove any bookmark to ADDRESS."
1778   (let ((url (elpher-address-to-url address)))
1779     (elpher-save-bookmarks
1780      (seq-filter (lambda (bookmark)
1781                    (not (equal (elpher-bookmark-url bookmark) url)))
1782                  (elpher-load-bookmarks)))))
1783
1784 ;;; Integrations
1785 ;;
1786
1787 ;;; Org
1788
1789 ;; Avoid byte compilation warnings.
1790 (eval-when-compile
1791   (declare-function org-link-store-props "ol")
1792   (declare-function org-link-set-parameters "ol"))
1793
1794 (defun elpher-org-export-link (link description format protocol)
1795   "Export a LINK with DESCRIPTION for the given PROTOCOL and FORMAT.
1796
1797 FORMAT is an Org export backend.  DESCRIPTION may be nil.  PROTOCOL may be one
1798 of gemini, gopher or finger."
1799   (let* ((url (if (equal protocol "elpher")
1800                   (string-remove-prefix "elpher:" link)
1801                 (format "%s:%s" protocol link)))
1802          (desc (or description url)))
1803     (pcase format
1804       (`gemini (format "=> %s %s" url desc))
1805       (`html (format "<a href=\"%s\">%s</a>" url desc))
1806       (`latex (format "\\href{%s}{%s}" url desc))
1807       (_ (if (not description)
1808              url
1809            (format "%s (%s)" desc url))))))
1810
1811 (defun elpher-org-store-link ()
1812   "Store link to an `elpher' page in Org."
1813   (when (eq major-mode 'elpher-mode)
1814     (let* ((url (elpher-info-current))
1815            (desc (car elpher-current-page))
1816            (protocol (cond
1817                       ((string-prefix-p "gemini:" url) "gemini")
1818                       ((string-prefix-p "gopher:" url) "gopher")
1819                       ((string-prefix-p "finger:" url) "finger")
1820                       (t "elpher"))))
1821       (when (equal "elpher" protocol)
1822         ;; Weird link. Or special inner link?
1823         (setq url (concat "elpher:" url)))
1824       (org-link-store-props :type protocol :link url :description desc)
1825       t)))
1826
1827 (defun elpher-org-follow-link (link protocol)
1828   "Visit a LINK for the given PROTOCOL.
1829
1830 PROTOCOL may be one of gemini, gopher or finger.  This method also
1831 supports the old protocol elpher, where the link is self-contained."
1832   (let ((url (if (equal protocol "elpher")
1833                  (string-remove-prefix "elpher:" link)
1834                (format "%s:%s" protocol link))))
1835     (elpher-go url)))
1836
1837 (with-eval-after-load 'org
1838   (org-link-set-parameters
1839    "elpher"
1840    :store #'elpher-org-store-link
1841    :export (lambda (link description format _plist)
1842              (elpher-org-export-link link description format "elpher"))
1843    :follow (lambda (link _arg) (elpher-org-follow-link link "elpher")))
1844   (org-link-set-parameters
1845    "gemini"
1846    :export (lambda (link description format _plist)
1847              (elpher-org-export-link link description format "gemini"))
1848    :follow (lambda (link _arg) (elpher-org-follow-link link "gemini")))
1849   (org-link-set-parameters
1850    "gopher"
1851    :export (lambda (link description format _plist)
1852              (elpher-org-export-link link description format "gopher"))
1853    :follow (lambda (link _arg) (elpher-org-follow-link link "gopher")))
1854   (org-link-set-parameters
1855    "finger"
1856    :export (lambda (link description format _plist)
1857              (elpher-org-export-link link description format "finger"))
1858    :follow (lambda (link _arg) (elpher-org-follow-link link "finger"))))
1859
1860 ;;; Browse URL
1861
1862 ;; Avoid byte compilation warnings.
1863 (eval-when-compile
1864   (defvar thing-at-point-uri-schemes))
1865
1866 ;;;###autoload
1867 (defun elpher-browse-url-elpher (url &rest _args)
1868   "Browse URL using Elpher.  This function is used by `browse-url'."
1869   (interactive (browse-url-interactive-arg "Elpher URL: "))
1870   (elpher-go url))
1871
1872 ;; Use elpher to open gopher, finger and gemini links
1873 ;; For recent version of `browse-url' package
1874 (if (boundp 'browse-url-default-handlers)
1875     (add-to-list
1876      'browse-url-default-handlers
1877      '("^\\(gopher\\|finger\\|gemini\\)://" . elpher-browse-url-elpher))
1878   ;; Patch `browse-url-browser-function' for older ones. The value of
1879   ;; that variable is `browse-url-default-browser' by default, so
1880   ;; that's the function that gets advised.
1881   (advice-add browse-url-browser-function :before-while
1882               (lambda (url &rest _args)
1883                 "Handle gemini, gopher, and finger schemes using Elpher."
1884                 (let ((scheme (downcase (car (split-string url ":" t)))))
1885                   (if (member scheme '("gemini" "gopher" "finger"))
1886                       ;; `elpher-go' always returns nil, which will stop the
1887                       ;; advice chain here in a before-while
1888                       (elpher-go url)
1889                     ;; chain must continue, then return t.
1890                     t)))))
1891
1892 ;; Register "gemini://" as a URI scheme so `browse-url' does the right thing
1893 (with-eval-after-load 'thingatpt
1894   (add-to-list 'thing-at-point-uri-schemes "gemini://"))
1895
1896 ;;; Mu4e:
1897
1898 (eval-when-compile
1899   (defvar mu4e~view-beginning-of-url-regexp))
1900
1901 (with-eval-after-load 'mu4e-view
1902   ;; Make mu4e aware of the gemini world
1903   (setq mu4e~view-beginning-of-url-regexp
1904         "\\(?:https?\\|gopher\\|finger\\|gemini\\)://\\|mailto:"))
1905
1906 ;;; Interactive procedures
1907 ;;
1908
1909 (defun elpher-next-link ()
1910   "Move point to the next link on the current page."
1911   (interactive)
1912   (forward-button 1))
1913
1914 (defun elpher-prev-link ()
1915   "Move point to the previous link on the current page."
1916   (interactive)
1917   (backward-button 1))
1918
1919 (defun elpher-follow-current-link ()
1920   "Open the link or url at point."
1921   (interactive)
1922   (push-button))
1923
1924 ;;;###autoload
1925 (defun elpher-go (host-or-url)
1926   "Go to a particular gopher site HOST-OR-URL.
1927 When run interactively HOST-OR-URL is read from the minibuffer."
1928   (interactive "sGopher or Gemini URL: ")
1929   (let* ((cleaned-host-or-url (string-trim host-or-url))
1930          (address (elpher-address-from-url cleaned-host-or-url))
1931          (page (elpher-make-page cleaned-host-or-url address)))
1932     (switch-to-buffer elpher-buffer-name)
1933     (elpher-visit-page page)
1934     nil))
1935
1936 (defun elpher-go-current ()
1937   "Go to a particular site read from the minibuffer, initialized with the current URL."
1938   (interactive)
1939   (let ((address (elpher-page-address elpher-current-page)))
1940     (let ((url (read-string "Gopher or Gemini URL: "
1941                             (unless (elpher-address-special-p address)
1942                               (elpher-address-to-url address)))))
1943       (elpher-visit-page (elpher-make-page url (elpher-address-from-url url))))))
1944
1945 (defun elpher-visit-gemini-numbered-link (n)
1946   "Visit link designated by a number N."
1947   (interactive "nLink number: ")
1948   (if (or (> n (length elpher--gemini-page-links))
1949           (< n 1))
1950       (user-error "Invalid link number"))
1951   (let ((address (nth (1- n) elpher--gemini-page-links)))
1952     (elpher-go (url-recreate-url address))))
1953
1954 (defun elpher-redraw ()
1955   "Redraw current page."
1956   (interactive)
1957   (elpher-visit-page elpher-current-page))
1958
1959 (defun elpher-reload ()
1960   "Reload current page."
1961   (interactive)
1962   (elpher-reload-current-page))
1963
1964 (defun elpher-toggle-tls ()
1965   "Toggle TLS encryption mode for gopher."
1966   (interactive)
1967   (setq elpher-use-tls (not elpher-use-tls))
1968   (if elpher-use-tls
1969       (if (gnutls-available-p)
1970           (message "TLS gopher mode enabled.  (Will not affect current page until reload.)")
1971         (setq elpher-use-tls nil)
1972         (error "Cannot enable TLS gopher mode: GnuTLS not available"))
1973     (message "TLS gopher mode disabled.  (Will not affect current page until reload.)")))
1974
1975 (defun elpher-view-raw ()
1976   "View raw server response for current page."
1977   (interactive)
1978   (if (elpher-address-special-p (elpher-page-address elpher-current-page))
1979       (error "This page was not generated by a server")
1980     (elpher-visit-page elpher-current-page
1981                        #'elpher-render-raw)))
1982
1983 (defun elpher-back ()
1984   "Go to previous site."
1985   (interactive)
1986   (elpher-visit-previous-page))
1987
1988 (defun elpher-back-to-start ()
1989   "Go all the way back to the start page."
1990   (interactive)
1991   (setq-local elpher-current-page nil)
1992   (setq-local elpher-history nil)
1993   (let ((start-page (elpher-make-page "Elpher Start Page"
1994                                       (elpher-make-special-address 'start))))
1995     (elpher-visit-page start-page)))
1996
1997 (defun elpher-download ()
1998   "Download the link at point."
1999   (interactive)
2000   (let ((button (button-at (point))))
2001     (if button
2002         (let ((page (button-get button 'elpher-page)))
2003           (if (elpher-address-special-p (elpher-page-address page))
2004               (error "Cannot download %s"
2005                      (elpher-page-display-string page))
2006             (elpher-visit-page (button-get button 'elpher-page)
2007                                #'elpher-render-download)))
2008       (error "No link selected"))))
2009
2010 (defun elpher-download-current ()
2011   "Download the current page."
2012   (interactive)
2013   (if (elpher-address-special-p (elpher-page-address elpher-current-page))
2014       (error "Cannot download %s"
2015              (elpher-page-display-string elpher-current-page))
2016     (elpher-visit-page (elpher-make-page
2017                         (elpher-page-display-string elpher-current-page)
2018                         (elpher-page-address elpher-current-page))
2019                        #'elpher-render-download
2020                        t)))
2021
2022 (defun elpher-build-link-map ()
2023   "Build alist mapping link names to destination pages in current buffer."
2024   (let ((link-map nil)
2025         (b (next-button (point-min) t)))
2026     (while b
2027       (push (cons (button-label b) b) link-map)
2028       (setq b (next-button (button-start b))))
2029     link-map))
2030
2031 (defun elpher-jump ()
2032   "Select a directory entry by name.  Similar to the info browser (m)enu command."
2033   (interactive)
2034   (let* ((link-map (elpher-build-link-map)))
2035     (if link-map
2036         (let ((key (let ((completion-ignore-case t))
2037                      (completing-read "Directory item/link: "
2038                                       link-map nil t))))
2039           (if (and key (> (length key) 0))
2040               (let ((b (cdr (assoc key link-map))))
2041                 (goto-char (button-start b))
2042                 (button-activate b)))))))
2043
2044 (defun elpher-root-dir ()
2045   "Visit root of current server."
2046   (interactive)
2047   (let ((address (elpher-page-address elpher-current-page)))
2048     (if (not (elpher-address-special-p address))
2049         (if (or (member (url-filename address) '("/" ""))
2050                 (and (elpher-address-gopher-p address)
2051                      (= (length (elpher-gopher-address-selector address)) 0)))
2052             (error "Already at root directory of current server")
2053           (let ((address-copy (elpher-address-from-url
2054                                (elpher-address-to-url address))))
2055             (setf (url-filename address-copy) "")
2056             (elpher-go (elpher-address-to-url address-copy))))
2057       (error "Command invalid for %s" (elpher-page-display-string elpher-current-page)))))
2058
2059 (defun elpher-bookmarks-current-p ()
2060   "Return non-nil if current page is a bookmarks page."
2061   (equal (elpher-address-type (elpher-page-address elpher-current-page))
2062          '(special bookmarks)))
2063
2064 (defun elpher-reload-bookmarks ()
2065   "Reload bookmarks if current page is a bookmarks page."
2066   (if (elpher-bookmarks-current-p)
2067       (elpher-reload-current-page)))
2068
2069 (defun elpher-bookmark-current ()
2070   "Bookmark the current page."
2071   (interactive)
2072   (let ((address (elpher-page-address elpher-current-page))
2073         (display-string (elpher-page-display-string elpher-current-page)))
2074     (if (not (elpher-address-special-p address))
2075         (let ((bookmark-display-string (read-string "Bookmark display string: "
2076                                                     display-string)))
2077           (elpher-add-address-bookmark address bookmark-display-string)
2078           (message "Bookmark added."))
2079       (error "Cannot bookmark %s" display-string))))
2080
2081 (defun elpher-bookmark-link ()
2082   "Bookmark the link at point."
2083   (interactive)
2084   (let ((button (button-at (point))))
2085     (if button
2086         (let* ((page (button-get button 'elpher-page))
2087                (address (elpher-page-address page))
2088                (display-string (elpher-page-display-string page)))
2089           (if (not (elpher-address-special-p address))
2090               (let ((bookmark-display-string (read-string "Bookmark display string: "
2091                                                           display-string)))
2092                 (elpher-add-address-bookmark address bookmark-display-string)
2093                 (elpher-reload-bookmarks)
2094                 (message "Bookmark added."))
2095             (error "Cannot bookmark %s" display-string)))
2096       (error "No link selected"))))
2097
2098 (defun elpher-unbookmark-current ()
2099   "Remove bookmark for the current page."
2100   (interactive)
2101   (let ((address (elpher-page-address elpher-current-page)))
2102     (when (and (not (elpher-address-special-p address))
2103                (y-or-n-p "Really remove bookmark for the current page? "))
2104       (elpher-remove-address-bookmark address)
2105       (message "Bookmark removed."))))
2106
2107 (defun elpher-unbookmark-link ()
2108   "Remove bookmark for the link at point."
2109   (interactive)
2110   (let ((button (button-at (point))))
2111     (if button
2112         (when (y-or-n-p "Really remove bookmark for this link? ")
2113           (let ((page (button-get button 'elpher-page)))
2114             (elpher-remove-address-bookmark (elpher-page-address page))
2115             (elpher-reload-bookmarks)
2116             (message "Bookmark removed.")))
2117       (error "No link selected"))))
2118
2119 ;;;###autoload
2120 (defun elpher-bookmarks ()
2121   "Visit bookmarks page."
2122   (interactive)
2123   (switch-to-buffer elpher-buffer-name)
2124   (elpher-visit-page
2125    (elpher-make-page "Bookmarks Page" (elpher-make-special-address 'bookmarks))))
2126
2127 (defun elpher-info-page (page)
2128   "Display information on PAGE."
2129   (let ((display-string (elpher-page-display-string page))
2130         (address (elpher-page-address page)))
2131     (if (elpher-address-special-p address)
2132         (message "Special page: %s" display-string)
2133       (message "%s" (elpher-address-to-url address)))))
2134
2135 (defun elpher-info-link ()
2136   "Display information on page corresponding to link at point."
2137   (interactive)
2138   (let ((button (button-at (point))))
2139     (if button
2140         (elpher-info-page (button-get button 'elpher-page))
2141       (error "No item selected"))))
2142
2143 (defun elpher-info-current ()
2144   "Display information on current page."
2145   (interactive)
2146   (elpher-info-page elpher-current-page))
2147
2148 (defun elpher-copy-page-url (page)
2149   "Copy URL representation of address of PAGE to `kill-ring'."
2150   (let ((address (elpher-page-address page)))
2151     (if (elpher-address-special-p address)
2152         (error (format "Cannot represent %s as URL" (elpher-page-display-string page)))
2153       (let ((url (elpher-address-to-url address)))
2154         (message "Copied \"%s\" to kill-ring/clipboard." url)
2155         (kill-new url)))))
2156
2157 (defun elpher-copy-link-url ()
2158   "Copy URL of item at point to `kill-ring'."
2159   (interactive)
2160   (let ((button (button-at (point))))
2161     (if button
2162         (elpher-copy-page-url (button-get button 'elpher-page))
2163       (error "No item selected"))))
2164
2165 (defun elpher-copy-current-url ()
2166   "Copy URL of current page to `kill-ring'."
2167   (interactive)
2168   (elpher-copy-page-url elpher-current-page))
2169
2170 (defun elpher-set-gopher-coding-system ()
2171   "Specify an explicit character coding system for gopher selectors."
2172   (interactive)
2173   (let ((system (read-coding-system "Set coding system to use for gopher (default is to autodetect): " nil)))
2174     (setq elpher-user-coding-system system)
2175     (if system
2176         (message "Gopher coding system fixed to %s. (Reload to see effect)." system)
2177       (message "Gopher coding system set to autodetect. (Reload to see effect)."))))
2178
2179
2180 ;;; Mode and keymap
2181 ;;
2182
2183 (defvar elpher-mode-map
2184   (let ((map (make-sparse-keymap)))
2185     (define-key map (kbd "TAB") 'elpher-next-link)
2186     (define-key map (kbd "<backtab>") 'elpher-prev-link)
2187     (define-key map (kbd "C-M-i") 'elpher-prev-link)
2188     (define-key map (kbd "u") 'elpher-back)
2189     (define-key map (kbd "U") 'elpher-back-to-start)
2190     (define-key map [mouse-3] 'elpher-back)
2191     (define-key map (kbd "O") 'elpher-root-dir)
2192     (define-key map (kbd "g") 'elpher-go)
2193     (define-key map (kbd "o") 'elpher-go-current)
2194     (define-key map (kbd "r") 'elpher-redraw)
2195     (define-key map (kbd "R") 'elpher-reload)
2196     (define-key map (kbd "T") 'elpher-toggle-tls)
2197     (define-key map (kbd ".") 'elpher-view-raw)
2198     (define-key map (kbd "d") 'elpher-download)
2199     (define-key map (kbd "D") 'elpher-download-current)
2200     (define-key map (kbd "m") 'elpher-jump)
2201     (define-key map (kbd "i") 'elpher-info-link)
2202     (define-key map (kbd "I") 'elpher-info-current)
2203     (define-key map (kbd "c") 'elpher-copy-link-url)
2204     (define-key map (kbd "C") 'elpher-copy-current-url)
2205     (define-key map (kbd "a") 'elpher-bookmark-link)
2206     (define-key map (kbd "A") 'elpher-bookmark-current)
2207     (define-key map (kbd "x") 'elpher-unbookmark-link)
2208     (define-key map (kbd "X") 'elpher-unbookmark-current)
2209     (define-key map (kbd "B") 'elpher-bookmarks)
2210     (define-key map (kbd "S") 'elpher-set-gopher-coding-system)
2211     (define-key map (kbd "F") 'elpher-forget-current-certificate)
2212     (define-key map (kbd "v") 'elpher-visit-gemini-numbered-link)
2213     (when (fboundp 'evil-define-key*)
2214       (evil-define-key*
2215        'motion map
2216        (kbd "TAB") 'elpher-next-link
2217        (kbd "C-") 'elpher-follow-current-link
2218        (kbd "C-t") 'elpher-back
2219        (kbd "u") 'elpher-back
2220        (kbd "-") 'elpher-back
2221        (kbd "^") 'elpher-back
2222        (kbd "U") 'elpher-back-to-start
2223        [mouse-3] 'elpher-back
2224        (kbd "o") 'elpher-go
2225        (kbd "O") 'elpher-go-current
2226        (kbd "r") 'elpher-redraw
2227        (kbd "R") 'elpher-reload
2228        (kbd "T") 'elpher-toggle-tls
2229        (kbd ".") 'elpher-view-raw
2230        (kbd "d") 'elpher-download
2231        (kbd "D") 'elpher-download-current
2232        (kbd "J") 'elpher-jump
2233        (kbd "i") 'elpher-info-link
2234        (kbd "I") 'elpher-info-current
2235        (kbd "c") 'elpher-copy-link-url
2236        (kbd "C") 'elpher-copy-current-url
2237        (kbd "a") 'elpher-bookmark-link
2238        (kbd "A") 'elpher-bookmark-current
2239        (kbd "x") 'elpher-unbookmark-link
2240        (kbd "X") 'elpher-unbookmark-current
2241        (kbd "B") 'elpher-bookmarks
2242        (kbd "S") 'elpher-set-gopher-coding-system
2243        (kbd "F") 'elpher-forget-current-certificate
2244        (kbd "v") 'elpher-visit-gemini-numbered-link))
2245     map)
2246   "Keymap for gopher client.")
2247
2248 (define-derived-mode elpher-mode special-mode "elpher"
2249   "Major mode for elpher, an elisp gopher client.
2250
2251 This mode is automatically enabled by the interactive
2252 functions which initialize the gopher client, namely
2253 `elpher', `elpher-go' and `elpher-bookmarks'."
2254   (setq-local elpher--gemini-page-headings nil)
2255   (setq-local elpher-current-page nil)
2256   (setq-local elpher-history nil)
2257   (setq-local elpher-buffer-name (buffer-name))
2258
2259   (setq-local imenu-create-index-function
2260               (lambda ()
2261                 elpher--gemini-page-headings)))
2262
2263 (when (fboundp 'evil-set-initial-state)
2264   (evil-set-initial-state 'elpher-mode 'motion))
2265
2266
2267 ;;; Main start procedure
2268 ;;
2269
2270 ;;;###autoload
2271 (defun elpher (&optional arg)
2272   "Start elpher with default landing page.
2273 The buffer used for Elpher sessions is determined by the value of
2274 ‘elpher-buffer-name’.  If there is already an Elpher session active in
2275 that buffer, Emacs will simply switch to it.  Otherwise, a new session
2276 will begin.  A numeric prefix ARG (as in ‘\\[universal-argument] 42
2277 \\[execute-extended-command] elpher RET’) switches to the session with
2278 that number, creating it if necessary.  A non numeric prefix ARG means
2279 to create a new session.  Returns the buffer selected (or created)."
2280   (interactive "P")
2281   (let* ((name (default-value 'elpher-buffer-name))
2282          (buf (cond ((numberp arg)
2283                      (get-buffer-create (format "%s<%d>" name arg)))
2284                     (arg
2285                      (generate-new-buffer name))
2286                     (t
2287                      (get-buffer-create name)))))
2288     (pop-to-buffer-same-window buf)
2289     (unless (buffer-modified-p)
2290       (elpher-mode)
2291       (let ((start-page (elpher-make-page
2292                          "Elpher Start Page"
2293                          (elpher-make-special-address 'start))))
2294         (elpher-visit-page start-page))
2295       "Started Elpher."))); Otherwise (elpher) evaluates to start page string.
2296
2297 ;;; elpher.el ends here