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