Compare commits

..

78 Commits

Author SHA1 Message Date
Solderpunk 88daabe091 Overhaul TOFU checking code.
Main motivation for this was to switch from keying the cache cert
database off hostname + address to hostname + port.  While making
the necessary changes I refactored to reduce code duplication and
make the overall flow of the TOFU checks more transparent.

The check of whether the "previous certificate" has expired has
been changed from using the most frequently seen previous cert to
the most recently seen, which makes a *lot* more sense and is
arguably a bug fix.

The address column of the DB is now used only for reporting, but
the column is not maintained well, or rather, the semantics are
currently "address cert was first received from", and we may want
something less static?
2024-01-17 20:58:59 +01:00
Solderpunk fc056ef680 Merge pull request 'Print <META> string before user input' (#44) from continue/AV-98:master into master
Reviewed-on: solderpunk/AV-98#44
2024-01-17 17:44:05 +00:00
Aleksey Ryndin 6d489e6ab3 Print <META> string before user input 2024-01-04 18:58:54 +03:00
Solderpunk 4b06b23e2a Merge pull request 'Fix: ERROR: local variable 'certdir' referenced before assignment' (#43) from continue/AV-98:master into master
Reviewed-on: solderpunk/AV-98#43
2023-12-09 19:06:16 +00:00
Aleksey Ryndin bf0db27d6f Merge branch 'master' of tildegit.org:continue/AV-98 2023-12-07 17:49:25 +03:00
Alexey Ryndin 3361c79c1e Fix: ERROR: local variable 'certdir' referenced before assignment 2023-12-06 13:57:56 +03:00
Alexey Ryndin 474787dab7 Merge branch 'master' of tildegit.org:solderpunk/AV-98 2023-12-06 11:58:46 +03:00
Aleksey Ryndin fae71f5746 Merge branch 'master' of tildegit.org:solderpunk/AV-98 2023-12-06 09:08:42 +03:00
Solderpunk 854369afad Add a 'user' command, analogous to 'root' but jumps to a pubnix user's capsule if the URL starts with ~username. 2023-11-26 12:36:49 +01:00
Solderpunk 0e9953882c Don't treat filename collisions as fatal. 2023-11-26 12:17:42 +01:00
Solderpunk e96d373eec Fix bug with default response to Y/N prompts. 2023-11-26 12:12:19 +01:00
Solderpunk 0e91b4f894 Rename the gus command to search, and the old search to filter. Add option to set search endpoint. 2023-11-25 16:16:54 +01:00
Solderpunk 0268cd426b Further splitting up and renaming of files.
Now that everything lives in src/av98/ as per the latest Python
fashion, it's a problem to have a file named av98.py.  So split
it out into main.py (which just implements the argument parsing)
and client.py.  The old clientcerts.py has become certmanager.py
so that tab completion for client.py is quick and easy.
2023-11-25 16:12:46 +01:00
Solderpunk 4b759aec70 Add --output command line option for use with --download. 2023-11-25 13:08:36 +01:00
Solderpunk 48c8fd9543 Get on board with modern Python packaging conventions.
Remember when we used to make fun of Java people for sticking
everything in a `src/` directory?
2023-11-22 11:20:05 +01:00
Solderpunk 188cacca1f Restore coloured debug output, like we had before the logging module was adopted. 2023-11-19 16:49:07 +01:00
Solderpunk b46b15905b Prepare to cut 1.1.0. 2023-11-19 16:26:48 +01:00
Solderpunk 3abf44d18c Make the new --download option play nicely with --tls_cert and --tls_key. 2023-11-19 16:23:36 +01:00
Solderpunk 203ffaea90 Replace VF-1's flight-themed sign off with AV-98 policing-themed sign off. 2023-11-19 15:25:29 +01:00
Solderpunk cbbc410976 Add curl/wget style --download option. 2023-11-19 15:24:26 +01:00
Solderpunk 305f7f9f2c Make do_quit() silent, move the farewell message to main(). 2023-11-19 14:40:26 +01:00
Solderpunk 4df88896a8 Ensure we drive a useable filename for saving items whose URL does not provide one. 2023-11-19 14:38:55 +01:00
Solderpunk c8c12cab86 Don't trigger a traceback in debug mode for 4x or 5x status codes. 2023-11-19 14:35:13 +01:00
Solderpunk a0eedac532 Include temporary buffer file name in debug output. 2023-11-19 14:34:29 +01:00
Solderpunk a459e49fa0 Extract titles from gemtext and use them as GeminiItem.name if that's missing. 2023-11-19 14:27:47 +01:00
Solderpunk 0a9846b342 Correctly report downloaded file size in debug messages.
Previously, the return value of fp.write() was used, however for
text files this counts the number of characters written, not the
number of bytes, and for non-ASCII content these differ.
2023-11-19 12:29:48 +01:00
Solderpunk 9970f21e47 Move a little more clutter from av98.py into util.py. 2023-11-19 10:41:08 +01:00
Solderpunk 73ce79310d Reuse a consistent function for getting Y/N type user input. 2023-11-19 10:20:54 +01:00
Solderpunk 03b90fcd5e Put config dir discovery/creation in own method, store computed filename of bookmarks. 2023-11-18 19:28:15 +01:00
Solderpunk 62972c0228 Restore cert prompt functionality. 2023-11-18 19:27:42 +01:00
Solderpunk 0393ae3ea3 Correctly track domains which a client cert has been sent to. 2023-11-18 17:15:17 +01:00
Solderpunk 2a70985176 General tidy-up of entire av98.py file.
Most a matter of rearranging the order of methods to flow
sensibly, as well writing or updating docstrings, getting rid of
old unused return values, and fixing a few very minor defects.
2023-11-18 15:59:36 +01:00
Solderpunk 247f01e3e7 Update bookmarks to reflect permanent redirects upon exiting. 2023-11-18 14:23:56 +01:00
Solderpunk de7e5dc254 Factor out client certificate management into its own class/file. 2023-11-18 14:22:32 +01:00
Solderpunk 607223c25a Get real persnickety about nice option/blackbox alignment. 2023-11-17 20:08:48 +01:00
Solderpunk a9b34278a8 Don't hardcode black box spacing values. 2023-11-17 19:59:12 +01:00
Solderpunk 4f354ab291 Nicely align setting names and values. 2023-11-17 19:56:47 +01:00
Solderpunk bd7c5c2110 Log network errors a little more carefully. 2023-11-17 19:44:06 +01:00
Solderpunk 71f8a3dc86 Gracefully handle requests for file:// URLs which point at a directory. 2023-11-16 19:18:30 +01:00
Solderpunk 0ce09f37a6 Gracefully handle requests for file:// URLs where the file does not exist. 2023-11-16 19:14:22 +01:00
Solderpunk 681b11b8a4 Include local file and cached resource handling inside nice try/except error printing. 2023-11-16 19:13:20 +01:00
Solderpunk 91ff51a0ef Fix subtle breakage on some certs, when ssl_dnsname_match throws a non-CertificateError exception. 2023-11-15 19:47:17 +01:00
Solderpunk 50c43c75b4 Provider progress animation when downloading files > 100 KiB. 2023-11-15 19:46:01 +01:00
Solderpunk f78b6ff780 Move handling of permanent redirects inside of _fetch_over_network(). 2023-11-15 19:45:36 +01:00
Solderpunk 9e2cce7ce0 Print full tracebacks from exceptions when debugging is enabled. 2023-11-15 19:38:45 +01:00
Solderpunk 23b0597b6d Update email address and copyright years. 2023-11-15 19:38:13 +01:00
Solderpunk 67729fb711 Count redirects in black box recorder. 2023-11-15 18:40:48 +01:00
Solderpunk 480f2cc15f Rejig how do_bookmark() handles an argument to simplify go_to_gi(). 2023-11-15 18:29:52 +01:00
Solderpunk d2fe381c3e Change Cache to use a TemporaryDirectory for its storage to
ensure and simplify thorough cleanups upon shutdown.

Thanks to Ghost for making me aware of this possibility!
2023-11-15 18:21:11 +01:00
Solderpunk 048b04bed2 Extensively refactor the way temporary files are used.
Instead of littering /tmp with one file per download plus one per
rendered gemtext file, just reuse the same two files over and
over.  If enabled, caching creates separate copies.

Pretty sure this solves Issue #35, but I'll test and close that
after also improving the use of cache files...
2023-11-15 18:06:33 +01:00
Solderpunk 713616d556 Refactor of networking logic.
1. Move client certificate handling stuff inside of _send_request().
2. Change _fetch_over_network() to not be recursive, by just looping
   through calls to _send_request().  This facilitates moving the
   redirect-tracking state inside _fetch_over_network(), instead of
   keeping it in GeminiClient.
3. Also allow _fetch_over_network() to save response to a provided
   filename, and use this to implement do_save(), rather than
   _go_to_gi().  This avoids the need for awkward gymnastics with
   the internal state.
2023-11-14 19:40:40 +01:00
Solderpunk 01da844141 Pull response parsing inside of _send_request(). 2023-11-14 08:56:39 +01:00
Solderpunk 7f1aa5cbf3 Remove unused imports. 2023-11-14 00:38:00 +01:00
Solderpunk 33e66b439b Test for saveability against a fetched GI, not a tempfile. 2023-11-14 00:36:43 +01:00
Solderpunk d689cbd04f Fix _get_active_tmpfile to handle local file GIs. 2023-11-14 00:35:47 +01:00
Solderpunk 3aedd549e5 Remove unecessary duplication of handling code between _handle_gemtext() and _go_to_gi(). 2023-11-14 00:33:48 +01:00
Solderpunk e4a44679dc Fix saving of local files. 2023-11-14 00:29:59 +01:00
Solderpunk 588d599cb4 Add actual support for reading local files, use it for bookmarks. 2023-11-14 00:15:32 +01:00
Solderpunk c6886d7eb9 Don't clutter go_to_gi() with error logging. 2023-11-13 23:58:12 +01:00
Solderpunk cdb2b0282c Don't expose Cache object's trim method. 2023-11-13 20:24:54 +01:00
Solderpunk 053dcb7254 Factor out certificate validation into its own class/file. 2023-11-12 15:36:54 +01:00
Solderpunk 79a6187eac Restore debugging output from cache using logging module. 2023-11-12 15:14:05 +01:00
Solderpunk e678bca089 Factor out caching functionality into own class/file. 2023-11-12 14:49:01 +01:00
Solderpunk 87473fee1b Acknowledge contributors of recently merged PRs. 2023-11-12 14:19:23 +01:00
Solderpunk 522047a209 Merge pull request 'Pass extra information to _handle_cert_request' (#29) from govynnus/AV-98:fix-cert-request into master
Reviewed-on: solderpunk/AV-98#29
2023-11-12 10:37:28 +00:00
Solderpunk b9d0633f38 Merge pull request 'Add support for touring a range where the start index is bigger than the end index' (#25) from rmgr/AV-98:reverse-range into master
Reviewed-on: solderpunk/AV-98#25
2023-11-12 10:33:10 +00:00
Solderpunk 24b02327b0 Merge pull request 'Add support for http/https -> gemini proxy' (#24) from rmgr/AV-98:http into master
Reviewed-on: solderpunk/AV-98#24
2023-11-12 10:28:52 +00:00
Solderpunk d5666c9c19 Merge pull request 'Swap GUS for geminispace.info' (#36) from sario528/AV-98:search-fix into master
Reviewed-on: solderpunk/AV-98#36
2023-11-12 10:22:39 +00:00
Solderpunk a1cb220113 Merge pull request 'improve compatibility with Python 3.10' (#40) from nic/AV-98:master into master
Reviewed-on: solderpunk/AV-98#40
2023-11-12 10:18:29 +00:00
Solderpunk cb1cbfec85 Merge pull request 'Fix: ValueError if MIME is empty string (like a #20)' (#42) from continue/AV-98:fix-empty-mime into master
Reviewed-on: solderpunk/AV-98#42
2023-11-12 10:12:37 +00:00
Aleksey Ryndin d84872d23f Revert "Fix: input() UnicodeDecodeError tolerance"
This reverts commit 8f1642c9a1.
2023-09-06 23:08:27 +03:00
Aleksey Ryndin 8f1642c9a1 Fix: input() UnicodeDecodeError tolerance 2023-09-06 13:15:29 +03:00
Aleksey Ryndin 22c7efce7c Fix: ValueError if MIME is empty string (like a #20) 2023-08-27 16:49:36 +03:00
Nic Waller 6ee2a0716d improve compatibility with Python 3.10 2022-06-29 20:57:34 -07:00
sario528 5dfe62fc63
Swap GUS for geminispace.info 2021-04-15 05:04:58 -05:00
Callum Brown 92da876795 Pass extra information to _handle_cert_request
This fixes a bug introduced in f45630 when handling a certificate request was
factored out of _fetch_over_network.
Also make the options consistent in terms of grammar.
2021-01-03 11:07:22 +00:00
rmgr ab913ebf54 Add support for touring a range where the start index is bigger than the end index 2020-09-15 20:19:32 +09:30
rmgr 20395cb826 Add support for http/https -> gemini proxy 2020-09-15 20:02:29 +09:30
37 changed files with 2204 additions and 6533 deletions

343
CHANGELOG
View File

@ -1,343 +0,0 @@
# Offpunk History
## 2.3 - Unreleased
- Wayland clipboard support through wl-clipboard (new suggested dependency)
- Xclip clipborad support (in case xsel is missing)
- offpunk/netcache: fix IPv6 as an URL (bug #40)
- ansicat: display empty files (instead of opening them with xdg-open)
- fix escape sequence warning in python 3.12 (by Étienne Mollier) (Debian #1064209)
- ansicat : fix crash when feedparser is crashing on bad RSS
- netcache: fix spartan protocol error
- opnk: fix a crash when caching returns None
- ansicat: remove the treshold argument when launching chafa (strange artifacts with new version)
## 2.2 - February 13th 2023
- cache folder is now configurable through $OFFPUNK_CACHE_PATH environment variable (by prx)
- offpunk: adding an URL to a list now update the view mode if url already present
- netcache: solve an infinite gemini loop with code 6X (see also bug #31)
- ansicat: added support for <video> HTML-element
- ansicat: if chafa fails to load an image, fallback to timg if available
- offpunk: add list autocompletion to "tour"
- offpunk: removed "blackbox", which has not been used nor maintained
- offpunk: "gus" was broken, it is functionnal again
- opnk/offpunk: more informative prompt in less
- ansicat: added support for HTML description elements <dt> and <dd> (by Bert Livens)
- opnk: added "--mode" command-line argument (bug #39)
- offpunk: support for "preformatted" theming (bug #38)
- opnk/netcache: added "--cache-validity" command-line argument (bug #37)
- ansicat: consider files as XML, not SVG, if they dont have .svg extension
- offpunk: fix "view link" crashing with link to empty files
## 2.1 - December 15th 2023
- freshly updated gemtext/rss links are highlighted ("new_link" theme option)
- offpunk : new "copy title" and "copy link" function
- offpunk : new "view XX" feature where XX is a number to view information about a link
- ansicat: added "--mode" option
- redirections are now reflected in links and the cache (bug #28)
- ansicat: avoid a crash when urllib.parse.urljoin fails
- offpunk: Fix a crash when gus is called without parameters (Von Hohenheiden)
- ansicat: fixed a crash when parsing wrong hidden_url in gemini (bug #32)
- offpunk: offpunk --version doesnt create the cache anymore (bug #27)
- ansicat: fix a crash with HTML without title (bug #33)
- netcache: gemini socket code can crash when IPv6 is disabled (mailing-list)
## 2.0 - November 16th 2023
Changes since 1.10
- IMPORTANT: Licence has been changed to AGPL for ideological reasons
- IMPORTANT: Contact adress has been changed to offpunk2 on the same domain (because of spam)
- IMPORTANT: code has been splitted into several differents files.
- IMPORTANT: migrating from flit to hatchling (patch by Jean Abou Samra)
Major features:
- New command-line tool: "netcache"
- New command-line tool: "ansicat"
- New command-line tool: "opnk"
- "theme" command allows customization of the colours
- "--config-file" allows to start offpunk with custom config (#16)
- "view source" to view the source code of a page
- introduced the "default_protocol" options (default to gemini)
Improvments:
- Reading position is saved in less for the whole session
- Rendering is cached for the session, allowing faster browsing of a page already visited
- "redirect" supports domains starting with "*" to also block all subdomins
- "--images-mode" allow to choose at startup which images should be dowloaded (none,readable,full)
- Support for embedded multi-format rendering (such as RSS feeds with html elements)
- The cache is now automatically upgraded if needed (see .version in your cache)
- Images of html files are now downloaded with the html (slower sync but better reading experience)
- "--sync" can optionnaly take some lists as arguments, in order to make for specific sync
- initial tentative to support podcasts in RSS/Atom feeds
Other notable changes from 1.X:
- "accept_bad_ssl_certificates" now more agressive for http and really accepts them all
- Gopher-only: we dont support naming a page after the name of the incoming link
- Gemini-only: support for client generated certificates has been removed
- "file" is now marked as a dependency (thank Guillaume Loret)
## 2.0 (beta3 - final 2.0) - Released as 2.0
Changes since beta2:
- bug #25 : makes python-requests optional again
- --disable-http had no effect: reimplemented
- introduced the "default_protocol" options (default to gemini) to enter URLs without the :// part (fixes bug #21)
## 2.0-beta2 - November 8th 2023
Changes since beta1
- IMPORTANT: migrating from flit to hatchling (patch by Jean Abou Samra)
- "--sync" can optionnaly take some lists as arguments, in order to make for specific sync
- "view source" to view the source code of a page
- initial tentative to support podcasts in RSS/Atom feeds
- new PlaintextRenderer which display .txt files without any margin/color/linebreaks
- default URL blocked list is now its own file to make contributions easier
- prompt color is now part of the theme
- improves handling of base64 images
- fixes gophermap being considered as gemtext files
- fixes opening mailto links
- fixes existing non-html ressources marked a to_fetch even when not needed (simple and/or confusion)
- fixes a crash with RSSfeeds without <link> element
- fixes a crash with data:image/svg+xml links
- fixes a bug in HTML renderer where some hX element were not closed properly
- fixes input in Gemini while online
- fixes a crash with invalid URL
- fixes a crash while parsing invalid dates in RSS
- fixes hang/crash when meeting the ";" itemtype in gopher
- attempt at hiding XMLparsedAsHTMLWarning from BS4 library
- chafa now used by default everywhere if version > 1.10
- ignoring encoding error in ansicat
## 2.0-beta1 - September 05th 2023
This is an an experimental release. Bug reports and feedbacks are welcome on the offpunk-devel list.
- WARNING: pyproject.toml has not been updated and is currently non-functional. Help needed!
- IMPORTANT: Licence has been changed to AGPL for ideological reasons
- IMPORTANT: Contact adress has been changed to offpunk2 on the same domain (because of spam)
- IMPORTANT: code has been splitted into 7 differents files. Installation/packaging should be adapted.
Major features:
- New command-line tool: "netcache"
- New command-line tool: "ansicat"
- New command-line tool: "opnk"
- "theme" command allows customization of the colours
- "--config-file" allows to start offpunk with custom config (#16)
Improvments:
- Reading position is saved for the whole session
- Rendering is cached for the session, allowing faster browsing of a page already visited
- "redirect" supports domains starting with "*" to also block all subdomins
- "--images-mode" allow to choose at startup which images should be dowloaded (none,readable,full)
- Support for multi-format rendering (such as RSS feeds with html elements)
- The cache is now automatically upgraded if needed (see .version in your cache)
Other changes from 1.X:
- Images of html files are now downloaded with the html (slower sync but better reading experience)
- URL do not default anymore to "gemini://" if not protocol are indicated. (ongoing discussion in #21)
- "accept_bad_ssl_certificates" now more agressive for http and really accepts them all
- Gopher-only: we dont support naming a page after the name of the incoming link
- Gemini-only: support for client generated certificates has been removed
- "file" is now marked as a dependency (thank Guillaume Loret)
## 1.10 - July 31st 2023
- IMPORTANT : new optional dependency : python-chardet
- IMPORTANT : Gopher directory index filename changed from "index.txt" to "gophermap". To update the cache to the new format run the `migrate-offpunk-cache` script (Sotiris Papatheodorou)
- "set accept_bad_ssl_certificates True" now also used for Gemini expired certificates
- Add missing chardet module (Sotiris Papatheodorou)
- Fix merging dictionaries with common keys (Sotiris Papatheodorou)
- Fix Gopher requests (rewrite URL parsing code per RFC 4266)
## 1.9.2 - March 13th 2023
- Switch from setup.py to flit (Anna cybertailor Vyalkova)
- Bump requirements to python >= 3.7 (Anna cybertailor Vyalkova)
## 1.9.1 - March 8th 2023
- Fixed crash with archive without GI (thanks Étienne Mollier)
## 1.9 - March 8th 2023
This is a bug-fixing release.
- We now have a man page thanks to phoebos!
- ".." as abbreviation to "up" (by Sotiris Papatheodorou)
- Fix support for UTF-8 domains in Gemini (Maeve Sproule, fixes #5)
- Assume UTF-8 when the header answer with an unknown encoding
- Default handlers have been removed (not everybody use feh and zathura)
- Fix a crash when subscribing without GI (reported by sodimel on linuxfr)
- Fix a crash when trying to access a link without GI (Ben Winston)
- Fix a crash when rss items dont have a title (eg: Mastodon rss)
- Fix a crash with badly formatted links in gopher ( #7 by xiu)
- Fix a crash were some HTML content is seen a bytes instead of a string
- Fix a crash when displaying embedded CDATA html in feed. But #10 is still open.
- Fix error handling assuming that requests is installed
- Ugly fix for a rare certificate bug (fix #11)
- Improve compatibility with python prior 3.9 by replacing a dict union
## 1.8 - December 11th 2022
- Official URL is now https://sr.ht/~lioploum/offpunk/
- SECURITY: Avoid passing improperly-escaped paths to shell (fixes notabug #9) (by Maeve Sproule)
- Add support for the finger protocol (by Sotiris Papatheodorou)
- "restricted" mode has been removed because unmaintained (code cleanup)
- "set accept_bad_ssl_certificates True" allows to lower HTTPS SSL requirements (also with --assume-yes)
- Accept "localhost" as a valid URL
- Better feedback when --sync an URL which is streaming
- Removed cgi dependency (soon deprecated)
- Fix: crash with some svg data:image (which are now ignored)
- Fix images from "full" mode not being downloaded
- Fix a crash when ls on empty page (thanks Marty Oehme)
- Fix: A variable was not initialised without python-cryptography
- Fix: "cp raw" was not accessing the temp_file correctly
- Fix: ANSI handling off arrows in readline (by Ben Winston)
## 1.7.1 - November 15th 2022
- Correcting a stupid crash in search (thanks kelbot for the report)
## 1.7 - November 15th 2022
- New "search" command which uses kennedy.gemi.dev by default.
- New "wikipedia" command, which uses vault.transjovian.org by default.
- Aliases "wen", "wfr" and "wes" for Wikipedia in English, French and Spanish.
- Autocompletion for the list/add/move commands (thats incredibly useful!)
- If a link is found in plain text in a gopher/gemini page, it is now
added to the list of links for that page. Useful for gopher.
- Create system lists when needed to avoid failure on clean system
- Solve a crash when parsing wrong URL (related to bug #9 )
- Solve a crash when loading webpages with empty links
- Solve a crash when trying to load a wrong URL into tour
=> gemini://ploum.be/2022-11-15-offpunk17-sourcehut.gmi
## 1.6 - October 12th 2022
- Support for base64 encoded pictures in HTML pages (opening them full screen only works offline)
- A list can be added to a tour with "tour $LIST_NAME".
- Check for timg > 1.3.2 to avoid dealing with old versions (bug reported by Valvin)
- Redirect are now honoured also when --sync (bug #15, thanks kelbot)
- RSS feeds are now automatically downloaded with a webpage (bug #14)
- Solved the bug where an invalid URL would break correspondance between url and numbers
- Considers .xml files as feed by default to avoid false-detection as SVG
- Replaced default libreddit.com redirection to teddit.net (bug #12 by kelbot)
- The "beta" option has been removed as it is not used (update your config if needed)
## 1.5 - August 4th 2022
- Removed optional dependency to ripgrep. "grep --color=auto" is good enough.
- "open url" to open current URL in a browser with xdg-open
- "redirect" now replaces "set redirects" to improve discoverability
- "redirect" now allows urls to be blocked. By default, facebook.com and google-analytics.com are blocked
- Fixed a bug when trying to download base64 image
=> gemini://rawtext.club/~ploum/2022-08-04-offpunk15.gmi
## 1.4 - April 25th 2022
- Making python-readability optional
- Removing "next" and "previous" which are quite confusing and not obvious
- Archiving now works regardless of the view you are in.
- Fixing a crash when accessing an empty html page
- Not trying to display non-image files to avoid errors. (this requires "file")
## 1.3 - April 2th 2022
- Removed dependency to python-magic. File is now used directly (and should be on every system).
- Removed dependency to python-editor. If no $VISUAL or $EDITOR, please use "set editor" in Offpunk.
- Images are now downloaded before displaying an HTML page (can be disabled with "set download_images_first False")
- Introduced "set redirects" which redirects twitter,youtube,medium,reddit to alternative frontends.
- New behaviour for "find" (or "/") which is to grep through current page (ripgrep used if detected)
- Default width set to 80 as many gopherholes and gemini capsules have it hardcoded
- Streaming URL without valid content-length are now closed after 5Mo of download (thanks to Eoin Carney for reporting the issue)
- Gif animations are now displayed once when viewed (instead of a still frame).
- Restored some AV-98 certificate validation code that was lost Idont know how.
- Improved clarity of dependencies in "version"
- Fixed a crash when the cache is already a dir inside a dir.
- Fixed a crash when manually entering an unknown gopher URL while offline
- Fixed an error with older less version
- Fixed bookmarks not being automatically created at first "add"
- Call to shell commands has been refactorised to improve compatibility with python 3.6 (with testing from Pelle Nilsson)
- requirements.txt has been contributed by Toby Kurien. Thanks!
=> gemini://rawtext.club/~ploum/2022-04-02-offpunk13.gmi
## 1.2 - March 24th 2022
Very experimental release:
- Completely rewritten the HMTL, Gemtext and Gopher renderer. Tests needed!
- Removed dependancy to ansiwrap. We dont use it anymore (which is an important achievement)
- Lists are now accessed via the protocol "list://".
- "view full" can now be bookmarked/synchronized as a separate entity.
- "view normal" introduced to get back to the normal view.
Small improvements:
- Limit width of --sync output
- Solved list names becoming very long in the history
- Fixed a crash when trying to save a folder
=> gemini://rawtext.club/~ploum/2022-03-24-ansi_html.gmi
## 1.1 - March 18th 2022
- Perfect rendering of pictures with chafa 1.8+ and compatible terminal (Kitty)
- timg is supported as an alternative to chafa (with a little glitch)
- "cp cache" put the path of the cached content in clipboard
- "cp url X" will copy the URL of link X (suggested by Eoin Carney)
- "fold" has been removed as it doesnt work well and can be replaced with "!fold".
- Improved clipboard URL detection an fixed crash when binary in clipboard
- HTML: renderering of <pre> has been improved
- HTML: links in titles were previously missed
- Fixed crash when chafa is not installed (Thanks Xavier Hinault for the report)
- Fixed crash when python-readability not installed (Thanks Nic for the report)
- Fixed some gif not being displayed
- Fixed some URL being wronlgy interpreted as IPv6
## 1.0 - March 14th 2022
- Default width is now the standard 72
- Content and pictures now centered for more elegant reading
- "less" has been renamed "view"
- "view feed" and "view feeds" to see the first/all feeds on a HTML page
- "view full" has been improved by dropping inline CSSand JS.
- "up" can now take integer as argument to go up multiple steps.
- Fixed a crash when accessing links in list (thanks Matthieu Talbot for the report)
- Fixed a crash in "info" due to a typo in a variable name rarely accessed.
- Removed dependancy to python-xdg by implementing the logic (which saved lines of code!)
- python-pil is only needed if chafa < 1.10
=> gemini://rawtext.club/~ploum/2022-03-14-offpunk_and_cyberpunk.gmi
## 0.9 - March 05th 2022
- Initial Spartan protocol support
- Http links with content above 20Mo are not downloaded during sync (except when explicitely requested)
- Improving subscriptions with more feedback and better detection
- Avoid deprecated SSL methods (thanks Phoebos for the report)
- Links in to_fetch are fetched, no matter the cache
- Fixed multiple crashes
=> gemini://rawtext.club/~ploum/2022-03-05-offpunk09.gmi
## 0.4 - Feb 21st 2022
UPGRADE: Users who subscribed to pages before 0.4 should run once the command "list subscribe subscribed". Without that, the subscribed list will be seen as a normal list by sync.
- New list command : "list freeze" and "list suscribe"
- Pictures are now displayed directely in terminal (suggested by kelbot)
- "open" command to open current page/image/file with external handler.
- "set width XX" now works to set the max width. If smaller, terminal width is used (thanks kelbot for reporting the bug)
- RSS feeds are now rendered as Gemlogs to improve consistency while browsing
- "subscribe" will detect feeds in html pages if any
- "less" will restore previous position in a page (requires less 572+)
- Improved syncing performances and multiple bug/crash fixes.
- "version" will now display info about your system installation
- "info" command will display technical information about current page
- "sync" allows you to do the sync from within Offpunk
=> gemini://rawtext.club/~ploum/2022-02-21-offpunk04.gmi
## 0.3 - Feb 11th 2022
New Features:
- Gopher supported natively (early version, might have many bugs)
- support for RSS and Atom feed (you can subscribe to them)
- "less full" allows to see the full html page instead of only the article view
(also works with feeds to see descriptions of each post instead of a simple list)
- Option --depth to customize your sync. Be warned, more than 1 is crazy.
- Option --disable-http to allows deep syncing of gemini-only ressources
- Vastly improved HTML rendering with support for images (you need the binary "chafa" on your system)
Other Small Improvements:
- Disabled https_everywhere by default (caching problems and some websites not supporting it)
- Modified --sync logic to make it more intuitive (thanks Bjorn Westergard)
- Caching more problems to avoid refetch
- Offpunk has now an User-Agent when http browsing to avoid being blocked as a bot
- Changed XDG logic to improve compatibility (thanks Klaus Alexander)
=> gemini://rawtext.club/~ploum/2022-02-11-offpunk03.gmi
## 0.2 - Jan 31st 2022
- config directories have been moved to follow the XDG specifications
- support for http, https and mailto links (https_everywhere is enabled by default, see "set" command)
- support for HTML pages, rendered as articles
- Mutiple bookmarks lists and management of them through commands list, add, archive, move
- Subscriptions have been moved to a separate list with the subscribe command
- History is persistent and saved to disk
- Copy command allows to copy content or url into buffer
- Search as been renamed find, in the hope of implementing a real search in the future
- --fetch-later allows to mark a content to be fetched from other software.
- --assume-yes allows to choose the default answer to certificates warnings during --sync.
=> gemini://rawtext.club/~ploum/2022-01-31-offpunk02.gmi Announcing Offpunk 0.2
## 0.1 - Jan 3rd 2022
- initial release as an independant software from AV-98 (thanks solarpunk)
- Including contributions published by Bjorn on Notabug (thanks ew0k)
- less used by default for all content with custom options
- online/offline mode
- content is cached for offline use
- bookmarks are cached and subscribed through the --sync option
- tour is persistent and saved to disk
- reload while offline mark the content to be fetched during next --sync
=> gemini://rawtext.club/~ploum/2022-01-03-offpunk.gmi Announce of Offpunk 0.1

View File

@ -1,19 +0,0 @@
Offpunk Offline Gemini client
And the Offpunk tools suite: netcache, ansicat, opnk.
(C) From 2021: Ploum <offpunk2@ploum.eu>
Derived from AV-98 and Agena by Solderpunk,
(C) 2019, 2020: Solderpunk <solderpunk@sdf.org>
AV-98 received contributions from:
- danceka <hannu.hartikainen@gmail.com>
- <jprjr@tilde.club>
- <vee@vnsf.xyz>
- Klaus Alexander Seistrup <klaus@seistrup.dk>
- govynnus <govynnus@sdf.org>
- Björn Wärmedal <bjorn.warmedal@gmail.com>
- <jake@rmgr.dev>
Offpunk received contributions from:
- Maeve Sproule <code@sprock.dev>

683
LICENSE
View File

@ -1,664 +1,23 @@
GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 2007
Copyright (c) 2022, Ploum <offpunk2 at ploum.eu> and contributors.
Copyright (c) 2020, Solderpunk <solderpunk@sdf.org> and contributors.
All rights reserved.
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU Affero General Public License is a free, copyleft license for
software and other kinds of works, specifically designed to ensure
cooperation with the community in the case of network server software.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
our General Public Licenses are intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
Developers that use our General Public Licenses protect your rights
with two steps: (1) assert copyright on the software, and (2) offer
you this License which gives you legal permission to copy, distribute
and/or modify the software.
A secondary benefit of defending all users' freedom is that
improvements made in alternate versions of the program, if they
receive widespread use, become available for other developers to
incorporate. Many developers of free software are heartened and
encouraged by the resulting cooperation. However, in the case of
software used on network servers, this result may fail to come about.
The GNU General Public License permits making a modified version and
letting the public access it on a server without ever releasing its
source code to the public.
The GNU Affero General Public License is designed specifically to
ensure that, in such cases, the modified source code becomes available
to the community. It requires the operator of a network server to
provide the source code of the modified version running there to the
users of that server. Therefore, public use of a modified version, on
a publicly accessible server, gives the public access to the source
code of the modified version.
An older license, called the Affero General Public License and
published by Affero, was designed to accomplish similar goals. This is
a different license, not a version of the Affero GPL, but Affero has
released a new version of the Affero GPL which permits relicensing under
this license.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU Affero General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Remote Network Interaction; Use with the GNU General Public License.
Notwithstanding any other provision of this License, if you modify the
Program, your modified version must prominently offer all users
interacting with it remotely through a computer network (if your version
supports such interaction) an opportunity to receive the Corresponding
Source of your version by providing access to the Corresponding Source
from a network server at no charge, through some standard or customary
means of facilitating copying of software. This Corresponding Source
shall include the Corresponding Source for any work covered by version 3
of the GNU General Public License that is incorporated pursuant to the
following paragraph.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the work with which it is combined will remain governed by version
3 of the GNU General Public License.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU Affero General Public License from time to time. Such new versions
will be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU Affero General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU Affero General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU Affero General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If your software can interact with users remotely through a computer
network, you should also make sure that it provides a way for users to
get its source. For example, if your program is a web application, its
interface could display a "Source" link that leads users to an archive
of the code. There are many ways you could offer source, and different
solutions will be better for different programs; see section 13 for the
specific requirements.
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU AGPL, see
<https://www.gnu.org/licenses/>.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

165
README.md
View File

@ -1,133 +1,62 @@
# OFFPUNK
# AV-98
A command-line and offline-first smolnet browser/feed reader for Gemini, Gopher, Spartan and Web by [Ploum](https://ploum.net).
The goal of Offpunk is to be able to synchronise your content once (a day, a week, a month) and then browse/organise it while staying disconnected.
Official project page (repository/mailing lists) : https://sr.ht/~lioploum/offpunk/
![Screenshot HTML page with picture](screenshot_offpunk1.png)
![Screenshot Gemini page](screenshot_offpunk2.png)
Offpunk is a fork of the original [AV-98](https://tildegit.org/solderpunk/AV-98) by Solderpunk and was originally called AV-98-offline as an experimental branch.
## How to use
Offpunk is a set of python files. Installation is optional, you can simply git clone the project and run "./offpunk.py" or "python3 offpunk.py" in a terminal.
You use the `go` command to visit a URL, e.g. `go gemini.circumlunar.space`. (gemini:// is assumed if no protocol is specified. Supported protocols are gemini, gopher, finger, http, https, mailto, spartan and file. Default protocol is configurable).
Links in pages are assigned numerical indices. Just type an index to follow that link. If page is too long to fit on your screen, the content is displayed in the less pager. Type `q` to quit and go back to Offpunk prompt. Type `view` or `v` to display it again. (`view full` or `v full` allows to see the full html page instead of the article view. `v feed` try to display the linked RSS feed and `v feeds` displays a list of available feeds. This only applies to html pages. `v source` allows you to see the source code of a page and `v normal` to go back to normal view)
Use `add` to add a page to your bookmarks and `bookmarks` or `bm` to show your bookmarks (you can create multiple bookmarks lists, edit and remove them. See the `list` manual with `help list`).
Use `offline` to only browse cached content and `online` to go back online. While offline, the `reload` command will force a re-fetch during the next synchronisation.
Use the `help` command to learn about additional commands. Some abreviations are available. See `abbrevs`.
When launched with the "--sync" option, offpunk will run non-interactively and fetch content from your bookmarks, lists and ressources tentatively accessed while offline. New content found in your subscriptions (see `help subscribe`) will be automatically added to your tour (use `tour ls` to see your current tour, `tour` without argument to access the next item and `tour X` where X is a link number to add the content of a link to your tour).
With "--sync", one could specify a "--cache validity" in seconds. This option will not refresh content if a cache exists and is less than the specified amount of seconds old.
For example, running
`offpunk --sync --cache-validity 43200`
will refresh your bookmarks if those are at least 12h old. If cache-validity is not set or set to 0, any cache is considered good and only content never cached before will be fetched. `--assume-yes` will automatically accept SSL certificates with errors instead of refusing them.
Sync can be applied to only a subset of list.
`offpunk --sync bookmarks tour to_fetch --cache-validity 3600`
Offpunk can also be configured as a browser by other tool. If you want to use offpunk directly with a given URL, simply type:
`offpunk URL`
To have offpunk fetch the URL at next sync and close immediately, run:
`offpunk --fetch-later URL`
## More
Important news and releases will be announced on the offpunk-devel mailing list
=> https://lists.sr.ht/~lioploum/offpunk-devel
Questions can be asked on the users mailing list:
=> https://lists.sr.ht/~lioploum/offpunk-users
AV-98 is an experimental client for the
[Gemini protocol](https://gemini.circumlunar.space). It is derived from the
[gopher client VF-1](https://github.com/solderpunk/VF-1) by the same author.
AV-98 is "experimental" in the sense that it may occasionally extend or deviate
from the official Gemini specification for the purposes of, well,
experimentation. Despite this, it is expected to be stable enough for regular
daily use at the same time.
## Dependencies
Offpunk has few "strict dependencies", i.e. it should run and work without anything
else beyond the Python standard library and the "less" pager. However, it will "opportunistically
AV-98 has no "strict dependencies", i.e. it will run and work without anything
else beyond the Python standard library. However, it will "opportunistically
import" a few other libraries if they are available to offer an improved
experience or some other features such as HTTP/HTML or image support.
experience.
To avoid using unstable or too recent libraries, the rule of thumb is that a library should be packaged in Debian/Ubuntu. Keep in mind that Offpunk is mainly tested will all libraries installed. If you encounter a crash without one optional dependencies, please report it. Patches and contributions to remove dependencies or support alternatives are highly appreciated.
* [List of existing Offpunk packages (Repology)](https://repology.org/project/offpunk/versions)
* PIP: [requirements file to install dependencies with pip](requirements.txt)
* Ubuntu/Debian: [command to install dependencies on Ubuntu/Debian without pip](ubuntu_dependencies.txt)
* Please contribute packages for other systems, theres a [mailing-list dedicated to packaging](https://lists.sr.ht/~lioploum/offpunk-packagers).
Run command `version` in offpunk to see if you are missing some dependencies.
Mandatory or highly recommended (packagers should probably make those mandatory):
* [less](http://www.greenwoodsoftware.com/less/): mandatory but is probably already on your system
* [file](https://www.darwinsys.com/file/) is used to get the MIME type of cached objects. Should already be on your system.
* [xdg-utils](https://www.freedesktop.org/wiki/Software/xdg-utils/) provides xdg-open which is highly recommended to open files without a renderer or a handler. It is also used for mailto: command.
* The [cryptography library](https://pypi.org/project/cryptography/) will provide a better and slightly more secure experience when using the default TOFU certificate validation mode and is recommended (apt-get install python3-cryptography).
Dependencies to enable web browsing (packagers may put those in an offpunk-web meta-package but it is recommended to have it for a better offpunk experience)
* [Python-requests](http://python-requests.org) is needed to handle http/https requests natively (apt-get install python3-requests). Without it, http links will be opened in an external browser
* [BeautifulSoup4](https://www.crummy.com/software/BeautifulSoup) and [Readability](https://github.com/buriy/python-readability) are both needed to render HTML. Without them, HTML will not be rendered or be sent to an external parser like Lynx. (apt-get install python3-bs4 python3-readability or pip3 install readability-lxml)
* [Python-feedparser](https://github.com/kurtmckee/feedparser) will allow parsing of RSS/Atom feeds and thus subscriptions to them. (apt-get install python3-feedparser)
* [Chafa](https://hpjansson.org/chafa/) allows to display pictures in your console. Install it and browse to an HTML page with picture to see the magic.
Gopher dependencies:
* [Python-chardet](https://github.com/chardet/chardet) is used to detect the character encoding on Gopher (and may be used more in the future)
Older dependencies which are only needed on older systems (where chafa < 1.10)
* [Timg](https://github.com/hzeller/timg) is a slower alternative to chafa for inline images. Might be deprecated in the future.
* [Python-pil](http://python-pillow.github.io/) is required to only display the first frame of animated gif with chafa if chafa version is lower than 1.10. Might be deprecated in the future.
Nice to have (packagers should may make those optional):
* [Xsel](http://www.vergenet.net/~conrad/software/xsel/) allows to `go` to the URL copied in the clipboard without having to paste it (both X and traditional clipboards are supported). Also needed to use the `copy` command. (apt-get install xsel). Xclip can be used too.
* [Wl-clipboard](https://github.com/bugaevc/wl-clipboard) allows the same feature than xsel but under Wayland
* [Python-setproctitle](https://github.com/dvarrazzo/py-setproctitle) will change the process name from "python" to "offpunk". Useful to kill it without killing every python service.
* The [ansiwrap library](https://pypi.org/project/ansiwrap/) may result in
neater display of text which makes use of ANSI escape codes to control colour.
* The [cryptography library](https://pypi.org/project/cryptography/) will
provide a better and slightly more secure experience when using the default
TOFU certificate validation mode and is highly recommended.
## Features
* Browse https/gemini/gopher without leaving your keyboard and without distractions
* Customize your experience with the `theme` command.
* Built-in documentation: type `help` to get the list of command or a specific help about a command.
* Offline mode to browse cached content without a connection. Requested elements are automatically fetched during the next synchronization and are added to your tour.
* HTML pages are prettified to focus on content. Read without being disturbed or see the full page with `view full`.
* RSS/Atom feeds are automatically discovered by `subscribe` and rendered as gemlogs. They can be explored with `view feed` and `view feeds`.
* Support "subscriptions" to a page. New content seen in subscribed pages are automatically added to your next tour.
* Complex bookmarks management through multiple lists, built-in edition, subscribing/freezing lists and archiving content.
* Advanced navigation tools like `tour` and `mark` (as per VF-1). Unlike AV-98, tour is saved on disk accross sessions.
* Ability to specify external handler programs for different MIME types (use `handler`)
* Enhanced privacy with `redirect` which allows to block a http domain or to redirect all request to a privacy friendly frontent (such as nitter for twitter).
* Non-interactive cache-building with configurable depth through the --sync command. The cache can easily be used by other software.
* `netcache`, a standalone CLI tool to retrieve the cached version of a network ressource.
* `ansicat`, a standalone CLI tool to render HTML/Gemtext/image in a terminal.
* `opnk`, a standalone CLI tool to open any kind of ressources (local or network) and display it in your terminal or, if not possible, fallback to `xdg-open`.
* TOFU or CA server certificate validation
* Extensive client certificate support if an `openssl` binary is available
* Ability to specify external handler programs for different MIME types
* Gopher proxy support (e.g. for use with
[Agena](https://tildegit.org/solderpunk/agena))
* Advanced navigation tools like `tour` and `mark` (as per VF-1)
* Bookmarks
* IPv6 support
* Supports any character encoding recognised by Python
## Lightning introduction
You use the `go` command to visit a URL, e.g. `go gemini.circumlunar.space`.
Links in Gemini documents are assigned numerical indices. Just type an index to
follow that link.
If a Gemini document is too long to fit on your screen, use the `less` command
to pipe it to the `less` pager.
Use the `help` command to learn about additional commands.
## RC files
You can use an RC file to automatically run any sequence of valid Offpunk
You can use an RC file to automatically run any sequence of valid AV-98
commands upon start up. This can be used to make settings controlled with the
`set`, `handler` or `themes` commands persistent. You can also put a `go` command in
`set` or `handler` commanders persistent. You can also put a `go` command in
your RC file to visit a "homepage" automatically on startup, or to pre-prepare
a `tour` of your favourite Gemini sites or `offline` to go offline by default.
The RC file should be called `offpunkrc` and goes in $XDG_CONFIG_DIR/offpunk (or .config/offpunk or .offpunk if xdg not available). In that file, simply write one command per line, just like you would type them in offpunk.
## Cache design
The offline content is stored in ~/.cache/offpunk/ as plain .gmi/.html files. The structure of the Gemini-space is tentatively recreated. One key element of the design is to avoid any database. The cache can thus be modified by hand, content can be removed, used or added by software other than offpunk.
The cache can be accessed/built with the `netcache` tool. See `netcache -h` for more informations.
Theres no feature to automatically trim the cache. But any part of the cache can safely be removed manually as there are no databases or complex synchronisation.
a `tour` of your favourite Gemini sites.
The RC file should be called `av98rc`. AV-98 will look for it first in
`~/.av98/` and second in `~/.config/av98/`. Note that either directory might
already exist even if you haven't created it manually, as AV-98 will, if
necessary, create the directory itself the first time you save a bookmark (the
bookmark file is saved in the same location). AV-98 will create
`~/.config/av98` only if `~/.config/` already exists on your system, otherwise
it will create `~/.av98/`.

1520
ansicat.py

File diff suppressed because it is too large Load Diff

View File

@ -1,2 +0,0 @@
#!/bin/bash
XDG_DATA_HOME="~/debug/data" XDG_CONFIG_HOME="~/debug/config" XDG_CACHE_HOME="~/debug/cache" python offpunk.py

View File

View File

View File

@ -1,17 +0,0 @@
# OFFPUNK - An Offline-First Browser for the Smolnet
Offpunk is a command-line browser and feed reader dedicated to browsing the Web, Gemini, Gopher and Spartan. Thanks to its permanent cache, it is optimised to be used offline with rare connections but works as well when connected.
Offpunk is optimised for reading and supports readability mode, displaying pictures, subscribing to pages or RSS feeds, managing complex lists of bookmarks. Its integrated help and easy commands make it a perfect tool for command-line novices while power-users will be amazed by its shell integration.
Offpunk is written in Python 3 by Ploum. It aims to be portable and minimise dependencies, making them optional. It supports http/https/gopher/gemini/spartan on both IPv4 and IPv6.
=> install.gmi Installing Offpunk and dependencies
=> tutorial.gmi First steps
=> config.gmi Configuring Offpunk
=> offline.gmi Using Offpunk offline
=> lists.gmi Lists and subscriptions
=> shell.gmi Shell and OS integrations
=> dev.gmi Roadmap & Contributions

View File

View File

View File

View File

View File

View File

@ -1,74 +0,0 @@
.Dd August 27, 2023
.Dt ANSICAT 1
.Os
.
.Sh NAME
.Nm ansicat
.Nd terminal gemini gemtext renderer for offpunk
.
.Sh SYNOPSIS
.Nm
.Op Fl \-format Ar RENDERER
.Op Fl \-mime Ar MIME
.Op Fl \-url Ar URL ...
.Op Ar INPUT ...
.Nm
.Fl h | \-help
.
.Sh DESCRIPTION
Ansicat is the rendering engine of the browser
.Xr offpunk 1 .
It will render nicely on the terminal any gemtext,
html,
gopher,
and a few other formats.
.Pp
.Xr Offpunk 1
is a command-line browser and feed reader dedicated to browsing the Web,
Gemini, Gopher and Spartan.
.Ss Positional arguments
.Bl -tag -width Ds -offset indent
.It Ar INPUT
path to the text to render.
It defaults to the standard input.
.El
.Ss Keyword arguments
.Bl -tag -width Ds -offset indent
.It Fl h , \-help
show a help message and exit.
.It Fl \-format Ar RENDERER
renderer to use.
Available renderers are
.Ic auto ,
.Ic gemtext ,
.Ic html ,
.Ic feed ,
.Ic gopher ,
.Ic image ,
and
.Ic folder .
The
.Ic auto
renderer will heuristically guess the format,
either thanks to the MIME type,
or from the file being rendered itself.
.It Fl \-mime Ar MIME
MIME type of the content to parse.
.It Fl \-mode Ar MODE
MODE to use to render to choose between normal (default), full or source
.It Fl \-url Ar URL ...
original URL of the content.
.El
.
.Sh EXIT STATUS
.Ex -std
.
.Sh SEE ALSO
.Xr migrate-offpunk-cache 1 ,
.Xr netcache 1 ,
.Xr offpunk 1 ,
.Xr opnk 1 ,
.Lk https://sr.ht/~lioploum/offpunk/
.
.Sh AUTHORS
.An Lionel Dricot (Ploum) Aq Mt offpunk2 at ploum.eu

View File

@ -1,74 +0,0 @@
.Dd August 27, 2023
.Dt NETCACHE 1
.Os
.
.Sh NAME
.Nm netcache
.Nd local Internet cache handler for offpunk
.
.Sh SYNOPSIS
.Nm
.Op Fl \-path
.Op Fl \-offline
.Op Fl \-max\-size Ar MAX_SIZE
.Op Fl \-timeout Ar TIMEOUT
.Op Ar URL ...
.Nm
.Fl h | \-help
.
.Sh DESCRIPTION
Netcache is the download and cache management engine of the browser
.Xr offpunk 1 .
It allows one to fetch a link and get its content,
writing the content through the local cache for ulterior reference.
Netcache can be forced into offline mode,
in order to only fetch resources from the local cache,
otherwise it would always refresh it from the version available online.
It is also useful for mapping a given URL to its location in the cache,
independently of whether it has been downloaded first.
.Pp
Default cache path is
.Pa ~/.cache/offpunk .
Set
.Ev OFFPUNK_CACHE_PATH
environment variable to use another location.
.Bd -literal
OFFPUNK_CACHE_PATH=/home/ploum/custom-cache netcache.py gemini://some.url
.Ed
.Pp
.Xr Offpunk 1
is a command-line browser and feed reader dedicated to browsing the Web,
Gemini, Gopher and Spartan.
.Ss Positional arguments
.Bl -tag -width Ds -offset indent
.It Ar URL
download the URL and output the content.
.El
.Ss Keyword arguments
.Bl -tag -width Ds -offset indent
.It Fl h , \-help
show a help message and exit.
.It Fl \-path
output the path to the cache instead of the content of the URL.
.It Fl \-max-size Ar MAX_SIZE
cancel download of items above that size.
The value is expressed in megabytes.
.It Fl \-timeout Ar TIMEOUT
time to wait before cancelling connection.
The value is expressed in seconds.
.It Fl \-cache-validity CACHE_VALIDITY
Maximum age (in second) of the cached version before redownloading a new version.
.El
.
.Sh EXIT STATUS
.Ex -std
.
.Sh SEE ALSO
.Xr ansicat 1 ,
.Xr migrate-offpunk-cache 1 ,
.Xr offpunk 1 ,
.Xr opnk 1 ,
.Lk https://sr.ht/~lioploum/offpunk/
.
.Sh AUTHORS
.An Lionel Dricot (Ploum) Aq Mt offpunk2 at ploum.eu

View File

@ -1,93 +0,0 @@
.Dd March 3, 2023
.Dt OFFPUNK 1
.Os
.
.Sh NAME
.Nm offpunk
.Nd command line gemini client
.
.Sh SYNOPSIS
.Nm
.Op Fl \-bookmarks
.Op Fl \-tls\-cert Ar FILE
.Op Fl \-tls\-key Ar FILE
.Op Fl \-sync
.Op Fl \-assume\-yes
.Op Fl \-disable\-http
.Op Fl \-fetch\-later
.Op Fl \-depth Ar DEPTH
.Op Fl \-cache\-validity Ar CACHE_VALIDITY
.Op Ar URL ...
.Nm
.Fl h | \-help
.Nm
.Fl \-version
.Nm
.Fl \-features
.
.Sh DESCRIPTION
Offpunk is a command-line browser and feed reader dedicated to browsing the Web,
Gemini, Gopher and Spartan.
Thanks to its permanent cache, it is optimised to be used offline with rare
connections but works as well when connected.
.Pp
Offpunk is optimised for reading and supports readability mode, displaying
pictures, subscribing to pages or RSS feeds,
managing complex lists of bookmarks.
Its integrated help and easy commands make it a perfect tool for command-line
novices while power-users will be amazed by its shell integration.
.Ss Positional arguments
.Bl -tag -width Ds -offset indent
.It URL
start with this URL
.El
.Ss Keyword arguments
.Bl -tag -width Ds -offset indent
.It Fl h , \-help
Show a help message and exit
.It Fl \-bookmarks
start with your list of bookmarks
.It Fl \-tls\-cert Ar FILE
TLS client certificate file
.It Fl \-tls\-key Ar FILE
TLS client certificate private key file
.It Fl \-sync
run non\-interactively to build cache by exploring bookmarks
.It Fl \-assume\-yes
assume\-yes when asked questions about certificates/redirections during sync
(lower security)
.It Fl \-disable\-http
do not try to get http(s) links (but already cached will be displayed)
.It Fl \-fetch\-later
run non\-interactively with an URL as argument to fetch it later
.It Fl \-depth Ar DEPTH
depth of the cache to build.
Default is 1.
More is crazy.
Use at your own risks!
.It Fl \-cache\-validity Ar CACHE_VALIDITY
duration for which a cache is valid before sync (seconds)
.It Fl \-version
display version information and quit
.It Fl \-features
display available features and dependancies then quit
.El
.
.Sh EXIT STATUS
.Ex -std
.
.Sh SEE ALSO
.Xr ansicat 1 ,
.Xr migrate-offpunk-cache 1 ,
.Xr netcache 1 ,
.Xr opnk 1 ,
.Lk https://sr.ht/~lioploum/offpunk/
.
.Sh HISTORY
.Nm
is a fork of the original AV-98 by
.An Solderpunk
and was originally called AV-98-offline as an experimental branch.
.
.Sh AUTHORS
.An Lionel Dricot (Ploum) Aq Mt offpunk2 at ploum.eu

View File

@ -1,57 +0,0 @@
.Dd August 27, 2023
.Dt OPNK 1
.Os
.
.Sh NAME
.Nm opnk
.Nd universal open (like a punk) for offpunk
.
.Sh SYNOPSIS
.Nm
.Op Ar INPUT ...
.Nm
.Fl h | \-help
.
.Sh DESCRIPTION
Opnk is the "universal open (like a punk)".
Opnk is a tool that will try to render any file or URL in the terminal,
using
.Xr netcache 1
and
.Xr ansicat 1 ,
and put them in
.Xr less 1 .
If that doesnt work,
it will fallback to
.Xr xdg-open 1 .
.Pp
.Xr Offpunk 1
is a command-line browser and feed reader dedicated to browsing the Web,
Gemini, Gopher and Spartan.
.Ss Positional arguments
.Bl -tag -width Ds -offset indent
.It Ar INPUT
path to the file or URL to open.
.El
.Ss Keyword arguments
.Bl -tag -width Ds -offset indent
.It Fl h , \-help
Show a help message and exit
.It Fl \-mode Ar MODE
MODE to use to render to choose between normal (default), full or source
.It Fl \-cache-validity CACHE_VALIDITY
Maximum age (in second) of the cached version before redownloading a new version.
.El
.
.Sh EXIT STATUS
.Ex -std
.
.Sh SEE ALSO
.Xr ansicat 1 ,
.Xr migrate-offpunk-cache 1 ,
.Xr netcache 1 ,
.Xr offpunk 1 ,
.Lk https://sr.ht/~lioploum/offpunk/
.
.Sh AUTHORS
.An Lionel Dricot (Ploum) Aq Mt offpunk2 at ploum.eu

View File

@ -1,913 +0,0 @@
#!/usr/bin/env python3
import os
import sys
import urllib.parse
import argparse
import codecs
import getpass
import socket
import ssl
import glob
import datetime
import hashlib
import sqlite3
from ssl import CertificateError
import ansicat
import offutils
from offutils import xdg
import time
try:
import chardet
_HAS_CHARDET = True
except ModuleNotFoundError:
_HAS_CHARDET = False
try:
from cryptography import x509
from cryptography.hazmat.backends import default_backend
_HAS_CRYPTOGRAPHY = True
_BACKEND = default_backend()
except(ModuleNotFoundError,ImportError):
_HAS_CRYPTOGRAPHY = False
try:
import requests
_DO_HTTP = True
except (ModuleNotFoundError,ImportError):
_DO_HTTP = False
# This list is also used as a list of supported protocols
standard_ports = {
"gemini" : 1965,
"gopher" : 70,
"finger" : 79,
"http" : 80,
"https" : 443,
"spartan": 300,
}
default_protocol = "gemini"
CRLF = '\r\n'
DEFAULT_TIMEOUT = 10
_MAX_REDIRECTS = 5
# monkey-patch Gemini support in urllib.parse
# see https://github.com/python/cpython/blob/master/Lib/urllib/parse.py
urllib.parse.uses_relative.append("gemini")
urllib.parse.uses_netloc.append("gemini")
urllib.parse.uses_relative.append("spartan")
urllib.parse.uses_netloc.append("spartan")
class UserAbortException(Exception):
pass
def parse_mime(mime):
options = {}
if mime:
if ";" in mime:
splited = mime.split(";",maxsplit=1)
mime = splited[0]
if len(splited) >= 1:
options_list = splited[1].split()
for o in options_list:
spl = o.split("=",maxsplit=1)
if len(spl) > 0:
options[spl[0]] = spl[1]
return mime, options
def normalize_url(url):
if "://" not in url and ("./" not in url and url[0] != "/"):
if not url.startswith("mailto:"):
url = "gemini://" + url
return url
def cache_last_modified(url):
if not url:
return None
path = get_cache_path(url)
if path and os.path.isfile(path):
return os.path.getmtime(path)
else:
return None
def is_cache_valid(url,validity=0):
# Validity is the acceptable time for
# a cache to be valid (in seconds)
# If 0, then any cache is considered as valid
# (use validity = 1 if you want to refresh everything)
if offutils.is_local(url):
return True
cache = get_cache_path(url)
if cache :
# If path is too long, we always return True to avoid
# fetching it.
if len(cache) > 259:
print("We return False because path is too long")
return False
if os.path.exists(cache) and not os.path.isdir(cache):
if validity > 0 :
last_modification = cache_last_modified(url)
now = time.time()
age = now - last_modification
return age < validity
else:
return True
else:
#Cache has not been build
return False
else:
#Theres not even a cache!
return False
def get_cache_path(url,add_index=True):
# Sometimes, cache_path became a folder! (which happens for index.html/index.gmi)
# In that case, we need to reconstruct it
# if add_index=False, we dont add that "index.gmi" at the ends of the cache_path
#First, we parse the URL
if not url:
return None
parsed = urllib.parse.urlparse(url)
if url[0] == "/" or url.startswith("./") or os.path.exists(url):
scheme = "file"
elif parsed.scheme:
scheme = parsed.scheme
else:
scheme = default_protocol
if scheme in ["file","mailto","list"]:
local = True
host = ""
port = None
# file:// is 7 char
if url.startswith("file://"):
path = url[7:]
elif scheme == "mailto":
path = parsed.path
elif url.startswith("list://"):
listdir = os.path.join(xdg("data"),"lists")
listname = url[7:].lstrip("/")
if listname in [""]:
name = "My Lists"
path = listdir
else:
name = listname
path = os.path.join(listdir, "%s.gmi"%listname)
else:
path = url
else:
local = False
# Convert unicode hostname to punycode using idna RFC3490
host = parsed.hostname #.encode("idna").decode()
port = parsed.port or standard_ports.get(scheme, 0)
# special gopher selector case
if scheme == "gopher":
if len(parsed.path) >= 2:
itemtype = parsed.path[1]
path = parsed.path[2:]
else:
itemtype = "1"
path = ""
if itemtype == "0":
mime = "text/gemini"
elif itemtype == "1":
mime = "text/gopher"
elif itemtype == "h":
mime = "text/html"
elif itemtype in ("9","g","I","s",";"):
mime = "binary"
else:
mime = "text/gopher"
else:
path = parsed.path
if parsed.query:
# we dont add the query if path is too long because path above 260 char
# are not supported and crash python.
# Also, very long query are usually useless stuff
if len(path+parsed.query) < 258:
path += "/" + parsed.query
# Now, we have a partial path. Lets make it full path.
if local:
cache_path = path
elif scheme and host:
cache_path = os.path.expanduser(xdg("cache") + scheme + "/" + host + path)
#Theres an OSlimitation of 260 characters per path.
#We will thus cut the path enough to add the index afterward
cache_path = cache_path[:249]
# this is a gross hack to give a name to
# index files. This will break if the index is not
# index.gmi. I dont know how to know the real name
# of the file. But first, we need to ensure that the domain name
# finish by "/". Else, the cache will create a file, not a folder.
if scheme.startswith("http"):
index = "index.html"
elif scheme == "finger":
index = "index.txt"
elif scheme == "gopher":
index = "gophermap"
else:
index = "index.gmi"
if path == "" or os.path.isdir(cache_path):
if not cache_path.endswith("/"):
cache_path += "/"
if not url.endswith("/"):
url += "/"
if add_index and cache_path.endswith("/"):
cache_path += index
#sometimes, the index itself is a dir
#like when folder/index.gmi?param has been created
#and we try to access folder
if add_index and os.path.isdir(cache_path):
cache_path += "/" + index
else:
#URL is missing either a supported scheme or a valid host
#print("Error: %s is not a supported url"%url)
return None
if len(cache_path) > 259:
print("Path is too long. This is an OS limitation.\n\n")
print(url)
return None
return cache_path
def write_body(url,body,mime=None):
## body is a copy of the raw gemtext
## Write_body() also create the cache !
#DEFAULT GEMINIMIME
mime, options = parse_mime(mime)
cache_path = get_cache_path(url)
if cache_path:
if mime and mime.startswith("text/"):
mode = "w"
else:
mode = "wb"
cache_dir = os.path.dirname(cache_path)
# If the subdirectory already exists as a file (not a folder)
# We remove it (happens when accessing URL/subfolder before
# URL/subfolder/file.gmi.
# This causes loss of data in the cache
# proper solution would be to save "sufolder" as "sufolder/index.gmi"
# If the subdirectory doesnt exist, we recursively try to find one
# until it exists to avoid a file blocking the creation of folders
root_dir = cache_dir
while not os.path.exists(root_dir):
root_dir = os.path.dirname(root_dir)
if os.path.isfile(root_dir):
os.remove(root_dir)
os.makedirs(cache_dir,exist_ok=True)
with open(cache_path, mode=mode) as f:
f.write(body)
f.close()
return cache_path
def set_error(url,err):
# If we get an error, we want to keep an existing cache
# but we need to touch it or to create an empty one
# to avoid hitting the error at each refresh
cache = get_cache_path(url)
if is_cache_valid(url):
os.utime(cache)
elif cache:
cache_dir = os.path.dirname(cache)
root_dir = cache_dir
while not os.path.exists(root_dir):
root_dir = os.path.dirname(root_dir)
if os.path.isfile(root_dir):
os.remove(root_dir)
os.makedirs(cache_dir,exist_ok=True)
if os.path.isdir(cache_dir):
with open(cache, "w") as c:
c.write(str(datetime.datetime.now())+"\n")
c.write("ERROR while caching %s\n\n" %url)
c.write("*****\n\n")
c.write(str(type(err)) + " = " + str(err))
#cache.write("\n" + str(err.with_traceback(None)))
c.write("\n*****\n\n")
c.write("If you believe this error was temporary, type ""reload"".\n")
c.write("The ressource will be tentatively fetched during next sync.\n")
c.close()
return cache
def _fetch_http(url,max_size=None,timeout=DEFAULT_TIMEOUT,accept_bad_ssl_certificates=False,**kwargs):
if not _DO_HTTP: return None
def too_large_error(url,length,max_size):
err = "Size of %s is %s Mo\n"%(url,length)
err += "Offpunk only download automatically content under %s Mo\n" %(max_size/1000000)
err += "To retrieve this content anyway, type 'reload'."
return set_error(url,err)
if accept_bad_ssl_certificates:
requests.packages.urllib3.util.ssl_.DEFAULT_CIPHERS = 'ALL:@SECLEVEL=1'
requests.packages.urllib3.disable_warnings()
verify=False
else:
requests.packages.urllib3.util.ssl_.DEFAULT_CIPHERS = 'ALL:@SECLEVEL=2'
verify=True
header = {}
header["User-Agent"] = "Netcache"
with requests.get(url,verify=verify,headers=header, stream=True,timeout=DEFAULT_TIMEOUT) as response:
if "content-type" in response.headers:
mime = response.headers['content-type']
else:
mime = None
if "content-length" in response.headers:
length = int(response.headers['content-length'])
else:
length = 0
if max_size and length > max_size:
response.close()
return too_large_error(url,str(length/100),max_size)
elif max_size and length == 0:
body = b''
downloaded = 0
for r in response.iter_content():
body += r
#We divide max_size for streamed content
#in order to catch them faster
size = sys.getsizeof(body)
max = max_size/2
current = round(size*100/max,1)
if current > downloaded:
downloaded = current
print(" -> Receiving stream: %s%% of allowed data"%downloaded,end='\r')
#print("size: %s (%s\% of maxlenght)"%(size,size/max_size))
if size > max_size/2:
response.close()
return too_large_error(url,"streaming",max_size)
response.close()
else:
body = response.content
response.close()
if mime and "text/" in mime:
body = body.decode("UTF-8","replace")
cache = write_body(url,body,mime)
return cache
def _fetch_gopher(url,timeout=DEFAULT_TIMEOUT,**kwargs):
parsed =urllib.parse.urlparse(url)
host = parsed.hostname
port = parsed.port or 70
if len(parsed.path) >= 2:
itemtype = parsed.path[1]
selector = parsed.path[2:]
else:
itemtype = "1"
selector = ""
addresses = socket.getaddrinfo(host, port, family=0,type=socket.SOCK_STREAM)
s = socket.create_connection((host,port))
for address in addresses:
s = socket.socket(address[0], address[1])
s.settimeout(timeout)
try:
s.connect(address[4])
break
except OSError as e:
err = e
if parsed.query:
request = selector + "\t" + parsed.query
else:
request = selector
request += "\r\n"
s.sendall(request.encode("UTF-8"))
response1 = s.makefile("rb")
response = response1.read()
# Transcode response into UTF-8
#if itemtype in ("0","1","h"):
if not itemtype in ("9","g","I","s",";"):
# Try most common encodings
for encoding in ("UTF-8", "ISO-8859-1"):
try:
response = response.decode("UTF-8")
break
except UnicodeDecodeError:
pass
else:
# try to find encoding
if _HAS_CHARDET:
detected = chardet.detect(response)
response = response.decode(detected["encoding"])
else:
raise UnicodeDecodeError
if itemtype == "0":
mime = "text/gemini"
elif itemtype == "1":
mime = "text/gopher"
elif itemtype == "h":
mime = "text/html"
elif itemtype in ("9","g","I","s",";"):
mime = None
else:
# by default, we should consider Gopher
mime = "text/gopher"
cache = write_body(url,response,mime)
return cache
def _fetch_finger(url,timeout=DEFAULT_TIMEOUT,**kwargs):
parsed = urllib.parse.urlparse(url)
host = parsed.hostname
port = parsed.port or standard_ports["finger"]
query = parsed.path.lstrip("/") + "\r\n"
with socket.create_connection((host,port)) as sock:
sock.settimeout(timeout)
sock.send(query.encode())
response = sock.makefile("rb").read().decode("UTF-8")
cache = write_body(response,"text/plain")
return cache
# Originally copied from reference spartan client by Michael Lazar
def _fetch_spartan(url,**kwargs):
cache = None
url_parts = urllib.parse.urlparse(url)
host = url_parts.hostname
port = url_parts.port or standard_ports["spartan"]
path = url_parts.path or "/"
query = url_parts.query
redirect_url = None
with socket.create_connection((host,port)) as sock:
if query:
data = urllib.parse.unquote_to_bytes(query)
else:
data = b""
encoded_host = host.encode("idna")
ascii_path = urllib.parse.unquote_to_bytes(path)
encoded_path = urllib.parse.quote_from_bytes(ascii_path).encode("ascii")
sock.send(b"%s %s %d\r\n" % (encoded_host,encoded_path,len(data)))
fp = sock.makefile("rb")
response = fp.readline(4096).decode("ascii").strip("\r\n")
parts = response.split(" ",maxsplit=1)
code,meta = int(parts[0]),parts[1]
if code == 2:
body = fp.read()
if meta.startswith("text"):
body = body.decode("UTF-8")
cache = write_body(url,body,meta)
elif code == 3:
redirect_url = url_parts._replace(path=meta).geturl()
else:
return set_error(url,"Spartan code %s: Error %s"%(code,meta))
if redirect_url:
cache = _fetch_spartan(redirect_url)
return cache
def _validate_cert(address, host, cert,accept_bad_ssl=False,automatic_choice=None):
"""
Validate a TLS certificate in TOFU mode.
If the cryptography module is installed:
- Check the certificate Common Name or SAN matches `host`
- Check the certificate's not valid before date is in the past
- Check the certificate's not valid after date is in the future
Whether the cryptography module is installed or not, check the
certificate's fingerprint against the TOFU database to see if we've
previously encountered a different certificate for this IP address and
hostname.
"""
now = datetime.datetime.utcnow()
if _HAS_CRYPTOGRAPHY:
# Using the cryptography module we can get detailed access
# to the properties of even self-signed certs, unlike in
# the standard ssl library...
c = x509.load_der_x509_certificate(cert, _BACKEND)
# Check certificate validity dates
if accept_bad_ssl:
if c.not_valid_before >= now:
raise CertificateError("Certificate not valid until: {}!".format(c.not_valid_before))
elif c.not_valid_after <= now:
raise CertificateError("Certificate expired as of: {})!".format(c.not_valid_after))
# Check certificate hostnames
names = []
common_name = c.subject.get_attributes_for_oid(x509.oid.NameOID.COMMON_NAME)
if common_name:
names.append(common_name[0].value)
try:
names.extend([alt.value for alt in c.extensions.get_extension_for_oid(x509.oid.ExtensionOID.SUBJECT_ALTERNATIVE_NAME).value])
except x509.ExtensionNotFound:
pass
names = set(names)
for name in names:
try:
ssl._dnsname_match(str(name), host)
break
except CertificateError:
continue
else:
# If we didn't break out, none of the names were valid
raise CertificateError("Hostname does not match certificate common name or any alternative names.")
sha = hashlib.sha256()
sha.update(cert)
fingerprint = sha.hexdigest()
db_path = os.path.join(xdg("config"), "tofu.db")
db_conn = sqlite3.connect(db_path)
db_cur = db_conn.cursor()
db_cur.execute("""CREATE TABLE IF NOT EXISTS cert_cache
(hostname text, address text, fingerprint text,
first_seen date, last_seen date, count integer)""")
# Have we been here before?
db_cur.execute("""SELECT fingerprint, first_seen, last_seen, count
FROM cert_cache
WHERE hostname=? AND address=?""", (host, address))
cached_certs = db_cur.fetchall()
# If so, check for a match
if cached_certs:
max_count = 0
most_frequent_cert = None
for cached_fingerprint, first, last, count in cached_certs:
if count > max_count:
max_count = count
most_frequent_cert = cached_fingerprint
if fingerprint == cached_fingerprint:
# Matched!
db_cur.execute("""UPDATE cert_cache
SET last_seen=?, count=?
WHERE hostname=? AND address=? AND fingerprint=?""",
(now, count+1, host, address, fingerprint))
db_conn.commit()
break
else:
certdir = os.path.join(xdg("config"), "cert_cache")
with open(os.path.join(certdir, most_frequent_cert+".crt"), "rb") as fp:
previous_cert = fp.read()
if _HAS_CRYPTOGRAPHY:
# Load the most frequently seen certificate to see if it has
# expired
previous_cert = x509.load_der_x509_certificate(previous_cert, _BACKEND)
previous_ttl = previous_cert.not_valid_after - now
print(previous_ttl)
print("****************************************")
print("[SECURITY WARNING] Unrecognised certificate!")
print("The certificate presented for {} ({}) has never been seen before.".format(host, address))
print("This MIGHT be a Man-in-the-Middle attack.")
print("A different certificate has previously been seen {} times.".format(max_count))
if _HAS_CRYPTOGRAPHY:
if previous_ttl < datetime.timedelta():
print("That certificate has expired, which reduces suspicion somewhat.")
else:
print("That certificate is still valid for: {}".format(previous_ttl))
print("****************************************")
print("Attempt to verify the new certificate fingerprint out-of-band:")
print(fingerprint)
if automatic_choice:
choice = automatic_choice
else:
choice = input("Accept this new certificate? Y/N ").strip().lower()
if choice in ("y", "yes"):
db_cur.execute("""INSERT INTO cert_cache
VALUES (?, ?, ?, ?, ?, ?)""",
(host, address, fingerprint, now, now, 1))
db_conn.commit()
with open(os.path.join(certdir, fingerprint+".crt"), "wb") as fp:
fp.write(cert)
else:
raise Exception("TOFU Failure!")
# If not, cache this cert
else:
db_cur.execute("""INSERT INTO cert_cache
VALUES (?, ?, ?, ?, ?, ?)""",
(host, address, fingerprint, now, now, 1))
db_conn.commit()
certdir = os.path.join(xdg("config"), "cert_cache")
if not os.path.exists(certdir):
os.makedirs(certdir)
with open(os.path.join(certdir, fingerprint+".crt"), "wb") as fp:
fp.write(cert)
def _fetch_gemini(url,timeout=DEFAULT_TIMEOUT,interactive=True,accept_bad_ssl_certificates=False,\
**kwargs):
cache = None
newurl = url
url_parts = urllib.parse.urlparse(url)
host = url_parts.hostname
port = url_parts.port or standard_ports["gemini"]
path = url_parts.path or "/"
query = url_parts.query
# In AV-98, this was the _send_request method
#Send a selector to a given host and port.
#Returns the resolved address and binary file with the reply."""
host = host.encode("idna").decode()
# Do DNS resolution
# DNS lookup - will get IPv4 and IPv6 records if IPv6 is enabled
if ":" in host:
# This is likely a literal IPv6 address, so we can *only* ask for
# IPv6 addresses or getaddrinfo will complain
family_mask = socket.AF_INET6
elif socket.has_ipv6:
# Accept either IPv4 or IPv6 addresses
family_mask = 0
else:
# IPv4 only
family_mask = socket.AF_INET
addresses = socket.getaddrinfo(host, port, family=family_mask,
type=socket.SOCK_STREAM)
# Sort addresses so IPv6 ones come first
addresses.sort(key=lambda add: add[0] == socket.AF_INET6, reverse=True)
## Continuation of send_request
# Prepare TLS context
protocol = ssl.PROTOCOL_TLS_CLIENT if sys.version_info.minor >=6 else ssl.PROTOCOL_TLSv1_2
context = ssl.SSLContext(protocol)
context.check_hostname=False
context.verify_mode = ssl.CERT_NONE
# Impose minimum TLS version
## In 3.7 and above, this is easy...
if sys.version_info.minor >= 7:
context.minimum_version = ssl.TLSVersion.TLSv1_2
## Otherwise, it seems very hard...
## The below is less strict than it ought to be, but trying to disable
## TLS v1.1 here using ssl.OP_NO_TLSv1_1 produces unexpected failures
## with recent versions of OpenSSL. What a mess...
else:
context.options |= ssl.OP_NO_SSLv3
context.options |= ssl.OP_NO_SSLv2
# Try to enforce sensible ciphers
try:
context.set_ciphers("AESGCM+ECDHE:AESGCM+DHE:CHACHA20+ECDHE:CHACHA20+DHE:!DSS:!SHA1:!MD5:@STRENGTH")
except ssl.SSLError:
# Rely on the server to only support sensible things, I guess...
pass
# Connect to remote host by any address possible
err = None
for address in addresses:
try:
s = socket.socket(address[0], address[1])
s.settimeout(timeout)
s = context.wrap_socket(s, server_hostname = host)
s.connect(address[4])
break
except OSError as e:
err = e
else:
# If we couldn't connect to *any* of the addresses, just
# bubble up the exception from the last attempt and deny
# knowledge of earlier failures.
raise err
# Do TOFU
cert = s.getpeercert(binary_form=True)
# Remember that we showed the current cert to this domain...
#TODO : accept badssl and automatic choice
_validate_cert(address[4][0], host, cert,automatic_choice="y")
# Send request and wrap response in a file descriptor
url = urllib.parse.urlparse(url)
new_netloc = host
#Handle IPV6 hostname
if ":" in new_netloc:
new_netloc = "[" + new_netloc + "]"
if port != standard_ports["gemini"]:
new_netloc += ":" + str(port)
url = urllib.parse.urlunparse(url._replace(netloc=new_netloc))
s.sendall((url + CRLF).encode("UTF-8"))
f= s.makefile(mode = "rb")
## end of send_request in AV98
# Spec dictates <META> should not exceed 1024 bytes,
# so maximum valid header length is 1027 bytes.
header = f.readline(1027)
header = urllib.parse.unquote(header.decode("UTF-8"))
if not header or header[-1] != '\n':
raise RuntimeError("Received invalid header from server!")
header = header.strip()
# Validate header
status, meta = header.split(maxsplit=1)
if len(meta) > 1024 or len(status) != 2 or not status.isnumeric():
f.close()
raise RuntimeError("Received invalid header from server!")
# Update redirect loop/maze escaping state
if not status.startswith("3"):
previous_redirectors = set()
#TODO FIXME
else:
#we set a previous_redirectors anyway because refactoring in progress
previous_redirectors = set()
# Handle non-SUCCESS headers, which don't have a response body
# Inputs
if status.startswith("1"):
if interactive:
print(meta)
if status == "11":
user_input = getpass.getpass("> ")
else:
#TODO:FIXME we should not ask for user input while non-interactive
user_input = input("> ")
newurl = url.split("?")[0]
return _fetch_gemini(newurl+"?"+user_input)
else:
return None,None
# Redirects
elif status.startswith("3"):
newurl = urllib.parse.urljoin(url,meta)
if newurl == url:
raise RuntimeError("URL redirects to itself!")
elif newurl in previous_redirectors:
raise RuntimeError("Caught in redirect loop!")
elif len(previous_redirectors) == _MAX_REDIRECTS:
raise RuntimeError("Refusing to follow more than %d consecutive redirects!" % _MAX_REDIRECTS)
# TODO: redirections handling should be refactored
# elif "interactive" in options and not options["interactive"]:
# follow = self.automatic_choice
# # Never follow cross-domain redirects without asking
# elif new_gi.host.encode("idna") != gi.host.encode("idna"):
# follow = input("Follow cross-domain redirect to %s? (y/n) " % new_gi.url)
# # Never follow cross-protocol redirects without asking
# elif new_gi.scheme != gi.scheme:
# follow = input("Follow cross-protocol redirect to %s? (y/n) " % new_gi.url)
# # Don't follow *any* redirect without asking if auto-follow is off
# elif not self.options["auto_follow_redirects"]:
# follow = input("Follow redirect to %s? (y/n) " % new_gi.url)
# # Otherwise, follow away
else:
follow = "yes"
if follow.strip().lower() not in ("y", "yes"):
raise UserAbortException()
previous_redirectors.add(url)
# if status == "31":
# # Permanent redirect
# self.permanent_redirects[gi.url] = new_gi.url
return _fetch_gemini(newurl)
# Errors
elif status.startswith("4") or status.startswith("5"):
raise RuntimeError(meta)
# Client cert
elif status.startswith("6"):
error = "Handling certificates for status 6X are not supported by offpunk\n"
error += "See bug #31 for discussion about the problem"
raise RuntimeError(error)
# Invalid status
elif not status.startswith("2"):
raise RuntimeError("Server returned undefined status code %s!" % status)
# If we're here, this must be a success and there's a response body
assert status.startswith("2")
mime = meta
# Read the response body over the network
fbody = f.read()
#DEFAULT GEMINIMIME
if mime == "":
mime = "text/gemini; charset=utf-8"
shortmime, mime_options = parse_mime(mime)
if "charset" in mime_options:
try:
codecs.lookup(mime_options["charset"])
except LookupError:
#raise RuntimeError("Header declared unknown encoding %s" % mime_options)
#If the encoding is wrong, theres a high probably its UTF-8 with a bad header
mime_options["charset"] = "UTF-8"
if shortmime.startswith("text/"):
#Get the charset and default to UTF-8 in none
encoding = mime_options.get("charset", "UTF-8")
try:
body = fbody.decode(encoding)
except UnicodeError:
raise RuntimeError("Could not decode response body using %s\
encoding declared in header!" % encoding)
else:
body = fbody
cache = write_body(url,body,mime)
return cache,newurl
def fetch(url,offline=False,download_image_first=True,images_mode="readable",validity=0,**kwargs):
url = normalize_url(url)
newurl = url
path=None
print_error = "print_error" in kwargs.keys() and kwargs["print_error"]
#Firt, we look if we have a valid cache, even if offline
#If we are offline, any cache is better than nothing
if is_cache_valid(url,validity=validity) or (offline and is_cache_valid(url,validity=0)):
path = get_cache_path(url)
#if the cache is a folder, we should add a "/" at the end of the URL
if not url.endswith("/") and os.path.isdir(get_cache_path(url,add_index=False)) :
newurl = url+"/"
elif offline and is_cache_valid(url,validity=0):
path = get_cache_path(url)
elif "://" in url and not offline:
try:
scheme = url.split("://")[0]
if scheme not in standard_ports:
if print_error:
print("%s is not a supported protocol"%scheme)
path = None
elif scheme in ("http","https"):
if _DO_HTTP:
path=_fetch_http(url,**kwargs)
else:
print("HTTP requires python-requests")
elif scheme == "gopher":
path=_fetch_gopher(url,**kwargs)
elif scheme == "finger":
path=_fetch_finger(url,**kwargs)
elif scheme == "gemini":
path,newurl=_fetch_gemini(url,**kwargs)
elif scheme == "spartan":
path,newurl=_fetch_spartan(url,**kwargs)
else:
print("scheme %s not implemented yet"%scheme)
except UserAbortException:
return None, newurl
except Exception as err:
cache = set_error(url, err)
# Print an error message
# we fail silently when sync_only
if isinstance(err, socket.gaierror):
if print_error:
print("ERROR: DNS error!")
elif isinstance(err, ConnectionRefusedError):
if print_error:
print("ERROR1: Connection refused!")
elif isinstance(err, ConnectionResetError):
if print_error:
print("ERROR2: Connection reset!")
elif isinstance(err, (TimeoutError, socket.timeout)):
if print_error:
print("""ERROR3: Connection timed out!
Slow internet connection? Use 'set timeout' to be more patient.""")
elif isinstance(err, FileExistsError):
if print_error:
print("""ERROR5: Trying to create a directory which already exists
in the cache : """)
print(err)
elif _DO_HTTP and isinstance(err,requests.exceptions.SSLError):
if print_error:
print("""ERROR6: Bad SSL certificate:\n""")
print(err)
print("""\n If you know what you are doing, you can try to accept bad certificates with the following command:\n""")
print("""set accept_bad_ssl_certificates True""")
elif _DO_HTTP and isinstance(err,requests.exceptions.ConnectionError):
if print_error:
print("""ERROR7: Cannot connect to URL:\n""")
print(str(err))
else:
if print_error:
import traceback
print("ERROR4: " + str(type(err)) + " : " + str(err))
#print("\n" + str(err.with_traceback(None)))
print(traceback.format_exc())
return cache, newurl
# We download images contained in the document (from full mode)
if not offline and download_image_first and images_mode:
renderer = ansicat.renderer_from_file(path,newurl)
if renderer:
for image in renderer.get_images(mode=images_mode):
#Image should exist, should be an url (not a data image)
#and should not be already cached
if image and not image.startswith("data:image/") and not is_cache_valid(image):
width = offutils.term_width() - 1
toprint = "Downloading %s" %image
toprint = toprint[:width]
toprint += " "*(width-len(toprint))
print(toprint,end="\r")
#d_i_f and images_mode are False/None to avoid recursive downloading
#if that ever happen
fetch(image,offline=offline,download_image_first=False,\
images_mode=None,validity=0,**kwargs)
return path, newurl
def main():
descri="Netcache is a command-line tool to retrieve, cache and access networked content.\n\
By default, netcache will returns a cached version of a given URL, downloading it \
only if not existing. A validity duration, in seconds, can also be given so that \
netcache downloads the content only if the existing cache is older than the validity."
# Parse arguments
parser = argparse.ArgumentParser(prog="netcache",description=descri)
parser.add_argument("--path", action="store_true",
help="return path to the cache instead of the content of the cache")
parser.add_argument("--offline", action="store_true",
help="Do not attempt to download, return cached version or error")
parser.add_argument("--max-size", type=int,
help="Cancel download of items above that size (value in Mb).")
parser.add_argument("--timeout", type=int,
help="Time to wait before cancelling connection (in second).")
parser.add_argument("--cache-validity",type=int, default=0,
help="maximum age, in second, of the cached version before \
redownloading a new version")
# No argument: write help
parser.add_argument('url', metavar='URL', nargs='*',
help='download URL and returns the content or the path to a cached version')
# --validity : returns the date of the cached version, Null if no version
# --force-download : download and replace cache, even if valid
args = parser.parse_args()
param = {}
for u in args.url:
if args.offline:
path = get_cache_path(u)
else:
path,url = fetch(u,max_size=args.max_size,timeout=args.timeout,\
validity=args.cache_validity)
if args.path:
print(path)
else:
with open(path,"r") as f:
print(f.read())
f.close()
if __name__== '__main__':
main()

View File

@ -1,31 +0,0 @@
#!/usr/bin/env python3
# SPDX-FileCopyrightText: 2023 Sotiris Papatheodorou
# SPDX-License-Identifier: BSD-2-Clause
"""
A script to migrate the offpunk cache to the newest version.
For each new version of offpunk that requires changes to the cache a migration
function should be written. The name of the function should have the format
v<major-version>_<minor-version>_<patch-version> and it should accept the
offpunk cache directory as a string. The function should perform a migration
from the immediately previous cache format. All migration functions must be
called at the end of this script from oldest to newest.
"""
import argparse
import os
import os.path
def upgrade_to_1(cache_dir: str) -> None:
"""
Rename index.txt to gophermap in the Gopher protocol cache.
"""
print("Upgrading cache to version 1: migrating index.txt to gophermap")
for root, _, files in os.walk(os.path.join(cache_dir, 'gopher')):
for f in files:
if f == 'index.txt':
src = os.path.join(root, f)
dst = os.path.join(root, 'gophermap')
os.rename(src, dst)

View File

@ -1,33 +0,0 @@
# The following are the default redirections from Offpunk
# Those are by default because they should make sens with offpunk
redirects = {
"*twitter.com" : "nitter.net",
"youtube.com" : "yewtu.be",
"youtu.be" : "yewtu.be",
"*reddit.com" : "teddit.net",
"*medium.com" : "scribe.rip",
}
#following are blocked URLs. Visiting them with offpunk doesnt make sense.
#Blocking them will save a lot of bandwith
blocked = {
"*facebook.com",
"*facebook.net",
"*fbcdn.net",
"*linkedin.com",
"*licdn.com",
"*admanager.google.com",
"*google-health-ads.blogspot.com",
"*firebase.google.com",
"*google-webfonts-helper.herokuapp.com",
"*tiktok.com" ,
"*doubleclick.net",
"*google-analytics.com" ,
"*ads.yahoo.com",
"*advertising.amazon.com",
"*advertising.theguardian.com",
"*advertise.newrepublic.com",
}

1939
offpunk.py

File diff suppressed because it is too large Load Diff

View File

@ -1,49 +0,0 @@
#!/bin/python
colors = {
"bold" : ["1","22"],
"faint" : ["2","22"],
"italic" : ["3","23"],
"underline": ["4","24"],
"black" : ["30","39"],
"red" : ["31","39"],
"green" : ["32","39"],
"yellow" : ["33","39"],
"blue" : ["34","39"],
"purple" : ["35","39"],
"cyan" : ["36","39"],
"white" : ["37","39"],
"background_black" : ["40","49"],
"background_red" : ["41","49"],
"background_green" : ["42","49"],
"background_yellow" : ["43","49"],
"background_blue" : ["44","49"],
"background_purple" : ["45","49"],
"background_cyan" : ["46","49"],
"background_white" : ["47","49"],
"bright_black" : ["90","39"],
"bright_red" : ["91","39"],
"bright_green" : ["92","39"],
"bright_yellow" : ["93","39"],
"bright_blue" : ["94","39"],
"bright_purple" : ["95","39"],
"bright_cyan" : ["96","39"],
"bright_white" : ["97","39"],
}
offpunk1 = {
"window_title" : ["red","bold"],
"window_subtitle" : ["red","faint"],
"title" : ["blue","bold","underline"],
"subtitle" : ["blue"],
"subsubtitle" : ["blue","faint"], #fallback to subtitle if none
"link" : ["blue","faint"],
"new_link": ["bold"],
"oneline_link": [], #for gopher/gemini. fallback to link if none
"image_link" : ["yellow","faint"],
"preformatted": ["faint"],
"blockquote" : ["italic"],
"prompt_on" : ["green"],
"prompt_off" : ["green"],
}
default = offpunk1

View File

@ -1,226 +0,0 @@
#!/bin/python
#This file contains some utilities common to offpunk, ansirenderer and netcache.
#Currently, there are the following utilities:
#
# run : run a shell command and get the results with some security
# term_width : get or set the width to display on the terminal
import os
import io
import subprocess
import shutil
import shlex
import urllib.parse
import urllib.parse
import netcache_migration
import netcache
CACHE_VERSION = 1
# We upgrade the cache only once at startup, hence the UPGRADED variable
# This is only to avoid unecessary checks each time the cache is accessed
UPGRADED=False
def upgrade_cache(cache_folder):
#Lets read current version of the cache
version_path = cache_folder + ".version"
current_version = 0
if os.path.exists(version_path):
current_str = None
with open(version_path) as f:
current_str = f.read()
f.close()
try:
current_version = int(current_str)
except:
current_version = 0
#Now, lets upgrade the cache if needed
while current_version < CACHE_VERSION:
current_version += 1
upgrade_func = getattr(netcache_migration,"upgrade_to_"+str(current_version))
upgrade_func(cache_folder)
with open(version_path,"w") as f:
f.write(str(current_version))
f.close()
UPGRADED=True
#get xdg folder. Folder should be "cache", "data" or "config"
def xdg(folder="cache"):
## Config directories
## We implement our own python-xdg to avoid conflict with existing libraries.
_home = os.path.expanduser('~')
data_home = os.environ.get('XDG_DATA_HOME') or \
os.path.join(_home,'.local','share')
config_home = os.environ.get('XDG_CONFIG_HOME') or \
os.path.join(_home,'.config')
_CONFIG_DIR = os.path.join(os.path.expanduser(config_home),"offpunk/")
_DATA_DIR = os.path.join(os.path.expanduser(data_home),"offpunk/")
_old_config = os.path.expanduser("~/.offpunk/")
## Look for pre-existing config directory, if any
if os.path.exists(_old_config):
_CONFIG_DIR = _old_config
#if no XDG .local/share and not XDG .config, we use the old config
if not os.path.exists(data_home) and os.path.exists(_old_config):
_DATA_DIR = _CONFIG_DIR
## get _CACHE_PATH from OFFPUNK_CACHE_PATH environment variable
# if OFFPUNK_CACHE_PATH empty, set default to ~/.cache/offpunk
cache_home = os.environ.get('XDG_CACHE_HOME') or\
os.path.join(_home,'.cache')
_CACHE_PATH = os.environ.get('OFFPUNK_CACHE_PATH', \
os.path.join(os.path.expanduser(cache_home),"offpunk/"))
#Check that the cache path ends with "/"
if not _CACHE_PATH.endswith("/"):
_CACHE_PATH += "/"
os.makedirs(_CACHE_PATH,exist_ok=True)
if folder == "cache" and not UPGRADED:
upgrade_cache(_CACHE_PATH)
if folder == "cache":
return _CACHE_PATH
elif folder == "config":
return _CONFIG_DIR
elif folder == "data":
return _DATA_DIR
else:
print("No XDG folder for %s. Check your code."%folder)
return None
#An IPV6 URL should be put between []
#We try to detect them has location with more than 2 ":"
def fix_ipv6_url(url):
if not url or url.startswith("mailto"):
return url
if "://" in url:
schema, schemaless = url.split("://",maxsplit=1)
else:
schema, schemaless = None, url
if "/" in schemaless:
netloc, rest = schemaless.split("/",1)
if netloc.count(":") > 2 and "[" not in netloc and "]" not in netloc:
schemaless = "[" + netloc + "]" + "/" + rest
elif schemaless.count(":") > 2 and "[" not in schemaless and "]" not in schemaless:
schemaless = "[" + schemaless + "]/"
if schema:
return schema + "://" + schemaless
return schemaless
# Cheap and cheerful URL detector
def looks_like_url(word):
try:
if not word.strip():
return False
url = fix_ipv6_url(word).strip()
parsed = urllib.parse.urlparse(url)
#sometimes, urllib crashed only when requesting the port
port = parsed.port
scheme = word.split("://")[0]
mailto = word.startswith("mailto:")
start = scheme in netcache.standard_ports
local = scheme in ["file","list"]
if mailto:
return "@" in word
elif not local:
if start:
#IPv4
if "." in word or "localhost" in word:
return True
#IPv6
elif "[" in word and ":" in word and "]" in word:
return True
else: return False
else: return False
return start and ("." in word or "localhost" in word or ":" in word)
else:
return "/" in word
except ValueError:
return False
## Those two functions add/remove the mode to the
# URLs. This is a gross hack to remember the mode
def mode_url(url,mode):
if mode and mode!= "readable" and "##offpunk=" not in url:
url += "##offpunk_mode=" + mode
return url
def unmode_url(url):
mode = None
splitted = url.split("##offpunk_mode=")
if len(splitted) > 1:
url = splitted[0]
mode = splitted[1]
return [url,mode]
# In terms of arguments, this can take an input file/string to be passed to
# stdin, a parameter to do (well-escaped) "%" replacement on the command, a
# flag requesting that the output go directly to the stdout, and a list of
# additional environment variables to set.
def run(cmd, *, input=None, parameter=None, direct_output=False, env={}):
if parameter:
cmd = cmd % shlex.quote(parameter)
e = os.environ
e.update(env)
if isinstance(input, io.IOBase):
stdin = input
input = None
else:
if input:
input = input.encode()
stdin = None
if not direct_output:
# subprocess.check_output() wouldn't allow us to pass stdin.
result = subprocess.run(cmd, check=True, env=e, input=input,
shell=True, stdin=stdin, stdout=subprocess.PIPE,
stderr=subprocess.STDOUT)
return result.stdout.decode()
else:
subprocess.run(cmd, env=e, input=input, shell=True, stdin=stdin)
global TERM_WIDTH
TERM_WIDTH = 72
#if absolute, returns the real terminal width, not the text width
def term_width(new_width=None,absolute=False):
if new_width:
global TERM_WIDTH
TERM_WIDTH = new_width
cur = shutil.get_terminal_size()[0]
if absolute:
return cur
width = TERM_WIDTH
if cur < width:
width = cur
return width
def is_local(url):
if not url: return True
elif "://" in url:
scheme,path = url.split("://",maxsplit=1)
return scheme in ["file","mail","list","mailto"]
else:
return True
# This method return the image URL or invent it if its a base64 inline image
# It returns [url,image_data] where image_data is None for normal image
def looks_like_base64(src,baseurl):
imgdata = None
imgname = src
if src and src.startswith("data:image/"):
if ";base64," in src:
splitted = src.split(";base64,")
#splitted[0] is something like data:image/jpg
if "/" in splitted[0]:
extension = splitted[0].split("/")[1]
else:
extension = "data"
imgdata = splitted[1]
imgname = imgdata[:20] + "." + extension
imgurl = urllib.parse.urljoin(baseurl, imgname)
else:
#We cant handle other data:image such as svg for now
imgurl = None
else:
imgurl = urllib.parse.urljoin(baseurl, imgname)
return imgurl,imgdata

300
opnk.py
View File

@ -1,300 +0,0 @@
#!/usr/bin/env python3
#opnk stand for "Open like a PuNK".
#It will open any file or URL and display it nicely in less.
#If not possible, it will fallback to xdg-open
#URL are retrieved through netcache
import os
import sys
import tempfile
import argparse
import netcache
import ansicat
import offutils
import shutil
import time
import fnmatch
from offutils import run,term_width,mode_url,unmode_url,is_local
_HAS_XDGOPEN = shutil.which('xdg-open')
_GREP = "grep --color=auto"
less_version = 0
if not shutil.which("less"):
print("Please install the pager \"less\" to run Offpunk.")
print("If you wish to use another pager, send me an email!")
print("(Im really curious to hear about people not having \"less\" on their system.)")
sys.exit()
output = run("less --version")
# We get less Version (which is the only integer on the first line)
words = output.split("\n")[0].split()
less_version = 0
for w in words:
if w.isdigit():
less_version = int(w)
# restoring position only works for version of less > 572
if less_version >= 572:
_LESS_RESTORE_POSITION = True
else:
_LESS_RESTORE_POSITION = False
#_DEFAULT_LESS = "less -EXFRfM -PMurl\ lines\ \%lt-\%lb/\%L\ \%Pb\%$ %s"
# -E : quit when reaching end of file (to behave like "cat")
# -F : quit if content fits the screen (behave like "cat")
# -X : does not clear the screen
# -R : interpret ANSI colors correctly
# -f : suppress warning for some contents
# -M : long prompt (to have info about where you are in the file)
# -W : hilite the new first line after a page skip (space)
# -i : ignore case in search
# -S : do not wrap long lines. Wrapping is done by offpunk, longlines
# are there on purpose (surch in asciiart)
#--incsearch : incremental search starting rev581
def less_cmd(file, histfile=None,cat=False,grep=None):
less_prompt = "page %%d/%%D- lines %%lb/%%L - %%Pb\\%%"
if less_version >= 581:
less_base = "less --incsearch --save-marks -~ -XRfWiS -P \"%s\""%less_prompt
elif less_version >= 572:
less_base = "less --save-marks -XRfMWiS"
else:
less_base = "less -XRfMWiS"
_DEFAULT_LESS = less_base + " \"+''\" %s"
_DEFAULT_CAT = less_base + " -EF %s"
if histfile:
env = {"LESSHISTFILE": histfile}
else:
env = {}
if cat:
cmd_str = _DEFAULT_CAT
elif grep:
grep_cmd = _GREP
#case insensitive for lowercase search
if grep.islower():
grep_cmd += " -i"
cmd_str = _DEFAULT_CAT + "|" + grep_cmd + " %s"%grep
else:
cmd_str = _DEFAULT_LESS
run(cmd_str, parameter=file, direct_output=True, env=env)
class opencache():
def __init__(self):
# We have a cache of the rendering of file and, for each one,
# a less_histfile containing the current position in the file
self.temp_files = {}
self.less_histfile = {}
# This dictionary contains an url -> ansirenderer mapping. This allows
# to reuse a renderer when visiting several times the same URL during
# the same session
# We save the time at which the renderer was created in renderer_time
# This way, we can invalidate the renderer if a new version of the source
# has been downloaded
self.rendererdic = {}
self.renderer_time = {}
self.mime_handlers = {}
self.last_mode = {}
self.last_width = term_width(absolute=True)
def _get_handler_cmd(self, mimetype):
# Now look for a handler for this mimetype
# Consider exact matches before wildcard matches
exact_matches = []
wildcard_matches = []
for handled_mime, cmd_str in self.mime_handlers.items():
if "*" in handled_mime:
wildcard_matches.append((handled_mime, cmd_str))
else:
exact_matches.append((handled_mime, cmd_str))
for handled_mime, cmd_str in exact_matches + wildcard_matches:
if fnmatch.fnmatch(mimetype, handled_mime):
break
else:
# Use "xdg-open" as a last resort.
if _HAS_XDGOPEN:
cmd_str = "xdg-open %s"
else:
cmd_str = "echo \"Cant find how to open \"%s"
print("Please install xdg-open (usually from xdg-util package)")
return cmd_str
# Return the handler for a specific mimetype.
# Return the whole dic if no specific mime provided
def get_handlers(self,mime=None):
if mime and mime in self.mime_handlers.keys():
return self.mime_handlers[mime]
elif mime:
return None
else:
return self.mime_handlers
def set_handler(self,mime,handler):
previous = None
if mime in self.mime_handlers.keys():
previous = self.mime_handlers[mime]
self.mime_handlers[mime] = handler
if "%s" not in handler:
print("WARNING: this handler has no %%s, no filename will be provided to the command")
if previous:
print("Previous handler was %s"%previous)
def get_renderer(self,inpath,mode=None,theme=None):
# We remove the ##offpunk_mode= from the URL
# If mode is already set, we dont use the part from the URL
inpath,newmode = unmode_url(inpath)
if not mode: mode = newmode
# If we still doesnt have a mode, we see if we used one before
if not mode and inpath in self.last_mode.keys():
mode = self.last_mode[inpath]
elif not mode:
#default mode is readable
mode = "readable"
renderer = None
path = netcache.get_cache_path(inpath)
if path:
usecache = inpath in self.rendererdic.keys() and not is_local(inpath)
#Screen size may have changed
width = term_width(absolute=True)
if usecache and self.last_width != width:
self.cleanup()
usecache = False
self.last_width = width
if usecache:
if inpath in self.renderer_time.keys():
last_downloaded = netcache.cache_last_modified(inpath)
last_cached = self.renderer_time[inpath]
if last_cached and last_downloaded:
usecache = last_cached > last_downloaded
else:
usecache = False
else:
usecache = False
if not usecache:
renderer = ansicat.renderer_from_file(path,url=inpath,theme=theme)
if renderer:
self.rendererdic[inpath] = renderer
self.renderer_time[inpath] = int(time.time())
else:
renderer = self.rendererdic[inpath]
return renderer
def get_temp_filename(self,url):
if url in self.temp_files.keys():
return self.temp_files[url]
else:
return None
def opnk(self,inpath,mode=None,terminal=True,grep=None,theme=None,**kwargs):
#Return True if inpath opened in Terminal
# False otherwise
# also returns the url in case it has been modified
#if terminal = False, we dont try to open in the terminal,
#we immediately fallback to xdg-open.
#netcache currently provide the path if its a file.
if not offutils.is_local(inpath):
kwargs["images_mode"] = mode
cachepath,inpath = netcache.fetch(inpath,**kwargs)
if not cachepath:
return False, inpath
# folowing line is for :// which are locals (file,list)
elif "://" in inpath:
cachepath,inpath = netcache.fetch(inpath,**kwargs)
elif inpath.startswith("mailto:"):
cachepath = inpath
elif os.path.exists(inpath):
cachepath = inpath
else:
print("%s does not exist"%inpath)
return False, inpath
renderer = self.get_renderer(inpath,mode=mode,theme=theme)
if renderer and mode:
renderer.set_mode(mode)
self.last_mode[inpath] = mode
if not mode and inpath in self.last_mode.keys():
mode = self.last_mode[inpath]
renderer.set_mode(mode)
#we use the full moded url as key for the dictionary
key = mode_url(inpath,mode)
if terminal and renderer:
#If this is an image and we have chafa/timg, we
#dont use less, we call it directly
if renderer.has_direct_display():
renderer.display(mode=mode,directdisplay=True)
return True, inpath
else:
body = renderer.display(mode=mode)
#Should we use the cache? only if it is not local and theres a cache
usecache = key in self.temp_files and not is_local(inpath)
if usecache:
#and the cache is still valid!
last_downloaded = netcache.cache_last_modified(inpath)
last_cached = os.path.getmtime(self.temp_files[key])
if last_downloaded > last_cached:
usecache = False
self.temp_files.pop(key)
self.less_histfile.pop(key)
# We actually put the body in a tmpfile before giving it to less
if not usecache:
tmpf = tempfile.NamedTemporaryFile("w", encoding="UTF-8", delete=False)
self.temp_files[key] = tmpf.name
tmpf.write(body)
tmpf.close()
if key not in self.less_histfile:
firsttime = True
tmpf = tempfile.NamedTemporaryFile("w", encoding="UTF-8", delete=False)
self.less_histfile[key] = tmpf.name
else:
#We dont want to restore positions in lists
firsttime = is_local(inpath)
less_cmd(self.temp_files[key], histfile=self.less_histfile[key],cat=firsttime,grep=grep)
return True, inpath
#maybe, we have no renderer. Or we want to skip it.
else:
mimetype = ansicat.get_mime(cachepath)
if mimetype == "mailto":
mail = inpath[7:]
resp = input("Send an email to %s Y/N? " %mail)
if resp.strip().lower() in ("y", "yes"):
if _HAS_XDGOPEN :
run("xdg-open mailto:%s", parameter=mail,direct_output=True)
else:
print("Cannot find a mail client to send mail to %s" %inpath)
print("Please install xdg-open (usually from xdg-util package)")
return False, inpath
else:
cmd_str = self._get_handler_cmd(mimetype)
try:
run(cmd_str, parameter=netcache.get_cache_path(inpath), direct_output=True)
except FileNotFoundError:
print("Handler program %s not found!" % shlex.split(cmd_str)[0])
print("You can use the ! command to specify another handler program or pipeline.")
return False, inpath
#We remove the renderers from the cache and we also delete temp files
def cleanup(self):
while len(self.temp_files) > 0:
os.remove(self.temp_files.popitem()[1])
while len(self.less_histfile) > 0:
os.remove(self.less_histfile.popitem()[1])
self.last_width = None
self.rendererdic = {}
self.renderer_time = {}
self.last_mode = {}
def main():
descri = "opnk is an universal open command tool that will try to display any file \
in the pager less after rendering its content with ansicat. If that fails, \
opnk will fallback to opening the file with xdg-open. If given an URL as input \
instead of a path, opnk will rely on netcache to get the networked content."
parser = argparse.ArgumentParser(prog="opnk",description=descri)
parser.add_argument("--mode", metavar="MODE",
help="Which mode should be used to render: normal (default), full or source.\
With HTML, the normal mode try to extract the article.")
parser.add_argument("content",metavar="INPUT", nargs="*",
default=sys.stdin, help="Path to the file or URL to open")
parser.add_argument("--cache-validity",type=int, default=0,
help="maximum age, in second, of the cached version before \
redownloading a new version")
args = parser.parse_args()
cache = opencache()
for f in args.content:
cache.opnk(f,mode=args.mode,validity=args.cache_validity)
if __name__ == "__main__":
main()

72
pyproject.toml Normal file → Executable file
View File

@ -1,58 +1,26 @@
[build-system]
requires = ["hatchling"]
build-backend = "hatchling.build"
requires = ["setuptools>=61.0"]
build-backend = "setuptools.build_meta"
[project]
name = "offpunk"
authors = [
{name = "Solderpunk", email = "solderpunk@sdf.org"},
{name = "Lionel Dricot (Ploum)", email = "offpunk2@ploum.eu"},
]
maintainers = [
{name = "Lionel Dricot (Ploum)", email = "offpunk2@ploum.eu"},
]
readme = "README.md"
name = "AV-98"
dynamic = ["version"]
description = "Command line Gemini client"
authors = [{name="Solderpunk", email="solderpunk@posteo.net"}]
classifiers = [
"Development Status :: 4 - Beta",
"Environment :: Console",
"License :: OSI Approved :: GNU Affero General Public License v3 or later (AGPLv3+)",
"Operating System :: OS Independent",
"Programming Language :: Python :: 3 :: Only",
"Topic :: Communications",
"Topic :: Internet",
"License :: OSI Approved :: BSD License",
"Programming Language :: Python :: 3 :: Only",
"Topic :: Communications",
"Intended Audience :: End Users/Desktop",
"Environment :: Console",
"Development Status :: 5 - Production/Stable",
]
keywords = ["gemini", "browser"]
requires-python = ">=3.7"
dynamic = ["version", "description"]
[project.license]
file = "LICENSE"
[project.optional-dependencies]
better-tofu = ["cryptography"]
chardet = ["chardet"]
html = ["bs4", "readability-lxml"]
http = ["requests"]
process-title = ["setproctitle"]
rss = ["feedparser"]
[project.urls]
Homepage = "https://sr.ht/~lioploum/offpunk/"
Source = "https://git.sr.ht/~lioploum/offpunk"
"Bug Tracker" = "https://todo.sr.ht/~lioploum/offpunk"
Homepage = "https://tildegit.org/solderpunk/AV-98/"
Issues = "https://tildegit.org/solderpunk/AV-98/issues"
[project.scripts]
offpunk = "offpunk:main"
netcache = "netcache:main"
ansicat = "ansicat:main"
opnk = "opnk:main"
[tool.hatch.version]
path = "offpunk.py" # read __version__
[tool.hatch.build.targets.wheel]
only-include = [
"ansicat.py", "netcache_migration.py", "netcache.py",
"offblocklist.py", "offpunk.py", "offthemes.py",
"offutils.py", "opnk.py",
]
av98 = "av98.main:main"
[project.optional-dependencies]
tofu = ["cryptography"]
colour = ["ansiwrap"]
[tool.setuptools.dynamic]
version = {attr = "av98.__version__"}

View File

@ -1,10 +0,0 @@
chardet
cryptography
requests
feedparser
bs4
readability-lxml
pillow
setproctitle
timg
file

Binary file not shown.

Before

Width:  |  Height:  |  Size: 83 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 81 KiB

1
src/av98/__init__.py Normal file
View File

@ -0,0 +1 @@
__version__ = "1.1.0dev"

76
src/av98/cache.py Normal file
View File

@ -0,0 +1,76 @@
_MAX_CACHE_SIZE = 10
_MAX_CACHE_AGE_SECS = 180
import logging
import os
import os.path
import shutil
import tempfile
import time
ui_out = logging.getLogger("av98_logger")
class Cache:
def __init__(self):
self.cache = {}
self.cache_timestamps = {}
self.tempdir = tempfile.TemporaryDirectory()
def check(self, url):
if url not in self.cache:
return False
now = time.time()
cached = self.cache_timestamps[url]
if now - cached > _MAX_CACHE_AGE_SECS:
ui_out.debug("Expiring old cached copy of resource.")
self._remove(url)
return False
ui_out.debug("Found cached copy of resource.")
return True
def _remove(self, url):
self.cache_timestamps.pop(url)
mime, filename = self.cache.pop(url)
os.unlink(filename)
self.validatecache()
def add(self, url, mime, filename):
# Copy client's buffer file to new cache file
tmpf = tempfile.NamedTemporaryFile(dir=self.tempdir.name, delete=False)
tmpf.close()
shutil.copyfile(filename, tmpf.name)
# Remember details
self.cache_timestamps[url] = time.time()
self.cache[url] = (mime, tmpf.name)
if len(self.cache) > _MAX_CACHE_SIZE:
self._trim()
self.validatecache()
def _trim(self):
# Order cache entries by age
lru = [(t, u) for (u, t) in self.cache_timestamps.items()]
lru.sort()
# Drop the oldest entry no matter what
_, url = lru[0]
ui_out.debug("Dropping cached copy of {} from full cache.".format(url))
self._remove(url)
# Drop other entries if they are older than the limit
now = time.time()
for cached, url in lru[1:]:
if now - cached > _MAX_CACHE_AGE_SECS:
ui_out.debug("Dropping cached copy of {} from full cache.".format(url))
self._remove(url)
else:
break
self.validatecache()
def get(self, url):
return self.cache[url]
def validatecache(self):
assert self.cache.keys() == self.cache_timestamps.keys()
for _, filename in self.cache.values():
assert os.path.isfile(filename)

233
src/av98/certmanager.py Normal file
View File

@ -0,0 +1,233 @@
import glob
import logging
import os
import os.path
import uuid
import av98.util as util
ui_out = logging.getLogger("av98_logger")
class ClientCertificateManager:
def __init__(self, config_dir):
self.config_dir = config_dir
self.client_certs = {
"active": None
}
self.active_cert_domains = []
self.active_is_transient = False
self.transient_certs_created = []
def cleanup(self):
for cert in self.transient_certs_created:
for ext in (".crt", ".key"):
certfile = os.path.join(self.config_dir, "transient_certs", cert+ext)
if os.path.exists(certfile):
os.remove(certfile)
def manage(self):
if self.client_certs["active"]:
print("Active certificate: {}".format(self.client_certs["active"][0]))
print("1. Deactivate client certificate.")
print("2. Generate new certificate.")
print("3. Load previously generated certificate.")
print("4. Load externally created client certificate from file.")
print("Enter blank line to exit certificate manager.")
choice = input("> ").strip()
if choice == "1":
print("Deactivating client certificate.")
self._deactivate_client_cert()
elif choice == "2":
self._generate_persistent_client_cert()
elif choice == "3":
self._choose_client_cert()
elif choice == "4":
self._load_client_cert()
else:
print("Aborting.")
def associate_client_cert(self, context, gi):
# Be careful with client certificates!
# Are we crossing a domain boundary?
if self.client_certs["active"] and gi.host not in self.active_cert_domains:
if self.active_is_transient:
if util.ask_yes_no("Permanently delete currently active transient certificate?"):
print("Destroying certificate.")
self._deactivate_client_cert()
else:
print("Staying here.")
return False
else:
if util.ask_yes_no("PRIVACY ALERT: Deactivate client cert before connecting to a new domain?"):
print("Deactivating certificate.")
self._deactivate_client_cert()
else:
print("Keeping certificate active for {}".format(gi.host))
self.active_cert_domains.append(gi.host)
self.client_certs[gi.host] = self.client_certs["active"]
# Suggest reactivating previous certs
if not self.client_certs["active"] and gi.host in self.client_certs:
if util.ask_yes_no("PRIVACY ALERT: Reactivate previously used client cert for {}?".format(gi.host)):
self._activate_client_cert(*self.client_certs[gi.host])
self.active_cert_domains.append(gi.host)
else:
print("Remaining unidentified.")
self.client_certs.pop(gi.host)
# Associate certs to context based on above
if self.client_certs["active"]:
certfile, keyfile = self.client_certs["active"]
context.load_cert_chain(certfile, keyfile)
return True
def is_cert_active(self):
return self.client_certs["active"] != None
def handle_cert_request(self, meta, status, host):
# Don't do client cert stuff in restricted mode, as in principle
# it could be used to fill up the disk by creating a whole lot of
# certificates
print("SERVER SAYS: ", meta)
# Present different messages for different 6x statuses, but
# handle them the same.
if status in ("64", "65"):
print("The server rejected your certificate because it is either expired or not yet valid.")
elif status == "63":
print("The server did not accept your certificate.")
print("You may need to e.g. coordinate with the admin to get your certificate fingerprint whitelisted.")
else:
print("The site {} is requesting a client certificate.".format(host))
print("This will allow the site to recognise you across requests.")
# Give the user choices
print("What do you want to do?")
print("1. Give up.")
print("2. Generate a new transient certificate.")
print("3. Generate a new persistent certificate.")
print("4. Load a previously generated certificate.")
print("5. Load a certificate from an external file.")
choice = input("> ").strip()
if choice == "2":
self._generate_transient_cert_cert()
elif choice == "3":
self._generate_persistent_client_cert()
elif choice == "4":
self._choose_client_cert()
elif choice == "5":
self._load_client_cert()
else:
print("Giving up.")
return False
if self.client_certs["active"]:
self.active_cert_domains.append(host)
self.client_certs[host] = self.client_certs["active"]
return True
def _load_client_cert(self):
"""
Interactively load a TLS client certificate from the filesystem in PEM
format.
"""
print("Loading client certificate file, in PEM format (blank line to cancel)")
certfile = input("Certfile path: ").strip()
if not certfile:
print("Aborting.")
return
certfile = os.path.expanduser(certfile)
if not os.path.isfile(certfile):
print("Certificate file {} does not exist.".format(certfile))
return
print("Loading private key file, in PEM format (blank line to cancel)")
keyfile = input("Keyfile path: ").strip()
if not keyfile:
print("Aborting.")
return
keyfile = os.path.expanduser(keyfile)
if not os.path.isfile(keyfile):
print("Private key file {} does not exist.".format(keyfile))
return
self._activate_client_cert(certfile, keyfile)
def _generate_transient_cert_cert(self):
"""
Use `openssl` command to generate a new transient client certificate
with 24 hours of validity.
"""
certdir = os.path.join(self.config_dir, "transient_certs")
name = str(uuid.uuid4())
self._generate_client_cert(certdir, name, transient=True)
self.active_is_transient = True
self.transient_certs_created.append(name)
def _generate_persistent_client_cert(self):
"""
Interactively use `openssl` command to generate a new persistent client
certificate with one year of validity.
"""
certdir = os.path.join(self.config_dir, "client_certs")
print("What do you want to name this new certificate?")
print("Answering `mycert` will create `{0}/mycert.crt` and `{0}/mycert.key`".format(certdir))
name = input("> ")
if not name.strip():
print("Aborting.")
return
self._generate_client_cert(certdir, name)
def _generate_client_cert(self, certdir, basename, transient=False):
"""
Use `openssl` binary to generate a client certificate (which may be
transient or persistent) and save the certificate and private key to the
specified directory with the specified basename.
"""
if not os.path.exists(certdir):
os.makedirs(certdir)
certfile = os.path.join(certdir, basename+".crt")
keyfile = os.path.join(certdir, basename+".key")
cmd = "openssl req -x509 -newkey rsa:2048 -days {} -nodes -keyout {} -out {}".format(1 if transient else 365, keyfile, certfile)
if transient:
cmd += " -subj '/CN={}'".format(basename)
os.system(cmd)
self._activate_client_cert(certfile, keyfile)
def _choose_client_cert(self):
"""
Interactively select a previously generated client certificate and
activate it.
"""
certdir = os.path.join(self.config_dir, "client_certs")
certs = glob.glob(os.path.join(certdir, "*.crt"))
if len(certs) == 0:
print("There are no previously generated certificates.")
return
certdir = {}
for n, cert in enumerate(certs):
certdir[str(n+1)] = (cert, os.path.splitext(cert)[0] + ".key")
print("{}. {}".format(n+1, os.path.splitext(os.path.basename(cert))[0]))
choice = input("> ").strip()
if choice in certdir:
certfile, keyfile = certdir[choice]
self._activate_client_cert(certfile, keyfile)
else:
print("What?")
def _activate_client_cert(self, certfile, keyfile):
self.client_certs["active"] = (certfile, keyfile)
self.active_cert_domains = []
ui_out.debug("Using ID {} / {}.".format(*self.client_certs["active"]))
def _deactivate_client_cert(self):
if self.active_is_transient:
for filename in self.client_certs["active"]:
os.remove(filename)
for domain in self.active_cert_domains:
self.client_certs.pop(domain)
self.client_certs["active"] = None
self.active_cert_domains = []
self.active_is_transient = False

1416
src/av98/client.py Executable file

File diff suppressed because it is too large Load Diff

130
src/av98/main.py Executable file
View File

@ -0,0 +1,130 @@
#!/usr/bin/env python3
# AV-98 Gemini client
# Dervied from VF-1 (https://github.com/solderpunk/VF-1),
# (C) 2019, 2020, 2023 Solderpunk <solderpunk@posteo.net>
# With contributions from:
# - danceka <hannu.hartikainen@gmail.com>
# - <jprjr@tilde.club>
# - <vee@vnsf.xyz>
# - Klaus Alexander Seistrup <klaus@seistrup.dk>
# - govynnus <govynnus@sdf.org>
# - Nik <nic@tilde.team>
# - <sario528@ctrl-c.club>
# - rmgr
# - Aleksey Ryndin
import argparse
import os.path
import shutil
import sys
from av98 import __version__
from av98.client import GeminiClient
def main():
# Parse args
parser = argparse.ArgumentParser(description='A command line gemini client.')
parser.add_argument('--bookmarks', action='store_true',
help='start with your list of bookmarks')
parser.add_argument('--dl', '--download', action='store_true',
help='download a single URL and quit')
parser.add_argument('-o', '--output', metavar='FILE',
help='filename to save --dl URL to')
parser.add_argument('--tls-cert', metavar='FILE', help='TLS client certificate file')
parser.add_argument('--tls-key', metavar='FILE', help='TLS client certificate private key file')
parser.add_argument('--restricted', action="store_true", help='Disallow shell, add, and save commands')
parser.add_argument('--version', action='store_true',
help='display version information and quit')
parser.add_argument('url', metavar='URL', nargs='*',
help='start with this URL')
args = parser.parse_args()
# Handle --version
if args.version:
print("AV-98 " + __version__)
sys.exit()
# Instantiate client
gc = GeminiClient(args.restricted)
# Activate client certs now in case they are needed for --download below
if args.tls_cert and args.tls_key:
gc.client_cert_manager._activate_client_cert(args.tls_cert, args.tls_key)
for url in args.url:
gi = GeminiItem(url)
gc.client_cert_manager.active_cert_domains.append(gi.host)
# Handle --download
if args.dl:
gc.onecmd("set debug True")
# Download
gi = GeminiItem(args.url[0])
gi, mime = gc._fetch_over_network(gi)
# Decide on a filename
if args.output:
filename = args.output
else:
if mime == "text/gemini":
# Parse gemtext in the hopes of getting a gi.name for the filename
gc.active_raw_file = gc.raw_file_buffer
gc._handle_gemtext(gi)
filename = gi.derive_filename(mime)
# Copy from temp file to pwd with a nice name
shutil.copyfile(gc.raw_file_buffer, filename)
size = os.path.getsize(filename)
# Notify user where the file ended up
print("Wrote %d byte %s response to %s." % (size, mime, filename))
gc.do_quit()
sys.exit()
# Process config file
rcfile = os.path.join(gc.config_dir, "av98rc")
if os.path.exists(rcfile):
print("Using config %s" % rcfile)
with open(rcfile, "r") as fp:
for line in fp:
line = line.strip()
if ((args.bookmarks or args.url) and
any((line.startswith(x) for x in ("go", "g", "tour", "t")))
):
if args.bookmarks:
print("Skipping rc command \"%s\" due to --bookmarks option." % line)
else:
print("Skipping rc command \"%s\" due to provided URLs." % line)
continue
gc.cmdqueue.append(line)
# Say hi
print("Welcome to AV-98!")
if args.restricted:
print("Restricted mode engaged!")
print("Enjoy your patrol through Geminispace...")
# Add commands to the queue based on command line arguments
if args.bookmarks:
gc.cmdqueue.append("bookmarks")
elif args.url:
if len(args.url) == 1:
gc.cmdqueue.append("go %s" % args.url[0])
else:
for url in args.url:
if not url.startswith("gemini://"):
url = "gemini://" + url
gc.cmdqueue.append("tour %s" % url)
gc.cmdqueue.append("tour")
# Endless interpret loop until user quits
while True:
try:
gc.cmdloop()
break
except KeyboardInterrupt:
print("")
# Say goodbye
print()
print("Thank you for patrolling with AV-98!")
sys.exit()
if __name__ == '__main__':
main()

210
src/av98/tofu.py Normal file
View File

@ -0,0 +1,210 @@
import datetime
import hashlib
import logging
import os
import os.path
import sqlite3
import ssl
import time
try:
from cryptography import x509
from cryptography.hazmat.backends import default_backend
_HAS_CRYPTOGRAPHY = True
_BACKEND = default_backend()
except ModuleNotFoundError:
_HAS_CRYPTOGRAPHY = False
import av98.util as util
ui_out = logging.getLogger("av98_logger")
class TofuStore:
def __init__(self, config_dir):
self.config_dir = config_dir
self.certdir = os.path.join(config_dir, "cert_cache")
if not os.path.exists(self.certdir):
os.makedirs(self.certdir)
db_path = os.path.join(self.config_dir, "tofu.db")
self.db_conn = sqlite3.connect(db_path)
self.db_cur = self.db_conn.cursor()
self.create_db()
self.update_db()
def create_db(self):
self.db_cur.execute("""CREATE TABLE IF NOT EXISTS cert_cache
(hostname text, port integer, address text, fingerprint text,
first_seen date, last_seen date, count integer)""")
def update_db(self):
# Update 1 - check for port column
try:
self.db_cur.execute("""SELECT port FROM cert_cache where 1=0""")
has_port = True
except sqlite3.OperationalError:
has_port = False
if not has_port:
self.db_cur.execute("""ALTER TABLE cert_cache ADD COLUMN port integer""")
self.db_cur.execute("""UPDATE cert_cache SET port= 1965 WHERE count > 0""")
def close(self):
self.db_conn.commit()
self.db_conn.close()
def validate_cert(self, address, port, host, cert):
"""
Validate a TLS certificate in TOFU mode.
If the cryptography module is installed:
- Check the certificate Common Name or SAN matches `host`
- Check the certificate's not valid before date is in the past
- Check the certificate's not valid after date is in the future
Whether the cryptography module is installed or not, check the
certificate's fingerprint against the TOFU database to see if we've
previously encountered a different certificate for this hostname and
port
"""
now = datetime.datetime.utcnow()
# Do 'advanced' checks if Cryptography library is installed
if _HAS_CRYPTOGRAPHY:
self.check_cert_expiry_and_names(cert, host, now)
# Compute SHA256 fingerprint
sha = hashlib.sha256()
sha.update(cert)
fingerprint = sha.hexdigest()
# Have we been here before?
self.db_cur.execute("""SELECT fingerprint, address, first_seen, last_seen, count
FROM cert_cache WHERE hostname=? AND port=?""", (host, port))
cached_certs = self.db_cur.fetchall()
# If not, cache this first cert and we're done
if not cached_certs:
ui_out.debug("TOFU: Blindly trusting first ever certificate for this host!")
self.cache_new_cert(cert, host, port, address, fingerprint, now)
return
# If we have, check the received cert against the cache
if self.find_cert_in_cache(host, port, fingerprint, cached_certs, now):
return
# Handle an unrecognised cert
ui_out.debug("TOFU: Unrecognised certificate {}! Raising the alarm...".format(fingerprint))
## Find the most recently seen previous cert for reporting
most_recent = None
for cached_fingerprint, cached_address, first, last, count in cached_certs:
if not most_recent or last > most_recent:
most_recent = last
most_recent_cert = cached_fingerprint
most_recent_address = cached_address
most_recent_count = count
## Report the situation
print("****************************************")
print("[SECURITY WARNING] Unrecognised certificate!")
print("The certificate presented for {}:{} ({}) has never been seen before.".format(host, port, address))
print("This MIGHT be a Man-in-the-Middle attack.")
print("A different certificate has previously been seen {} times.".format(most_recent_count))
if _HAS_CRYPTOGRAPHY:
previous_ttl = self.get_cached_cert_expiry(most_recent_cert) - now
if previous_ttl < datetime.timedelta():
print("That certificate has expired, which reduces suspicion somewhat.")
else:
print("That certificate is still valid for: {}".format(previous_ttl))
if most_recent_address == address:
print("The new certificate is being served from the same IP address as the previous one.")
else:
print("The new certificate is being served from a DIFFERNET IP address as the previous one.")
print("****************************************")
print("Attempt to verify the new certificate fingerprint out-of-band:")
print(fingerprint)
## Ask the question
if util.ask_yes_no("Accept this new certificate?"):
self.cache_new_cert(cert, host, port, address, fingerprint, now)
else:
raise Exception("TOFU Failure!")
def cache_new_cert(self, cert, host, port, address, fingerprint, now):
"""
Accept a new certificate for a given host/port combo.
"""
# Save cert to disk
with open(os.path.join(self.certdir, fingerprint+".crt"), "wb") as fp:
fp.write(cert)
# Record in DB
self.db_cur.execute("""INSERT INTO cert_cache
(hostname, port, address, fingerprint, first_seen, last_seen, count)
VALUES (?, ?, ?, ?, ?, ?, ?)""",
(host, port, address, fingerprint, now, now, 1))
self.db_conn.commit()
def check_cert_expiry_and_names(self, cert, host, now):
"""
- Check the certificate Common Name or SAN matches `host`
- Check the certificate's not valid before date is in the past
- Check the certificate's not valid after date is in the future
"""
c = x509.load_der_x509_certificate(cert, _BACKEND)
# Check certificate validity dates
if c.not_valid_before >= now:
raise ssl.CertificateError("Certificate not valid until: {}!".format(c.not_valid_before))
elif c.not_valid_after <= now:
raise ssl.CertificateError("Certificate expired as of: {})!".format(c.not_valid_after))
# Check certificate hostnames
names = []
common_name = c.subject.get_attributes_for_oid(x509.oid.NameOID.COMMON_NAME)
if common_name:
names.append(common_name[0].value)
try:
names.extend([alt.value for alt in c.extensions.get_extension_for_oid(x509.oid.ExtensionOID.SUBJECT_ALTERNATIVE_NAME).value])
except x509.ExtensionNotFound:
pass
names = set(names)
for name in names:
try:
ssl._dnsname_match(name, host)
break
except Exception:
continue
else:
# If we didn't break out, none of the names were valid
raise ssl.CertificateError("Hostname does not match certificate common name or any alternative names.")
def find_cert_in_cache(self, host, port, fingerprint, cached_certs, now):
"""
Try to find a cached certificate for the given host:port matching the
given fingerprint. If one is found, update the "last seen" DB value.
"""
for cached_fingerprint, cached_address, first, last, count in cached_certs:
if fingerprint == cached_fingerprint:
# Matched!
ui_out.debug("TOFU: Accepting previously seen ({} times) certificate {}".format(count, fingerprint))
self.db_cur.execute("""UPDATE cert_cache
SET last_seen=?, count=?
WHERE hostname=? AND port=? AND fingerprint=?""",
(now, count+1, host, port, fingerprint))
self.db_conn.commit()
return True
return False
def get_cached_cert_expiry(self, fingerprint):
"""
Parse the stored certificate with a given fingerprint and return its
expiry date.
"""
with open(os.path.join(self.certdir, fingerprint+".crt"), "rb") as fp:
previous_cert = fp.read()
previous_cert = x509.load_der_x509_certificate(previous_cert, _BACKEND)
return previous_cert.not_valid_after

50
src/av98/util.py Normal file
View File

@ -0,0 +1,50 @@
import os.path
# Cheap and cheerful URL detector
def looks_like_url(word):
return "." in word and word.startswith("gemini://")
def handle_filename_collisions(filename):
while os.path.exists(filename):
print("File %s already exists!" % filename)
filename = input("Choose a new one, or leave blank to abort: ")
return filename
def ask_yes_no(prompt, default=None):
print(prompt)
if default == True:
prompt = "(Y)/N: "
elif default == False:
prompt = "Y/(N): "
else:
prompt = "Y/N: "
while True:
resp = input(prompt)
if not resp.strip() and default != None:
return default
elif resp.strip().lower() in ("y", "yes"):
return True
elif resp.strip().lower() in ("n","no"):
return False
def fix_ipv6_url(url):
if not url.count(":") > 2: # Best way to detect them?
return url
# If there's a pair of []s in there, it's probably fine as is.
if "[" in url and "]" in url:
return url
# Easiest case is a raw address, no schema, no path.
# Just wrap it in square brackets and whack a slash on the end
if "/" not in url:
return "[" + url + "]/"
# Now the trickier cases...
if "://" in url:
schema, schemaless = url.split("://")
else:
schema, schemaless = None, url
if "/" in schemaless:
netloc, rest = schemaless.split("/",1)
schemaless = "[" + netloc + "]" + "/" + rest
if schema:
return schema + "://" + schemaless
return schemaless

View File

@ -1 +0,0 @@
sudo apt install less file xdg-utils xsel chafa timg python3-cryptography python3-requests python3-feedparser python3-bs4 python3-readability python3-pil python3-setproctitle python3-chardet file python3-lxml-html-clean wl-clipboard