]> Cypherpunks.ru repositories - nncp.git/blob - src/cmd/nncp-daemon/main.go
Merge branch 'develop'
[nncp.git] / src / cmd / nncp-daemon / main.go
1 /*
2 NNCP -- Node to Node copy, utilities for store-and-forward data exchange
3 Copyright (C) 2016-2021 Sergey Matveev <stargrave@stargrave.org>
4
5 This program is free software: you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation, version 3 of the License.
8
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12 GNU General Public License for more details.
13
14 You should have received a copy of the GNU General Public License
15 along with this program.  If not, see <http://www.gnu.org/licenses/>.
16 */
17
18 // NNCP TCP daemon.
19 package main
20
21 import (
22         "flag"
23         "fmt"
24         "log"
25         "net"
26         "os"
27         "time"
28
29         "github.com/dustin/go-humanize"
30         "go.cypherpunks.ru/nncp/v6"
31         "golang.org/x/net/netutil"
32 )
33
34 func usage() {
35         fmt.Fprintf(os.Stderr, nncp.UsageHeader())
36         fmt.Fprintf(os.Stderr, "nncp-daemon -- TCP daemon\n\n")
37         fmt.Fprintf(os.Stderr, "Usage: %s [options]\nOptions:\n", os.Args[0])
38         flag.PrintDefaults()
39 }
40
41 type InetdConn struct {
42         r *os.File
43         w *os.File
44 }
45
46 func (c InetdConn) Read(p []byte) (n int, err error) {
47         return c.r.Read(p)
48 }
49
50 func (c InetdConn) Write(p []byte) (n int, err error) {
51         return c.w.Write(p)
52 }
53
54 func (c InetdConn) SetReadDeadline(t time.Time) error {
55         return c.r.SetReadDeadline(t)
56 }
57
58 func (c InetdConn) SetWriteDeadline(t time.Time) error {
59         return c.w.SetWriteDeadline(t)
60 }
61
62 func (c InetdConn) Close() error {
63         if err := c.r.Close(); err != nil {
64                 c.w.Close() // #nosec G104
65                 return err
66         }
67         return c.w.Close()
68 }
69
70 func performSP(
71         ctx *nncp.Ctx,
72         conn nncp.ConnDeadlined,
73         nice uint8,
74         noCK bool,
75         nodeIdC chan *nncp.NodeId,
76 ) {
77         state := nncp.SPState{
78                 Ctx:  ctx,
79                 Nice: nice,
80                 NoCK: noCK,
81         }
82         if err := state.StartR(conn); err == nil {
83                 ctx.LogI(
84                         "call-started",
85                         nncp.LEs{{K: "Node", V: state.Node.Id}},
86                         func(les nncp.LEs) string { return "Connection with " + state.Node.Name },
87                 )
88                 nodeIdC <- state.Node.Id
89                 state.Wait()
90                 ctx.LogI("call-finished", nncp.LEs{
91                         {K: "Node", V: state.Node.Id},
92                         {K: "Duration", V: int64(state.Duration.Seconds())},
93                         {K: "RxBytes", V: state.RxBytes},
94                         {K: "TxBytes", V: state.TxBytes},
95                         {K: "RxSpeed", V: state.RxSpeed},
96                         {K: "TxSpeed", V: state.TxSpeed},
97                 }, func(les nncp.LEs) string {
98                         return fmt.Sprintf(
99                                 "Finished call with %s (%d:%d:%d): %s received (%s/sec), %s transferred (%s/sec)",
100                                 state.Node.Name,
101                                 int(state.Duration.Hours()),
102                                 int(state.Duration.Minutes()),
103                                 int(state.Duration.Seconds()),
104                                 humanize.IBytes(uint64(state.RxBytes)),
105                                 humanize.IBytes(uint64(state.RxSpeed)),
106                                 humanize.IBytes(uint64(state.TxBytes)),
107                                 humanize.IBytes(uint64(state.TxSpeed)),
108                         )
109                 })
110         } else {
111                 nodeId := "unknown"
112                 if state.Node == nil {
113                         nodeIdC <- nil
114                 } else {
115                         nodeIdC <- state.Node.Id
116                         nodeId = state.Node.Id.String()
117                 }
118                 ctx.LogI(
119                         "call-started",
120                         nncp.LEs{{K: "Node", V: nodeId}},
121                         func(les nncp.LEs) string { return "Connected to " + state.Node.Name },
122                 )
123         }
124         close(nodeIdC)
125 }
126
127 func main() {
128         var (
129                 cfgPath   = flag.String("cfg", nncp.DefaultCfgPath, "Path to configuration file")
130                 niceRaw   = flag.String("nice", nncp.NicenessFmt(255), "Minimal required niceness")
131                 bind      = flag.String("bind", "[::]:5400", "Address to bind to")
132                 inetd     = flag.Bool("inetd", false, "Is it started as inetd service")
133                 maxConn   = flag.Int("maxconn", 128, "Maximal number of simultaneous connections")
134                 noCK      = flag.Bool("nock", false, "Do no checksum checking")
135                 spoolPath = flag.String("spool", "", "Override path to spool")
136                 logPath   = flag.String("log", "", "Override path to logfile")
137                 quiet     = flag.Bool("quiet", false, "Print only errors")
138                 showPrgrs = flag.Bool("progress", false, "Force progress showing")
139                 omitPrgrs = flag.Bool("noprogress", false, "Omit progress showing")
140                 debug     = flag.Bool("debug", false, "Print debug messages")
141                 version   = flag.Bool("version", false, "Print version information")
142                 warranty  = flag.Bool("warranty", false, "Print warranty information")
143
144                 autoToss       = flag.Bool("autotoss", false, "Toss after call is finished")
145                 autoTossDoSeen = flag.Bool("autotoss-seen", false, "Create .seen files during tossing")
146                 autoTossNoFile = flag.Bool("autotoss-nofile", false, "Do not process \"file\" packets during tossing")
147                 autoTossNoFreq = flag.Bool("autotoss-nofreq", false, "Do not process \"freq\" packets during tossing")
148                 autoTossNoExec = flag.Bool("autotoss-noexec", false, "Do not process \"exec\" packets during tossing")
149                 autoTossNoTrns = flag.Bool("autotoss-notrns", false, "Do not process \"trns\" packets during tossing")
150         )
151         flag.Usage = usage
152         flag.Parse()
153         if *warranty {
154                 fmt.Println(nncp.Warranty)
155                 return
156         }
157         if *version {
158                 fmt.Println(nncp.VersionGet())
159                 return
160         }
161         nice, err := nncp.NicenessParse(*niceRaw)
162         if err != nil {
163                 log.Fatalln(err)
164         }
165
166         ctx, err := nncp.CtxFromCmdline(
167                 *cfgPath,
168                 *spoolPath,
169                 *logPath,
170                 *quiet,
171                 *showPrgrs,
172                 *omitPrgrs,
173                 *debug,
174         )
175         if err != nil {
176                 log.Fatalln("Error during initialization:", err)
177         }
178         if ctx.Self == nil {
179                 log.Fatalln("Config lacks private keys")
180         }
181         ctx.Umask()
182
183         if *inetd {
184                 os.Stderr.Close() // #nosec G104
185                 conn := &InetdConn{os.Stdin, os.Stdout}
186                 nodeIdC := make(chan *nncp.NodeId)
187                 go performSP(ctx, conn, nice, *noCK, nodeIdC)
188                 nodeId := <-nodeIdC
189                 var autoTossFinish chan struct{}
190                 var autoTossBadCode chan bool
191                 if *autoToss && nodeId != nil {
192                         autoTossFinish, autoTossBadCode = ctx.AutoToss(
193                                 nodeId,
194                                 nice,
195                                 *autoTossDoSeen,
196                                 *autoTossNoFile,
197                                 *autoTossNoFreq,
198                                 *autoTossNoExec,
199                                 *autoTossNoTrns,
200                         )
201                 }
202                 <-nodeIdC // call completion
203                 if *autoToss {
204                         close(autoTossFinish)
205                         <-autoTossBadCode
206                 }
207                 conn.Close() // #nosec G104
208                 return
209         }
210
211         ln, err := net.Listen("tcp", *bind)
212         if err != nil {
213                 log.Fatalln("Can not listen:", err)
214         }
215         ln = netutil.LimitListener(ln, *maxConn)
216         for {
217                 conn, err := ln.Accept()
218                 if err != nil {
219                         log.Fatalln("Can not accept connection:", err)
220                 }
221                 ctx.LogD(
222                         "daemon-accepted",
223                         nncp.LEs{{K: "Addr", V: conn.RemoteAddr()}},
224                         func(les nncp.LEs) string {
225                                 return "Accepted connection with " + conn.RemoteAddr().String()
226                         },
227                 )
228                 go func(conn net.Conn) {
229                         nodeIdC := make(chan *nncp.NodeId)
230                         go performSP(ctx, conn, nice, *noCK, nodeIdC)
231                         nodeId := <-nodeIdC
232                         var autoTossFinish chan struct{}
233                         var autoTossBadCode chan bool
234                         if *autoToss && nodeId != nil {
235                                 autoTossFinish, autoTossBadCode = ctx.AutoToss(
236                                         nodeId,
237                                         nice,
238                                         *autoTossDoSeen,
239                                         *autoTossNoFile,
240                                         *autoTossNoFreq,
241                                         *autoTossNoExec,
242                                         *autoTossNoTrns,
243                                 )
244                         }
245                         <-nodeIdC // call completion
246                         if *autoToss {
247                                 close(autoTossFinish)
248                                 <-autoTossBadCode
249                         }
250                         conn.Close() // #nosec G104
251                 }(conn)
252         }
253 }