From: Sergey Matveev Date: Wed, 28 Jul 2021 09:48:49 +0000 (+0300) Subject: Merge branch 'develop' X-Git-Tag: v7.5.0^0 X-Git-Url: http://www.git.cypherpunks.ru/?a=commitdiff_plain;h=666cb88f87341bc9ecce23550641c843027acca3;hp=22a3ed111c98f81f884df47bf1040a76c36e84ab;p=nncp.git Merge branch 'develop' --- diff --git a/doc/admin.texi b/doc/admin.texi index ff978e6..9a4c8e8 100644 --- a/doc/admin.texi +++ b/doc/admin.texi @@ -95,7 +95,7 @@ EOF @url{https://en.wikipedia.org/wiki/Inetd, inetd} service on UUCP's port: @example -uucp stream tcp6 nowait nncpuser /usr/local/bin/nncp-daemon nncp-daemon -quiet -inetd +uucp stream tcp6 nowait nncpuser /usr/local/bin/nncp-daemon nncp-daemon -quiet -ucspi @end example @item @@ -108,8 +108,8 @@ uucp stream tcp6 nowait nncpuser /usr/local/bin/nncp-daemon nncp-daemon -quiet - # cat > run < log/run < ... -$ nncp-bundle [options] -rx -delete [-dryrun] [NODE ...] < ... -$ nncp-bundle [options] -rx [-check] [-dryrun] [NODE ...] < ... +$ nncp-bundle [options] -tx [-delete] NODE [NODE @dots{}] > ... +$ nncp-bundle [options] -rx -delete [-dryrun] [NODE @dots{}] < ... +$ nncp-bundle [options] -rx [-check] [-dryrun] [NODE @dots{}] < ... @end example With @option{-tx} option, this command creates @ref{Bundles, bundle} of diff --git a/doc/cmd/nncp-call.texi b/doc/cmd/nncp-call.texi index 9dc32bd..54609fe 100644 --- a/doc/cmd/nncp-call.texi +++ b/doc/cmd/nncp-call.texi @@ -7,11 +7,12 @@ $ nncp-call [options] [-maxonlinetime INT] [-rx|-tx] [-list] - [-pkts PKT,PKT,...] + [-pkts PKT,PKT,@dots{}] [-rxrate INT] [-txrate INT] [-autotoss*] [-nock] + [-ucspi] NODE[:ADDR] [FORCEADDR] @end example @@ -42,6 +43,10 @@ success. Optionally you can force @option{FORCEADDR} address usage, instead of addresses taken from configuration file. You can specify both @verb{|host:port|} and @verb{#|some command#} formats. +If you specify @option{-ucspi} option, then it is assumed that you run +@command{nncp-call} command under some UCSPI-TCP compatible utility, +that provides read/write channels through 6/7 file descriptors. + @option{-autotoss} option runs tosser on node's spool every second during the call. All @option{-autotoss-*} options is the same as in @ref{nncp-toss} command. diff --git a/doc/cmd/nncp-caller.texi b/doc/cmd/nncp-caller.texi index 0b309d8..a4d0dc5 100644 --- a/doc/cmd/nncp-caller.texi +++ b/doc/cmd/nncp-caller.texi @@ -2,7 +2,7 @@ @section nncp-caller @example -$ nncp-caller [options] [NODE ...] +$ nncp-caller [options] [NODE @dots{}] @end example Croned daemon that calls remote nodes from time to time, according to diff --git a/doc/cmd/nncp-cfgdir.texi b/doc/cmd/nncp-cfgdir.texi index ec45ddd..c4f96e4 100644 --- a/doc/cmd/nncp-cfgdir.texi +++ b/doc/cmd/nncp-cfgdir.texi @@ -2,7 +2,7 @@ @section nncp-cfgdir @example -$ nncp-cfgdir [options] [-cfg ...] -dump /path/to/dir +$ nncp-cfgdir [options] [-cfg @dots{}] -dump /path/to/dir $ nncp-cfgdir [options] -load /path/to/dir > cfg.hjson @end example diff --git a/doc/cmd/nncp-daemon.texi b/doc/cmd/nncp-daemon.texi index aa11aca..4b5fa33 100644 --- a/doc/cmd/nncp-daemon.texi +++ b/doc/cmd/nncp-daemon.texi @@ -3,7 +3,7 @@ @example $ nncp-daemon [options] - [-maxconn INT] [-bind ADDR] [-inetd] + [-maxconn INT] [-bind ADDR] [-ucspi] [-autotoss*] [-nock] [-mcd-once] @end example @@ -16,14 +16,21 @@ time to time. can handle. @option{-bind} option specifies @option{addr:port} it must bind to and listen. -It could be run as @command{inetd} service, by specifying -@option{-inetd} option. Pay attention that because it uses -@code{stdin}/@code{stdout}, it can not effectively work with IO timeouts -and connection closing can propagate up to 5 minutes in practice. -Example inetd-entry: +It could be run as @url{http://cr.yp.to/ucspi-tcp.html, UCSPI-TCP} +service, by specifying @option{-ucspi} option. Pay attention that +because it uses @code{stdin}/@code{stdout}, it can not effectively work +with IO timeouts and connection closing can propagate up to 5 minutes in +practice. Example startup command: @verbatim -uucp stream tcp6 nowait nncpuser /usr/local/bin/nncp-daemon nncp-daemon -quiet -inetd +tcpserver -DHR -l 0 ::0 uucp nncp-daemon -quiet -ucspi +@end verbatim + +Also it is some kind of backward compatible with @command{inetd} +interface, just lacking knowledge or remote's address: + +@verbatim +uucp stream tcp6 nowait nncpuser /usr/local/bin/nncp-daemon nncp-daemon -quiet -ucspi @end verbatim @option{-autotoss} option runs tosser on node's spool every second diff --git a/doc/cmd/nncp-exec.texi b/doc/cmd/nncp-exec.texi index 7bd7508..7eb5e8a 100644 --- a/doc/cmd/nncp-exec.texi +++ b/doc/cmd/nncp-exec.texi @@ -2,8 +2,8 @@ @section nncp-exec @example -$ nncp-exec [options] [-use-tmp] [-nocompress] NODE HANDLE [ARG0 ARG1 ...] -$ nncp-exec [options] [-use-tmp] [-nocompress] area:AREA HANDLE [ARG0 ARG1 ...] +$ nncp-exec [options] [-use-tmp] [-nocompress] NODE HANDLE [ARG0 ARG1 @dots{}] +$ nncp-exec [options] [-use-tmp] [-nocompress] area:AREA HANDLE [ARG0 ARG1 @dots{}] @end example Send execution command to @option{NODE} for specified @option{HANDLE}. diff --git a/doc/cmd/nncp-hash.texi b/doc/cmd/nncp-hash.texi index adc6e8f..babd150 100644 --- a/doc/cmd/nncp-hash.texi +++ b/doc/cmd/nncp-hash.texi @@ -2,7 +2,7 @@ @section nncp-hash @example -$ nncp-hash [-file ...] [-seek X] [-debug] [-progress] +$ nncp-hash [-file @dots{}] [-seek X] [-debug] [-progress] @end example Calculate @ref{MTH} hash of either stdin, or @option{-file} if diff --git a/doc/cmd/nncp-trns.texi b/doc/cmd/nncp-trns.texi index 8e66205..c9b77cc 100644 --- a/doc/cmd/nncp-trns.texi +++ b/doc/cmd/nncp-trns.texi @@ -2,8 +2,8 @@ @section nncp-trns @example -$ nncp-trns [options] -via NODEx[,...] NODE:PKT -$ nncp-trns [options] -via NODEx[,...] /path/to/PKT +$ nncp-trns [options] -via NODEx[,@dots{}] NODE:PKT +$ nncp-trns [options] -via NODEx[,@dots{}] /path/to/PKT @end example diff --git a/doc/cronexpr.texi b/doc/cronexpr.texi index 3331b12..e0e4394 100644 --- a/doc/cronexpr.texi +++ b/doc/cronexpr.texi @@ -28,7 +28,7 @@ every month. Slashes describe increments of ranges. For example @verb{|3-59/15|} in the minute field indicate the third minute of the hour and every 15 minutes thereafter. The form @verb{|*/...|} is equivalent to the form -"first-last/...", that is, an increment over the largest possible range +"first-last/@dots{}", that is, an increment over the largest possible range of the field. @item Comma (@verb{|,|}) diff --git a/doc/download.texi b/doc/download.texi index 54c5217..d01f85f 100644 --- a/doc/download.texi +++ b/doc/download.texi @@ -28,6 +28,10 @@ Tarballs include all necessary required libraries: @multitable {XXXXX} {XXXX-XX-XX} {XXXX KiB} {link sign} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} @headitem Version @tab Date @tab Size @tab Tarball @tab SHA256 checksum +@item @ref{Release 7_4_0, 7.4.0} @tab 2021-07-19 @tab 1153 KiB +@tab @url{download/nncp-7.4.0.tar.xz, link} @url{download/nncp-7.4.0.tar.xz.sig, sign} +@tab @code{F7499FBF B0658054 F2732722 D54FE31E A0F105FD 9970B5BB 6413A9CC 065CB0EB} + @item @ref{Release 7_3_2, 7.3.2} @tab 2021-07-12 @tab 1141 KiB @tab @url{download/nncp-7.3.2.tar.xz, link} @url{download/nncp-7.3.2.tar.xz.sig, sign} @tab @code{65F6A230 04189D3F 307D160C AE97F99A 620DDA23 52821652 15DDC946 F6CC4B7F} diff --git a/doc/index.texi b/doc/index.texi index fb19da8..fc2ab37 100644 --- a/doc/index.texi +++ b/doc/index.texi @@ -63,7 +63,7 @@ There are also articles about its usage outside this website: @end menu @include comparison.texi -@include usecases.texi +@include usecases/index.texi @include workflow.texi @include news.texi @include russian.texi @@ -71,7 +71,7 @@ There are also articles about its usage outside this website: @include cfg/index.texi @include call.texi @include multicast.texi -@include integration.texi +@include integration/index.texi @include cmd/index.texi @include admin.texi @include niceness.texi diff --git a/doc/integration.texi b/doc/integration.texi deleted file mode 100644 index b7fa15f..0000000 --- a/doc/integration.texi +++ /dev/null @@ -1,540 +0,0 @@ -@node Integration -@unnumbered Integration with existing software - -Here is some examples of how you can solve popular tasks with NNCP, -making them store-and-forward friendly. - -@menu -* Index files for freqing: FreqIndex -* Postfix:: -* Exim:: -* Web feeds: Feeds -* Web pages: WARCs -* BitTorrent and huge files: BitTorrent -* Downloading service: DownloadService -* Git:: -* Multimedia streaming: Multimedia -@end menu - -@node FreqIndex -@section Index files for freqing - -In many cases you do not know exact files list on remote machine you -want to freq from. Because files can be updated there. It is useful to -run cron-ed job on it to create files listing you can freq and search -for files in it: - -@example -0 4 * * * cd /storage ; tmp=`mktemp` ; \ - tree -f -h -N --du --timefmt \%Y-\%m-\%d | - zstdmt -19 > $tmp && chmod 644 $tmp && mv $tmp TREE.txt.zst ; \ - tree -J -f --timefmt \%Y-\%m-\%d | - zstdmt -19 > $tmp && chmod 644 $tmp && mv $tmp TREE.json.zst -@end example - -@node Postfix -@section Integration with Postfix - -This section is taken from @url{http://www.postfix.org/UUCP_README.html, -Postfix and UUCP} manual and just replaces UUCP-related calls with NNCP -ones. - -@strong{Setting up a Postfix Internet to NNCP gateway} - -Here is how to set up a machine that sits on the Internet and that forwards -mail to a LAN that is connected via NNCP. - -@itemize - -@item You need an @ref{nncp-exec} program that extracts the sender -address from mail that arrives via NNCP, and that feeds the mail into -the Postfix @command{sendmail} command. - -@item Define a @command{pipe(8)} based mail delivery transport for -delivery via NNCP: -@example -/usr/local/etc/postfix/master.cf: -nncp unix - n n - - pipe - flags=Rqhu user=nncp argv=nncp-exec -quiet $nexthop sendmail $recipient -@end example - -This runs the @command{nncp-exec} command to place outgoing mail into -the NNCP queue after replacing @var{$nexthop} by the receiving NNCP -node and after replacing @var{$recipient} by the recipients. The -@command{pipe(8)} delivery agent executes the @command{nncp-exec} -command without assistance from the shell, so there are no problems with -shell meta characters in command-line parameters. - -Pay attention to @code{flags}, containing @code{R}, telling Postfix to -include @code{Return-Path:} header. Otherwise that envelope sender -information may be lost. Possibly you will also need somehow to -preserve that header on the receiving side, because @command{sendmail} -command will replace it. For example you can rename it before feeding to -@command{sendmail} with -@code{reformail -R Return-Path: X-Original-Return-Path: | sendmail}, or -extract with: - -@verbatiminclude sendmail.sh - -Also pay attention that @command{maildrop} does not like @code{From_} -mbox-style header, so you possibly want: - -@example -mailbox_command = reformail -f0 | maildrop -d $@{USER@} -@end example - -@item Specify that mail for @emph{example.com}, should be delivered via -NNCP, to a host named @emph{nncp-host}: - -@example -/usr/local/etc/postfix/transport: - example.com nncp:nncp-host - .example.com nncp:nncp-host -@end example - -See the @command{transport(5)} manual page for more details. - -@item Execute the command @command{postmap /etc/postfix/transport} -whenever you change the @file{transport} file. - -@item Enable @file{transport} table lookups: - -@example -/usr/local/etc/postfix/main.cf: - transport_maps = hash:$config_directory/transport -@end example - -@item Add @emph{example.com} to the list of domains that your site is -willing to relay mail for. - -@example -/usr/local/etc/postfix/main.cf: - relay_domains = example.com ...other relay domains... -@end example - -See the @option{relay_domains} configuration parameter description for -details. - -@item Execute the command @command{postfix reload} to make the changes -effective. - -@end itemize - -@strong{Setting up a Postfix LAN to NNCP gateway} - -Here is how to relay mail from a LAN via NNCP to the Internet. - -@itemize - -@item You need an @ref{nncp-exec} program that extracts the sender -address from mail that arrives via NNCP, and that feeds the mail into -the Postfix @command{sendmail} command. - -@item Specify that all remote mail must be sent via the @command{nncp} -mail transport to your NNCP gateway host, say, @emph{nncp-gateway}: - -@example -/usr/local/etc/postfix/main.cf: - relayhost = nncp-gateway - default_transport = nncp -@end example - -Postfix 2.0 and later also allows the following more succinct form: - -@example -/usr/local/etc/postfix/main.cf: - default_transport = nncp:nncp-gateway -@end example - -@item Define a @command{pipe(8)} based message delivery transport for -mail delivery via NNCP: - -@example -/usr/local/etc/postfix/master.cf: -nncp unix - n n - - pipe - flags=Fqhu user=nncp argv=nncp-exec -quiet $nexthop sendmail $recipient -@end example - -This runs the @command{nncp-exec} command to place outgoing mail into -the NNCP queue. It substitutes the hostname (@emph{nncp-gateway}, or -whatever you specified) and the recipients before execution of the -command. The @command{nncp-exec} command is executed without assistance -from the shell, so there are no problems with shell meta characters. - -@item Execute the command @command{postfix reload} to make the changes -effective. - -@end itemize - -@node Exim -@section Integration with Exim - -This section is unaltered copy-paste of -@url{https://changelog.complete.org/archives/10165-asynchronous-email-exim-over-nncp-or-uucp, Asynchronous Email: Exim over NNCP (or UUCP)} -article by John Goerzen, with his permission. - -@strong{Sending from Exim to a smarthost} - -One common use for async email is from a satellite system: one that -doesn't receive mail, or have local mailboxes, but just needs to get -email out to the Internet. This is a common situation even for -conventionally-connected systems; in Exim speak, this is a "satellite -system that routes mail via a smarthost". That is, every outbound -message goes to a specific target, which then is responsible for -eventual delivery (over the Internet, LAN, whatever). - -This is fairly simple in Exim. - -We actually have two choices for how to do this: bsmtp or rmail mode. -bsmtp (batch SMTP) is the more modern way, and is essentially a -derivative of SMTP that explicitly can be queued asynchronously. -Basically it's a set of SMTP commands that can be saved in a file. The -alternative is "rmail" (which is just an alias for sendmail these days), -where the data is piped to rmail/sendmail with the recipients given on -the command line. Both can work with Exim and NNCP, but because we're -doing shiny new things, we'll use bsmtp. - -These instructions are loosely based on the -@url{https://people.debian.org/~jdg/bsmtp.html, Using outgoing BSMTP with Exim HOWTO}. -Some of these may assume Debianness in the configuration, but should be -easily enough extrapolated to other configs as well. - -First, configure Exim to use satellite mode with minimal DNS lookups -(assuming that you may not have working DNS anyhow). - -Then, in the Exim primary router section for smarthost -(@file{router/200_exim4-config_primary} in Debian split configurations), -just change @code{transport = remote_smtp_smarthost to transport = nncp}. - -Now, define the NNCP transport. If you are on Debian, you might name this -@file{transports/40_exim4-config_local_nncp}: - -@example -nncp: - debug_print = "T: nncp transport for $local_part@@$domain" - driver = pipe - user = nncp - batch_max = 100 - use_bsmtp - command = /usr/local/nncp/bin/nncp-exec -noprogress -quiet hostname_goes_here rsmtp -.ifdef REMOTE_SMTP_HEADERS_REWRITE - headers_rewrite = REMOTE_SMTP_HEADERS_REWRITE -.endif -.ifdef REMOTE_SMTP_RETURN_PATH - return_path = REMOTE_SMTP_RETURN_PATH -.endif -@end example - -This is pretty straightforward. We pipe to @command{nncp-exec}, run it -as the nncp user. @command{nncp-exec} sends it to a target node and runs -whatever that node has called @command{rsmtp} (the command to receive -bsmtp data). When the target node processes the request, it will run the -configured command and pipe the data in to it. - -@strong{More complicated: Routing to various NNCP nodes} - -Perhaps you would like to be able to send mail directly to various NNCP -nodes. There are a lot of ways to do that. - -Fundamentally, you will need a setup similar to the UUCP example in -@url{https://www.exim.org/exim-html-current/doc/html/spec_html/ch-the_manualroute_router.html, -Exim's manualroute manual}, which lets you define how to reach various -hosts via UUCP/NNCP. Perhaps you have a star topology (every NNCP node -exchanges email with a central hub). In the NNCP world, you have two -choices of how you do this. You could, at the Exim level, make the -central hub the smarthost for all the side nodes, and let it -redistribute mail. That would work, but requires decrypting messages at -the hub to let Exim process. The other alternative is to configure NNCP -to just send to the destinations via the central hub; that takes -advantage of onion routing and doesn't require any Exim processing at -the central hub at all. - -@strong{Receiving mail from NNCP} - -On the receiving side, first you need to configure NNCP to authorize the -execution of a mail program. In the section of your receiving host where -you set the permissions for the client, include something like this: - -@example -exec: @{ - rsmtp: ["/usr/sbin/sendmail", "-bS"] -@} -@end example - -The -bS option is what tells Exim to receive BSMTP on @code{stdin}. - -Now, you need to tell Exim that nncp is a trusted user (able to set From -headers arbitrarily). Assuming you are running NNCP as the nncp user, -then add @code{MAIN_TRUSTED_USERS = nncp} to a file such as -@file{/etc/exim4/conf.d/main/01_exim4-config_local-nncp}. That's it! - -Some hosts, of course, both send and receive mail via NNCP and will need -configurations for both. - -@node Feeds -@section Integration with Web feeds - -RSS and Atom feeds could be collected using -@url{https://github.com/wking/rss2email, rss2email} program. It converts -all incoming feed entries to email messages. Read about how to integrate -@ref{Postfix}/@ref{Exim} with email. @command{rss2email} could be run in -a cron, to collect feeds without any user interaction. Also this program -supports ETags and won't pollute the channel if remote server supports -them too. - -After installing @command{rss2email}, create configuration file: - -@example -$ r2e new rss-robot@@address.com -@end example - -and add feeds you want to retrieve: - -@example -$ r2e add http://www.git.cypherpunks.ru/?p=nncp.git;a=atom -@end example - -and run the process: - -@example -$ r2e run -@end example - -@node WARCs -@section Integration with Web pages - -Simple HTML web page can be downloaded very easily for sending and -viewing it offline after: - -@example -$ wget http://www.example.com/page.html -@end example - -But most web pages contain links to images, CSS and JavaScript files, -required for complete rendering. -@url{https://www.gnu.org/software/wget/, GNU Wget} supports that -documents parsing and understanding page dependencies. You can download -the whole page with dependencies the following way: - -@example -$ wget \ - --page-requisites \ - --convert-links \ - --adjust-extension \ - --restrict-file-names=ascii \ - --span-hosts \ - --random-wait \ - --execute robots=off \ - http://www.example.com/page.html -@end example - -that will create @file{www.example.com} directory with all files -necessary to view @file{page.html} web page. You can create single file -compressed tarball with that directory and send it to remote node: - -@example -$ tar cf - www.example.com | zstd | - nncp-file - remote.node:www.example.com-page.tar.zst -@end example - -But there are multi-paged articles, there are the whole interesting -sites you want to get in a single package. You can mirror the whole web -site by utilizing @command{wget}'s recursive feature: - -@example -$ wget \ - --recursive \ - --timestamping \ - -l inf \ - --no-remove-listing \ - --no-parent \ - [...] - http://www.example.com/ -@end example - -There is a standard for creating -@url{https://en.wikipedia.org/wiki/Web_ARChive, Web ARChives}: -@strong{WARC}. Fortunately again, @command{wget} supports it as an -output format. - -@example -$ wget \ - --warc-file www.example_com-$(date '+%Y%M%d%H%m%S') \ - --no-warc-compression \ - --no-warc-keep-log \ - [...] - http://www.example.com/ -@end example - -That command will create uncompressed @file{www.example_com-XXX.warc} -web archive. By default, WARCs are compressed using -@url{https://en.wikipedia.org/wiki/Gzip, gzip}, but, in example above, -we have disabled it to compress with stronger and faster -@url{https://en.wikipedia.org/wiki/Zstd, zstd}, before sending via -@command{nncp-file}. - -There are plenty of software acting like HTTP proxy for your browser, -allowing to view that WARC files. However you can extract files from -that archive using @url{https://pypi.python.org/pypi/Warcat, warcat} -utility, producing usual directory hierarchy: - -@example -$ python3 -m warcat extract \ - www.example_com-XXX.warc \ - --output-dir www.example.com-XXX \ - --progress -@end example - -@node BitTorrent -@section BitTorrent and huge files - -If dealing with @ref{Git}, @ref{Feeds, web feeds} and @ref{Multimedia, -multimedia} goes relatively fast, then BitTorrent and huge files -consumes much time. You can not wait for downloads finish, but want to -queue them after. - -@url{http://aria2.github.io/, aria2} multi-protocol download utility -could be used for solving that issue conveniently. It supports HTTP, -HTTPS, FTP, SFTP and BitTorrent protocols, together with -@url{http://tools.ietf.org/html/rfc5854, Metalink} format. BitTorrent -support is fully-featured: UDP trackers, DHT, PEX, encryption, magnet -URIs, Web-seeding, selective downloads, LPD. @command{aria2} can -accelerate HTTP*/*FTP downloads by segmented multiple parallel -connections. - -You can queue you files after they are completely downloaded. -@file{aria2-downloaded.sh} contents: - -@verbatiminclude aria2-downloaded.sh - -Also you can prepare -@url{http://aria2.github.io/manual/en/html/aria2c.html#files, input file} -with the jobs you want to download: - -@example -$ cat jobs -http://www.nncpgo.org/download/nncp-0.11.tar.xz - out=nncp.txz -http://www.nncpgo.org/download/nncp-0.11.tar.xz.sig - out=nncp.txz.sig -$ aria2c \ - --on-download-complete aria2-downloaded.sh \ - --input-file jobs -@end example - -and all that downloaded (@file{nncp.txz}, @file{nncp.txz.sig}) files -will be sent to @file{remote.node} when finished. - -@node DownloadService -@section Downloading service - -Previous sections tell about manual downloading and sending results to -remote node. But one wish to remotely initiate downloading. That can be -easily solved with @ref{CfgExec, exec} handles. - -@verbatim -exec: { - warcer: ["/bin/sh", "/path/to/warcer.sh"] - wgeter: ["/bin/sh", "/path/to/wgeter.sh"] - aria2c: [ - "/usr/local/bin/aria2c", - "--on-download-complete", "aria2-downloaded.sh", - "--on-bt-download-complete", "aria2-downloaded.sh" - ] -} -@end verbatim - -@file{warcer.sh} contents: - -@verbatiminclude warcer.sh - -@file{wgeter.sh} contents: - -@verbatiminclude wgeter.sh - -Now you can queue that node to send you some website's page, file or -BitTorrents: - -@example -$ echo http://www.nncpgo.org/Postfix.html | - nncp-exec remote.node warcer postfix-whole-page -$ echo http://www.nncpgo.org/Postfix.html | - nncp-exec remote.node wgeter postfix-html-page -$ echo \ - http://www.nncpgo.org/download/nncp-0.11.tar.xz - http://www.nncpgo.org/download/nncp-0.11.tar.xz.sig | - nncp-exec remote.node aria2c -@end example - -@node Git -@section Integration with Git - -@url{https://git-scm.com/, Git} version control system already has all -necessary tools for store-and-forward networking. -@url{https://git-scm.com/docs/git-bundle, git-bundle} command is -everything you need. - -Use it to create bundles containing all required blobs/trees/commits and tags: - -@example -$ git bundle create repo-initial.bundle master --tags --branches -$ git tag -f last-bundle -$ nncp-file repo-initial.bundle remote.node:repo-$(date % '+%Y%M%d%H%m%S').bundle -@end example - -Do usual working with the Git: commit, add, branch, checkout, etc. When -you decide to queue your changes for sending, create diff-ed bundle and -transfer them: - -@example -$ git bundle create repo-$(date '+%Y%M%d%H%m%S').bundle last-bundle..master -or maybe -$ git bundle create repo-$(date '+%Y%M%d').bundle --since=10.days master -@end example - -Received bundle on remote machine acts like usual remote: - -@example -$ git clone -b master repo-XXX.bundle -@end example - -overwrite @file{repo.bundle} file with newer bundles you retrieve and -fetch all required branches and commits: - -@example -$ git pull # assuming that origin remote points to repo.bundle -$ git fetch repo.bundle master:localRef -$ git ls-remote repo.bundle -@end example - -Bundles are also useful when cloning huge repositories (like Linux has). -Git's native protocol does not support any kind of interrupted download -resuming, so you will start from the beginning if connection is lost. -Bundles, being an ordinary files, can be downloaded with native -HTTP/FTP/NNCP resuming capabilities. After you fetch repository via the -bundle, you can add an ordinary @file{git://} remote and fetch the -difference. - -Also you can find the following exec-handler useful: - -@verbatiminclude git-bundler.sh - -And it allows you to request for bundles like that: -@code{echo some-old-commit..master | nncp-exec REMOTE bundler REPONAME}. - -@node Multimedia -@section Integration with multimedia streaming - -Many video and audio streams could be downloaded using -@url{http://yt-dl.org/, youtube-dl} program. -@url{https://rg3.github.io/youtube-dl/supportedsites.html, Look} how -many of them are supported, including @emph{Dailymotion}, @emph{Vimeo} -and @emph{YouTube}. - -When you multimedia becomes an ordinary file, you can transfer it easily. - -@example -$ youtube-dl \ - --exec 'nncp-file @{@} remote.node:' \ - 'https://www.youtube.com/watch?list=PLd2Cw8x5CytxPAEBwzilrhQUHt_UN10FJ' -@end example diff --git a/doc/integration/bittorrent.texi b/doc/integration/bittorrent.texi new file mode 100644 index 0000000..841391e --- /dev/null +++ b/doc/integration/bittorrent.texi @@ -0,0 +1,39 @@ +@node BitTorrent +@section BitTorrent and huge files + +If dealing with @ref{Git}, @ref{Feeds, web feeds} and @ref{Multimedia, +multimedia} goes relatively fast, then BitTorrent and huge files +consumes much time. You can not wait for downloads finish, but want to +queue them after. + +@url{http://aria2.github.io/, aria2} multi-protocol download utility +could be used for solving that issue conveniently. It supports HTTP, +HTTPS, FTP, SFTP and BitTorrent protocols, together with +@url{http://tools.ietf.org/html/rfc5854, Metalink} format. BitTorrent +support is fully-featured: UDP trackers, DHT, PEX, encryption, magnet +URIs, Web-seeding, selective downloads, LPD. @command{aria2} can +accelerate HTTP*/*FTP downloads by segmented multiple parallel +connections. + +You can queue you files after they are completely downloaded. +@file{aria2-downloaded.sh} contents: + +@verbatiminclude aria2-downloaded.sh + +Also you can prepare +@url{http://aria2.github.io/manual/en/html/aria2c.html#files, input file} +with the jobs you want to download: + +@example +$ cat jobs +http://www.nncpgo.org/download/nncp-0.11.tar.xz + out=nncp.txz +http://www.nncpgo.org/download/nncp-0.11.tar.xz.sig + out=nncp.txz.sig +$ aria2c \ + --on-download-complete aria2-downloaded.sh \ + --input-file jobs +@end example + +and all that downloaded (@file{nncp.txz}, @file{nncp.txz.sig}) files +will be sent to @file{remote.node} when finished. diff --git a/doc/integration/download.texi b/doc/integration/download.texi new file mode 100644 index 0000000..c4ca2ac --- /dev/null +++ b/doc/integration/download.texi @@ -0,0 +1,40 @@ +@node DownloadService +@section Downloading service + +Previous sections tell about manual downloading and sending results to +remote node. But one wish to remotely initiate downloading. That can be +easily solved with @ref{CfgExec, exec} handles. + +@verbatim +exec: { + warcer: ["/bin/sh", "/path/to/warcer.sh"] + wgeter: ["/bin/sh", "/path/to/wgeter.sh"] + aria2c: [ + "/usr/local/bin/aria2c", + "--on-download-complete", "aria2-downloaded.sh", + "--on-bt-download-complete", "aria2-downloaded.sh" + ] +} +@end verbatim + +@file{warcer.sh} contents: + +@verbatiminclude warcer.sh + +@file{wgeter.sh} contents: + +@verbatiminclude wgeter.sh + +Now you can queue that node to send you some website's page, file or +BitTorrents: + +@example +$ echo http://www.nncpgo.org/Postfix.html | + nncp-exec remote.node warcer postfix-whole-page +$ echo http://www.nncpgo.org/Postfix.html | + nncp-exec remote.node wgeter postfix-html-page +$ echo \ + http://www.nncpgo.org/download/nncp-0.11.tar.xz + http://www.nncpgo.org/download/nncp-0.11.tar.xz.sig | + nncp-exec remote.node aria2c +@end example diff --git a/doc/integration/exim.texi b/doc/integration/exim.texi new file mode 100644 index 0000000..26472ea --- /dev/null +++ b/doc/integration/exim.texi @@ -0,0 +1,105 @@ +@node Exim +@section Integration with Exim + +This section is unaltered copy-paste of +@url{https://changelog.complete.org/archives/10165-asynchronous-email-exim-over-nncp-or-uucp, Asynchronous Email: Exim over NNCP (or UUCP)} +article by John Goerzen, with his permission. + +@strong{Sending from Exim to a smarthost} + +One common use for async email is from a satellite system: one that +doesn't receive mail, or have local mailboxes, but just needs to get +email out to the Internet. This is a common situation even for +conventionally-connected systems; in Exim speak, this is a "satellite +system that routes mail via a smarthost". That is, every outbound +message goes to a specific target, which then is responsible for +eventual delivery (over the Internet, LAN, whatever). + +This is fairly simple in Exim. + +We actually have two choices for how to do this: @command{bsmtp} or +@command{rmail} mode. bsmtp (batch SMTP) is the more modern way, and is +essentially a derivative of SMTP that explicitly can be queued +asynchronously. Basically it's a set of SMTP commands that can be saved +in a file. The alternative is @command{rmail} (which is just an alias +for sendmail these days), where the data is piped to +@command{rmail}/@command{sendmail} with the recipients given on the +command line. Both can work with Exim and NNCP, but because we're doing +shiny new things, we'll use @command{bsmtp}. + +These instructions are loosely based on the +@url{https://people.debian.org/~jdg/bsmtp.html, Using outgoing BSMTP with Exim HOWTO}. +Some of these may assume Debianness in the configuration, but should be +easily enough extrapolated to other configs as well. + +First, configure Exim to use satellite mode with minimal DNS lookups +(assuming that you may not have working DNS anyhow). + +Then, in the Exim primary router section for smarthost +(@file{router/200_exim4-config_primary} in Debian split configurations), +just change @code{transport = remote_smtp_smarthost to transport = nncp}. + +Now, define the NNCP transport. If you are on Debian, you might name this +@file{transports/40_exim4-config_local_nncp}: + +@example +nncp: + debug_print = "T: nncp transport for $local_part@@$domain" + driver = pipe + user = nncp + batch_max = 100 + use_bsmtp + command = /usr/local/nncp/bin/nncp-exec -noprogress -quiet hostname_goes_here rsmtp +.ifdef REMOTE_SMTP_HEADERS_REWRITE + headers_rewrite = REMOTE_SMTP_HEADERS_REWRITE +.endif +.ifdef REMOTE_SMTP_RETURN_PATH + return_path = REMOTE_SMTP_RETURN_PATH +.endif +@end example + +This is pretty straightforward. We pipe to @command{nncp-exec}, run it +as the nncp user. @command{nncp-exec} sends it to a target node and runs +whatever that node has called @command{rsmtp} (the command to receive +bsmtp data). When the target node processes the request, it will run the +configured command and pipe the data in to it. + +@strong{More complicated: Routing to various NNCP nodes} + +Perhaps you would like to be able to send mail directly to various NNCP +nodes. There are a lot of ways to do that. + +Fundamentally, you will need a setup similar to the UUCP example in +@url{https://www.exim.org/exim-html-current/doc/html/spec_html/ch-the_manualroute_router.html, +Exim's manualroute manual}, which lets you define how to reach various +hosts via UUCP/NNCP. Perhaps you have a star topology (every NNCP node +exchanges email with a central hub). In the NNCP world, you have two +choices of how you do this. You could, at the Exim level, make the +central hub the smarthost for all the side nodes, and let it +redistribute mail. That would work, but requires decrypting messages at +the hub to let Exim process. The other alternative is to configure NNCP +to just send to the destinations via the central hub; that takes +advantage of onion routing and doesn't require any Exim processing at +the central hub at all. + +@strong{Receiving mail from NNCP} + +On the receiving side, first you need to configure NNCP to authorize the +execution of a mail program. In the section of your receiving host where +you set the permissions for the client, include something like this: + +@example +exec: @{ + rsmtp: ["/usr/sbin/sendmail", "-bS"] +@} +@end example + +The @option{-bS} option is what tells Exim to receive BSMTP on @code{stdin}. + +Now, you need to tell Exim that nncp is a trusted user (able to set From +headers arbitrarily). Assuming you are running NNCP as the @code{nncp} user, +then add @code{MAIN_TRUSTED_USERS = nncp} to a file such as +@file{/etc/exim4/conf.d/main/01_exim4-config_local-nncp}. That's it! + +Some hosts, of course, both send and receive mail via NNCP and will need +configurations for both. diff --git a/doc/integration/feeds.texi b/doc/integration/feeds.texi new file mode 100644 index 0000000..27a25c1 --- /dev/null +++ b/doc/integration/feeds.texi @@ -0,0 +1,28 @@ +@node Feeds +@section Integration with Web feeds + +RSS and Atom feeds could be collected using +@url{https://github.com/wking/rss2email, rss2email} program. It converts +all incoming feed entries to email messages. Read about how to integrate +@ref{Postfix}/@ref{Exim} with email. @command{rss2email} could be run in +a cron, to collect feeds without any user interaction. Also this program +supports ETags and won't pollute the channel if remote server supports +them too. + +After installing @command{rss2email}, create configuration file: + +@example +$ r2e new rss-robot@@address.com +@end example + +and add feeds you want to retrieve: + +@example +$ r2e add http://www.git.cypherpunks.ru/?p=nncp.git;a=atom +@end example + +and run the process: + +@example +$ r2e run +@end example diff --git a/doc/integration/freqindex.texi b/doc/integration/freqindex.texi new file mode 100644 index 0000000..cec8463 --- /dev/null +++ b/doc/integration/freqindex.texi @@ -0,0 +1,15 @@ +@node FreqIndex +@section Index files for freqing + +In many cases you do not know exact files list on remote machine you +want to freq from. Because files can be updated there. It is useful to +run cron-ed job on it to create files listing you can freq and search +for files in it: + +@example +0 4 * * * cd /storage ; tmp=`mktemp` ; \ + tree -f -h -N --du --timefmt \%Y-\%m-\%d | + zstdmt -19 > $tmp && chmod 644 $tmp && mv $tmp TREE.txt.zst ; \ + tree -J -f --timefmt \%Y-\%m-\%d | + zstdmt -19 > $tmp && chmod 644 $tmp && mv $tmp TREE.json.zst +@end example diff --git a/doc/integration/git.texi b/doc/integration/git.texi new file mode 100644 index 0000000..a159cf8 --- /dev/null +++ b/doc/integration/git.texi @@ -0,0 +1,55 @@ +@node Git +@section Integration with Git + +@url{https://git-scm.com/, Git} version control system already has all +necessary tools for store-and-forward networking. +@url{https://git-scm.com/docs/git-bundle, git-bundle} command is +everything you need. + +Use it to create bundles containing all required blobs/trees/commits and tags: + +@example +$ git bundle create repo-initial.bundle master --tags --branches +$ git tag -f last-bundle +$ nncp-file repo-initial.bundle remote.node:repo-$(date % '+%Y%M%d%H%m%S').bundle +@end example + +Do usual working with the Git: commit, add, branch, checkout, etc. When +you decide to queue your changes for sending, create diff-ed bundle and +transfer them: + +@example +$ git bundle create repo-$(date '+%Y%M%d%H%m%S').bundle last-bundle..master +or maybe +$ git bundle create repo-$(date '+%Y%M%d').bundle --since=10.days master +@end example + +Received bundle on remote machine acts like usual remote: + +@example +$ git clone -b master repo-XXX.bundle +@end example + +overwrite @file{repo.bundle} file with newer bundles you retrieve and +fetch all required branches and commits: + +@example +$ git pull # assuming that origin remote points to repo.bundle +$ git fetch repo.bundle master:localRef +$ git ls-remote repo.bundle +@end example + +Bundles are also useful when cloning huge repositories (like Linux has). +Git's native protocol does not support any kind of interrupted download +resuming, so you will start from the beginning if connection is lost. +Bundles, being an ordinary files, can be downloaded with native +HTTP/FTP/NNCP resuming capabilities. After you fetch repository via the +bundle, you can add an ordinary @file{git://} remote and fetch the +difference. + +Also you can find the following exec-handler useful: + +@verbatiminclude git-bundler.sh + +And it allows you to request for bundles like that: +@code{echo some-old-commit..master | nncp-exec REMOTE bundler REPONAME}. diff --git a/doc/integration/index.texi b/doc/integration/index.texi new file mode 100644 index 0000000..315868b --- /dev/null +++ b/doc/integration/index.texi @@ -0,0 +1,29 @@ +@node Integration +@unnumbered Integration with existing software + +Here is some examples of how you can solve popular tasks with NNCP, +making them store-and-forward friendly. + +@menu +* Index files for freqing: FreqIndex +* Postfix:: +* Exim:: +* Web feeds: Feeds +* Web pages: WARCs +* BitTorrent and huge files: BitTorrent +* Downloading service: DownloadService +* Git:: +* Multimedia streaming: Multimedia +* Serial connection: PPP +@end menu + +@include integration/freqindex.texi +@include integration/postfix.texi +@include integration/exim.texi +@include integration/feeds.texi +@include integration/warc.texi +@include integration/bittorrent.texi +@include integration/download.texi +@include integration/git.texi +@include integration/multimedia.texi +@include integration/ppp.texi diff --git a/doc/integration/multimedia.texi b/doc/integration/multimedia.texi new file mode 100644 index 0000000..bcdfb7b --- /dev/null +++ b/doc/integration/multimedia.texi @@ -0,0 +1,16 @@ +@node Multimedia +@section Integration with multimedia streaming + +Many video and audio streams could be downloaded using +@url{http://yt-dl.org/, youtube-dl} program. +@url{https://rg3.github.io/youtube-dl/supportedsites.html, Look} how +many of them are supported, including @emph{Dailymotion}, @emph{Vimeo} +and @emph{YouTube}. + +When you multimedia becomes an ordinary file, you can transfer it easily. + +@example +$ youtube-dl \ + --exec 'nncp-file @{@} remote.node:' \ + 'https://www.youtube.com/watch?list=PLd2Cw8x5CytxPAEBwzilrhQUHt_UN10FJ' +@end example diff --git a/doc/integration/postfix.texi b/doc/integration/postfix.texi new file mode 100644 index 0000000..f02dca0 --- /dev/null +++ b/doc/integration/postfix.texi @@ -0,0 +1,133 @@ +@node Postfix +@section Integration with Postfix + +This section is taken from @url{http://www.postfix.org/UUCP_README.html, +Postfix and UUCP} manual and just replaces UUCP-related calls with NNCP +ones. + +@strong{Setting up a Postfix Internet to NNCP gateway} + +Here is how to set up a machine that sits on the Internet and that forwards +mail to a LAN that is connected via NNCP. + +@itemize + +@item You need an @ref{nncp-exec} program that extracts the sender +address from mail that arrives via NNCP, and that feeds the mail into +the Postfix @command{sendmail} command. + +@item Define a @command{pipe(8)} based mail delivery transport for +delivery via NNCP: +@example +/usr/local/etc/postfix/master.cf: +nncp unix - n n - - pipe + flags=Rqhu user=nncp argv=nncp-exec -quiet $nexthop sendmail $recipient +@end example + +This runs the @command{nncp-exec} command to place outgoing mail into +the NNCP queue after replacing @var{$nexthop} by the receiving NNCP +node and after replacing @var{$recipient} by the recipients. The +@command{pipe(8)} delivery agent executes the @command{nncp-exec} +command without assistance from the shell, so there are no problems with +shell meta characters in command-line parameters. + +Pay attention to @code{flags}, containing @code{R}, telling Postfix to +include @code{Return-Path:} header. Otherwise that envelope sender +information may be lost. Possibly you will also need somehow to +preserve that header on the receiving side, because @command{sendmail} +command will replace it. For example you can rename it before feeding to +@command{sendmail} with +@code{reformail -R Return-Path: X-Original-Return-Path: | sendmail}, or +extract with: + +@verbatiminclude sendmail.sh + +Also pay attention that @command{maildrop} does not like @code{From_} +mbox-style header, so you possibly want: + +@example +mailbox_command = reformail -f0 | maildrop -d $@{USER@} +@end example + +@item Specify that mail for @emph{example.com}, should be delivered via +NNCP, to a host named @emph{nncp-host}: + +@example +/usr/local/etc/postfix/transport: + example.com nncp:nncp-host + .example.com nncp:nncp-host +@end example + +See the @command{transport(5)} manual page for more details. + +@item Execute the command @command{postmap /etc/postfix/transport} +whenever you change the @file{transport} file. + +@item Enable @file{transport} table lookups: + +@example +/usr/local/etc/postfix/main.cf: + transport_maps = hash:$config_directory/transport +@end example + +@item Add @emph{example.com} to the list of domains that your site is +willing to relay mail for. + +@example +/usr/local/etc/postfix/main.cf: + relay_domains = example.com @dots{}other relay domains@dots{} +@end example + +See the @option{relay_domains} configuration parameter description for +details. + +@item Execute the command @command{postfix reload} to make the changes +effective. + +@end itemize + +@strong{Setting up a Postfix LAN to NNCP gateway} + +Here is how to relay mail from a LAN via NNCP to the Internet. + +@itemize + +@item You need an @ref{nncp-exec} program that extracts the sender +address from mail that arrives via NNCP, and that feeds the mail into +the Postfix @command{sendmail} command. + +@item Specify that all remote mail must be sent via the @command{nncp} +mail transport to your NNCP gateway host, say, @emph{nncp-gateway}: + +@example +/usr/local/etc/postfix/main.cf: + relayhost = nncp-gateway + default_transport = nncp +@end example + +Postfix 2.0 and later also allows the following more succinct form: + +@example +/usr/local/etc/postfix/main.cf: + default_transport = nncp:nncp-gateway +@end example + +@item Define a @command{pipe(8)} based message delivery transport for +mail delivery via NNCP: + +@example +/usr/local/etc/postfix/master.cf: +nncp unix - n n - - pipe + flags=Fqhu user=nncp argv=nncp-exec -quiet $nexthop sendmail $recipient +@end example + +This runs the @command{nncp-exec} command to place outgoing mail into +the NNCP queue. It substitutes the hostname (@emph{nncp-gateway}, or +whatever you specified) and the recipients before execution of the +command. The @command{nncp-exec} command is executed without assistance +from the shell, so there are no problems with shell meta characters. + +@item Execute the command @command{postfix reload} to make the changes +effective. + +@end itemize diff --git a/doc/integration/ppp.texi b/doc/integration/ppp.texi new file mode 100644 index 0000000..e274cd1 --- /dev/null +++ b/doc/integration/ppp.texi @@ -0,0 +1,78 @@ +@node PPP +@section Serial connection + +It is not trivial to run online @command{nncp-daemon}, +@command{nncp-call} and @command{nncp-caller} commands over the serial +link, because it is link without built-in error detection. For efficient +usage you have to use some kind of window-sliding error correction +protocol, like Kermit, ZMODEM, UUCP's g-protocol and similar well known +ones. + +However TCP is already satisfying and existing protocol for the same +purposes. So it would be more easier to bring up the IP interconnection +and use TCP over it. Most distributions already have +@url{https://en.wikipedia.org/wiki/Point-to-point_protocol, PPP} +protocol out-of-box. + +Ordinary man page for @command{ppp} in FreeBSD is enough for being able +to setup it: + +@itemize + +@item Enable PPP-aware default terminal to run @command{ppplogin} script: + +@example +/etc/gettytab: + default:pp=/usr/local/bin/ppplogin:@dots{} +@end example + +@example +/usr/local/bin/ppplogin: + #!/bin/sh + exec /usr/sbin/ppp -direct incoming +@end example + +@item Enable listening on necessary UART: + +@example +/etc/ttys: + ttyU0 "/usr/libexec/getty 3wire.115200" vt100 on +@end example + +@item +Create @code{incoming} PPP profile, allowing authenticated @code{ppp} +user to log in: + +@example +/etc/ppp/ppp.conf: + incoming: + allow ppp + disable deflate pred1 mppe protocomp vjcomp ipcp dns + enable lqr # null-modem cables might not have carrier detection +/etc/ppp/ppp.secret: + ppp PASSWORD +@end example + +@item +Configure PPP client to access that server: + +@example +/etc/ppp/ppp.conf: + outgoing: + set device /dev/cuaU0 + set speed 115200 + set dial + set login + set authname ppp + set authkey PASSWORD + disable deflate pred1 mppe protocomp vjcomp ipcp dns + enable lqr +@end example + +@end itemize + +That configuration does not negotiate any kind of IPv4 addresses, +routing or DNS servers. Also all compression is turned off, because +NNCP's traffic is encrypted and uncompressible. Only IPV6CP will +negotiate IPv6 link-local addresses, on which you can run @ref{MCD, +multicast discovered} daemons for simplicity. diff --git a/doc/integration/warc.texi b/doc/integration/warc.texi new file mode 100644 index 0000000..de7cc92 --- /dev/null +++ b/doc/integration/warc.texi @@ -0,0 +1,82 @@ +@node WARCs +@section Integration with Web pages + +Simple HTML web page can be downloaded very easily for sending and +viewing it offline after: + +@example +$ wget http://www.example.com/page.html +@end example + +But most web pages contain links to images, CSS and JavaScript files, +required for complete rendering. +@url{https://www.gnu.org/software/wget/, GNU Wget} supports that +documents parsing and understanding page dependencies. You can download +the whole page with dependencies the following way: + +@example +$ wget \ + --page-requisites \ + --convert-links \ + --adjust-extension \ + --restrict-file-names=ascii \ + --span-hosts \ + --random-wait \ + --execute robots=off \ + http://www.example.com/page.html +@end example + +that will create @file{www.example.com} directory with all files +necessary to view @file{page.html} web page. You can create single file +compressed tarball with that directory and send it to remote node: + +@example +$ tar cf - www.example.com | zstd | + nncp-file - remote.node:www.example.com-page.tar.zst +@end example + +But there are multi-paged articles, there are the whole interesting +sites you want to get in a single package. You can mirror the whole web +site by utilizing @command{wget}'s recursive feature: + +@example +$ wget \ + --recursive \ + --timestamping \ + -l inf \ + --no-remove-listing \ + --no-parent [@dots{}] \ + http://www.example.com/ +@end example + +There is a standard for creating +@url{https://en.wikipedia.org/wiki/Web_ARChive, Web ARChives}: +@strong{WARC}. Fortunately again, @command{wget} supports it as an +output format. + +@example +$ wget \ + --warc-file www.example_com-$(date '+%Y%M%d%H%m%S') \ + --no-warc-compression \ + --no-warc-keep-log [@dots{}] \ + http://www.example.com/ +@end example + +That command will create uncompressed @file{www.example_com-XXX.warc} +web archive. By default, WARCs are compressed using +@url{https://en.wikipedia.org/wiki/Gzip, gzip}, but, in example above, +we have disabled it to compress with stronger and faster +@url{https://en.wikipedia.org/wiki/Zstd, zstd}, before sending via +@command{nncp-file}. + +There are plenty of software acting like HTTP proxy for your browser, +allowing to view that WARC files. However you can extract files from +that archive using @url{https://pypi.python.org/pypi/Warcat, warcat} +utility, producing usual directory hierarchy: + +@example +$ python3 -m warcat extract \ + www.example_com-XXX.warc \ + --output-dir www.example.com-XXX \ + --progress +@end example diff --git a/doc/news.ru.texi b/doc/news.ru.texi index 8d0bca9..ca867b1 100644 --- a/doc/news.ru.texi +++ b/doc/news.ru.texi @@ -1,6 +1,26 @@ @node Новости @section Новости +@node Релиз 7.5.0 +@subsection Релиз 7.5.0 +@itemize + +@item +@command{nncp-daemon} соблюдает UCSPI-TCP интерфейс, благодаря чему в +журнале будет присутствовать адрес удалённой системы (при запуске под +совместимой утилитой). Желательно применять @option{-ucspi} опцию вместо +@option{-inetd}. + +@item +@command{nncp-call} может быть UCSPI-TCP клиентом, используя +@option{-ucspi} опцию. + +@item +Не выходить если не получается слушать на каком-либо MCD сетевом +интерфейсе -- только предупреждать об ошибке. + +@end itemize + @node Релиз 7.4.0 @subsection Релиз 7.4.0 @itemize @@ -525,7 +545,7 @@ SP протокол порождает меньше вызовов записе @item @option{freq}, @option{freqminsize}, @option{freqchunked} опции конфигурационного файла заменены на структуру -@option{freq: @{path: ..., minsize: ..., chunked: ...@}}. +@option{freq: @{path: @dots{}, minsize: @dots{}, chunked: @dots{}@}}. @item Добавлена @option{freq.maxsize} опция конфигурационного файл, diff --git a/doc/news.texi b/doc/news.texi index c9106f8..a17cdad 100644 --- a/doc/news.texi +++ b/doc/news.texi @@ -3,6 +3,24 @@ See also this page @ref{Новости, on russian}. +@node Release 7_5_0 +@section Release 7.5.0 +@itemize + +@item +@command{nncp-daemon} is compatible with UCSPI-TCP interface, so log +will contain remote side's address (when running under appropriate +utility). @option{-ucspi} option should be used instead of @option{-inetd}. + +@item +@command{nncp-call} can be UCSPI-TCP client, using @option{-ucspi} option. + +@item +Do not exit if some of MCD network interfaces can not be listened -- +only warn about that. + +@end itemize + @node Release 7_4_0 @section Release 7.4.0 @itemize @@ -511,7 +529,7 @@ Free disk space is checked during outbound packets creation. @item @option{freq}, @option{freqminsize}, @option{freqchunked} configuration file options replaced with the structure: -@option{freq: @{path: ..., minsize: ..., chunked: ...@}}. +@option{freq: @{path: @dots{}, minsize: @dots{}, chunked: @dots{}@}}. @item Added @option{freq.maxsize} configuration file option, forbidding of diff --git a/doc/nncp.info.do b/doc/nncp.info.do index e336238..8d60761 100644 --- a/doc/nncp.info.do +++ b/doc/nncp.info.do @@ -4,9 +4,12 @@ redo-ifchange \ *.texi \ cfg/*.texi \ cmd/*.texi \ + integration/*.texi \ + pedro.txt \ pkt/*.texi \ sp.plantuml.txt \ - pedro.txt + usecases.ru/*.texi \ + usecases/*.texi . ../config ${MAKEINFO:-makeinfo} \ -D "VERSION `cat ../VERSION`" \ diff --git a/doc/russian.texi b/doc/russian.texi index 8be9438..88a1cdc 100644 --- a/doc/russian.texi +++ b/doc/russian.texi @@ -10,5 +10,5 @@ @include about.ru.texi @include comparison.ru.texi -@include usecases.ru.texi +@include usecases.ru/index.texi @include news.ru.texi diff --git a/doc/usecases.ru.texi b/doc/usecases.ru.texi deleted file mode 100644 index 860f401..0000000 --- a/doc/usecases.ru.texi +++ /dev/null @@ -1,501 +0,0 @@ -@node Сценарии -@section Сценарии использования - -@menu -* Доступность почтового сервера время от времени: UsecaseMailRU -* Легковесная и быстрая замена POP3/IMAP4: UsecasePOPRU -* Ненадёжный/дорогой канал связи: UsecaseUnreliableRU -* Медленная/дорогая связь для больших объёмов данных, плохой QoS: UsecaseQoSRU -* Экстремальные наземные окружающие условия, нет связи: UsecaseNoLinkRU -* Односторонняя широковещательная связь: UsecaseBroadcastRU -* Спутниковые каналы связи: UsecaseSatelliteLinksRU -* Частные, изолированные MitM/Sybil-устойчивые сети: UsecaseF2FRU -* Высоко защищённые изолированные компьютеры с воздушным зазором: UsecaseAirgapRU -* Обход сетевой цензуры, здоровье: UsecaseCensorRU -* Разведка, шпионаж, тайная агентура: UsecaseSpyRU -* Дешёвая ночная связь: UsecaseCallerRU -* Мультивещательная flooding рассылка: UsecaseMulticastRU -@end menu - -@node UsecaseMailRU -@subsection Доступность почтового сервера время от времени - -Представьте, что у вас есть собственный @url{http://www.postfix.org/, -Postfix}/@url{http://www.exim.org/, Exim} SMTP сервер подключённый к -Интернету. Но вы читаете и пишете почтовые сообщения на своём ноутбуке, -который подключается к нему лишь время от времени. Как опустошить -очередь из ожидающих сообщений когда ноутбук подключён? - -Одна из возможностей это войти на сервер и сделать что-то типа -@command{postqueue -f}, но по умолчанию у вас есть только несколько дней -на это, плюс отправитель будет получать уведомления о том, что его -сообщение всё ещё не доставлено. Кроме того, вы должны использовать -безопасный канал связи (SSH, VPN, итд). - -Другая возможность это использовать POP3/IMAP4 сервер, но это слишком -переусложнённо и громоздко для такой простой задачи. Не вариант. -@url{https://ru.wikipedia.org/wiki/KISS_(%D0%BF%D1%80%D0%B8%D0%BD%D1%86%D0%B8%D0%BF), -KISS}! - -Просто скажите вашим обоим Postfix/Exim-ам (на сервере и ноутбуке) -отправлять сообщения через NNCP (@ref{nncp-exec}) на заданный узел. -Более подробно читайте для Postfix @ref{Postfix, здесь}, а для Exim -@ref{Exim, здесь}. Вся почта будет сохранятся в NNCP @ref{Spool, спуле}, -который после обмена данных и распаковки вызовет локальный -@command{sendmail} для доставки почты, как-будто это произошло на этой -же машине. - -@node UsecasePOPRU -@subsection Легковесная и быстрая замена POP3/IMAP4 - -@ref{nncp-daemon} может быть соединён с @ref{nncp-caller} длительное -время -- он создаёт TCP соединение на многие часы. Когда SMTP сервер -получает письмо, то вызывает @ref{nncp-exec} для создания исходящего -зашифрованного пакета. Демон ежесекундно проверяет исходящую директорию -и сразу же посылает оповещение о недоставленных пакетах противоположной -стороне, которая сразу же их может скачать. - -Всего несколько дюжин байт оповещают о входящих пакетах, дюжины байт -начинающие доставку этих пакетов. Почтовые пакеты сжимаются (POP3 и -IMAP4, как правило, нет). У вас легковесный, сжатый, надёжный канал -связи с низкими задержками для почты, с сильным шифрованием и -двусторонней аутентификацией! - -@node UsecaseUnreliableRU -@subsection Ненадёжный/дорогой канал связи - -Представьте, что у вас медленный модем/радио/спутниковый канал связи, -который часто обрывается и вызывает timeout у TCP. Не все HTTP серверы -поддерживают возобновляемые скачивания. SMTP вообще не поддерживает -продолжение оборванного приёма и тяжёлые сообщения становится очень -проблематично получить. Более того, каждый обрыв может приводить к -отсылке данных с самого начала, что не всегда по карману. - -Просто отправьте вашу @ref{nncp-exec, почту} и @ref{nncp-file, файлы} -через NNCP. Вы сможете использовать или offline методы доставки -- -читайте о них в следующем разделе, либо использовать поставляемый NNCP -@ref{nncp-daemon, TCP демон}. - -Команды: - -@example -$ nncp-file file_i_want_to_send bob: -$ nncp-file another_file bob:movie.avi -@end example - -добавят в очередь отправки два файла для узла @emph{bob}. -Выстрелил-и-забыл! Теперь это работа демона (или offline передачи) -доставить частями эти файлы до удалённой системы когда она будет -доступна. - -@node UsecaseQoSRU -@subsection Медленная/дорогая связь для больших объёмов данных, плохой QoS - -Представьте, что относительно дешёвый 2 TiB переносной жёсткий диск вы -отдаёте кому-нибудь утром каждый день (и забираете назад вечером). Это -равносильно 185 мегабитному качественному однонаправленному каналу -связи. Как насчёт большего количества и бОльших жёстких дисков? Этот -метод обмена данными называется -@url{https://ru.wikipedia.org/wiki/%D0%A4%D0%BB%D0%BE%D0%BF%D0%BF%D0%B8%D0%BD%D0%B5%D1%82, -флоппинет}. - -NNCP поддерживает @ref{Niceness, приоритезацию трафика}: каждый пакет -имеет уровень "приятности", который гарантирует что он будет обработан -раньше или позднее остальных. Почти все команды имеют соответствующую -опцию: - -@example -$ nncp-file -nice FLASH myfile node:dst -$ nncp-xfer -nice PRIORITY /mnt/shared -$ nncp-call -nice NORMAL bob -[...] -@end example - -Огромные файлы могут быть разбиты на маленькие @ref{Chunked, части}, -давая возможность передачи, по сути, любых объёмов используя накопители -небольших размеров. - -Вы также можете использовать CD-ROM и ленточные накопители: - -@example -$ nncp-bundle -tx bob | cdrecord -tao - -$ nncp-bundle -tx bob | dd of=/dev/sa0 bs=10240 -@end example - -@node UsecaseNoLinkRU -@subsection Экстремальные наземные окружающие условия, нет связи - -Это, в некотором роде, вариант очень медленного канала связи. Offline -методы доставки -- единственный выбор. Просто отправьте, файлы как было -показано в предыдущем разделе, но используйте переносные накопители для -передачи пакетов другим узлам. - -Представьте, что вы послали два файла узлу @emph{bob}. Вставьте USB -устройство (SD гораздо предпочтительнее!) хранения, подмонтируйте и -запустите @ref{nncp-xfer}: - -@example -$ nncp-xfer -node bob /media/usbstick -@end example - -чтобы скопировать все исходящие пакеты относящиеся к @emph{bob}. -Используйте @option{-mkdir} опцию чтобы создать все необходимые -директории на накопителе, если их нет (например когда запускаемся первый -раз). - -Если вы используете один и тот же накопитель для передачи данных и к -@emph{bob} и к @emph{alice}, то тогда просто не указывайте -@option{-node} опцию, чтобы скопировать все доступные исходящие пакеты. - -@example -$ nncp-xfer /media/usbstick -@end example - -Размонтируйте и передайте накопитель Бобу и Алисе. Когда они вставят -накопитель в свои компьютеры, то выполнят точно такую же команду: - -@example -$ nncp-xfer /media/usbstick -@end example - -чтобы найти все пакеты относящиеся к их узлу и локально скопируют для -дальнейшей обработки. @command{nncp-xfer} это единственная команда -используемая с переносными устройствами хранения. - -@node UsecaseBroadcastRU -@subsection Односторонняя широковещательная связь - -Иногда у вас есть ёмкий, но односторонний, канал связи, например -широковещательный сигнал со спутника. Вы не можете использовать online -@ref{Sync, протокол синхронизации}, потому что он требует двустороннего -взаимодействия. - -Вы можете использовать, так называемые, @ref{Bundles, пачки} и потоково -отсылать их. Они -- всего-лишь последовательность @ref{Encrypted, -зашифрованных пакетов}, которые вы можете принять. - -@example -$ nncp-bundle -tx alice bob eve ... | команда для отправки широковещательной рассылки -$ команда для приёма широковещательной рассылки | nncp-bundle -rx -@end example - -Встроенная возможность определять дубляжи пакетов позволит вам -переотправлять широковещательные рассылки время от времени, повышая -шансы на то, что получатель примет их, регулярно слушая рассылку. - -@node UsecaseSatelliteLinksRU -@subsection Спутниковые каналы связи - -Спутниковые каналы связи имеют @strong{очень} большие задержки вместе с -высокими пропускными способностями. Вы можете посылать мегабиты данных в -секунду, но они достигнут удалённой стороны только спустя полсекунды! -Большинство протоколов обмена файлами, таких как -@url{https://en.wikipedia.org/wiki/Files_transferred_over_shell_protocol, FISH}, -@url{https://ru.wikipedia.org/wiki/FTP, FTP}, -@url{https://ru.wikipedia.org/wiki/SCP, scp}, -@url{https://en.wikipedia.org/wiki/XMODEM, XMODEM} will perform very -будут работать очень плохо из-за большого количества приёмо-передач -(round-trips). Каждая передача файла явно генерирует пакеты запросов и -подтверждений, посылаемые поверх канала связи. Удалённая сторона ничего -не будет делать пока она их не получит. Более того, не все протоколы -позволяют делать дуплексную отправку данных (когда обе стороны посылают -данные одновременно). - -@ref{Sync, Протокол синхронизации} (SP) NNCP пытается решить все эти -особенности за счёт сокращения количества приёмо-передач, количества -проходящих пакетов. Все списки файлов, запросов на скачивание файла -группируются вместе (pipelined) в один огромный пакет. Только запросы на -остановку передачи и подтверждения успешного приёма файла явно -посылаются. Можно запросить чтобы SP только принимал или отправлял -пакеты для нашей ноды. SP может игнорировать файлы с маленьким -приоритетом. Полные списки файлов отправляются уже на этапе процедуры -рукопожатия. - -@node UsecaseF2FRU -@subsection Частные, изолированные MitM/Sybil-устойчивые сети - -Все Интернет соединения могут быть прослушаны и сфальсифицированы. Вы -@strong{вынуждены} использовать шифрование и аутентификацию для -безопасности. Но очень сложно обезопасить метаданные, которые утекают -при каждой online сессии. Когда вы запускаете свой новый сверкающий -программный сервер, то имейте в виду, что может существовать огромное -количество поддельных узлов пытающихся произвести -@url{https://en.wikipedia.org/wiki/Sybil_attack, Sybil атаку}. Открытые -узел-к-узлу (peer-to-peer) сети опасны. - -Наиболее популярный криптографический протокол в Интернете это -@url{https://ru.wikipedia.org/wiki/TLS, TLS}, который крайне сложно -правильно реализовать и сконфигурировать для двусторонней аутентификации -собеседников. Не все конфигурации TLS обладают свойством -@url{https://ru.wikipedia.org/wiki/Perfect_forward_secrecy, совершенной -прямой секретности} -- все ранее перехваченные пакеты могут быть -прочтены если приватные ключи скомпрометированы. - -Друг-к-другу (friend-to-friend) сети, "тёмные сети" (darknet) могут -нивелировать возможные риски связанные с поддельными и фиктивными -узлами. Хотя они и сложнее в поддержке и требуют больше затрат на -построение. - -@ref{nncp-daemon, TCP демон} NNCP использует -@url{http://noiseprotocol.org/, Noise-IK} протокол для двусторонней -аутентификации узлов и предоставляет эффективный (оба участника могут -отослать полезную нагрузку сразу же в самом первом пакете) безопасный -транспорт с свойством совершенной прямой секретности. - -@example -$ nncp-daemon -bind "[::]":5400 -@end example - -запустит TCP демон, который будет слушать входящие соединения на всех -интерфейсах. - -@example -$ nncp-call bob -@end example - -попытается подключиться к известному TCP-адресу узла @emph{bob} (взятого -из конфигурационного файла), послать все связанные с ним исходящие -пакеты и получить от него. Все прерванные передачи будут автоматически -возобновлены. - -А наличие возможности @ref{MCD, multicast обнаружения} участников сети в -IPv6 сетях позволяет вообще не возиться с заданием сетевых адресов. - -@node UsecaseAirgapRU -@subsection Высокозащищённые изолированные компьютеры с воздушным зазором - -Если вы сильно беспокоитесь о безопасности, то компьютер с -@url{https://ru.wikipedia.org/wiki/%D0%92%D0%BE%D0%B7%D0%B4%D1%83%D1%88%D0%BD%D1%8B%D0%B9_%D0%B7%D0%B0%D0%B7%D0%BE%D1%80_(%D1%81%D0%B5%D1%82%D0%B8_%D0%BF%D0%B5%D1%80%D0%B5%D0%B4%D0%B0%D1%87%D0%B8_%D0%B4%D0%B0%D0%BD%D0%BD%D1%8B%D1%85), -воздушным зазором} может будет вашим единственным позволительным -выбором. Компьютер без каких-либо модемов, проводных и беспроводных -сетей. Очевидно, что единственная возможность обмениваться почтой и -файлами -- использовать физически переносимые устройства хранения типа -CD-ROM, жёстких дисков, SD, лент и USB накопителей (@strong{худший} -вариант, из-за сложности подобных устройств). - -Предполагаем что у вас есть ещё один собственный узел, стоящий "до" -безопасного, который делает базовые проверки полученных накопителей, -возможно перезаписывая данные с USB/жёстких дисков на CD-RW. - -NNCP из коробки поддерживает ретрансляцию пакетов. - -@verbatim -neigh: { - bob: { - [...] - addrs: { - lan: "[fe80::5400%igb0]:5400" - } - } - bob-airgap: - [...] - via: ["bob"] - } -} -@end verbatim - -Такой @ref{Configuration, конфигурационный файл} говорит что у нас есть -два известных соседа: @emph{bob} и @emph{bob-airgap}. @emph{bob} -доступен через online соединение, используя @emph{lan} адрес. -@emph{bob-airgap} доступен путём посылки промежуточного ретранслируемого -пакета через узел @emph{bob}. - -Любая команда типа @command{nncp-file myfile bob-airgap:} автоматически -создаст инкапсулированный пакет: один непосредственно для целевой точки, -а другой несущий его для промежуточного узла. - -Имейте в виду, что узел-ретранслятор ничего не знает о внутреннем -пакете, кроме его полного размера и приоритета. Все промежуточные пакеты -тоже зашифрованы: используя хорошо известную технологию -@url{https://ru.wikipedia.org/wiki/%D0%9B%D1%83%D0%BA%D0%BE%D0%B2%D0%B0%D1%8F_%D0%BC%D0%B0%D1%80%D1%88%D1%80%D1%83%D1%82%D0%B8%D0%B7%D0%B0%D1%86%D0%B8%D1%8F, -луковой маршрутизации}. @emph{bob} не может прочитать пакеты -@emph{bob-airgap}. - -@node UsecaseCensorRU -@subsection Обход сетевой цензуры, здоровье - -Это тоже подвид плохого канала связи. Некоторые правительства склонны к -запрету @strong{любого} вида личного (приватного) общения между людьми, -разрешая только доставку развлекательного контента и доступ к популярным -социальным сетям (которые уже вовсю наводнены рекламой, локально -исполняемым @url{https://www.gnu.org/philosophy/free-sw.ru.html, -проприетарным} JavaScript кодом (для слежкой за действиями пользователя, -сбором данных), бесстыдно и бессовестно эксплуатируя базовые потребности -человека в общении). - -Это их естественное желание. Но никто вас не заставляет насильно -подчиняться огромным корпорациям типа Apple, Google или Microsoft. Ваш -выбор это создавать изолированные друг-к-другу сети с кучами безобидного -контента и приватными сообщениями. Только хищники тихо наблюдают за -своими жертвами в мире млекопитающих -- слежка и чувство что вы жертва, -сделавшая что-то плохое, вредит вашему здоровью. - -@node UsecaseSpyRU -@subsection Разведка, шпионаж, тайная агентура - -Эти ребята знают насколько небезопасен Интернет, несовместим с -понятием приватности. Им необходим быстрый сброс и забор данных. Нет -возможности провести несколько итераций приёмо-передач (round-trips) -- -только сбросить данные, выстрелить и забыть. Опять же, это может быть -переносной накопитель и/или -@url{https://en.wikipedia.org/wiki/USB_dead_drop, USB тайник} (dead drop), -@url{https://en.wikipedia.org/wiki/PirateBox, PirateBox}ы, -@url{https://en.wikipedia.org/wiki/Short-range_agent_communications, -связь малой дальности (SRAC)}. Короткоживущие сети малой дальности типа -Bluetooth и WiFi могут быть и довольно быстрыми, позволяя быстро -"выстреливать" порциями исходящих пакетов. - -Очень важное свойство -- компрометация этих тайников или накопителей не -должна быть ни фатальна, ни даже опасна. Пакеты посылаемые через сети -или обмениваемые через устройства -- @ref{Encrypted, зашифрованы} по -принципу точка-точка (но, к сожалению, без совершенной прямой -секретности). Никаких имён файлов, получателей почтовых сообщений не -видно. - -Общение узлов между собой происходит в, так называемой, @ref{Spool, -спул} области: директории содержащей только необработанные зашифрованные -пакеты. После передачи пакета вы всё равно не сможете его прочитать: -необходимо запустить другую фазу: @ref{nncp-toss, распаковку}, которая -использует ваши приватные криптографические ключи. То есть, даже если вы -потеряете свой компьютер, устройства хранения и тому прочее -- это не -так плохо, потому что вы не носите с собой приватные ключи (ведь так?), -вы не "распаковываете" эти пакеты сразу же на том же самом устройстве. -Распаковка (чтение этих зашифрованных пакетов с извлечением переданных -файлов и почтовых сообщений) может и должна бы быть произведена на -отдельном компьютере (@ref{nncp-cfgmin} команда может помочь с созданием -конфигурационного файла без приватных ключей для этой цели). - -Если вы действительно хотите взять с собой приватные ключи, то -@ref{nncp-cfgenc} команда способна зашифровать ваш конфигурационный -файл. Парольная фраза вами введённая усиливается функцией нагружающей и -центральный процессор и память. - -@node UsecaseCallerRU -@subsection Дешёвая ночная связь - -Стоимость Интернет/телефонного трафика может варьироваться, в -зависимости от времени дня. Ночные звонки/соединения могут быть дешевле -в два раза. Вы хотите посылать ваши файлы в это время, но позволять -изредка проходить высокоприоритетной почте в любое время. А также вы -хотите проходить любому трафику когда узел доступен через ЛВС (LAN). - -Вы легко можете настроить ваши предпочтения в @ref{Call, настройках -звонков} для @ref{nncp-caller} команды, используемой при online связи. - -@verbatim -neigh: { - [...] - some-node: { - [...] - addrs: { - lan: "[fe80::be5f:f4ff:fedd:2752%igb0]:5400" - wan: "some-node.com:5400" - } - calls: [ - { - cron: "*/1 * * * *" - addr: lan - nice: MAX - onlinedeadline: 3600 - } - { - cron: "*/10 * * * *" - addr: wan - nice: PRIORITY - xx: rx - } - { - cron: "*/1 0-7 * * *" - addr: wan - nice: BULK - onlinedeadline: 3600 - maxonlinetime: 3600 - } - ] - } -} -@end verbatim - -@node UsecaseMulticastRU -@subsection Мультивещательная flooding рассылка - -Необходимо разослать одно и то же почтовое сообщение или файл многим -участникам? Например обновления какой либо программы, списка участников -сети или доступных файлов? Но при этом вы не соединены лично с каждым из -них: - -@verbatim - A-------->E---->F A <-> B C E - / \ |\ ^ C <-> H J - / \ | \ | E <-> D F G -v v v \v D <-> G -B C D---->G J <-> K - / \ ^ / K <-> D G - / \ | / - v v v / - H J<->K<- -@end verbatim - -В NNCP есть особые @ref{Multicast, мультивещательные} форматы пакетов -позволяющие организовывать эффективную передачу одно единственного -пакета сразу нескольким получателям (flooding алгоритм). @strong{A} -отправляет пакет трём получателям. @strong{C} в свою очередь отсылает -ещё двум, а @strong{E} трём. Некоторые участники сети получат несколько -копий одного и того же пакета, как например @strong{D}, @strong{J}, -@strong{G}, @strong{F}, но копии будут просто проигнорированы. Если -@strong{B} отошлёт пакет единственному ему известному @strong{A}, то -этот пакет распространится по всей сети подписантов широковещательной -зоны и дальше. - -Более того, мультивещательные пакеты зашифрованы и для прочтения требуют -знание ключей. Но это не мешает их обрабатывать для дальнейшей пересылки! -Кроме того, совершенно не обязательно знать ключи отправителя. Таким -образом можно создать эхоконференцию для передачи файлов или команд -(например доставки почтовых сообщений). - -Создаём ключи для мультивещательной зоны: - -@example -$ nncp-cfgnew -area filelists -nocomments -areas: @{ - filelists: @{ - id: TOU5TKOW4JBIZJBX63D4776C72FMWDAUAUSZNJX4DFOITVYQ5ZQA - pub: DSHL5O6BK2R3QKJAIJ7BC4UIGE73EC2LJPOV3VTS44KYOTUQYZLA - prv: AYD5FAA4GDDSAD5N65NJLLFS6TG2NSPQ46KAQO5U722JLVG34SOQ - @} -@} -@end example - -и отправляем ключевую пару всем кто может и хочет читать данную зону. -Посредникам, готовым участвовать в переотправке пакетов подписантам, но -которым не стоит "читать" пакеты, достаточно отправить только -идентификатор зоны. Например @strong{A} добавляет себе в конфигурацию: - -@example -areas: @{ - filelists: @{ - id: TOU... - pub: DSH... - prv: AYD... - subs: ["B", "C", "E"] - incoming: /home/A/areas/filelists - @} -@end example - -а @strong{E}, являющимся (как было решено) просто посредником: - -@example -areas: @{ - filelists: @{ - id: TOU... - subs: ["D", "F", "G"] - @} -@end example - -После распространения знания о @code{filelists} мультивещательной зоне -можно обмениваться @ref{FreqIndex, списками файлов}: - -@example -$ nncp-file tree-of-A-20210715.txt.zst area:filelists: -$ nncp-toss -node self -@end example diff --git a/doc/usecases.ru/airgap.texi b/doc/usecases.ru/airgap.texi new file mode 100644 index 0000000..a6591d6 --- /dev/null +++ b/doc/usecases.ru/airgap.texi @@ -0,0 +1,49 @@ +@node UsecaseAirgapRU +@subsection Высокозащищённые изолированные компьютеры с воздушным зазором + +Если вы сильно беспокоитесь о безопасности, то компьютер с +@url{https://ru.wikipedia.org/wiki/%D0%92%D0%BE%D0%B7%D0%B4%D1%83%D1%88%D0%BD%D1%8B%D0%B9_%D0%B7%D0%B0%D0%B7%D0%BE%D1%80_(%D1%81%D0%B5%D1%82%D0%B8_%D0%BF%D0%B5%D1%80%D0%B5%D0%B4%D0%B0%D1%87%D0%B8_%D0%B4%D0%B0%D0%BD%D0%BD%D1%8B%D1%85), +воздушным зазором} может будет вашим единственным позволительным +выбором. Компьютер без каких-либо модемов, проводных и беспроводных +сетей. Очевидно, что единственная возможность обмениваться почтой и +файлами -- использовать физически переносимые устройства хранения типа +CD-ROM, жёстких дисков, SD, лент и USB накопителей (@strong{худший} +вариант, из-за сложности подобных устройств). + +Предполагаем что у вас есть ещё один собственный узел, стоящий "до" +безопасного, который делает базовые проверки полученных накопителей, +возможно перезаписывая данные с USB/жёстких дисков на CD-RW. + +NNCP из коробки поддерживает ретрансляцию пакетов. + +@verbatim +neigh: { + bob: { + [...] + addrs: { + lan: "[fe80::5400%igb0]:5400" + } + } + bob-airgap: + [...] + via: ["bob"] + } +} +@end verbatim + +Такой @ref{Configuration, конфигурационный файл} говорит что у нас есть +два известных соседа: @emph{bob} и @emph{bob-airgap}. @emph{bob} +доступен через online соединение, используя @emph{lan} адрес. +@emph{bob-airgap} доступен путём посылки промежуточного ретранслируемого +пакета через узел @emph{bob}. + +Любая команда типа @command{nncp-file myfile bob-airgap:} автоматически +создаст инкапсулированный пакет: один непосредственно для целевой точки, +а другой несущий его для промежуточного узла. + +Имейте в виду, что узел-ретранслятор ничего не знает о внутреннем +пакете, кроме его полного размера и приоритета. Все промежуточные пакеты +тоже зашифрованы: используя хорошо известную технологию +@url{https://ru.wikipedia.org/wiki/%D0%9B%D1%83%D0%BA%D0%BE%D0%B2%D0%B0%D1%8F_%D0%BC%D0%B0%D1%80%D1%88%D1%80%D1%83%D1%82%D0%B8%D0%B7%D0%B0%D1%86%D0%B8%D1%8F, +луковой маршрутизации}. @emph{bob} не может прочитать пакеты +@emph{bob-airgap}. diff --git a/doc/usecases.ru/broadcast.texi b/doc/usecases.ru/broadcast.texi new file mode 100644 index 0000000..5b97a4d --- /dev/null +++ b/doc/usecases.ru/broadcast.texi @@ -0,0 +1,20 @@ +@node UsecaseBroadcastRU +@subsection Односторонняя широковещательная связь + +Иногда у вас есть ёмкий, но односторонний, канал связи, например +широковещательный сигнал со спутника. Вы не можете использовать online +@ref{Sync, протокол синхронизации}, потому что он требует двустороннего +взаимодействия. + +Вы можете использовать, так называемые, @ref{Bundles, пачки} и потоково +отсылать их. Они -- всего-лишь последовательность @ref{Encrypted, +зашифрованных пакетов}, которые вы можете принять. + +@example +$ nncp-bundle -tx alice bob eve @dots{} | команда для отправки широковещательной рассылки +$ команда для приёма широковещательной рассылки | nncp-bundle -rx +@end example + +Встроенная возможность определять дубляжи пакетов позволит вам +переотправлять широковещательные рассылки время от времени, повышая +шансы на то, что получатель примет их, регулярно слушая рассылку. diff --git a/doc/usecases.ru/caller.texi b/doc/usecases.ru/caller.texi new file mode 100644 index 0000000..af80359 --- /dev/null +++ b/doc/usecases.ru/caller.texi @@ -0,0 +1,45 @@ +@node UsecaseCallerRU +@subsection Дешёвая ночная связь + +Стоимость Интернет/телефонного трафика может варьироваться, в +зависимости от времени дня. Ночные звонки/соединения могут быть дешевле +в два раза. Вы хотите посылать ваши файлы в это время, но позволять +изредка проходить высокоприоритетной почте в любое время. А также вы +хотите проходить любому трафику когда узел доступен через ЛВС (LAN). + +Вы легко можете настроить ваши предпочтения в @ref{Call, настройках +звонков} для @ref{nncp-caller} команды, используемой при online связи. + +@verbatim +neigh: { + [...] + some-node: { + [...] + addrs: { + lan: "[fe80::be5f:f4ff:fedd:2752%igb0]:5400" + wan: "some-node.com:5400" + } + calls: [ + { + cron: "*/1 * * * *" + addr: lan + nice: MAX + onlinedeadline: 3600 + } + { + cron: "*/10 * * * *" + addr: wan + nice: PRIORITY + xx: rx + } + { + cron: "*/1 0-7 * * *" + addr: wan + nice: BULK + onlinedeadline: 3600 + maxonlinetime: 3600 + } + ] + } +} +@end verbatim diff --git a/doc/usecases.ru/censor.texi b/doc/usecases.ru/censor.texi new file mode 100644 index 0000000..1a5a95e --- /dev/null +++ b/doc/usecases.ru/censor.texi @@ -0,0 +1,18 @@ +@node UsecaseCensorRU +@subsection Обход сетевой цензуры, здоровье + +Это тоже подвид плохого канала связи. Некоторые правительства склонны к +запрету @strong{любого} вида личного (приватного) общения между людьми, +разрешая только доставку развлекательного контента и доступ к популярным +социальным сетям (которые уже вовсю наводнены рекламой, локально +исполняемым @url{https://www.gnu.org/philosophy/free-sw.ru.html, +проприетарным} JavaScript кодом (для слежкой за действиями пользователя, +сбором данных), бесстыдно и бессовестно эксплуатируя базовые потребности +человека в общении). + +Это их естественное желание. Но никто вас не заставляет насильно +подчиняться огромным корпорациям типа Apple, Google или Microsoft. Ваш +выбор это создавать изолированные друг-к-другу сети с кучами безобидного +контента и приватными сообщениями. Только хищники тихо наблюдают за +своими жертвами в мире млекопитающих -- слежка и чувство что вы жертва, +сделавшая что-то плохое, вредит вашему здоровью. diff --git a/doc/usecases.ru/f2f.texi b/doc/usecases.ru/f2f.texi new file mode 100644 index 0000000..0eb8bb8 --- /dev/null +++ b/doc/usecases.ru/f2f.texi @@ -0,0 +1,49 @@ +@node UsecaseF2FRU +@subsection Частные, изолированные MitM/Sybil-устойчивые сети + +Все Интернет соединения могут быть прослушаны и сфальсифицированы. Вы +@strong{вынуждены} использовать шифрование и аутентификацию для +безопасности. Но очень сложно обезопасить метаданные, которые утекают +при каждой online сессии. Когда вы запускаете свой новый сверкающий +программный сервер, то имейте в виду, что может существовать огромное +количество поддельных узлов пытающихся произвести +@url{https://en.wikipedia.org/wiki/Sybil_attack, Sybil атаку}. Открытые +узел-к-узлу (peer-to-peer) сети опасны. + +Наиболее популярный криптографический протокол в Интернете это +@url{https://ru.wikipedia.org/wiki/TLS, TLS}, который крайне сложно +правильно реализовать и сконфигурировать для двусторонней аутентификации +собеседников. Не все конфигурации TLS обладают свойством +@url{https://ru.wikipedia.org/wiki/Perfect_forward_secrecy, совершенной +прямой секретности} -- все ранее перехваченные пакеты могут быть +прочтены если приватные ключи скомпрометированы. + +Друг-к-другу (friend-to-friend) сети, "тёмные сети" (darknet) могут +нивелировать возможные риски связанные с поддельными и фиктивными +узлами. Хотя они и сложнее в поддержке и требуют больше затрат на +построение. + +@ref{nncp-daemon, TCP демон} NNCP использует +@url{http://noiseprotocol.org/, Noise-IK} протокол для двусторонней +аутентификации узлов и предоставляет эффективный (оба участника могут +отослать полезную нагрузку сразу же в самом первом пакете) безопасный +транспорт с свойством совершенной прямой секретности. + +@example +$ nncp-daemon -bind "[::]":5400 +@end example + +запустит TCP демон, который будет слушать входящие соединения на всех +интерфейсах. + +@example +$ nncp-call bob +@end example + +попытается подключиться к известному TCP-адресу узла @emph{bob} (взятого +из конфигурационного файла), послать все связанные с ним исходящие +пакеты и получить от него. Все прерванные передачи будут автоматически +возобновлены. + +А наличие возможности @ref{MCD, multicast обнаружения} участников сети в +IPv6 сетях позволяет вообще не возиться с заданием сетевых адресов. diff --git a/doc/usecases.ru/index.texi b/doc/usecases.ru/index.texi new file mode 100644 index 0000000..7aecbea --- /dev/null +++ b/doc/usecases.ru/index.texi @@ -0,0 +1,32 @@ +@node Сценарии +@section Сценарии использования + +@menu +* Доступность почтового сервера время от времени: UsecaseMailRU +* Легковесная и быстрая замена POP3/IMAP4: UsecasePOPRU +* Ненадёжный/дорогой канал связи: UsecaseUnreliableRU +* Медленная/дорогая связь для больших объёмов данных, плохой QoS: UsecaseQoSRU +* Экстремальные наземные окружающие условия, нет связи: UsecaseNoLinkRU +* Односторонняя широковещательная связь: UsecaseBroadcastRU +* Спутниковые каналы связи: UsecaseSatelliteLinksRU +* Частные, изолированные MitM/Sybil-устойчивые сети: UsecaseF2FRU +* Высоко защищённые изолированные компьютеры с воздушным зазором: UsecaseAirgapRU +* Обход сетевой цензуры, здоровье: UsecaseCensorRU +* Разведка, шпионаж, тайная агентура: UsecaseSpyRU +* Дешёвая ночная связь: UsecaseCallerRU +* Мультивещательная flooding рассылка: UsecaseMulticastRU +@end menu + +@include usecases.ru/mail.texi +@include usecases.ru/pop.texi +@include usecases.ru/unreliable.texi +@include usecases.ru/qos.texi +@include usecases.ru/nolink.texi +@include usecases.ru/broadcast.texi +@include usecases.ru/satellite.texi +@include usecases.ru/f2f.texi +@include usecases.ru/airgap.texi +@include usecases.ru/censor.texi +@include usecases.ru/spy.texi +@include usecases.ru/caller.texi +@include usecases.ru/multicast.texi diff --git a/doc/usecases.ru/mail.texi b/doc/usecases.ru/mail.texi new file mode 100644 index 0000000..48a3474 --- /dev/null +++ b/doc/usecases.ru/mail.texi @@ -0,0 +1,27 @@ +@node UsecaseMailRU +@subsection Доступность почтового сервера время от времени + +Представьте, что у вас есть собственный @url{http://www.postfix.org/, +Postfix}/@url{http://www.exim.org/, Exim} SMTP сервер подключённый к +Интернету. Но вы читаете и пишете почтовые сообщения на своём ноутбуке, +который подключается к нему лишь время от времени. Как опустошить +очередь из ожидающих сообщений когда ноутбук подключён? + +Одна из возможностей это войти на сервер и сделать что-то типа +@command{postqueue -f}, но по умолчанию у вас есть только несколько дней +на это, плюс отправитель будет получать уведомления о том, что его +сообщение всё ещё не доставлено. Кроме того, вы должны использовать +безопасный канал связи (SSH, VPN, итд). + +Другая возможность это использовать POP3/IMAP4 сервер, но это слишком +переусложнённо и громоздко для такой простой задачи. Не вариант. +@url{https://ru.wikipedia.org/wiki/KISS_(%D0%BF%D1%80%D0%B8%D0%BD%D1%86%D0%B8%D0%BF), +KISS}! + +Просто скажите вашим обоим Postfix/Exim-ам (на сервере и ноутбуке) +отправлять сообщения через NNCP (@ref{nncp-exec}) на заданный узел. +Более подробно читайте для Postfix @ref{Postfix, здесь}, а для Exim +@ref{Exim, здесь}. Вся почта будет сохранятся в NNCP @ref{Spool, спуле}, +который после обмена данных и распаковки вызовет локальный +@command{sendmail} для доставки почты, как-будто это произошло на этой +же машине. diff --git a/doc/usecases.ru/multicast.texi b/doc/usecases.ru/multicast.texi new file mode 100644 index 0000000..86b17cb --- /dev/null +++ b/doc/usecases.ru/multicast.texi @@ -0,0 +1,83 @@ +@node UsecaseMulticastRU +@subsection Мультивещательная flooding рассылка + +Необходимо разослать одно и то же почтовое сообщение или файл многим +участникам? Например обновления какой либо программы, списка участников +сети или доступных файлов? Но при этом вы не соединены лично с каждым из +них: + +@verbatim + A-------->E---->F A <-> B C E + / \ |\ ^ C <-> H J + / \ | \ | E <-> D F G +v v v \v D <-> G +B C D---->G J <-> K + / \ ^ / K <-> D G + / \ | / + v v v / + H J<->K<- +@end verbatim + +В NNCP есть особые @ref{Multicast, мультивещательные} форматы пакетов +позволяющие организовывать эффективную передачу одно единственного +пакета сразу нескольким получателям (flooding алгоритм). @strong{A} +отправляет пакет трём получателям. @strong{C} в свою очередь отсылает +ещё двум, а @strong{E} трём. Некоторые участники сети получат несколько +копий одного и того же пакета, как например @strong{D}, @strong{J}, +@strong{G}, @strong{F}, но копии будут просто проигнорированы. Если +@strong{B} отошлёт пакет единственному ему известному @strong{A}, то +этот пакет распространится по всей сети подписантов широковещательной +зоны и дальше. + +Более того, мультивещательные пакеты зашифрованы и для прочтения требуют +знание ключей. Но это не мешает их обрабатывать для дальнейшей пересылки! +Кроме того, совершенно не обязательно знать ключи отправителя. Таким +образом можно создать эхоконференцию для передачи файлов или команд +(например доставки почтовых сообщений). + +Создаём ключи для мультивещательной зоны: + +@verbatim +$ nncp-cfgnew -area filelists -nocomments +areas: { + filelists: { + id: TOU5TKOW4JBIZJBX63D4776C72FMWDAUAUSZNJX4DFOITVYQ5ZQA + pub: DSHL5O6BK2R3QKJAIJ7BC4UIGE73EC2LJPOV3VTS44KYOTUQYZLA + prv: AYD5FAA4GDDSAD5N65NJLLFS6TG2NSPQ46KAQO5U722JLVG34SOQ + } +} +@end verbatim + +и отправляем ключевую пару всем кто может и хочет читать данную зону. +Посредникам, готовым участвовать в переотправке пакетов подписантам, но +которым не стоит "читать" пакеты, достаточно отправить только +идентификатор зоны. Например @strong{A} добавляет себе в конфигурацию: + +@verbatim +areas: { + filelists: { + id: TOU... + pub: DSH... + prv: AYD... + subs: ["B", "C", "E"] + incoming: /home/A/areas/filelists + } +@end verbatim + +а @strong{E}, являющимся (как было решено) просто посредником: + +@verbatim +areas: { + filelists: { + id: TOU... + subs: ["D", "F", "G"] + } +@end verbatim + +После распространения знания о @code{filelists} мультивещательной зоне +можно обмениваться @ref{FreqIndex, списками файлов}: + +@example +$ nncp-file tree-of-A-20210715.txt.zst area:filelists: +$ nncp-toss -node self +@end example diff --git a/doc/usecases.ru/nolink.texi b/doc/usecases.ru/nolink.texi new file mode 100644 index 0000000..bacc7c0 --- /dev/null +++ b/doc/usecases.ru/nolink.texi @@ -0,0 +1,39 @@ +@node UsecaseNoLinkRU +@subsection Экстремальные наземные окружающие условия, нет связи + +Это, в некотором роде, вариант очень медленного канала связи. Offline +методы доставки -- единственный выбор. Просто отправьте, файлы как было +показано в предыдущем разделе, но используйте переносные накопители для +передачи пакетов другим узлам. + +Представьте, что вы послали два файла узлу @emph{bob}. Вставьте USB +устройство (SD гораздо предпочтительнее!) хранения, подмонтируйте и +запустите @ref{nncp-xfer}: + +@example +$ nncp-xfer -node bob /media/usbstick +@end example + +чтобы скопировать все исходящие пакеты относящиеся к @emph{bob}. +Используйте @option{-mkdir} опцию чтобы создать все необходимые +директории на накопителе, если их нет (например когда запускаемся первый +раз). + +Если вы используете один и тот же накопитель для передачи данных и к +@emph{bob} и к @emph{alice}, то тогда просто не указывайте +@option{-node} опцию, чтобы скопировать все доступные исходящие пакеты. + +@example +$ nncp-xfer /media/usbstick +@end example + +Размонтируйте и передайте накопитель Бобу и Алисе. Когда они вставят +накопитель в свои компьютеры, то выполнят точно такую же команду: + +@example +$ nncp-xfer /media/usbstick +@end example + +чтобы найти все пакеты относящиеся к их узлу и локально скопируют для +дальнейшей обработки. @command{nncp-xfer} это единственная команда +используемая с переносными устройствами хранения. diff --git a/doc/usecases.ru/pop.texi b/doc/usecases.ru/pop.texi new file mode 100644 index 0000000..98a9312 --- /dev/null +++ b/doc/usecases.ru/pop.texi @@ -0,0 +1,15 @@ +@node UsecasePOPRU +@subsection Легковесная и быстрая замена POP3/IMAP4 + +@ref{nncp-daemon} может быть соединён с @ref{nncp-caller} длительное +время -- он создаёт TCP соединение на многие часы. Когда SMTP сервер +получает письмо, то вызывает @ref{nncp-exec} для создания исходящего +зашифрованного пакета. Демон ежесекундно проверяет исходящую директорию +и сразу же посылает оповещение о недоставленных пакетах противоположной +стороне, которая сразу же их может скачать. + +Всего несколько дюжин байт оповещают о входящих пакетах, дюжины байт +начинающие доставку этих пакетов. Почтовые пакеты сжимаются (POP3 и +IMAP4, как правило, нет). У вас легковесный, сжатый, надёжный канал +связи с низкими задержками для почты, с сильным шифрованием и +двусторонней аутентификацией! diff --git a/doc/usecases.ru/qos.texi b/doc/usecases.ru/qos.texi new file mode 100644 index 0000000..4b67c73 --- /dev/null +++ b/doc/usecases.ru/qos.texi @@ -0,0 +1,33 @@ +@node UsecaseQoSRU +@subsection Медленная/дорогая связь для больших объёмов данных, плохой QoS + +Представьте, что относительно дешёвый 2 TiB переносной жёсткий диск вы +отдаёте кому-нибудь утром каждый день (и забираете назад вечером). Это +равносильно 185 мегабитному качественному однонаправленному каналу +связи. Как насчёт большего количества и бОльших жёстких дисков? Этот +метод обмена данными называется +@url{https://ru.wikipedia.org/wiki/%D0%A4%D0%BB%D0%BE%D0%BF%D0%BF%D0%B8%D0%BD%D0%B5%D1%82, +флоппинет}. + +NNCP поддерживает @ref{Niceness, приоритезацию трафика}: каждый пакет +имеет уровень "приятности", который гарантирует что он будет обработан +раньше или позднее остальных. Почти все команды имеют соответствующую +опцию: + +@example +$ nncp-file -nice FLASH myfile node:dst +$ nncp-xfer -nice PRIORITY /mnt/shared +$ nncp-call -nice NORMAL bob +[@dots{}] +@end example + +Огромные файлы могут быть разбиты на маленькие @ref{Chunked, части}, +давая возможность передачи, по сути, любых объёмов используя накопители +небольших размеров. + +Вы также можете использовать CD-ROM и ленточные накопители: + +@example +$ nncp-bundle -tx bob | cdrecord -tao - +$ nncp-bundle -tx bob | dd of=/dev/sa0 bs=10240 +@end example diff --git a/doc/usecases.ru/satellite.texi b/doc/usecases.ru/satellite.texi new file mode 100644 index 0000000..749a5e7 --- /dev/null +++ b/doc/usecases.ru/satellite.texi @@ -0,0 +1,27 @@ +@node UsecaseSatelliteLinksRU +@subsection Спутниковые каналы связи + +Спутниковые каналы связи имеют @strong{очень} большие задержки вместе с +высокими пропускными способностями. Вы можете посылать мегабиты данных в +секунду, но они достигнут удалённой стороны только спустя полсекунды! +Большинство протоколов обмена файлами, таких как +@url{https://en.wikipedia.org/wiki/Files_transferred_over_shell_protocol, FISH}, +@url{https://ru.wikipedia.org/wiki/FTP, FTP}, +@url{https://ru.wikipedia.org/wiki/SCP, scp}, +@url{https://en.wikipedia.org/wiki/XMODEM, XMODEM} will perform very +будут работать очень плохо из-за большого количества приёмо-передач +(round-trips). Каждая передача файла явно генерирует пакеты запросов и +подтверждений, посылаемые поверх канала связи. Удалённая сторона ничего +не будет делать пока она их не получит. Более того, не все протоколы +позволяют делать дуплексную отправку данных (когда обе стороны посылают +данные одновременно). + +@ref{Sync, Протокол синхронизации} (SP) NNCP пытается решить все эти +особенности за счёт сокращения количества приёмо-передач, количества +проходящих пакетов. Все списки файлов, запросов на скачивание файла +группируются вместе (pipelined) в один огромный пакет. Только запросы на +остановку передачи и подтверждения успешного приёма файла явно +посылаются. Можно запросить чтобы SP только принимал или отправлял +пакеты для нашей ноды. SP может игнорировать файлы с маленьким +приоритетом. Полные списки файлов отправляются уже на этапе процедуры +рукопожатия. diff --git a/doc/usecases.ru/spy.texi b/doc/usecases.ru/spy.texi new file mode 100644 index 0000000..a81035b --- /dev/null +++ b/doc/usecases.ru/spy.texi @@ -0,0 +1,39 @@ +@node UsecaseSpyRU +@subsection Разведка, шпионаж, тайная агентура + +Эти ребята знают насколько небезопасен Интернет, несовместим с +понятием приватности. Им необходим быстрый сброс и забор данных. Нет +возможности провести несколько итераций приёмо-передач (round-trips) -- +только сбросить данные, выстрелить и забыть. Опять же, это может быть +переносной накопитель и/или +@url{https://en.wikipedia.org/wiki/USB_dead_drop, USB тайник} (dead drop), +@url{https://en.wikipedia.org/wiki/PirateBox, PirateBox}ы, +@url{https://en.wikipedia.org/wiki/Short-range_agent_communications, +связь малой дальности (SRAC)}. Короткоживущие сети малой дальности типа +Bluetooth и WiFi могут быть и довольно быстрыми, позволяя быстро +"выстреливать" порциями исходящих пакетов. + +Очень важное свойство -- компрометация этих тайников или накопителей не +должна быть ни фатальна, ни даже опасна. Пакеты посылаемые через сети +или обмениваемые через устройства -- @ref{Encrypted, зашифрованы} по +принципу точка-точка (но, к сожалению, без совершенной прямой +секретности). Никаких имён файлов, получателей почтовых сообщений не +видно. + +Общение узлов между собой происходит в, так называемой, @ref{Spool, +спул} области: директории содержащей только необработанные зашифрованные +пакеты. После передачи пакета вы всё равно не сможете его прочитать: +необходимо запустить другую фазу: @ref{nncp-toss, распаковку}, которая +использует ваши приватные криптографические ключи. То есть, даже если вы +потеряете свой компьютер, устройства хранения и тому прочее -- это не +так плохо, потому что вы не носите с собой приватные ключи (ведь так?), +вы не "распаковываете" эти пакеты сразу же на том же самом устройстве. +Распаковка (чтение этих зашифрованных пакетов с извлечением переданных +файлов и почтовых сообщений) может и должна бы быть произведена на +отдельном компьютере (@ref{nncp-cfgmin} команда может помочь с созданием +конфигурационного файла без приватных ключей для этой цели). + +Если вы действительно хотите взять с собой приватные ключи, то +@ref{nncp-cfgenc} команда способна зашифровать ваш конфигурационный +файл. Парольная фраза вами введённая усиливается функцией нагружающей и +центральный процессор и память. diff --git a/doc/usecases.ru/unreliable.texi b/doc/usecases.ru/unreliable.texi new file mode 100644 index 0000000..22542e0 --- /dev/null +++ b/doc/usecases.ru/unreliable.texi @@ -0,0 +1,26 @@ +@node UsecaseUnreliableRU +@subsection Ненадёжный/дорогой канал связи + +Представьте, что у вас медленный модем/радио/спутниковый канал связи, +который часто обрывается и вызывает timeout у TCP. Не все HTTP серверы +поддерживают возобновляемые скачивания. SMTP вообще не поддерживает +продолжение оборванного приёма и тяжёлые сообщения становится очень +проблематично получить. Более того, каждый обрыв может приводить к +отсылке данных с самого начала, что не всегда по карману. + +Просто отправьте вашу @ref{nncp-exec, почту} и @ref{nncp-file, файлы} +через NNCP. Вы сможете использовать или offline методы доставки -- +читайте о них в следующем разделе, либо использовать поставляемый NNCP +@ref{nncp-daemon, TCP демон}. + +Команды: + +@example +$ nncp-file file_i_want_to_send bob: +$ nncp-file another_file bob:movie.avi +@end example + +добавят в очередь отправки два файла для узла @emph{bob}. +Выстрелил-и-забыл! Теперь это работа демона (или offline передачи) +доставить частями эти файлы до удалённой системы когда она будет +доступна. diff --git a/doc/usecases.texi b/doc/usecases.texi deleted file mode 100644 index f676e89..0000000 --- a/doc/usecases.texi +++ /dev/null @@ -1,477 +0,0 @@ -@node Use cases -@unnumbered Use cases - -See also this page @ref{Сценарии, on russian}. - -@menu -* Occasional connection to mail server: UsecaseMail -* Lightweight fast POP3/IMAP4 replacement: UsecasePOP -* Unreliable/expensive communication link: UsecaseUnreliable -* Slow/expensive link for high-volume data, bad QoS: UsecaseQoS -* Extreme terrestrial environments, no link: UsecaseNoLink -* One-way broadcasting communications: UsecaseBroadcast -* Satellite links: UsecaseSatelliteLinks -* Private, isolated MitM/Sybil-resistant networks: UsecaseF2F -* Highly secure isolated air-gap computers: UsecaseAirgap -* Network censorship bypassing, health: UsecaseCensor -* Reconnaissance, spying, intelligence, covert agents: UsecaseSpy -* Cheap night transfers: UsecaseCaller -* Multicast flooding transmission: UsecaseMulticast -@end menu - -@node UsecaseMail -@section Occasional connection to mail server - -Assume that you have got your own @url{http://www.postfix.org/, -Postfix}/@url{http://www.exim.org/, Exim} SMTP server connected to the -Internet. But you read and write emails on your notebook, that is -connected to it just from time to time. How can you flush buffered mail -queues when your notebook is connected? - -One possibility is to log in and run something like @command{postqueue --f}, but by default you have got only several days so and sender will -receive notification emails that his messages still are not delivered -yet. Also you must have secure link (SSH, VPN, etc). - -Another possibility is to use POP3/IMAP4 servers, but this is too -overcomplicated and bloated for the simple task. Not an option. -@url{https://en.wikipedia.org/wiki/KISS_principle, KISS}! - -Just tell both of your Postfix/Exim (on the server and notebook) to drop -email as a mail via NNCP (@ref{nncp-exec}) to specified node. - -More information for Postfix is @ref{Postfix, here} and for Exim is -@ref{Exim, here}. All mail will be stored in NNCP @ref{Spool, spool}, -that after exchanging and tossing will call local @command{sendmail} -command to deliver them just like that happened on the same machine. - -@node UsecasePOP -@section Lightweight fast POP3/IMAP4 replacement - -@ref{nncp-daemon} can be connected with @ref{nncp-caller} for a long -time -- it can create TCP connection that lasts for many hours. When -SMTP server receives mail, it will call @ref{nncp-exec} creating an -outbound encrypted packet. Daemon checks outbound directory each second -and immediately sends notification about undelivered packets to remote -side, that also downloads it at once. - -There are only dozens of bytes notifying about incoming packets, dozens -of bytes telling to download those packets. Mail packets are compressed -(POP3 and IMAP4 as a rule do not). You have lightweight, compressed, -low-delay, reliable link for the mail with strong encryption and mutual -sides authentication! - -@node UsecaseUnreliable -@section Unreliable/expensive communication link - -Assume that you have got slow modem/radio/cellular link that frequently -disconnects and causes TCP timeouts. Not all HTTP servers support file -download continuation. SMTP does not support resuming at all and heavy -messages is problematic to retrieve. Moreover, each disconnect leads to -the same data retransmission again, that can not be afforded sometimes. - -Just send your @ref{nncp-exec, mail} and @ref{nncp-file, files} through -NNCP. You can use either offline delivery methods -- read about them in -the next section, or you can use included NNCP @ref{nncp-daemon, TCP -daemon}. - -The command: - -@example -$ nncp-file file_i_want_to_send bob: -$ nncp-file another_file bob:movie.avi -@end example - -will queue two files for sending to @emph{bob} node. Fire and forget! -Now this is daemon's job (or offline transfer) to send this files part -by part to remote system when it is available. - -@node UsecaseQoS -@section Slow/expensive link for high-volume data, bad QoS - -Assume that you can give your relatively cheap 2 TiB removable hard -drive to someone each day at the morning (and take it back at the -evening). This equals to 185 Mbps good quality (without any speed -degradation) link in single direction. What about more and bigger hard -drives? This type of data exchange is called -@url{https://en.wikipedia.org/wiki/Sneakernet, sneakernet}/floppynet. - -NNCP allows traffic @ref{Niceness, prioritizing}: each packet has -niceness level, that will guarantee that it will be processed earlier or -later than the other ones. Nearly all commands has corresponding option: - -@example -$ nncp-file -nice FLASH myfile node:dst -$ nncp-xfer -nice PRIORITY /mnt/shared -$ nncp-call -nice NORMAL bob -[...] -@end example - -Huge files could be split on smaller @ref{Chunked, chunks}, giving -possibility to transfer virtually any volumes using small capacity -storages. - -You can also use CD-ROM and tape drives: - -@example -$ nncp-bundle -tx bob | cdrecord -tao - -$ nncp-bundle -tx bob | dd of=/dev/sa0 bs=10240 -@end example - -@node UsecaseNoLink -@section Extreme terrestrial environments, no link - -This is some kind of too slow link. Offline delivery methods is the only -choice. Just send files as shown in previous section, but use removable -media for transferring packets to other nodes. - -Assume that you send two files to @emph{bob} node. Insert USB storage -device (SD is preferable!), mount it and run @ref{nncp-xfer}: - -@example -$ nncp-xfer -node bob /media/usbstick -@end example - -to copy all outbound packets related to @emph{bob}. Use @option{-mkdir} -option to create related directory on USB/SD storage if they are missing -(for example when running for the first time). - -If you use single storage device to transfer data both to @emph{bob} and -@emph{alice}, then just omit @option{-node} option to copy all available -outgoing packets. - -@example -$ nncp-xfer /media/usbstick -@end example - -Unmount it and transfer storage to Bob and Alice. When they will insert -it in their computers, they will use exactly the same command: - -@example -$ nncp-xfer /media/usbstick -@end example - -to find all packets related to their node and copy them locally for -further processing. @command{nncp-xfer} is the only command used with -removable devices. - -@node UsecaseBroadcast -@section One-way broadcasting communications - -Sometimes you have got high-bandwidth but unidirectional link, for -example, satellite's broadcasting signal. You are not able to use online -@ref{Sync, synchronization protocol} because it requires mutual interaction. - -You can use @ref{Bundles, bundles} and stream them above. They are just -a sequence of @ref{Encrypted, encrypted packets} you can catch on. - -@example -$ nncp-bundle -tx alice bob eve ... | command to send broadcast -$ command to receive broadcast | nncp-bundle -rx -@end example - -With built-in packet duplicates detection ability, you can retransmit -your broadcasts from time to time, to increase chances the recipient -will catch them by regular stream listening. - -@node UsecaseSatelliteLinks -@section Satellite links - -Satellite links have @strong{very} high delays together with high -bandwidths. You can send several megabits of data per second, but they -will reach the remote side only after half a second! -Most file sharing protocols like -@url{https://en.wikipedia.org/wiki/Files_transferred_over_shell_protocol, FISH}, -@url{https://en.wikipedia.org/wiki/FTP, FTP}, -@url{https://en.wikipedia.org/wiki/Secure_copy, scp}, -@url{https://en.wikipedia.org/wiki/XMODEM, XMODEM} -will perform very badly because of round-trips quantity. Each file -transmission explicitly generates request and acknowledgement packets -that are send over the link. Remote side won't do anything until it -receives them. Moreover not all protocols allow duplex data -transmission (when both sides are sending data simultaneously). - -NNCP's @ref{Sync, synchronization protocol} (SP) tries to mitigate all -that issues by reducing number of round-trips, number of packets passing -through. All file lists, file download requests are grouped together -(pipelined) in one huge packet. Only transmission halt and successful -file download acknowledgements are sent explicitly. SP could be asked -only either to upload or download packets for our node. SP could ignore -files with low priority. Full files listing is passing even during the -handshake procedure. - -@node UsecaseF2F -@section Private, isolated MitM/Sybil-resistant networks - -All Internet connections can be eavesdropped and forged. You -@strong{have to} to use encryption and authentication for securing them. -But it is very hard to secure metadata, that leaks during each online -session. When you start your shiny new software server be sure that -there could be huge quantity of bogus peers trying to perform -@url{https://en.wikipedia.org/wiki/Sybil_attack, Sybil attack}. Opennet -peer-to-peer networking is dangerous thing to do. - -The most popular cryptographic protocol in Internet is -@url{https://en.wikipedia.org/wiki/Transport_Layer_Security, TLS} that -is very hard to implement correctly and hard to configure for mutual -participants authentication. Not all TLS configurations and related -protocols provide @url{https://en.wikipedia.org/wiki/Forward_secrecy, -forward secrecy} property -- all previously intercepted packets could be -read if private keys are compromised. - -Friend-to-friend networks, darknets can mitigate risks related to fake -and forged nodes. However they are harder to support and require more -time to be done right. - -NNCP's @ref{nncp-daemon, TCP daemon} uses -@url{http://noiseprotocol.org/, Noise-IK} protocol to mutually -authenticate peers and provide effective (both participants send payload -in the very first packet) secure transport with forward secrecy -property. - -@example -$ nncp-daemon -bind "[::]":5400 -@end example - -will start TCP daemon listening on all interfaces for incoming -connections. - -@example -$ nncp-call bob -@end example - -will try to connect to @emph{bob}'s node known TCP addresses (taken from -configuration file) and send all related outbound packets and retrieve -those the Bob has. All interrupted transfers will be automatically -resumed. - -Ability to do @ref{MCD, multicast nodes discovery} of participant in -IPv6 networks allows complete ignorance of network addresses specifying. - -@node UsecaseAirgap -@section Highly secure isolated air-gap computers - -If you worry much about security, then air-gapped computer could be the -only choice you can afford. Computer without any modems, wired and -wireless networks. Obviously the only possibility to exchange mail and -files is to use physically removable storage devices like CD-ROM, hard -drive, SD, tape and USB flash drives (@strong{worst} choice, due to -those devices complexity). - -Presumably you have got another own hop before that computer: another -intermediate node which performs basic verification of retrieved storage -devices, possibly by rewriting the data from USB/hard drives to CD-RWs. - -NNCP supports packets relying (transitioning) out-of-box. - -@verbatim -neigh: { - bob: { - [...] - addrs: { - lan: "[fe80::5400%igb0]:5400" - } - } - bob-airgap: - [...] - via: ["bob"] - } -} -@end verbatim - -That @ref{Configuration, configuration file} tells that we have got two -known neighbours: @emph{bob} and @emph{bob-airgap}. @emph{bob} can be -reached via online connection using @emph{lan} address. -@emph{bob-airgap} can be reached by sending intermediate relay packet -through the @emph{bob}. - -Any command like @command{nncp-file myfile bob-airgap:} will -automatically create an encapsulated packet: one for the destination -endpoint, and other carrying it for intermediate relaying node. - -Pay attention that relaying node knows nothing about the packet inside, -but just its size and priority. Transition packets are encrypted too: -using well-known @url{https://en.wikipedia.org/wiki/Onion_routing, onion -routing} technology. @emph{bob} can not read @emph{bob-airgap}'s packets. - -@node UsecaseCensor -@section Network censorship bypassing, health - -This is some kind of bad link too. Some governments tend to forbid -@strong{any} kind of private communication between people, allowing only -entertainment content delivering and popular social networks access -(that are already bloated with advertisements, locally executed -@url{https://www.gnu.org/philosophy/free-sw.html, proprietary} -JavaScript code (for spying on user activities, collect data on them), -shamelessly exploiting the very basic human need of communication). - -This is their natural wish. But nobody forces you to obey huge -corporations like Apple, Google or Microsoft. It is your choice to -create an isolated friend-to-friend network with piles of harmless -content and private messaging. Only predators silently watch for their -victims in mammals world -- it harms your health being watched and -feeling that you are the victim that has already done something wrong. - -@node UsecaseSpy -@section Reconnaissance, spying, intelligence, covert agents - -Those guys know how Internet is a dangerous place incompatible with -privacy. They require quick, fast dropping and picking of data. No -possibility of many round-trips -- just drop the data, fire-and-forget. -It could be either removable media again and/or -@url{https://en.wikipedia.org/wiki/USB_dead_drop, USB dead drops}, -@url{https://en.wikipedia.org/wiki/PirateBox, PirateBox}es, -@url{https://en.wikipedia.org/wiki/Short-range_agent_communications, SRAC}. -Short lived short range networks like Bluetooth and WiFi can also -be pretty fast, allowing to quickly fire chunks of queued packets. - -Very important property is that compromising of those dead drops and -storages must be neither fatal nor even dangerous. Packets sent through -the network and exchanged via those devices are end-to-end -@ref{Encrypted, encrypted} (but unfortunately lacking forward secrecy). -No filenames, mail recipients are seen. - -All node communications are done with so-called @ref{Spool, spool} area: -directory containing only those unprocessed encrypted packets. After -packet transfer you still can not read any of them: you have to run -another stage: @ref{nncp-toss, tossing}, that involves your private -cryptographic keys. So even if your loose your computer, storage devices -and so on -- it is not so bad, because you are not carrying private keys -with it (don't you?), you do not "toss" those packets immediately on the -same device. Tossing (reading those encrypted packets and extracting -transferred files and mail messages) could and should be done on a -separate computer (@ref{nncp-cfgmin} command could help creating -configuration file without private keys for that purpose). - -If you really want to carry your private keys, then @ref{nncp-cfgenc} -command will be able to encrypt your configuration file. Passphrase you -enter is strengthened with both CPU and memory hard function. - -@node UsecaseCaller -@section Cheap night transfers - -Your Internet/telephone traffic price can vary, depending on daytime. -Night calls/connections could be twice as cheaper. You wish to send your -files at that time, but keep high priority email infrequently passing -through in anytime. Also you wish to pass any kind of traffic when the -node is available through the LAN. - -You can easily set your preferences in @ref{Call, call -configurations} for @ref{nncp-caller} command used in online -communications. - -@verbatim -neigh: { - [...] - some-node: { - [...] - addrs: { - lan: "[fe80::be5f:f4ff:fedd:2752%igb0]:5400" - wan: "some-node.com:5400" - } - calls: [ - { - cron: "*/1 * * * *" - addr: lan - nice: MAX - onlinedeadline: 3600 - } - { - cron: "*/10 * * * *" - addr: wan - nice: PRIORITY - xx: rx - } - { - cron: "*/1 0-7 * * *" - addr: wan - nice: BULK - onlinedeadline: 3600 - maxonlinetime: 3600 - } - ] - } -} -@end verbatim - -@node UsecaseMulticast -@section Multicast flooding transmission - -Do you need to send single mail message or file to many recipients at -once? For example an update of some program, network participants list -or available files for freqing? But you are not connected directly to -each of them? - -@verbatim - A-------->E---->F A -> B C E - / \ |\ ^ C -> H J - / \ | \ | E -> D F G -v v v \v D -> G -B C D---->G J -> K - / \ ^ / K -> D G - / \ | / - v v v / - H J<->K<- -@end verbatim - -NNCP has @ref{Multicast, multicast} packets format, allowing you to -flood transmission of the single packet to multiple recipients. -@strong{A} sends packet to three destinations. @strong{C} sends it to -the two nodes next. @strong{E} sends it to three. Some participants may -receive multiple copies of the same packet, like @strong{D}, @strong{J}, -@strong{G}, @strong{F}, but that copies will be just ignored. If -@strong{B} sends packet to single known to him @strong{A}, then that -packet will be distributed among all other multicast area subscribers. - -Moreover those multicast packets are encrypted and require key knowledge -for reading. But that does not prevent their relaying! Also you are not -required to know sender's public keys. That way you can easily create -echo-conferences for files or commands (like mail message delivering) -transmission. - -Let's create keys for the new multicast area: - -@example -$ nncp-cfgnew -area filelists -nocomments -areas: @{ - filelists: @{ - id: TOU5TKOW4JBIZJBX63D4776C72FMWDAUAUSZNJX4DFOITVYQ5ZQA - pub: DSHL5O6BK2R3QKJAIJ7BC4UIGE73EC2LJPOV3VTS44KYOTUQYZLA - prv: AYD5FAA4GDDSAD5N65NJLLFS6TG2NSPQ46KAQO5U722JLVG34SOQ - @} -@} -@end example - -and send that keypair everybody who wants to read that area. -For intermediaries willing to relay packets on, but that should not read -them, you just need to send area's identity. For example @strong{A} adds -to his configuration: - -@example -areas: @{ - filelists: @{ - id: TOU... - pub: DSH... - prv: AYD... - subs: ["B", "C", "E"] - incoming: /home/A/areas/filelists - @} -@end example - -and @strong{E}, that will be relaying intermediary (as we decided): - -@example -areas: @{ - filelists: @{ - id: TOU... - subs: ["D", "F", "G"] - @} -@end example - -After you distributed the knowledge about @code{nodelist} multicast -area, you can share @ref{FreqIndex, file lists}: - -@example -$ nncp-file tree-of-A-20210715.txt.zst area:filelists: -$ nncp-toss -node self -@end example diff --git a/doc/usecases/airgap.texi b/doc/usecases/airgap.texi new file mode 100644 index 0000000..2c75d19 --- /dev/null +++ b/doc/usecases/airgap.texi @@ -0,0 +1,45 @@ +@node UsecaseAirgap +@section Highly secure isolated air-gap computers + +If you worry much about security, then air-gapped computer could be the +only choice you can afford. Computer without any modems, wired and +wireless networks. Obviously the only possibility to exchange mail and +files is to use physically removable storage devices like CD-ROM, hard +drive, SD, tape and USB flash drives (@strong{worst} choice, due to +those devices complexity). + +Presumably you have got another own hop before that computer: another +intermediate node which performs basic verification of retrieved storage +devices, possibly by rewriting the data from USB/hard drives to CD-RWs. + +NNCP supports packets relying (transitioning) out-of-box. + +@verbatim +neigh: { + bob: { + [...] + addrs: { + lan: "[fe80::5400%igb0]:5400" + } + } + bob-airgap: + [...] + via: ["bob"] + } +} +@end verbatim + +That @ref{Configuration, configuration file} tells that we have got two +known neighbours: @emph{bob} and @emph{bob-airgap}. @emph{bob} can be +reached via online connection using @emph{lan} address. +@emph{bob-airgap} can be reached by sending intermediate relay packet +through the @emph{bob}. + +Any command like @command{nncp-file myfile bob-airgap:} will +automatically create an encapsulated packet: one for the destination +endpoint, and other carrying it for intermediate relaying node. + +Pay attention that relaying node knows nothing about the packet inside, +but just its size and priority. Transition packets are encrypted too: +using well-known @url{https://en.wikipedia.org/wiki/Onion_routing, onion +routing} technology. @emph{bob} can not read @emph{bob-airgap}'s packets. diff --git a/doc/usecases/broadcast.texi b/doc/usecases/broadcast.texi new file mode 100644 index 0000000..a6c32f8 --- /dev/null +++ b/doc/usecases/broadcast.texi @@ -0,0 +1,18 @@ +@node UsecaseBroadcast +@section One-way broadcasting communications + +Sometimes you have got high-bandwidth but unidirectional link, for +example, satellite's broadcasting signal. You are not able to use online +@ref{Sync, synchronization protocol} because it requires mutual interaction. + +You can use @ref{Bundles, bundles} and stream them above. They are just +a sequence of @ref{Encrypted, encrypted packets} you can catch on. + +@example +$ nncp-bundle -tx alice bob eve @dots{} | command to send broadcast +$ command to receive broadcast | nncp-bundle -rx +@end example + +With built-in packet duplicates detection ability, you can retransmit +your broadcasts from time to time, to increase chances the recipient +will catch them by regular stream listening. diff --git a/doc/usecases/caller.texi b/doc/usecases/caller.texi new file mode 100644 index 0000000..df40dce --- /dev/null +++ b/doc/usecases/caller.texi @@ -0,0 +1,46 @@ +@node UsecaseCaller +@section Cheap night transfers + +Your Internet/telephone traffic price can vary, depending on daytime. +Night calls/connections could be twice as cheaper. You wish to send your +files at that time, but keep high priority email infrequently passing +through in anytime. Also you wish to pass any kind of traffic when the +node is available through the LAN. + +You can easily set your preferences in @ref{Call, call +configurations} for @ref{nncp-caller} command used in online +communications. + +@verbatim +neigh: { + [...] + some-node: { + [...] + addrs: { + lan: "[fe80::be5f:f4ff:fedd:2752%igb0]:5400" + wan: "some-node.com:5400" + } + calls: [ + { + cron: "*/1 * * * *" + addr: lan + nice: MAX + onlinedeadline: 3600 + } + { + cron: "*/10 * * * *" + addr: wan + nice: PRIORITY + xx: rx + } + { + cron: "*/1 0-7 * * *" + addr: wan + nice: BULK + onlinedeadline: 3600 + maxonlinetime: 3600 + } + ] + } +} +@end verbatim diff --git a/doc/usecases/censor.texi b/doc/usecases/censor.texi new file mode 100644 index 0000000..c32225f --- /dev/null +++ b/doc/usecases/censor.texi @@ -0,0 +1,17 @@ +@node UsecaseCensor +@section Network censorship bypassing, health + +This is some kind of bad link too. Some governments tend to forbid +@strong{any} kind of private communication between people, allowing only +entertainment content delivering and popular social networks access +(that are already bloated with advertisements, locally executed +@url{https://www.gnu.org/philosophy/free-sw.html, proprietary} +JavaScript code (for spying on user activities, collect data on them), +shamelessly exploiting the very basic human need of communication). + +This is their natural wish. But nobody forces you to obey huge +corporations like Apple, Google or Microsoft. It is your choice to +create an isolated friend-to-friend network with piles of harmless +content and private messaging. Only predators silently watch for their +victims in mammals world -- it harms your health being watched and +feeling that you are the victim that has already done something wrong. diff --git a/doc/usecases/f2f.texi b/doc/usecases/f2f.texi new file mode 100644 index 0000000..7d53e04 --- /dev/null +++ b/doc/usecases/f2f.texi @@ -0,0 +1,47 @@ +@node UsecaseF2F +@section Private, isolated MitM/Sybil-resistant networks + +All Internet connections can be eavesdropped and forged. You +@strong{have to} to use encryption and authentication for securing them. +But it is very hard to secure metadata, that leaks during each online +session. When you start your shiny new software server be sure that +there could be huge quantity of bogus peers trying to perform +@url{https://en.wikipedia.org/wiki/Sybil_attack, Sybil attack}. Opennet +peer-to-peer networking is dangerous thing to do. + +The most popular cryptographic protocol in Internet is +@url{https://en.wikipedia.org/wiki/Transport_Layer_Security, TLS} that +is very hard to implement correctly and hard to configure for mutual +participants authentication. Not all TLS configurations and related +protocols provide @url{https://en.wikipedia.org/wiki/Forward_secrecy, +forward secrecy} property -- all previously intercepted packets could be +read if private keys are compromised. + +Friend-to-friend networks, darknets can mitigate risks related to fake +and forged nodes. However they are harder to support and require more +time to be done right. + +NNCP's @ref{nncp-daemon, TCP daemon} uses +@url{http://noiseprotocol.org/, Noise-IK} protocol to mutually +authenticate peers and provide effective (both participants send payload +in the very first packet) secure transport with forward secrecy +property. + +@example +$ nncp-daemon -bind "[::]":5400 +@end example + +will start TCP daemon listening on all interfaces for incoming +connections. + +@example +$ nncp-call bob +@end example + +will try to connect to @emph{bob}'s node known TCP addresses (taken from +configuration file) and send all related outbound packets and retrieve +those the Bob has. All interrupted transfers will be automatically +resumed. + +Ability to do @ref{MCD, multicast nodes discovery} of participant in +IPv6 networks allows complete ignorance of network addresses specifying. diff --git a/doc/usecases/index.texi b/doc/usecases/index.texi new file mode 100644 index 0000000..938908f --- /dev/null +++ b/doc/usecases/index.texi @@ -0,0 +1,34 @@ +@node Use cases +@unnumbered Use cases + +See also this page @ref{Сценарии, on russian}. + +@menu +* Occasional connection to mail server: UsecaseMail +* Lightweight fast POP3/IMAP4 replacement: UsecasePOP +* Unreliable/expensive communication link: UsecaseUnreliable +* Slow/expensive link for high-volume data, bad QoS: UsecaseQoS +* Extreme terrestrial environments, no link: UsecaseNoLink +* One-way broadcasting communications: UsecaseBroadcast +* Satellite links: UsecaseSatelliteLinks +* Private, isolated MitM/Sybil-resistant networks: UsecaseF2F +* Highly secure isolated air-gap computers: UsecaseAirgap +* Network censorship bypassing, health: UsecaseCensor +* Reconnaissance, spying, intelligence, covert agents: UsecaseSpy +* Cheap night transfers: UsecaseCaller +* Multicast flooding transmission: UsecaseMulticast +@end menu + +@include usecases/mail.texi +@include usecases/pop.texi +@include usecases/unreliable.texi +@include usecases/qos.texi +@include usecases/nolink.texi +@include usecases/broadcast.texi +@include usecases/satellite.texi +@include usecases/f2f.texi +@include usecases/airgap.texi +@include usecases/censor.texi +@include usecases/spy.texi +@include usecases/caller.texi +@include usecases/multicast.texi diff --git a/doc/usecases/mail.texi b/doc/usecases/mail.texi new file mode 100644 index 0000000..2336136 --- /dev/null +++ b/doc/usecases/mail.texi @@ -0,0 +1,25 @@ +@node UsecaseMail +@section Occasional connection to mail server + +Assume that you have got your own @url{http://www.postfix.org/, +Postfix}/@url{http://www.exim.org/, Exim} SMTP server connected to the +Internet. But you read and write emails on your notebook, that is +connected to it just from time to time. How can you flush buffered mail +queues when your notebook is connected? + +One possibility is to log in and run something like @command{postqueue +-f}, but by default you have got only several days so and sender will +receive notification emails that his messages still are not delivered +yet. Also you must have secure link (SSH, VPN, etc). + +Another possibility is to use POP3/IMAP4 servers, but this is too +overcomplicated and bloated for the simple task. Not an option. +@url{https://en.wikipedia.org/wiki/KISS_principle, KISS}! + +Just tell both of your Postfix/Exim (on the server and notebook) to drop +email as a mail via NNCP (@ref{nncp-exec}) to specified node. + +More information for Postfix is @ref{Postfix, here} and for Exim is +@ref{Exim, here}. All mail will be stored in NNCP @ref{Spool, spool}, +that after exchanging and tossing will call local @command{sendmail} +command to deliver them just like that happened on the same machine. diff --git a/doc/usecases/multicast.texi b/doc/usecases/multicast.texi new file mode 100644 index 0000000..8c3bf31 --- /dev/null +++ b/doc/usecases/multicast.texi @@ -0,0 +1,81 @@ +@node UsecaseMulticast +@section Multicast flooding transmission + +Do you need to send single mail message or file to many recipients at +once? For example an update of some program, network participants list +or available files for freqing? But you are not connected directly to +each of them? + +@verbatim + A-------->E---->F A -> B C E + / \ |\ ^ C -> H J + / \ | \ | E -> D F G +v v v \v D -> G +B C D---->G J -> K + / \ ^ / K -> D G + / \ | / + v v v / + H J<->K<- +@end verbatim + +NNCP has @ref{Multicast, multicast} packets format, allowing you to +flood transmission of the single packet to multiple recipients. +@strong{A} sends packet to three destinations. @strong{C} sends it to +the two nodes next. @strong{E} sends it to three. Some participants may +receive multiple copies of the same packet, like @strong{D}, @strong{J}, +@strong{G}, @strong{F}, but that copies will be just ignored. If +@strong{B} sends packet to single known to him @strong{A}, then that +packet will be distributed among all other multicast area subscribers. + +Moreover those multicast packets are encrypted and require key knowledge +for reading. But that does not prevent their relaying! Also you are not +required to know sender's public keys. That way you can easily create +echo-conferences for files or commands (like mail message delivering) +transmission. + +Let's create keys for the new multicast area: + +@verbatim +$ nncp-cfgnew -area filelists -nocomments +areas: { + filelists: { + id: TOU5TKOW4JBIZJBX63D4776C72FMWDAUAUSZNJX4DFOITVYQ5ZQA + pub: DSHL5O6BK2R3QKJAIJ7BC4UIGE73EC2LJPOV3VTS44KYOTUQYZLA + prv: AYD5FAA4GDDSAD5N65NJLLFS6TG2NSPQ46KAQO5U722JLVG34SOQ + } +} +@end verbatim + +and send that keypair everybody who wants to read that area. +For intermediaries willing to relay packets on, but that should not read +them, you just need to send area's identity. For example @strong{A} adds +to his configuration: + +@verbatim +areas: { + filelists: { + id: TOU... + pub: DSH... + prv: AYD... + subs: ["B", "C", "E"] + incoming: /home/A/areas/filelists + } +@end verbatim + +and @strong{E}, that will be relaying intermediary (as we decided): + +@verbatim +areas: { + filelists: { + id: TOU... + subs: ["D", "F", "G"] + } +@end verbatim + +After you distributed the knowledge about @code{nodelist} multicast +area, you can share @ref{FreqIndex, file lists}: + +@example +$ nncp-file tree-of-A-20210715.txt.zst area:filelists: +$ nncp-toss -node self +@end example diff --git a/doc/usecases/nolink.texi b/doc/usecases/nolink.texi new file mode 100644 index 0000000..7886e81 --- /dev/null +++ b/doc/usecases/nolink.texi @@ -0,0 +1,36 @@ +@node UsecaseNoLink +@section Extreme terrestrial environments, no link + +This is some kind of too slow link. Offline delivery methods is the only +choice. Just send files as shown in previous section, but use removable +media for transferring packets to other nodes. + +Assume that you send two files to @emph{bob} node. Insert USB storage +device (SD is preferable!), mount it and run @ref{nncp-xfer}: + +@example +$ nncp-xfer -node bob /media/usbstick +@end example + +to copy all outbound packets related to @emph{bob}. Use @option{-mkdir} +option to create related directory on USB/SD storage if they are missing +(for example when running for the first time). + +If you use single storage device to transfer data both to @emph{bob} and +@emph{alice}, then just omit @option{-node} option to copy all available +outgoing packets. + +@example +$ nncp-xfer /media/usbstick +@end example + +Unmount it and transfer storage to Bob and Alice. When they will insert +it in their computers, they will use exactly the same command: + +@example +$ nncp-xfer /media/usbstick +@end example + +to find all packets related to their node and copy them locally for +further processing. @command{nncp-xfer} is the only command used with +removable devices. diff --git a/doc/usecases/pop.texi b/doc/usecases/pop.texi new file mode 100644 index 0000000..5edc3e8 --- /dev/null +++ b/doc/usecases/pop.texi @@ -0,0 +1,15 @@ +@node UsecasePOP +@section Lightweight fast POP3/IMAP4 replacement + +@ref{nncp-daemon} can be connected with @ref{nncp-caller} for a long +time -- it can create TCP connection that lasts for many hours. When +SMTP server receives mail, it will call @ref{nncp-exec} creating an +outbound encrypted packet. Daemon checks outbound directory each second +and immediately sends notification about undelivered packets to remote +side, that also downloads it at once. + +There are only dozens of bytes notifying about incoming packets, dozens +of bytes telling to download those packets. Mail packets are compressed +(POP3 and IMAP4 as a rule do not). You have lightweight, compressed, +low-delay, reliable link for the mail with strong encryption and mutual +sides authentication! diff --git a/doc/usecases/qos.texi b/doc/usecases/qos.texi new file mode 100644 index 0000000..8089888 --- /dev/null +++ b/doc/usecases/qos.texi @@ -0,0 +1,31 @@ +@node UsecaseQoS +@section Slow/expensive link for high-volume data, bad QoS + +Assume that you can give your relatively cheap 2 TiB removable hard +drive to someone each day at the morning (and take it back at the +evening). This equals to 185 Mbps good quality (without any speed +degradation) link in single direction. What about more and bigger hard +drives? This type of data exchange is called +@url{https://en.wikipedia.org/wiki/Sneakernet, sneakernet}/floppynet. + +NNCP allows traffic @ref{Niceness, prioritizing}: each packet has +niceness level, that will guarantee that it will be processed earlier or +later than the other ones. Nearly all commands has corresponding option: + +@example +$ nncp-file -nice FLASH myfile node:dst +$ nncp-xfer -nice PRIORITY /mnt/shared +$ nncp-call -nice NORMAL bob +[@dots{}] +@end example + +Huge files could be split on smaller @ref{Chunked, chunks}, giving +possibility to transfer virtually any volumes using small capacity +storages. + +You can also use CD-ROM and tape drives: + +@example +$ nncp-bundle -tx bob | cdrecord -tao - +$ nncp-bundle -tx bob | dd of=/dev/sa0 bs=10240 +@end example diff --git a/doc/usecases/satellite.texi b/doc/usecases/satellite.texi new file mode 100644 index 0000000..d152a3b --- /dev/null +++ b/doc/usecases/satellite.texi @@ -0,0 +1,25 @@ +@node UsecaseSatelliteLinks +@section Satellite links + +Satellite links have @strong{very} high delays together with high +bandwidths. You can send several megabits of data per second, but they +will reach the remote side only after half a second! +Most file sharing protocols like +@url{https://en.wikipedia.org/wiki/Files_transferred_over_shell_protocol, FISH}, +@url{https://en.wikipedia.org/wiki/FTP, FTP}, +@url{https://en.wikipedia.org/wiki/Secure_copy, scp}, +@url{https://en.wikipedia.org/wiki/XMODEM, XMODEM} +will perform very badly because of round-trips quantity. Each file +transmission explicitly generates request and acknowledgement packets +that are send over the link. Remote side won't do anything until it +receives them. Moreover not all protocols allow duplex data +transmission (when both sides are sending data simultaneously). + +NNCP's @ref{Sync, synchronization protocol} (SP) tries to mitigate all +that issues by reducing number of round-trips, number of packets passing +through. All file lists, file download requests are grouped together +(pipelined) in one huge packet. Only transmission halt and successful +file download acknowledgements are sent explicitly. SP could be asked +only either to upload or download packets for our node. SP could ignore +files with low priority. Full files listing is passing even during the +handshake procedure. diff --git a/doc/usecases/spy.texi b/doc/usecases/spy.texi new file mode 100644 index 0000000..b1e1de8 --- /dev/null +++ b/doc/usecases/spy.texi @@ -0,0 +1,34 @@ +@node UsecaseSpy +@section Reconnaissance, spying, intelligence, covert agents + +Those guys know how Internet is a dangerous place incompatible with +privacy. They require quick, fast dropping and picking of data. No +possibility of many round-trips -- just drop the data, fire-and-forget. +It could be either removable media again and/or +@url{https://en.wikipedia.org/wiki/USB_dead_drop, USB dead drops}, +@url{https://en.wikipedia.org/wiki/PirateBox, PirateBox}es, +@url{https://en.wikipedia.org/wiki/Short-range_agent_communications, SRAC}. +Short lived short range networks like Bluetooth and WiFi can also +be pretty fast, allowing to quickly fire chunks of queued packets. + +Very important property is that compromising of those dead drops and +storages must be neither fatal nor even dangerous. Packets sent through +the network and exchanged via those devices are end-to-end +@ref{Encrypted, encrypted} (but unfortunately lacking forward secrecy). +No filenames, mail recipients are seen. + +All node communications are done with so-called @ref{Spool, spool} area: +directory containing only those unprocessed encrypted packets. After +packet transfer you still can not read any of them: you have to run +another stage: @ref{nncp-toss, tossing}, that involves your private +cryptographic keys. So even if your loose your computer, storage devices +and so on -- it is not so bad, because you are not carrying private keys +with it (don't you?), you do not "toss" those packets immediately on the +same device. Tossing (reading those encrypted packets and extracting +transferred files and mail messages) could and should be done on a +separate computer (@ref{nncp-cfgmin} command could help creating +configuration file without private keys for that purpose). + +If you really want to carry your private keys, then @ref{nncp-cfgenc} +command will be able to encrypt your configuration file. Passphrase you +enter is strengthened with both CPU and memory hard function. diff --git a/doc/usecases/unreliable.texi b/doc/usecases/unreliable.texi new file mode 100644 index 0000000..93a40d9 --- /dev/null +++ b/doc/usecases/unreliable.texi @@ -0,0 +1,24 @@ +@node UsecaseUnreliable +@section Unreliable/expensive communication link + +Assume that you have got slow modem/radio/cellular link that frequently +disconnects and causes TCP timeouts. Not all HTTP servers support file +download continuation. SMTP does not support resuming at all and heavy +messages is problematic to retrieve. Moreover, each disconnect leads to +the same data retransmission again, that can not be afforded sometimes. + +Just send your @ref{nncp-exec, mail} and @ref{nncp-file, files} through +NNCP. You can use either offline delivery methods -- read about them in +the next section, or you can use included NNCP @ref{nncp-daemon, TCP +daemon}. + +The command: + +@example +$ nncp-file file_i_want_to_send bob: +$ nncp-file another_file bob:movie.avi +@end example + +will queue two files for sending to @emph{bob} node. Fire and forget! +Now this is daemon's job (or offline transfer) to send this files part +by part to remote system when it is available. diff --git a/src/call.go b/src/call.go index 1e20aa2..e8b3f76 100644 --- a/src/call.go +++ b/src/call.go @@ -18,8 +18,10 @@ along with this program. If not, see . package nncp import ( + "errors" "fmt" "net" + "os" "time" "github.com/dustin/go-humanize" @@ -68,6 +70,19 @@ func (ctx *Ctx) CallNode( var err error if addr[0] == '|' { conn, err = NewPipeConn(addr[1:]) + } else if addr == UCSPITCPClient { + ucspiConn := UCSPIConn{R: os.NewFile(6, "R"), W: os.NewFile(7, "W")} + if ucspiConn.R == nil { + err = errors.New("no 6 file descriptor") + } + if ucspiConn.W == nil { + err = errors.New("no 7 file descriptor") + } + conn = ucspiConn + addr = UCSPITCPRemoteAddr() + if addr == "" { + addr = UCSPITCPClient + } } else { conn, err = net.Dial("tcp", addr) } diff --git a/src/cmd/nncp-call/main.go b/src/cmd/nncp-call/main.go index 09c3e18..7d12066 100644 --- a/src/cmd/nncp-call/main.go +++ b/src/cmd/nncp-call/main.go @@ -40,6 +40,7 @@ func usage() { func main() { var ( cfgPath = flag.String("cfg", nncp.DefaultCfgPath, "Path to configuration file") + ucspi = flag.Bool("ucspi", false, "Is it started as UCSPI-TCP client") niceRaw = flag.String("nice", nncp.NicenessFmt(255), "Minimal required niceness") rxOnly = flag.Bool("rx", false, "Only receive packets") txOnly = flag.Bool("tx", false, "Only transmit packets") @@ -133,7 +134,9 @@ func main() { } var addrs []string - if flag.NArg() == 2 { + if *ucspi { + addrs = append(addrs, nncp.UCSPITCPClient) + } else if flag.NArg() == 2 { addrs = append(addrs, flag.Arg(1)) } else if len(splitted) == 2 { addr, known := ctx.Neigh[*node.Id].Addrs[splitted[1]] diff --git a/src/cmd/nncp-caller/main.go b/src/cmd/nncp-caller/main.go index d1a5b34..614a051 100644 --- a/src/cmd/nncp-caller/main.go +++ b/src/cmd/nncp-caller/main.go @@ -124,7 +124,7 @@ func main() { for _, ifiName := range ctx.MCDRxIfis { if err = ctx.MCDRx(ifiName); err != nil { - log.Fatalln("Can not run MCD reception:", err) + log.Printf("Can not run MCD reception on %s: %s", ifiName, err) } } diff --git a/src/cmd/nncp-daemon/main.go b/src/cmd/nncp-daemon/main.go index b0628fe..485199c 100644 --- a/src/cmd/nncp-daemon/main.go +++ b/src/cmd/nncp-daemon/main.go @@ -40,35 +40,6 @@ func usage() { flag.PrintDefaults() } -type InetdConn struct { - r *os.File - w *os.File -} - -func (c InetdConn) Read(p []byte) (n int, err error) { - return c.r.Read(p) -} - -func (c InetdConn) Write(p []byte) (n int, err error) { - return c.w.Write(p) -} - -func (c InetdConn) SetReadDeadline(t time.Time) error { - return c.r.SetReadDeadline(t) -} - -func (c InetdConn) SetWriteDeadline(t time.Time) error { - return c.w.SetWriteDeadline(t) -} - -func (c InetdConn) Close() error { - if err := c.r.Close(); err != nil { - c.w.Close() // #nosec G104 - return err - } - return c.w.Close() -} - func performSP( ctx *nncp.Ctx, conn nncp.ConnDeadlined, @@ -138,7 +109,8 @@ func main() { cfgPath = flag.String("cfg", nncp.DefaultCfgPath, "Path to configuration file") niceRaw = flag.String("nice", nncp.NicenessFmt(255), "Minimal required niceness") bind = flag.String("bind", "[::]:5400", "Address to bind to") - inetd = flag.Bool("inetd", false, "Is it started as inetd service") + ucspi = flag.Bool("ucspi", false, "Is it started as UCSPI-TCP server") + inetd = flag.Bool("inetd", false, "Obsolete, use -ucspi") maxConn = flag.Int("maxconn", 128, "Maximal number of simultaneous connections") noCK = flag.Bool("nock", false, "Do no checksum checking") mcdOnce = flag.Bool("mcd-once", false, "Send MCDs once and quit") @@ -174,6 +146,9 @@ func main() { if err != nil { log.Fatalln(err) } + if *inetd { + *ucspi = true + } ctx, err := nncp.CtxFromCmdline( *cfgPath, @@ -192,11 +167,15 @@ func main() { } ctx.Umask() - if *inetd { + if *ucspi { os.Stderr.Close() // #nosec G104 - conn := &InetdConn{os.Stdin, os.Stdout} + conn := &nncp.UCSPIConn{R: os.Stdin, W: os.Stdout} nodeIdC := make(chan *nncp.NodeId) - go performSP(ctx, conn, "PIPE", nice, *noCK, nodeIdC) + addr := nncp.UCSPITCPRemoteAddr() + if addr == "" { + addr = "PIPE" + } + go performSP(ctx, conn, addr, nice, *noCK, nodeIdC) nodeId := <-nodeIdC var autoTossFinish chan struct{} var autoTossBadCode chan bool diff --git a/src/go.mod b/src/go.mod index e84a8f4..5267dd2 100644 --- a/src/go.mod +++ b/src/go.mod @@ -9,9 +9,9 @@ require ( github.com/klauspost/compress v1.13.1 go.cypherpunks.ru/balloon v1.1.1 go.cypherpunks.ru/recfile v0.4.3 - golang.org/x/crypto v0.0.0-20210616213533-5ff15b29337e + golang.org/x/crypto v0.0.0-20210711020723-a769d52b0f97 golang.org/x/net v0.0.0-20210614182718-04defd469f4e - golang.org/x/sys v0.0.0-20210616094352-59db8d763f22 + golang.org/x/sys v0.0.0-20210630005230-0f9fa26af87c golang.org/x/term v0.0.0-20210615171337-6886f2dfbf5b lukechampine.com/blake3 v1.1.5 ) diff --git a/src/go.sum b/src/go.sum index 48b6e3b..4caa9b0 100644 --- a/src/go.sum +++ b/src/go.sum @@ -24,16 +24,16 @@ go.cypherpunks.ru/balloon v1.1.1/go.mod h1:k4s4ozrIrhpBjj78Z7LX8ZHxMQ+XE7DZUWl8g go.cypherpunks.ru/recfile v0.4.3 h1:ephokihmV//p0ob6gx2FWXvm28/NBDbWTOJPUNahxO8= go.cypherpunks.ru/recfile v0.4.3/go.mod h1:sR+KajB+vzofL3SFVFwKt3Fke0FaCcN1g3YPNAhU3qI= golang.org/x/crypto v0.0.0-20210322153248-0c34fe9e7dc2/go.mod h1:T9bdIzuCu7OtxOm1hfPfRQxPLYneinmdGuTeoZ9dtd4= -golang.org/x/crypto v0.0.0-20210616213533-5ff15b29337e h1:gsTQYXdTw2Gq7RBsWvlQ91b+aEQ6bXFUngBGuR8sPpI= -golang.org/x/crypto v0.0.0-20210616213533-5ff15b29337e/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= +golang.org/x/crypto v0.0.0-20210711020723-a769d52b0f97 h1:/UOmuWzQfxxo9UtlXMwuQU8CMgg1eZXqTRwkSQJWKOI= +golang.org/x/crypto v0.0.0-20210711020723-a769d52b0f97/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= golang.org/x/net v0.0.0-20210614182718-04defd469f4e h1:XpT3nA5TvE525Ne3hInMh6+GETgn27Zfm9dxsThnX2Q= golang.org/x/net v0.0.0-20210614182718-04defd469f4e/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20210616094352-59db8d763f22 h1:RqytpXGR1iVNX7psjB3ff8y7sNFinVFvkx1c8SjBkio= -golang.org/x/sys v0.0.0-20210616094352-59db8d763f22/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20210630005230-0f9fa26af87c h1:F1jZWGFhYfh0Ci55sIpILtKKK8p3i2/krTr0H1rg74I= +golang.org/x/sys v0.0.0-20210630005230-0f9fa26af87c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/term v0.0.0-20210615171337-6886f2dfbf5b h1:9zKuko04nR4gjZ4+DNjHqRlAJqbJETHwiNKDqTfOjfE= golang.org/x/term v0.0.0-20210615171337-6886f2dfbf5b/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= diff --git a/src/nncp.go b/src/nncp.go index 64489bc..2ee727f 100644 --- a/src/nncp.go +++ b/src/nncp.go @@ -40,7 +40,7 @@ along with this program. If not, see .` const Base32Encoded32Len = 52 var ( - Version string = "7.4.0" + Version string = "7.5.0" Base32Codec *base32.Encoding = base32.StdEncoding.WithPadding(base32.NoPadding) ) diff --git a/src/ucspi.go b/src/ucspi.go new file mode 100644 index 0000000..33e265d --- /dev/null +++ b/src/ucspi.go @@ -0,0 +1,67 @@ +/* +NNCP -- Node to Node copy, utilities for store-and-forward data exchange +Copyright (C) 2016-2021 Sergey Matveev + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, version 3 of the License. + +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 General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program. If not, see . +*/ + +package nncp + +import ( + "fmt" + "os" + "time" +) + +const UCSPITCPClient = "UCSPI-TCP-CLIENT" + +type UCSPIConn struct { + R *os.File + W *os.File +} + +func (c UCSPIConn) Read(p []byte) (n int, err error) { + return c.R.Read(p) +} + +func (c UCSPIConn) Write(p []byte) (n int, err error) { + return c.W.Write(p) +} + +func (c UCSPIConn) SetReadDeadline(t time.Time) error { + return c.R.SetReadDeadline(t) +} + +func (c UCSPIConn) SetWriteDeadline(t time.Time) error { + return c.W.SetWriteDeadline(t) +} + +func (c UCSPIConn) Close() error { + if err := c.R.Close(); err != nil { + c.W.Close() + return err + } + return c.W.Close() +} + +func UCSPITCPRemoteAddr() (addr string) { + if proto := os.Getenv("PROTO"); proto == "TCP" { + port := os.Getenv("TCPREMOTEPORT") + if host := os.Getenv("TCPREMOTEHOST"); host == "" { + addr = fmt.Sprintf("[%s]:%s", os.Getenv("TCPREMOTEIP"), port) + } else { + addr = fmt.Sprintf("%s:%s", host, port) + } + } + return +}