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