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