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