av98.py 62 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660
  1. #!/usr/bin/env python3
  2. # AV-98 Gemini client
  3. # Dervied from VF-1 (https://github.com/solderpunk/VF-1),
  4. # (C) 2019, 2020 Solderpunk <solderpunk@sdf.org>
  5. # With contributions from:
  6. # - danceka <hannu.hartikainen@gmail.com>
  7. # - <jprjr@tilde.club>
  8. # - <vee@vnsf.xyz>
  9. # - Klaus Alexander Seistrup <klaus@seistrup.dk>
  10. # - govynnus <govynnus@sdf.org>
  11. # - Björn Wärmedal <bjorn.warmedal@gmail.com>
  12. # - <jake@rmgr.dev>
  13. import argparse
  14. import cmd
  15. import cgi
  16. import codecs
  17. import collections
  18. import datetime
  19. import fnmatch
  20. import getpass
  21. import glob
  22. import hashlib
  23. import io
  24. import mimetypes
  25. import os
  26. import os.path
  27. import random
  28. import shlex
  29. import shutil
  30. import socket
  31. import sqlite3
  32. import ssl
  33. from ssl import CertificateError
  34. import subprocess
  35. import sys
  36. import tempfile
  37. import time
  38. import urllib.parse
  39. import uuid
  40. import webbrowser
  41. try:
  42. import ansiwrap as textwrap
  43. except ModuleNotFoundError:
  44. import textwrap
  45. try:
  46. from cryptography import x509
  47. from cryptography.hazmat.backends import default_backend
  48. _HAS_CRYPTOGRAPHY = True
  49. _BACKEND = default_backend()
  50. except ModuleNotFoundError:
  51. _HAS_CRYPTOGRAPHY = False
  52. _VERSION = "1.0.4dev"
  53. _MAX_REDIRECTS = 5
  54. _MAX_CACHE_SIZE = 10
  55. _MAX_CACHE_AGE_SECS = 180
  56. # Command abbreviations
  57. _ABBREVS = {
  58. "a": "add",
  59. "b": "back",
  60. "bb": "blackbox",
  61. "bm": "bookmarks",
  62. "book": "bookmarks",
  63. "f": "fold",
  64. "fo": "forward",
  65. "g": "go",
  66. "h": "history",
  67. "hist": "history",
  68. "l": "less",
  69. "n": "next",
  70. "p": "previous",
  71. "prev": "previous",
  72. "q": "quit",
  73. "r": "reload",
  74. "s": "save",
  75. "se": "search",
  76. "/": "search",
  77. "t": "tour",
  78. "u": "up",
  79. }
  80. _MIME_HANDLERS = {
  81. "application/pdf": "xpdf %s",
  82. "audio/mpeg": "mpg123 %s",
  83. "audio/ogg": "ogg123 %s",
  84. "image/*": "feh %s",
  85. "text/html": "lynx -dump -force_html %s",
  86. "text/*": "cat %s",
  87. }
  88. # monkey-patch Gemini support in urllib.parse
  89. # see https://github.com/python/cpython/blob/master/Lib/urllib/parse.py
  90. urllib.parse.uses_relative.append("gemini")
  91. urllib.parse.uses_netloc.append("gemini")
  92. def fix_ipv6_url(url):
  93. if not url.count(":") > 2: # Best way to detect them?
  94. return url
  95. # If there's a pair of []s in there, it's probably fine as is.
  96. if "[" in url and "]" in url:
  97. return url
  98. # Easiest case is a raw address, no schema, no path.
  99. # Just wrap it in square brackets and whack a slash on the end
  100. if "/" not in url:
  101. return "[" + url + "]/"
  102. # Now the trickier cases...
  103. if "://" in url:
  104. schema, schemaless = url.split("://")
  105. else:
  106. schema, schemaless = None, url
  107. if "/" in schemaless:
  108. netloc, rest = schemaless.split("/",1)
  109. schemaless = "[" + netloc + "]" + "/" + rest
  110. if schema:
  111. return schema + "://" + schemaless
  112. return schemaless
  113. standard_ports = {
  114. "gemini": 1965,
  115. "gopher": 70,
  116. }
  117. class GeminiItem():
  118. def __init__(self, url, name=""):
  119. if "://" not in url and ("./" not in url and url[0] != "/"):
  120. url = "gemini://" + url
  121. self.url = fix_ipv6_url(url)
  122. self.name = name
  123. self.local = False
  124. parsed = urllib.parse.urlparse(self.url)
  125. self.scheme = parsed.scheme
  126. self.host = parsed.hostname
  127. self.port = parsed.port or standard_ports.get(self.scheme, 0)
  128. self.path = parsed.path
  129. if self.host == None:
  130. h = self.url.split('/')
  131. self.host = h[0:len(h)-1]
  132. self.local = True
  133. self.scheme = 'local'
  134. def root(self):
  135. return GeminiItem(self._derive_url("/"))
  136. def up(self):
  137. pathbits = list(os.path.split(self.path.rstrip('/')))
  138. # Don't try to go higher than root
  139. if len(pathbits) == 1:
  140. return self
  141. # Get rid of bottom component
  142. pathbits.pop()
  143. new_path = os.path.join(*pathbits)
  144. return GeminiItem(self._derive_url(new_path))
  145. def query(self, query):
  146. query = urllib.parse.quote(query)
  147. return GeminiItem(self._derive_url(query=query))
  148. def _derive_url(self, path="", query=""):
  149. """
  150. A thin wrapper around urlunparse which avoids inserting standard ports
  151. into URLs just to keep things clean.
  152. """
  153. return urllib.parse.urlunparse((self.scheme,
  154. self.host if self.port == standard_ports[self.scheme] else self.host + ":" + str(self.port),
  155. path or self.path, "", query, ""))
  156. def absolutise_url(self, relative_url):
  157. """
  158. Convert a relative URL to an absolute URL by using the URL of this
  159. GeminiItem as a base.
  160. """
  161. return urllib.parse.urljoin(self.url, relative_url)
  162. def to_map_line(self, name=None):
  163. if name or self.name:
  164. return "=> {} {}\n".format(self.url, name or self.name)
  165. else:
  166. return "=> {}\n".format(self.url)
  167. @classmethod
  168. def from_map_line(cls, line, origin_gi):
  169. assert line.startswith("=>")
  170. assert line[2:].strip()
  171. bits = line[2:].strip().split(maxsplit=1)
  172. bits[0] = origin_gi.absolutise_url(bits[0])
  173. return cls(*bits)
  174. CRLF = '\r\n'
  175. # Cheap and cheerful URL detector
  176. def looks_like_url(word):
  177. return "." in word and word.startswith("gemini://")
  178. class UserAbortException(Exception):
  179. pass
  180. # GeminiClient Decorators
  181. def needs_gi(inner):
  182. def outer(self, *args, **kwargs):
  183. if not self.gi:
  184. print("You need to 'go' somewhere, first")
  185. return None
  186. else:
  187. return inner(self, *args, **kwargs)
  188. outer.__doc__ = inner.__doc__
  189. return outer
  190. def restricted(inner):
  191. def outer(self, *args, **kwargs):
  192. if self.restricted:
  193. print("Sorry, this command is not available in restricted mode!")
  194. return None
  195. else:
  196. return inner(self, *args, **kwargs)
  197. outer.__doc__ = inner.__doc__
  198. return outer
  199. class GeminiClient(cmd.Cmd):
  200. def __init__(self, restricted=False):
  201. cmd.Cmd.__init__(self)
  202. # Set umask so that nothing we create can be read by anybody else.
  203. # The certificate cache and TOFU database contain "browser history"
  204. # type sensitivie information.
  205. os.umask(0o077)
  206. # Find config directory
  207. ## Look for something pre-existing
  208. for confdir in ("~/.av98/", "~/.config/av98/"):
  209. confdir = os.path.expanduser(confdir)
  210. if os.path.exists(confdir):
  211. self.config_dir = confdir
  212. break
  213. ## Otherwise, make one in .config if it exists
  214. else:
  215. if os.path.exists(os.path.expanduser("~/.config/")):
  216. self.config_dir = os.path.expanduser("~/.config/av98/")
  217. else:
  218. self.config_dir = os.path.expanduser("~/.av98/")
  219. print("Creating config directory {}".format(self.config_dir))
  220. os.makedirs(self.config_dir)
  221. self.no_cert_prompt = "\x1b[38;5;76m" + "AV-98" + "\x1b[38;5;255m" + "> " + "\x1b[0m"
  222. self.cert_prompt = "\x1b[38;5;202m" + "AV-98" + "\x1b[38;5;255m"
  223. self.prompt = self.no_cert_prompt
  224. self.gi = None
  225. self.history = []
  226. self.hist_index = 0
  227. self.idx_filename = ""
  228. self.index = []
  229. self.index_index = -1
  230. self.lookup = self.index
  231. self.marks = {}
  232. self.page_index = 0
  233. self.permanent_redirects = {}
  234. self.previous_redirectors = set()
  235. self.restricted = restricted
  236. self.tmp_filename = ""
  237. self.visited_hosts = set()
  238. self.waypoints = []
  239. self.client_certs = {
  240. "active": None
  241. }
  242. self.active_cert_domains = []
  243. self.active_is_transient = False
  244. self.transient_certs_created = []
  245. self.options = {
  246. "debug" : False,
  247. "ipv6" : True,
  248. "timeout" : 600,
  249. "width" : 80,
  250. "auto_follow_redirects" : True,
  251. "gopher_proxy" : None,
  252. "tls_mode" : "tofu",
  253. "http_proxy": None,
  254. "cache" : False
  255. }
  256. self.log = {
  257. "start_time": time.time(),
  258. "requests": 0,
  259. "ipv4_requests": 0,
  260. "ipv6_requests": 0,
  261. "bytes_recvd": 0,
  262. "ipv4_bytes_recvd": 0,
  263. "ipv6_bytes_recvd": 0,
  264. "dns_failures": 0,
  265. "refused_connections": 0,
  266. "reset_connections": 0,
  267. "timeouts": 0,
  268. "cache_hits": 0,
  269. }
  270. self._connect_to_tofu_db()
  271. self.cache = {}
  272. self.cache_timestamps = {}
  273. def _connect_to_tofu_db(self):
  274. db_path = os.path.join(self.config_dir, "tofu.db")
  275. self.db_conn = sqlite3.connect(db_path)
  276. self.db_cur = self.db_conn.cursor()
  277. self.db_cur.execute("""CREATE TABLE IF NOT EXISTS cert_cache
  278. (hostname text, address text, fingerprint text,
  279. first_seen date, last_seen date, count integer)""")
  280. def _go_to_gi(self, gi, update_hist=True, check_cache=True, handle=True):
  281. """This method might be considered "the heart of AV-98".
  282. Everything involved in fetching a gemini resource happens here:
  283. sending the request over the network, parsing the response if
  284. its a menu, storing the response in a temporary file, choosing
  285. and calling a handler program, and updating the history."""
  286. # Don't try to speak to servers running other protocols
  287. if gi.scheme in ("http", "https"):
  288. if not self.options.get("http_proxy",None):
  289. webbrowser.open_new_tab(gi.url)
  290. return
  291. else:
  292. print("Do you want to try to open this link with a http proxy?")
  293. resp = input("(Y)/N ")
  294. if resp.strip().lower() in ("n","no"):
  295. webbrowser.open_new_tab(gi.url)
  296. return
  297. elif gi.scheme == "gopher" and not self.options.get("gopher_proxy", None):
  298. print("""AV-98 does not speak Gopher natively.
  299. However, you can use `set gopher_proxy hostname:port` to tell it about a
  300. Gopher-to-Gemini proxy (such as a running Agena instance), in which case
  301. you'll be able to transparently follow links to Gopherspace!""")
  302. return
  303. elif gi.local:
  304. if os.path.exists(gi.path):
  305. with open(gi.path,'r') as f:
  306. body = f.read()
  307. self._handle_gemtext(body,gi)
  308. self.gi = gi
  309. self._update_history(gi)
  310. return
  311. else:
  312. print("Sorry, that file does not exist.")
  313. return
  314. elif gi.scheme not in ("gemini", "gopher"):
  315. print("Sorry, no support for {} links.".format(gi.scheme))
  316. return
  317. # Obey permanent redirects
  318. if gi.url in self.permanent_redirects:
  319. new_gi = GeminiItem(self.permanent_redirects[gi.url], name=gi.name)
  320. self._go_to_gi(new_gi)
  321. return
  322. # Use cache, or hit the network if resource is not cached
  323. if check_cache and self.options["cache"] and self._is_cached(gi.url):
  324. mime, body, tmpfile = self._get_cached(gi.url)
  325. else:
  326. try:
  327. gi, mime, body, tmpfile = self._fetch_over_network(gi)
  328. except UserAbortException:
  329. return
  330. except Exception as err:
  331. # Print an error message
  332. if isinstance(err, socket.gaierror):
  333. self.log["dns_failures"] += 1
  334. print("ERROR: DNS error!")
  335. elif isinstance(err, ConnectionRefusedError):
  336. self.log["refused_connections"] += 1
  337. print("ERROR: Connection refused!")
  338. elif isinstance(err, ConnectionResetError):
  339. self.log["reset_connections"] += 1
  340. print("ERROR: Connection reset!")
  341. elif isinstance(err, (TimeoutError, socket.timeout)):
  342. self.log["timeouts"] += 1
  343. print("""ERROR: Connection timed out!
  344. Slow internet connection? Use 'set timeout' to be more patient.""")
  345. else:
  346. print("ERROR: " + str(err))
  347. return
  348. # Pass file to handler, unless we were asked not to
  349. if handle:
  350. if mime == "text/gemini":
  351. self._handle_gemtext(body, gi)
  352. else:
  353. cmd_str = self._get_handler_cmd(mime)
  354. try:
  355. subprocess.call(shlex.split(cmd_str % tmpfile))
  356. except FileNotFoundError:
  357. print("Handler program %s not found!" % shlex.split(cmd_str)[0])
  358. print("You can use the ! command to specify another handler program or pipeline.")
  359. # Update state
  360. self.gi = gi
  361. self.mime = mime
  362. if update_hist:
  363. self._update_history(gi)
  364. def _fetch_over_network(self, gi):
  365. # Be careful with client certificates!
  366. # Are we crossing a domain boundary?
  367. if self.active_cert_domains and gi.host not in self.active_cert_domains:
  368. if self.active_is_transient:
  369. print("Permanently delete currently active transient certificate?")
  370. resp = input("Y/N? ")
  371. if resp.strip().lower() in ("y", "yes"):
  372. print("Destroying certificate.")
  373. self._deactivate_client_cert()
  374. else:
  375. print("Staying here.")
  376. raise UserAbortException()
  377. else:
  378. print("PRIVACY ALERT: Deactivate client cert before connecting to a new domain?")
  379. resp = input("Y/N? ")
  380. if resp.strip().lower() in ("n", "no"):
  381. print("Keeping certificate active for {}".format(gi.host))
  382. else:
  383. print("Deactivating certificate.")
  384. self._deactivate_client_cert()
  385. # Suggest reactivating previous certs
  386. if not self.client_certs["active"] and gi.host in self.client_certs:
  387. print("PRIVACY ALERT: Reactivate previously used client cert for {}?".format(gi.host))
  388. resp = input("Y/N? ")
  389. if resp.strip().lower() in ("y", "yes"):
  390. self._activate_client_cert(*self.client_certs[gi.host])
  391. else:
  392. print("Remaining unidentified.")
  393. self.client_certs.pop(gi.host)
  394. # Is this a local file?
  395. if gi.local:
  396. address, f = None, open(gi.path, "rb")
  397. else:
  398. address, f = self._send_request(gi)
  399. # Spec dictates <META> should not exceed 1024 bytes,
  400. # so maximum valid header length is 1027 bytes.
  401. header = f.readline(1027)
  402. header = header.decode("UTF-8")
  403. if not header or header[-1] != '\n':
  404. raise RuntimeError("Received invalid header from server!")
  405. header = header.strip()
  406. self._debug("Response header: %s." % header)
  407. # Validate header
  408. status, meta = header.split(maxsplit=1)
  409. if len(meta) > 1024 or len(status) != 2 or not status.isnumeric():
  410. f.close()
  411. raise RuntimeError("Received invalid header from server!")
  412. # Update redirect loop/maze escaping state
  413. if not status.startswith("3"):
  414. self.previous_redirectors = set()
  415. # Handle non-SUCCESS headers, which don't have a response body
  416. # Inputs
  417. if status.startswith("1"):
  418. print(meta)
  419. if status == "11":
  420. user_input = getpass.getpass("> ")
  421. else:
  422. user_input = input("> ")
  423. return self._fetch_over_network(gi.query(user_input))
  424. # Redirects
  425. elif status.startswith("3"):
  426. new_gi = GeminiItem(gi.absolutise_url(meta))
  427. if new_gi.url == gi.url:
  428. raise RuntimeError("URL redirects to itself!")
  429. elif new_gi.url in self.previous_redirectors:
  430. raise RuntimeError("Caught in redirect loop!")
  431. elif len(self.previous_redirectors) == _MAX_REDIRECTS:
  432. raise RuntimeError("Refusing to follow more than %d consecutive redirects!" % _MAX_REDIRECTS)
  433. # Never follow cross-domain redirects without asking
  434. elif new_gi.host != gi.host:
  435. follow = input("Follow cross-domain redirect to %s? (y/n) " % new_gi.url)
  436. # Never follow cross-protocol redirects without asking
  437. elif new_gi.scheme != gi.scheme:
  438. follow = input("Follow cross-protocol redirect to %s? (y/n) " % new_gi.url)
  439. # Don't follow *any* redirect without asking if auto-follow is off
  440. elif not self.options["auto_follow_redirects"]:
  441. follow = input("Follow redirect to %s? (y/n) " % new_gi.url)
  442. # Otherwise, follow away
  443. else:
  444. follow = "yes"
  445. if follow.strip().lower() not in ("y", "yes"):
  446. raise UserAbortException()
  447. self._debug("Following redirect to %s." % new_gi.url)
  448. self._debug("This is consecutive redirect number %d." % len(self.previous_redirectors))
  449. self.previous_redirectors.add(gi.url)
  450. if status == "31":
  451. # Permanent redirect
  452. self.permanent_redirects[gi.url] = new_gi.url
  453. return self._fetch_over_network(new_gi)
  454. # Errors
  455. elif status.startswith("4") or status.startswith("5"):
  456. raise RuntimeError(meta)
  457. # Client cert
  458. elif status.startswith("6"):
  459. self._handle_cert_request(meta)
  460. return self._fetch_over_network(gi)
  461. # Invalid status
  462. elif not status.startswith("2"):
  463. raise RuntimeError("Server returned undefined status code %s!" % status)
  464. # If we're here, this must be a success and there's a response body
  465. assert status.startswith("2")
  466. mime = meta
  467. if mime == "":
  468. mime = "text/gemini; charset=utf-8"
  469. mime, mime_options = cgi.parse_header(mime)
  470. if "charset" in mime_options:
  471. try:
  472. codecs.lookup(mime_options["charset"])
  473. except LookupError:
  474. raise RuntimeError("Header declared unknown encoding %s" % value)
  475. # Read the response body over the network
  476. body = f.read()
  477. # Save the result in a temporary file
  478. ## Set file mode
  479. if mime.startswith("text/"):
  480. mode = "w"
  481. encoding = mime_options.get("charset", "UTF-8")
  482. try:
  483. body = body.decode(encoding)
  484. except UnicodeError:
  485. raise RuntimeError("Could not decode response body using %s encoding declared in header!" % encoding)
  486. else:
  487. mode = "wb"
  488. encoding = None
  489. ## Write
  490. tmpf = tempfile.NamedTemporaryFile(mode, encoding=encoding, delete=False)
  491. size = tmpf.write(body)
  492. tmpf.close()
  493. self.tmp_filename = tmpf.name
  494. self._debug("Wrote %d byte response to %s." % (size, self.tmp_filename))
  495. # Maintain cache and log
  496. if self.options["cache"]:
  497. self._add_to_cache(gi.url, mime, self.tmp_filename)
  498. self._log_visit(gi, address, size)
  499. return gi, mime, body, self.tmp_filename
  500. def _send_request(self, gi):
  501. """Send a selector to a given host and port.
  502. Returns the resolved address and binary file with the reply."""
  503. if gi.scheme == "gemini":
  504. # For Gemini requests, connect to the host and port specified in the URL
  505. host, port = gi.host, gi.port
  506. elif gi.scheme == "gopher":
  507. # For Gopher requests, use the configured proxy
  508. host, port = self.options["gopher_proxy"].rsplit(":", 1)
  509. self._debug("Using gopher proxy: " + self.options["gopher_proxy"])
  510. elif gi.scheme in ("http", "https"):
  511. host, port = self.options["http_proxy"].rsplit(":",1)
  512. self._debug("Using http proxy: " + self.options["http_proxy"])
  513. # Do DNS resolution
  514. addresses = self._get_addresses(host, port)
  515. # Prepare TLS context
  516. protocol = ssl.PROTOCOL_TLS_CLIENT # if sys.version_info.minor >=6 else ssl.PROTOCOL_TLSv1_2
  517. context = ssl.SSLContext(protocol)
  518. # Use CAs or TOFU
  519. if self.options["tls_mode"] == "ca":
  520. context.verify_mode = ssl.CERT_REQUIRED
  521. context.check_hostname = True
  522. context.load_default_certs()
  523. else:
  524. context.check_hostname = False
  525. context.verify_mode = ssl.CERT_NONE
  526. # Impose minimum TLS version
  527. ## In 3.7 and above, this is easy...
  528. if sys.version_info.minor >= 7:
  529. context.minimum_version = ssl.TLSVersion.TLSv1_2
  530. ## Otherwise, it seems very hard...
  531. ## The below is less strict than it ought to be, but trying to disable
  532. ## TLS v1.1 here using ssl.OP_NO_TLSv1_1 produces unexpected failures
  533. ## with recent versions of OpenSSL. What a mess...
  534. else:
  535. context.options |= ssl.OP_NO_SSLv3
  536. context.options |= ssl.OP_NO_SSLv2
  537. # Try to enforce sensible ciphers
  538. try:
  539. context.set_ciphers("AESGCM+ECDHE:AESGCM+DHE:CHACHA20+ECDHE:CHACHA20+DHE:!DSS:!SHA1:!MD5:@STRENGTH")
  540. except ssl.SSLError:
  541. # Rely on the server to only support sensible things, I guess...
  542. pass
  543. # Load client certificate if needed
  544. if self.client_certs["active"]:
  545. certfile, keyfile = self.client_certs["active"]
  546. context.load_cert_chain(certfile, keyfile)
  547. # Connect to remote host by any address possible
  548. err = None
  549. for address in addresses:
  550. self._debug("Connecting to: " + str(address[4]))
  551. s = socket.socket(address[0], address[1])
  552. s.settimeout(self.options["timeout"])
  553. s = context.wrap_socket(s, server_hostname = gi.host)
  554. try:
  555. s.connect(address[4])
  556. break
  557. except OSError as e:
  558. err = e
  559. else:
  560. # If we couldn't connect to *any* of the addresses, just
  561. # bubble up the exception from the last attempt and deny
  562. # knowledge of earlier failures.
  563. raise err
  564. if sys.version_info.minor >=5:
  565. self._debug("Established {} connection.".format(s.version()))
  566. self._debug("Cipher is: {}.".format(s.cipher()))
  567. # Do TOFU
  568. if self.options["tls_mode"] != "ca":
  569. cert = s.getpeercert(binary_form=True)
  570. self._validate_cert(address[4][0], host, cert)
  571. # Remember that we showed the current cert to this domain...
  572. if self.client_certs["active"]:
  573. self.active_cert_domains.append(gi.host)
  574. self.client_certs[gi.host] = self.client_certs["active"]
  575. # Send request and wrap response in a file descriptor
  576. self._debug("Sending %s<CRLF>" % gi.url)
  577. s.sendall((gi.url + CRLF).encode("UTF-8"))
  578. return address, s.makefile(mode = "rb")
  579. def _get_addresses(self, host, port):
  580. # DNS lookup - will get IPv4 and IPv6 records if IPv6 is enabled
  581. if ":" in host:
  582. # This is likely a literal IPv6 address, so we can *only* ask for
  583. # IPv6 addresses or getaddrinfo will complain
  584. family_mask = socket.AF_INET6
  585. elif socket.has_ipv6 and self.options["ipv6"]:
  586. # Accept either IPv4 or IPv6 addresses
  587. family_mask = 0
  588. else:
  589. # IPv4 only
  590. family_mask = socket.AF_INET
  591. addresses = socket.getaddrinfo(host, port, family=family_mask,
  592. type=socket.SOCK_STREAM)
  593. # Sort addresses so IPv6 ones come first
  594. addresses.sort(key=lambda add: add[0] == socket.AF_INET6, reverse=True)
  595. return addresses
  596. def _is_cached(self, url):
  597. if url not in self.cache:
  598. return False
  599. now = time.time()
  600. cached = self.cache_timestamps[url]
  601. if now - cached > _MAX_CACHE_AGE_SECS:
  602. self._debug("Expiring old cached copy of resource.")
  603. self._remove_from_cache(url)
  604. return False
  605. self._debug("Found cached copy of resource.")
  606. return True
  607. def _remove_from_cache(self, url):
  608. self.cache_timestamps.pop(url)
  609. mime, filename = self.cache.pop(url)
  610. os.unlink(filename)
  611. self._validate_cache()
  612. def _add_to_cache(self, url, mime, filename):
  613. self.cache_timestamps[url] = time.time()
  614. self.cache[url] = (mime, filename)
  615. if len(self.cache) > _MAX_CACHE_SIZE:
  616. self._trim_cache()
  617. self._validate_cache()
  618. def _trim_cache(self):
  619. # Order cache entries by age
  620. lru = [(t, u) for (u, t) in self.cache_timestamps.items()]
  621. lru.sort()
  622. # Drop the oldest entry no matter what
  623. _, url = lru[0]
  624. self._debug("Dropping cached copy of {} from full cache.".format(url))
  625. self._remove_from_cache(url)
  626. # Drop other entries if they are older than the limit
  627. now = time.time()
  628. for cached, url in lru[1:]:
  629. if now - cached > _MAX_CACHE_AGE_SECS:
  630. self._debug("Dropping cached copy of {} from full cache.".format(url))
  631. self._remove_from_cache(url)
  632. else:
  633. break
  634. self._validate_cache()
  635. def _get_cached(self, url):
  636. mime, filename = self.cache[url]
  637. self.log["cache_hits"] += 1
  638. if mime.startswith("text/gemini"):
  639. with open(filename, "r") as fp:
  640. body = fp.read()
  641. return mime, body, filename
  642. else:
  643. return mime, None, filename
  644. def _empty_cache(self):
  645. for mime, filename in self.cache.values():
  646. if os.path.exists(filename):
  647. os.unlink(filename)
  648. def _validate_cache(self):
  649. assert self.cache.keys() == self.cache_timestamps.keys()
  650. for _, filename in self.cache.values():
  651. assert os.path.isfile(filename)
  652. def _handle_cert_request(self, meta):
  653. # Don't do client cert stuff in restricted mode, as in principle
  654. # it could be used to fill up the disk by creating a whole lot of
  655. # certificates
  656. if self.restricted:
  657. print("The server is requesting a client certificate.")
  658. print("These are not supported in restricted mode, sorry.")
  659. raise UserAbortException()
  660. print("SERVER SAYS: ", meta)
  661. # Present different messages for different 6x statuses, but
  662. # handle them the same.
  663. if status in ("64", "65"):
  664. print("The server rejected your certificate because it is either expired or not yet valid.")
  665. elif status == "63":
  666. print("The server did not accept your certificate.")
  667. print("You may need to e.g. coordinate with the admin to get your certificate fingerprint whitelisted.")
  668. else:
  669. print("The site {} is requesting a client certificate.".format(gi.host))
  670. print("This will allow the site to recognise you across requests.")
  671. # Give the user choices
  672. print("What do you want to do?")
  673. print("1. Give up.")
  674. print("2. Generate a new transient certificate.")
  675. print("3. Generate a new persistent certificate.")
  676. print("4. Load a previously generated persistent.")
  677. print("5. Load certificate from an external file.")
  678. choice = input("> ").strip()
  679. if choice == "2":
  680. self._generate_transient_cert_cert()
  681. elif choice == "3":
  682. self._generate_persistent_client_cert()
  683. elif choice == "4":
  684. self._choose_client_cert()
  685. elif choice == "5":
  686. self._load_client_cert()
  687. else:
  688. print("Giving up.")
  689. raise UserAbortException()
  690. def _validate_cert(self, address, host, cert):
  691. """
  692. Validate a TLS certificate in TOFU mode.
  693. If the cryptography module is installed:
  694. - Check the certificate Common Name or SAN matches `host`
  695. - Check the certificate's not valid before date is in the past
  696. - Check the certificate's not valid after date is in the future
  697. Whether the cryptography module is installed or not, check the
  698. certificate's fingerprint against the TOFU database to see if we've
  699. previously encountered a different certificate for this IP address and
  700. hostname.
  701. """
  702. now = datetime.datetime.utcnow()
  703. if _HAS_CRYPTOGRAPHY:
  704. # Using the cryptography module we can get detailed access
  705. # to the properties of even self-signed certs, unlike in
  706. # the standard ssl library...
  707. c = x509.load_der_x509_certificate(cert, _BACKEND)
  708. sha = hashlib.sha256()
  709. sha.update(cert)
  710. fingerprint = sha.hexdigest()
  711. # Have we been here before?
  712. self.db_cur.execute("""SELECT fingerprint, first_seen, last_seen, count
  713. FROM cert_cache
  714. WHERE hostname=? AND address=?""", (host, address))
  715. cached_certs = self.db_cur.fetchall()
  716. # If so, check for a match
  717. if cached_certs:
  718. max_count = 0
  719. most_frequent_cert = None
  720. for cached_fingerprint, first, last, count in cached_certs:
  721. if count > max_count:
  722. max_count = count
  723. most_frequent_cert = cached_fingerprint
  724. if fingerprint == cached_fingerprint:
  725. # Matched!
  726. self._debug("TOFU: Accepting previously seen ({} times) certificate {}".format(count, fingerprint))
  727. self.db_cur.execute("""UPDATE cert_cache
  728. SET last_seen=?, count=?
  729. WHERE hostname=? AND address=? AND fingerprint=?""",
  730. (now, count+1, host, address, fingerprint))
  731. self.db_conn.commit()
  732. break
  733. else:
  734. if _HAS_CRYPTOGRAPHY:
  735. # Load the most frequently seen certificate to see if it has
  736. # expired
  737. certdir = os.path.join(self.config_dir, "cert_cache")
  738. with open(os.path.join(certdir, most_frequent_cert+".crt"), "rb") as fp:
  739. previous_cert = fp.read()
  740. previous_cert = x509.load_der_x509_certificate(previous_cert, _BACKEND)
  741. previous_ttl = previous_cert.not_valid_after - now
  742. print(previous_ttl)
  743. self._debug("TOFU: Unrecognised certificate {}! Raising the alarm...".format(fingerprint))
  744. print("****************************************")
  745. print("[SECURITY WARNING] Unrecognised certificate!")
  746. print("The certificate presented for {} ({}) has never been seen before.".format(host, address))
  747. print("This MIGHT be a Man-in-the-Middle attack.")
  748. print("A different certificate has previously been seen {} times.".format(max_count))
  749. if _HAS_CRYPTOGRAPHY:
  750. if previous_ttl < datetime.timedelta():
  751. print("That certificate has expired, which reduces suspicion somewhat.")
  752. else:
  753. print("That certificate is still valid for: {}".format(previous_ttl))
  754. print("****************************************")
  755. print("Attempt to verify the new certificate fingerprint out-of-band:")
  756. print(fingerprint)
  757. choice = input("Accept this new certificate? Y/N ").strip().lower()
  758. if choice in ("y", "yes"):
  759. self.db_cur.execute("""INSERT INTO cert_cache
  760. VALUES (?, ?, ?, ?, ?, ?)""",
  761. (host, address, fingerprint, now, now, 1))
  762. self.db_conn.commit()
  763. with open(os.path.join(certdir, fingerprint+".crt"), "wb") as fp:
  764. fp.write(cert)
  765. else:
  766. raise Exception("TOFU Failure!")
  767. # If not, cache this cert
  768. else:
  769. self._debug("TOFU: Blindly trusting first ever certificate for this host!")
  770. self.db_cur.execute("""INSERT INTO cert_cache
  771. VALUES (?, ?, ?, ?, ?, ?)""",
  772. (host, address, fingerprint, now, now, 1))
  773. self.db_conn.commit()
  774. certdir = os.path.join(self.config_dir, "cert_cache")
  775. if not os.path.exists(certdir):
  776. os.makedirs(certdir)
  777. with open(os.path.join(certdir, fingerprint+".crt"), "wb") as fp:
  778. fp.write(cert)
  779. def _get_handler_cmd(self, mimetype):
  780. # Now look for a handler for this mimetype
  781. # Consider exact matches before wildcard matches
  782. exact_matches = []
  783. wildcard_matches = []
  784. for handled_mime, cmd_str in _MIME_HANDLERS.items():
  785. if "*" in handled_mime:
  786. wildcard_matches.append((handled_mime, cmd_str))
  787. else:
  788. exact_matches.append((handled_mime, cmd_str))
  789. for handled_mime, cmd_str in exact_matches + wildcard_matches:
  790. if fnmatch.fnmatch(mimetype, handled_mime):
  791. break
  792. else:
  793. # Use "xdg-open" as a last resort.
  794. cmd_str = "xdg-open %s"
  795. self._debug("Using handler: %s" % cmd_str)
  796. return cmd_str
  797. def _handle_gemtext(self, body, menu_gi, display=True):
  798. self.options["width"] = os.get_terminal_size().columns
  799. self.index = []
  800. preformatted = False
  801. if self.idx_filename:
  802. os.unlink(self.idx_filename)
  803. tmpf = tempfile.NamedTemporaryFile("w", encoding="UTF-8", delete=False)
  804. self.idx_filename = tmpf.name
  805. for line in body.splitlines():
  806. if line.startswith("```"):
  807. preformatted = not preformatted
  808. elif preformatted:
  809. tmpf.write(line + "\n")
  810. elif line.startswith("=>"):
  811. try:
  812. gi = GeminiItem.from_map_line(line, menu_gi)
  813. self.index.append(gi)
  814. tmpf.write(self._format_geminiitem(len(self.index), gi) + "\n")
  815. except:
  816. self._debug("Skipping possible link: %s" % line)
  817. elif line.startswith("* "):
  818. line = line[1:].lstrip("\t ")
  819. tmpf.write(textwrap.fill(line, self.options["width"],
  820. initial_indent = "• ", subsequent_indent=" ") + "\n")
  821. elif line.startswith(">"):
  822. line = line[1:].lstrip("\t ")
  823. tmpf.write(textwrap.fill(line, self.options["width"],
  824. initial_indent = "> ", subsequent_indent="> ") + "\n")
  825. elif line.startswith("###"):
  826. line = line[3:].lstrip("\t ")
  827. tmpf.write("\x1b[4m" + line + "\x1b[0m""\n")
  828. elif line.startswith("##"):
  829. line = line[2:].lstrip("\t ")
  830. tmpf.write("\x1b[1m" + line + "\x1b[0m""\n")
  831. elif line.startswith("#"):
  832. line = line[1:].lstrip("\t ")
  833. tmpf.write("\x1b[1m\x1b[4m" + line + "\x1b[0m""\n")
  834. else:
  835. tmpf.write(textwrap.fill(line, self.options["width"]) + "\n")
  836. tmpf.close()
  837. self.lookup = self.index
  838. self.page_index = 0
  839. self.index_index = -1
  840. if display:
  841. cmd_str = self._get_handler_cmd("text/gemini")
  842. subprocess.call(shlex.split(cmd_str % self.idx_filename))
  843. def _format_geminiitem(self, index, gi, url=False):
  844. protocol = "" if gi.scheme == "gemini" else " %s" % gi.scheme
  845. line = f"[{index}{protocol}] {gi.url} {gi.name}" if gi.name and url else f"[{index}{protocol}] {gi.name}"
  846. return line
  847. def _show_lookup(self, offset=0, end=None, url=False):
  848. for n, gi in enumerate(self.lookup[offset:end]):
  849. print(self._format_geminiitem(n+offset+1, gi, url))
  850. def _update_history(self, gi):
  851. # Don't duplicate
  852. if self.history and self.history[self.hist_index] == gi:
  853. return
  854. self.history = self.history[0:self.hist_index+1]
  855. self.history.append(gi)
  856. self.hist_index = len(self.history) - 1
  857. def _log_visit(self, gi, address, size):
  858. if not address:
  859. return
  860. self.log["requests"] += 1
  861. self.log["bytes_recvd"] += size
  862. self.visited_hosts.add(address)
  863. if address[0] == socket.AF_INET:
  864. self.log["ipv4_requests"] += 1
  865. self.log["ipv4_bytes_recvd"] += size
  866. elif address[0] == socket.AF_INET6:
  867. self.log["ipv6_requests"] += 1
  868. self.log["ipv6_bytes_recvd"] += size
  869. def _get_active_tmpfile(self):
  870. if self.mime == "text/gemini":
  871. return self.idx_filename
  872. else:
  873. return self.tmp_filename
  874. def _debug(self, debug_text):
  875. if not self.options["debug"]:
  876. return
  877. debug_text = "\x1b[0;32m[DEBUG] " + debug_text + "\x1b[0m"
  878. print(debug_text)
  879. def _load_client_cert(self):
  880. """
  881. Interactively load a TLS client certificate from the filesystem in PEM
  882. format.
  883. """
  884. print("Loading client certificate file, in PEM format (blank line to cancel)")
  885. certfile = input("Certfile path: ").strip()
  886. if not certfile:
  887. print("Aborting.")
  888. return
  889. certfile = os.path.expanduser(certfile)
  890. if not os.path.isfile(certfile):
  891. print("Certificate file {} does not exist.".format(certfile))
  892. return
  893. print("Loading private key file, in PEM format (blank line to cancel)")
  894. keyfile = input("Keyfile path: ").strip()
  895. if not keyfile:
  896. print("Aborting.")
  897. return
  898. keyfile = os.path.expanduser(keyfile)
  899. if not os.path.isfile(keyfile):
  900. print("Private key file {} does not exist.".format(keyfile))
  901. return
  902. self._activate_client_cert(certfile, keyfile)
  903. def _generate_transient_cert_cert(self):
  904. """
  905. Use `openssl` command to generate a new transient client certificate
  906. with 24 hours of validity.
  907. """
  908. certdir = os.path.join(self.config_dir, "transient_certs")
  909. name = str(uuid.uuid4())
  910. self._generate_client_cert(certdir, name, transient=True)
  911. self.active_is_transient = True
  912. self.transient_certs_created.append(name)
  913. def _generate_persistent_client_cert(self):
  914. """
  915. Interactively use `openssl` command to generate a new persistent client
  916. certificate with one year of validity.
  917. """
  918. certdir = os.path.join(self.config_dir, "client_certs")
  919. print("What do you want to name this new certificate?")
  920. print("Answering `mycert` will create `{0}/mycert.crt` and `{0}/mycert.key`".format(certdir))
  921. name = input("> ")
  922. if not name.strip():
  923. print("Aborting.")
  924. return
  925. self._generate_client_cert(certdir, name)
  926. def _generate_client_cert(self, certdir, basename, transient=False):
  927. """
  928. Use `openssl` binary to generate a client certificate (which may be
  929. transient or persistent) and save the certificate and private key to the
  930. specified directory with the specified basename.
  931. """
  932. if not os.path.exists(certdir):
  933. os.makedirs(certdir)
  934. certfile = os.path.join(certdir, basename+".crt")
  935. keyfile = os.path.join(certdir, basename+".key")
  936. cmd = "openssl req -x509 -newkey rsa:2048 -days {} -nodes -keyout {} -out {}".format(1 if transient else 365, keyfile, certfile)
  937. if transient:
  938. cmd += " -subj '/CN={}'".format(basename)
  939. os.system(cmd)
  940. self._activate_client_cert(certfile, keyfile)
  941. def _choose_client_cert(self):
  942. """
  943. Interactively select a previously generated client certificate and
  944. activate it.
  945. """
  946. certdir = os.path.join(self.config_dir, "client_certs")
  947. certs = glob.glob(os.path.join(certdir, "*.crt"))
  948. if len(certs) == 0:
  949. print("There are no previously generated certificates.")
  950. return
  951. certdir = {}
  952. for n, cert in enumerate(certs):
  953. certdir[str(n+1)] = (cert, os.path.splitext(cert)[0] + ".key")
  954. print("{}. {}".format(n+1, os.path.splitext(os.path.basename(cert))[0]))
  955. choice = input("> ").strip()
  956. if choice in certdir:
  957. certfile, keyfile = certdir[choice]
  958. self._activate_client_cert(certfile, keyfile)
  959. else:
  960. print("What?")
  961. def _activate_client_cert(self, certfile, keyfile):
  962. self.client_certs["active"] = (certfile, keyfile)
  963. self.active_cert_domains = []
  964. self.prompt = self.cert_prompt + "+" + os.path.basename(certfile).replace('.crt','') + "> " + "\x1b[0m"
  965. self._debug("Using ID {} / {}.".format(*self.client_certs["active"]))
  966. def _deactivate_client_cert(self):
  967. if self.active_is_transient:
  968. for filename in self.client_certs["active"]:
  969. os.remove(filename)
  970. for domain in self.active_cert_domains:
  971. self.client_certs.pop(domain)
  972. self.client_certs["active"] = None
  973. self.active_cert_domains = []
  974. self.prompt = self.no_cert_prompt
  975. self.active_is_transient = False
  976. # Cmd implementation follows
  977. def default(self, line):
  978. if line.strip() == "EOF":
  979. return self.onecmd("quit")
  980. elif line.strip() == "..":
  981. return self.do_up()
  982. elif line.startswith("/"):
  983. return self.do_search(line[1:])
  984. # Expand abbreviated commands
  985. first_word = line.split()[0].strip()
  986. if first_word in _ABBREVS:
  987. full_cmd = _ABBREVS[first_word]
  988. expanded = line.replace(first_word, full_cmd, 1)
  989. return self.onecmd(expanded)
  990. # Try to parse numerical index for lookup table
  991. try:
  992. n = int(line.strip())
  993. except ValueError:
  994. print("What?")
  995. return
  996. try:
  997. gi = self.lookup[n-1]
  998. except IndexError:
  999. print ("Index too high!")
  1000. return
  1001. self.index_index = n
  1002. self._go_to_gi(gi)
  1003. ### Settings
  1004. @restricted
  1005. def do_set(self, line):
  1006. """View or set various options."""
  1007. if not line.strip():
  1008. # Show all current settings
  1009. for option in sorted(self.options.keys()):
  1010. print("%s %s" % (option, self.options[option]))
  1011. elif len(line.split()) == 1:
  1012. # Show current value of one specific setting
  1013. option = line.strip()
  1014. if option in self.options:
  1015. print("%s %s" % (option, self.options[option]))
  1016. else:
  1017. print("Unrecognised option %s" % option)
  1018. else:
  1019. # Set value of one specific setting
  1020. option, value = line.split(" ", 1)
  1021. if option not in self.options:
  1022. print("Unrecognised option %s" % option)
  1023. return
  1024. # Validate / convert values
  1025. if option == "gopher_proxy":
  1026. if ":" not in value:
  1027. value += ":1965"
  1028. else:
  1029. host, port = value.rsplit(":",1)
  1030. if not port.isnumeric():
  1031. print("Invalid proxy port %s" % port)
  1032. return
  1033. elif option == "tls_mode":
  1034. if value.lower() not in ("ca", "tofu"):
  1035. print("TLS mode must be `ca` or `tofu`!")
  1036. return
  1037. elif value.isnumeric():
  1038. value = int(value)
  1039. elif value.lower() == "false":
  1040. value = False
  1041. elif value.lower() == "true":
  1042. value = True
  1043. else:
  1044. try:
  1045. value = float(value)
  1046. except ValueError:
  1047. pass
  1048. self.options[option] = value
  1049. @restricted
  1050. def do_cert(self, line):
  1051. """Manage client certificates"""
  1052. print("Managing client certificates")
  1053. if self.client_certs["active"]:
  1054. print("Active certificate: {}".format(self.client_certs["active"][0]))
  1055. print("1. Deactivate client certificate.")
  1056. print("2. Generate new certificate.")
  1057. print("3. Load previously generated certificate.")
  1058. print("4. Load externally created client certificate from file.")
  1059. print("Enter blank line to exit certificate manager.")
  1060. choice = input("> ").strip()
  1061. if choice == "1":
  1062. print("Deactivating client certificate.")
  1063. self._deactivate_client_cert()
  1064. elif choice == "2":
  1065. self._generate_persistent_client_cert()
  1066. elif choice == "3":
  1067. self._choose_client_cert()
  1068. elif choice == "4":
  1069. self._load_client_cert()
  1070. else:
  1071. print("Aborting.")
  1072. @restricted
  1073. def do_handler(self, line):
  1074. """View or set handler commands for different MIME types."""
  1075. if not line.strip():
  1076. # Show all current handlers
  1077. for mime in sorted(_MIME_HANDLERS.keys()):
  1078. print("%s %s" % (mime, _MIME_HANDLERS[mime]))
  1079. elif len(line.split()) == 1:
  1080. mime = line.strip()
  1081. if mime in _MIME_HANDLERS:
  1082. print("%s %s" % (mime, _MIME_HANDLERS[mime]))
  1083. else:
  1084. print("No handler set for MIME type %s" % mime)
  1085. else:
  1086. mime, handler = line.split(" ", 1)
  1087. _MIME_HANDLERS[mime] = handler
  1088. if "%s" not in handler:
  1089. print("Are you sure you don't want to pass the filename to the handler?")
  1090. def do_abbrevs(self, *args):
  1091. """Print all AV-98 command abbreviations."""
  1092. header = "Command Abbreviations:"
  1093. self.stdout.write("\n{}\n".format(str(header)))
  1094. if self.ruler:
  1095. self.stdout.write("{}\n".format(str(self.ruler * len(header))))
  1096. for k, v in _ABBREVS.items():
  1097. self.stdout.write("{:<7} {}\n".format(k, v))
  1098. self.stdout.write("\n")
  1099. ### Stuff for getting around
  1100. def do_go(self, line):
  1101. """Go to a gemini URL or marked item."""
  1102. line = line.strip()
  1103. if not line:
  1104. print("Go where?")
  1105. # First, check for possible marks
  1106. elif line in self.marks:
  1107. gi = self.marks[line]
  1108. self._go_to_gi(gi)
  1109. # or a local file
  1110. elif os.path.exists(os.path.expanduser(line)):
  1111. self._go_to_gi(GeminiItem(line))
  1112. # If this isn't a mark, treat it as a URL
  1113. else:
  1114. self._go_to_gi(GeminiItem(line))
  1115. @needs_gi
  1116. def do_reload(self, *args):
  1117. """Reload the current URL."""
  1118. self._go_to_gi(self.gi, check_cache=False)
  1119. @needs_gi
  1120. def do_up(self, *args):
  1121. """Go up one directory in the path."""
  1122. self._go_to_gi(self.gi.up())
  1123. def do_back(self, *args):
  1124. """Go back to the previous gemini item."""
  1125. if not self.history or self.hist_index == 0:
  1126. return
  1127. self.hist_index -= 1
  1128. gi = self.history[self.hist_index]
  1129. self._go_to_gi(gi, update_hist=False)
  1130. def do_forward(self, *args):
  1131. """Go forward to the next gemini item."""
  1132. if not self.history or self.hist_index == len(self.history) - 1:
  1133. return
  1134. self.hist_index += 1
  1135. gi = self.history[self.hist_index]
  1136. self._go_to_gi(gi, update_hist=False)
  1137. def do_next(self, *args):
  1138. """Go to next item after current in index."""
  1139. return self.onecmd(str(self.index_index+1))
  1140. def do_previous(self, *args):
  1141. """Go to previous item before current in index."""
  1142. self.lookup = self.index
  1143. return self.onecmd(str(self.index_index-1))
  1144. @needs_gi
  1145. def do_root(self, *args):
  1146. """Go to root selector of the server hosting current item."""
  1147. self._go_to_gi(self.gi.root())
  1148. def do_tour(self, line):
  1149. """Add index items as waypoints on a tour, which is basically a FIFO
  1150. queue of gemini items.
  1151. Items can be added with `tour 1 2 3 4` or ranges like `tour 1-4`.
  1152. All items in current menu can be added with `tour *`.
  1153. Current tour can be listed with `tour ls` and scrubbed with `tour clear`."""
  1154. line = line.strip()
  1155. if not line:
  1156. # Fly to next waypoint on tour
  1157. if not self.waypoints:
  1158. print("End of tour.")
  1159. else:
  1160. gi = self.waypoints.pop(0)
  1161. self._go_to_gi(gi)
  1162. elif line == "ls":
  1163. old_lookup = self.lookup
  1164. self.lookup = self.waypoints
  1165. self._show_lookup()
  1166. self.lookup = old_lookup
  1167. elif line == "clear":
  1168. self.waypoints = []
  1169. elif line == "*":
  1170. self.waypoints.extend(self.lookup)
  1171. elif looks_like_url(line):
  1172. self.waypoints.append(GeminiItem(line))
  1173. else:
  1174. for index in line.split():
  1175. try:
  1176. pair = index.split('-')
  1177. if len(pair) == 1:
  1178. # Just a single index
  1179. n = int(index)
  1180. gi = self.lookup[n-1]
  1181. self.waypoints.append(gi)
  1182. elif len(pair) == 2:
  1183. # Two endpoints for a range of indices
  1184. if int(pair[0]) < int(pair[1]):
  1185. for n in range(int(pair[0]), int(pair[1]) + 1):
  1186. gi = self.lookup[n-1]
  1187. self.waypoints.append(gi)
  1188. else:
  1189. for n in range(int(pair[0]), int(pair[1]) - 1, -1):
  1190. gi = self.lookup[n-1]
  1191. self.waypoints.append(gi)
  1192. else:
  1193. # Syntax error
  1194. print("Invalid use of range syntax %s, skipping" % index)
  1195. except ValueError:
  1196. print("Non-numeric index %s, skipping." % index)
  1197. except IndexError:
  1198. print("Invalid index %d, skipping." % n)
  1199. @needs_gi
  1200. def do_mark(self, line):
  1201. """Mark the current item with a single letter. This letter can then
  1202. be passed to the 'go' command to return to the current item later.
  1203. Think of it like marks in vi: 'mark a'='ma' and 'go a'=''a'."""
  1204. line = line.strip()
  1205. if not line:
  1206. for mark, gi in self.marks.items():
  1207. print("[%s] %s (%s)" % (mark, gi.name, gi.url))
  1208. elif line.isalpha() and len(line) == 1:
  1209. self.marks[line] = self.gi
  1210. else:
  1211. print("Invalid mark, must be one letter")
  1212. def do_version(self, line):
  1213. """Display version information."""
  1214. print("AV-98 " + _VERSION)
  1215. ### Stuff that modifies the lookup table
  1216. def do_ls(self, line):
  1217. """List contents of current index.
  1218. Use 'ls -l' to see URLs."""
  1219. self.lookup = self.index
  1220. self._show_lookup(url = "-l" in line)
  1221. self.page_index = 0
  1222. def do_gus(self, line):
  1223. """Submit a search query to the geminispace.info search engine."""
  1224. gus = GeminiItem("gemini://geminispace.info/search")
  1225. self._go_to_gi(gus.query(line))
  1226. def do_history(self, *args):
  1227. """Display history."""
  1228. self.lookup = self.history
  1229. self._show_lookup(url=True)
  1230. self.page_index = 0
  1231. def do_search(self, searchterm):
  1232. """Search index (case insensitive)."""
  1233. results = [
  1234. gi for gi in self.lookup if searchterm.lower() in gi.name.lower()]
  1235. if results:
  1236. self.lookup = results
  1237. self._show_lookup()
  1238. self.page_index = 0
  1239. else:
  1240. print("No results found.")
  1241. def emptyline(self):
  1242. """Page through index ten lines at a time."""
  1243. i = self.page_index
  1244. if i > len(self.lookup):
  1245. return
  1246. self._show_lookup(offset=i, end=i+10)
  1247. self.page_index += 10
  1248. ### Stuff that does something to most recently viewed item
  1249. @needs_gi
  1250. def do_cat(self, *args):
  1251. """Run most recently visited item through "cat" command."""
  1252. subprocess.call(shlex.split("cat %s" % self._get_active_tmpfile()))
  1253. @needs_gi
  1254. def do_less(self, *args):
  1255. """Run most recently visited item through "less" command."""
  1256. cmd_str = self._get_handler_cmd(self.mime)
  1257. cmd_str = cmd_str % self._get_active_tmpfile()
  1258. subprocess.call("%s | less -R" % cmd_str, shell=True)
  1259. @needs_gi
  1260. def do_fold(self, *args):
  1261. """Run most recently visited item through "fold" command."""
  1262. cmd_str = self._get_handler_cmd(self.mime)
  1263. cmd_str = cmd_str % self._get_active_tmpfile()
  1264. subprocess.call("%s | fold -w 70 -s" % cmd_str, shell=True)
  1265. @restricted
  1266. @needs_gi
  1267. def do_shell(self, line):
  1268. """'cat' most recently visited item through a shell pipeline."""
  1269. subprocess.call(("cat %s |" % self._get_active_tmpfile()) + line, shell=True)
  1270. @restricted
  1271. @needs_gi
  1272. def do_save(self, line):
  1273. """Save an item to the filesystem.
  1274. 'save n filename' saves menu item n to the specified filename.
  1275. 'save filename' saves the last viewed item to the specified filename.
  1276. 'save n' saves menu item n to an automagic filename."""
  1277. args = line.strip().split()
  1278. # First things first, figure out what our arguments are
  1279. if len(args) == 0:
  1280. # No arguments given at all
  1281. # Save current item, if there is one, to a file whose name is
  1282. # inferred from the gemini path
  1283. if not self.tmp_filename:
  1284. print("You need to visit an item first!")
  1285. return
  1286. else:
  1287. index = None
  1288. filename = None
  1289. elif len(args) == 1:
  1290. # One argument given
  1291. # If it's numeric, treat it as an index, and infer the filename
  1292. try:
  1293. index = int(args[0])
  1294. filename = None
  1295. # If it's not numeric, treat it as a filename and
  1296. # save the current item
  1297. except ValueError:
  1298. index = None
  1299. filename = os.path.expanduser(args[0])
  1300. elif len(args) == 2:
  1301. # Two arguments given
  1302. # Treat first as an index and second as filename
  1303. index, filename = args
  1304. try:
  1305. index = int(index)
  1306. except ValueError:
  1307. print("First argument is not a valid item index!")
  1308. return
  1309. filename = os.path.expanduser(filename)
  1310. else:
  1311. print("You must provide an index, a filename, or both.")
  1312. return
  1313. # Next, fetch the item to save, if it's not the current one.
  1314. if index:
  1315. last_gi = self.gi
  1316. try:
  1317. gi = self.lookup[index-1]
  1318. self._go_to_gi(gi, update_hist = False, handle = False)
  1319. except IndexError:
  1320. print ("Index too high!")
  1321. self.gi = last_gi
  1322. return
  1323. else:
  1324. gi = self.gi
  1325. # Derive filename from current GI's path, if one hasn't been set
  1326. if not filename:
  1327. filename = os.path.basename(gi.path)
  1328. # Check for filename collisions and actually do the save if safe
  1329. if os.path.exists(filename):
  1330. print("File %s already exists!" % filename)
  1331. else:
  1332. # Don't use _get_active_tmpfile() here, because we want to save the
  1333. # "source code" of menus, not the rendered view - this way AV-98
  1334. # can navigate to it later.
  1335. shutil.copyfile(self.tmp_filename, filename)
  1336. print("Saved to %s" % filename)
  1337. # Restore gi if necessary
  1338. if index != None:
  1339. self._go_to_gi(last_gi, handle=False)
  1340. @needs_gi
  1341. def do_url(self, *args):
  1342. """Print URL of most recently visited item."""
  1343. print(self.gi.url)
  1344. ### Bookmarking stuff
  1345. @restricted
  1346. @needs_gi
  1347. def do_add(self, line):
  1348. """Add the current URL to the bookmarks menu.
  1349. Optionally, specify the new name for the bookmark."""
  1350. with open(os.path.join(self.config_dir, "bookmarks.gmi"), "a") as fp:
  1351. fp.write(self.gi.to_map_line(line))
  1352. def do_bookmarks(self, line):
  1353. """Show or access the bookmarks menu.
  1354. 'bookmarks' shows all bookmarks.
  1355. 'bookmarks n' navigates immediately to item n in the bookmark menu.
  1356. Bookmarks are stored using the 'add' command."""
  1357. bm_file = os.path.join(self.config_dir, "bookmarks.gmi")
  1358. if not os.path.exists(bm_file):
  1359. print("You need to 'add' some bookmarks, first!")
  1360. return
  1361. args = line.strip()
  1362. if len(args.split()) > 1 or (args and not args.isnumeric()):
  1363. print("bookmarks command takes a single integer argument!")
  1364. return
  1365. with open(bm_file, "r") as fp:
  1366. body = fp.read()
  1367. gi = GeminiItem("localhost/" + bm_file)
  1368. self._handle_gemtext(body, gi, display = not args)
  1369. if args:
  1370. # Use argument as a numeric index
  1371. self.default(line)
  1372. ### Help
  1373. def do_help(self, arg):
  1374. """ALARM! Recursion detected! ALARM! Prepare to eject!"""
  1375. if arg == "!":
  1376. print("! is an alias for 'shell'")
  1377. elif arg == "?":
  1378. print("? is an alias for 'help'")
  1379. else:
  1380. cmd.Cmd.do_help(self, arg)
  1381. ### Flight recorder
  1382. def do_blackbox(self, *args):
  1383. """Display contents of flight recorder, showing statistics for the
  1384. current gemini browsing session."""
  1385. lines = []
  1386. # Compute flight time
  1387. now = time.time()
  1388. delta = now - self.log["start_time"]
  1389. hours, remainder = divmod(delta, 3600)
  1390. minutes, seconds = divmod(remainder, 60)
  1391. # Count hosts
  1392. ipv4_hosts = len([host for host in self.visited_hosts if host[0] == socket.AF_INET])
  1393. ipv6_hosts = len([host for host in self.visited_hosts if host[0] == socket.AF_INET6])
  1394. # Assemble lines
  1395. lines.append(("Patrol duration", "%02d:%02d:%02d" % (hours, minutes, seconds)))
  1396. lines.append(("Requests sent:", self.log["requests"]))
  1397. lines.append((" IPv4 requests:", self.log["ipv4_requests"]))
  1398. lines.append((" IPv6 requests:", self.log["ipv6_requests"]))
  1399. lines.append(("Bytes received:", self.log["bytes_recvd"]))
  1400. lines.append((" IPv4 bytes:", self.log["ipv4_bytes_recvd"]))
  1401. lines.append((" IPv6 bytes:", self.log["ipv6_bytes_recvd"]))
  1402. lines.append(("Unique hosts visited:", len(self.visited_hosts)))
  1403. lines.append((" IPv4 hosts:", ipv4_hosts))
  1404. lines.append((" IPv6 hosts:", ipv6_hosts))
  1405. lines.append(("DNS failures:", self.log["dns_failures"]))
  1406. lines.append(("Timeouts:", self.log["timeouts"]))
  1407. lines.append(("Refused connections:", self.log["refused_connections"]))
  1408. lines.append(("Reset connections:", self.log["reset_connections"]))
  1409. lines.append(("Cache hits:", self.log["cache_hits"]))
  1410. # Print
  1411. for key, value in lines:
  1412. print(key.ljust(24) + str(value).rjust(8))
  1413. ### The end!
  1414. def do_quit(self, *args):
  1415. """Exit AV-98."""
  1416. # Close TOFU DB
  1417. self.db_conn.commit()
  1418. self.db_conn.close()
  1419. # Clean up after ourself
  1420. self._empty_cache()
  1421. if self.tmp_filename and os.path.exists(self.tmp_filename):
  1422. os.unlink(self.tmp_filename)
  1423. if self.idx_filename and os.path.exists(self.idx_filename):
  1424. os.unlink(self.idx_filename)
  1425. for cert in self.transient_certs_created:
  1426. for ext in (".crt", ".key"):
  1427. certfile = os.path.join(self.config_dir, "transient_certs", cert+ext)
  1428. if os.path.exists(certfile):
  1429. os.remove(certfile)
  1430. print()
  1431. print("Thank you for flying AV-98!")
  1432. sys.exit()
  1433. do_exit = do_quit
  1434. # Main function
  1435. def main():
  1436. # Parse args
  1437. parser = argparse.ArgumentParser(description='A command line gemini client.')
  1438. parser.add_argument('--bookmarks', action='store_true',
  1439. help='start with your list of bookmarks')
  1440. parser.add_argument('--tls-cert', metavar='FILE', help='TLS client certificate file')
  1441. parser.add_argument('--tls-key', metavar='FILE', help='TLS client certificate private key file')
  1442. parser.add_argument('--restricted', action="store_true", help='Disallow shell, add, and save commands')
  1443. parser.add_argument('--version', action='store_true',
  1444. help='display version information and quit')
  1445. parser.add_argument('url', metavar='URL', nargs='*',
  1446. help='start with this URL')
  1447. args = parser.parse_args()
  1448. # Handle --version
  1449. if args.version:
  1450. print("AV-98 " + _VERSION)
  1451. sys.exit()
  1452. # Instantiate client
  1453. gc = GeminiClient(args.restricted)
  1454. # Process config file
  1455. rcfile = os.path.join(gc.config_dir, "av98rc")
  1456. if os.path.exists(rcfile):
  1457. print("Using config %s" % rcfile)
  1458. with open(rcfile, "r") as fp:
  1459. for line in fp:
  1460. line = line.strip()
  1461. if ((args.bookmarks or args.url) and
  1462. any((line.startswith(x) for x in ("go", "g", "tour", "t")))
  1463. ):
  1464. if args.bookmarks:
  1465. print("Skipping rc command \"%s\" due to --bookmarks option." % line)
  1466. else:
  1467. print("Skipping rc command \"%s\" due to provided URLs." % line)
  1468. continue
  1469. gc.cmdqueue.append(line)
  1470. # Say hi
  1471. print("Welcome to AV-98!")
  1472. if args.restricted:
  1473. print("Restricted mode engaged!")
  1474. print("Enjoy your patrol through Geminispace...")
  1475. # Act on args
  1476. if args.tls_cert:
  1477. # If tls_key is None, python will attempt to load the key from tls_cert.
  1478. gc._activate_client_cert(args.tls_cert, args.tls_key)
  1479. if args.bookmarks:
  1480. gc.cmdqueue.append("bookmarks")
  1481. elif args.url:
  1482. if len(args.url) == 1:
  1483. gc.cmdqueue.append("go %s" % args.url[0])
  1484. else:
  1485. for url in args.url:
  1486. if not url.startswith("gemini://"):
  1487. url = "gemini://" + url
  1488. gc.cmdqueue.append("tour %s" % url)
  1489. gc.cmdqueue.append("tour")
  1490. # Endless interpret loop
  1491. while True:
  1492. try:
  1493. gc.cmdloop()
  1494. except KeyboardInterrupt:
  1495. print("")
  1496. if __name__ == '__main__':
  1497. main()