]> Cypherpunks.ru repositories - nncp.git/blob - src/cmd/nncp-daemon/main.go
MTH
[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         "strconv"
28         "strings"
29         "time"
30
31         "github.com/dustin/go-humanize"
32         "go.cypherpunks.ru/nncp/v7"
33         "golang.org/x/net/netutil"
34 )
35
36 func usage() {
37         fmt.Fprintf(os.Stderr, nncp.UsageHeader())
38         fmt.Fprintf(os.Stderr, "nncp-daemon -- TCP daemon\n\n")
39         fmt.Fprintf(os.Stderr, "Usage: %s [options]\nOptions:\n", os.Args[0])
40         flag.PrintDefaults()
41 }
42
43 type InetdConn struct {
44         r *os.File
45         w *os.File
46 }
47
48 func (c InetdConn) Read(p []byte) (n int, err error) {
49         return c.r.Read(p)
50 }
51
52 func (c InetdConn) Write(p []byte) (n int, err error) {
53         return c.w.Write(p)
54 }
55
56 func (c InetdConn) SetReadDeadline(t time.Time) error {
57         return c.r.SetReadDeadline(t)
58 }
59
60 func (c InetdConn) SetWriteDeadline(t time.Time) error {
61         return c.w.SetWriteDeadline(t)
62 }
63
64 func (c InetdConn) Close() error {
65         if err := c.r.Close(); err != nil {
66                 c.w.Close() // #nosec G104
67                 return err
68         }
69         return c.w.Close()
70 }
71
72 func performSP(
73         ctx *nncp.Ctx,
74         conn nncp.ConnDeadlined,
75         addr string,
76         nice uint8,
77         noCK bool,
78         nodeIdC chan *nncp.NodeId,
79 ) {
80         state := nncp.SPState{
81                 Ctx:  ctx,
82                 Nice: nice,
83                 NoCK: noCK,
84         }
85         if err := state.StartR(conn); err == nil {
86                 ctx.LogI(
87                         "call-started",
88                         nncp.LEs{{K: "Node", V: state.Node.Id}},
89                         func(les nncp.LEs) string {
90                                 return fmt.Sprintf("Connection with %s (%s)", state.Node.Name, addr)
91                         },
92                 )
93                 nodeIdC <- state.Node.Id
94                 state.Wait()
95                 ctx.LogI("call-finished", nncp.LEs{
96                         {K: "Node", V: state.Node.Id},
97                         {K: "Duration", V: int64(state.Duration.Seconds())},
98                         {K: "RxBytes", V: state.RxBytes},
99                         {K: "TxBytes", V: state.TxBytes},
100                         {K: "RxSpeed", V: state.RxSpeed},
101                         {K: "TxSpeed", V: state.TxSpeed},
102                 }, func(les nncp.LEs) string {
103                         return fmt.Sprintf(
104                                 "Finished call with %s (%d:%d:%d): %s received (%s/sec), %s transferred (%s/sec)",
105                                 state.Node.Name,
106                                 int(state.Duration.Hours()),
107                                 int(state.Duration.Minutes()),
108                                 int(state.Duration.Seconds()/60),
109                                 humanize.IBytes(uint64(state.RxBytes)),
110                                 humanize.IBytes(uint64(state.RxSpeed)),
111                                 humanize.IBytes(uint64(state.TxBytes)),
112                                 humanize.IBytes(uint64(state.TxSpeed)),
113                         )
114                 })
115         } else {
116                 var nodeId string
117                 var nodeName string
118                 if state.Node == nil {
119                         nodeId = "unknown"
120                         nodeName = "unknown"
121                         nodeIdC <- nil
122                 } else {
123                         nodeId = state.Node.Id.String()
124                         nodeName = state.Node.Name
125                         nodeIdC <- state.Node.Id
126                 }
127                 ctx.LogI(
128                         "call-started",
129                         nncp.LEs{{K: "Node", V: nodeId}},
130                         func(les nncp.LEs) string { return "Connected to " + nodeName },
131                 )
132         }
133         close(nodeIdC)
134 }
135
136 func main() {
137         var (
138                 cfgPath   = flag.String("cfg", nncp.DefaultCfgPath, "Path to configuration file")
139                 niceRaw   = flag.String("nice", nncp.NicenessFmt(255), "Minimal required niceness")
140                 bind      = flag.String("bind", "[::]:5400", "Address to bind to")
141                 inetd     = flag.Bool("inetd", false, "Is it started as inetd service")
142                 maxConn   = flag.Int("maxconn", 128, "Maximal number of simultaneous connections")
143                 noCK      = flag.Bool("nock", false, "Do no checksum checking")
144                 mcdOnce   = flag.Bool("mcd-once", false, "Send MCDs once and quit")
145                 spoolPath = flag.String("spool", "", "Override path to spool")
146                 logPath   = flag.String("log", "", "Override path to logfile")
147                 quiet     = flag.Bool("quiet", false, "Print only errors")
148                 showPrgrs = flag.Bool("progress", false, "Force progress showing")
149                 omitPrgrs = flag.Bool("noprogress", false, "Omit progress showing")
150                 debug     = flag.Bool("debug", false, "Print debug messages")
151                 version   = flag.Bool("version", false, "Print version information")
152                 warranty  = flag.Bool("warranty", false, "Print warranty information")
153
154                 autoToss       = flag.Bool("autotoss", false, "Toss after call is finished")
155                 autoTossDoSeen = flag.Bool("autotoss-seen", false, "Create .seen files during tossing")
156                 autoTossNoFile = flag.Bool("autotoss-nofile", false, "Do not process \"file\" packets during tossing")
157                 autoTossNoFreq = flag.Bool("autotoss-nofreq", false, "Do not process \"freq\" packets during tossing")
158                 autoTossNoExec = flag.Bool("autotoss-noexec", false, "Do not process \"exec\" packets during tossing")
159                 autoTossNoTrns = flag.Bool("autotoss-notrns", false, "Do not process \"trns\" packets during tossing")
160         )
161         log.SetFlags(log.Lshortfile)
162         flag.Usage = usage
163         flag.Parse()
164         if *warranty {
165                 fmt.Println(nncp.Warranty)
166                 return
167         }
168         if *version {
169                 fmt.Println(nncp.VersionGet())
170                 return
171         }
172         nice, err := nncp.NicenessParse(*niceRaw)
173         if err != nil {
174                 log.Fatalln(err)
175         }
176
177         ctx, err := nncp.CtxFromCmdline(
178                 *cfgPath,
179                 *spoolPath,
180                 *logPath,
181                 *quiet,
182                 *showPrgrs,
183                 *omitPrgrs,
184                 *debug,
185         )
186         if err != nil {
187                 log.Fatalln("Error during initialization:", err)
188         }
189         if ctx.Self == nil {
190                 log.Fatalln("Config lacks private keys")
191         }
192         ctx.Umask()
193
194         if *inetd {
195                 os.Stderr.Close() // #nosec G104
196                 conn := &InetdConn{os.Stdin, os.Stdout}
197                 nodeIdC := make(chan *nncp.NodeId)
198                 go performSP(ctx, conn, "PIPE", nice, *noCK, nodeIdC)
199                 nodeId := <-nodeIdC
200                 var autoTossFinish chan struct{}
201                 var autoTossBadCode chan bool
202                 if *autoToss && nodeId != nil {
203                         autoTossFinish, autoTossBadCode = ctx.AutoToss(
204                                 nodeId,
205                                 nice,
206                                 *autoTossDoSeen,
207                                 *autoTossNoFile,
208                                 *autoTossNoFreq,
209                                 *autoTossNoExec,
210                                 *autoTossNoTrns,
211                         )
212                 }
213                 <-nodeIdC // call completion
214                 if *autoToss {
215                         close(autoTossFinish)
216                         <-autoTossBadCode
217                 }
218                 conn.Close() // #nosec G104
219                 return
220         }
221
222         cols := strings.Split(*bind, ":")
223         port, err := strconv.Atoi(cols[len(cols)-1])
224         if err != nil {
225                 log.Fatalln("Can not parse port:", err)
226         }
227
228         if *mcdOnce {
229                 for ifiName := range ctx.MCDTxIfis {
230                         if err = ctx.MCDTx(ifiName, port, 0); err != nil {
231                                 log.Fatalln("Can not do MCD transmission:", err)
232                         }
233                 }
234                 return
235         }
236
237         ln, err := net.Listen("tcp", *bind)
238         if err != nil {
239                 log.Fatalln("Can not listen:", err)
240         }
241
242         for ifiName, secs := range ctx.MCDTxIfis {
243                 if err = ctx.MCDTx(ifiName, port, time.Duration(secs)*time.Second); err != nil {
244                         log.Fatalln("Can not run MCD transmission:", err)
245                 }
246         }
247
248         ln = netutil.LimitListener(ln, *maxConn)
249         for {
250                 conn, err := ln.Accept()
251                 if err != nil {
252                         log.Fatalln("Can not accept connection:", err)
253                 }
254                 ctx.LogD(
255                         "daemon-accepted",
256                         nncp.LEs{{K: "Addr", V: conn.RemoteAddr()}},
257                         func(les nncp.LEs) string {
258                                 return "Accepted connection with " + conn.RemoteAddr().String()
259                         },
260                 )
261                 go func(conn net.Conn) {
262                         nodeIdC := make(chan *nncp.NodeId)
263                         go performSP(ctx, conn, conn.RemoteAddr().String(), nice, *noCK, nodeIdC)
264                         nodeId := <-nodeIdC
265                         var autoTossFinish chan struct{}
266                         var autoTossBadCode chan bool
267                         if *autoToss && nodeId != nil {
268                                 autoTossFinish, autoTossBadCode = ctx.AutoToss(
269                                         nodeId,
270                                         nice,
271                                         *autoTossDoSeen,
272                                         *autoTossNoFile,
273                                         *autoTossNoFreq,
274                                         *autoTossNoExec,
275                                         *autoTossNoTrns,
276                                 )
277                         }
278                         <-nodeIdC // call completion
279                         if *autoToss {
280                                 close(autoTossFinish)
281                                 <-autoTossBadCode
282                         }
283                         conn.Close() // #nosec G104
284                 }(conn)
285         }
286 }