]> Cypherpunks.ru repositories - nncp.git/blob - src/cmd/nncp-daemon/main.go
Wrap long lines
[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-2023 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         "regexp"
28         "strconv"
29         "strings"
30         "time"
31
32         "github.com/dustin/go-humanize"
33         "go.cypherpunks.ru/nncp/v8"
34         nncpYggdrasil "go.cypherpunks.ru/nncp/v8/yggdrasil"
35         "golang.org/x/net/netutil"
36 )
37
38 func usage() {
39         fmt.Fprint(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 startMCDTx(ctx *nncp.Ctx, port int, zeroInterval bool) error {
109         ifis, err := net.Interfaces()
110         if err != nil {
111                 return err
112         }
113         for ifiReString, secs := range ctx.MCDTxIfis {
114                 ifiRe, err := regexp.CompilePOSIX(ifiReString)
115                 if err != nil {
116                         return err
117                 }
118                 var interval time.Duration
119                 if !zeroInterval {
120                         interval = time.Duration(secs) * time.Second
121                 }
122                 for _, ifi := range ifis {
123                         if ifiRe.MatchString(ifi.Name) {
124                                 if err = ctx.MCDTx(ifi.Name, port, interval); err != nil {
125                                         return err
126                                 }
127                         }
128                 }
129         }
130         return nil
131 }
132
133 func main() {
134         var (
135                 cfgPath   = flag.String("cfg", nncp.DefaultCfgPath, "Path to configuration file")
136                 niceRaw   = flag.String("nice", nncp.NicenessFmt(255), "Minimal required niceness")
137                 bind      = flag.String("bind", "[::]:5400", "Address to bind to")
138                 ucspi     = flag.Bool("ucspi", false, "Is it started as UCSPI-TCP server")
139                 inetd     = flag.Bool("inetd", false, "Obsolete, use -ucspi")
140                 yggdrasil = flag.String("yggdrasil", "",
141                         "Start Yggdrasil listener: yggdrasils://PRV[:PORT]?[bind=BIND][&pub=PUB][&peer=PEER][&mcast=REGEX[:PORT]]")
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,
155                         "Toss after call is finished")
156                 autoTossDoSeen = flag.Bool("autotoss-seen", false,
157                         "Create seen/ files during tossing")
158                 autoTossNoFile = flag.Bool("autotoss-nofile", false,
159                         "Do not process \"file\" packets during tossing")
160                 autoTossNoFreq = flag.Bool("autotoss-nofreq", false,
161                         "Do not process \"freq\" packets during tossing")
162                 autoTossNoExec = flag.Bool("autotoss-noexec", false,
163                         "Do not process \"exec\" packets during tossing")
164                 autoTossNoTrns = flag.Bool("autotoss-notrns", false,
165                         "Do not process \"trns\" packets during tossing")
166                 autoTossNoArea = flag.Bool("autotoss-noarea", false,
167                         "Do not process \"area\" packets during tossing")
168                 autoTossNoACK = flag.Bool("autotoss-noack", false,
169                         "Do not process \"ack\" packets during tossing")
170         )
171         log.SetFlags(log.Lshortfile)
172         flag.Usage = usage
173         flag.Parse()
174         if *warranty {
175                 fmt.Println(nncp.Warranty)
176                 return
177         }
178         if *version {
179                 fmt.Println(nncp.VersionGet())
180                 return
181         }
182         nice, err := nncp.NicenessParse(*niceRaw)
183         if err != nil {
184                 log.Fatalln(err)
185         }
186         if *inetd {
187                 *ucspi = true
188         }
189
190         ctx, err := nncp.CtxFromCmdline(
191                 *cfgPath,
192                 *spoolPath,
193                 *logPath,
194                 *quiet,
195                 *showPrgrs,
196                 *omitPrgrs,
197                 *debug,
198         )
199         if err != nil {
200                 log.Fatalln("Error during initialization:", err)
201         }
202         if ctx.Self == nil {
203                 log.Fatalln("Config lacks private keys")
204         }
205         ctx.Umask()
206
207         if *ucspi {
208                 os.Stderr.Close()
209                 conn := &nncp.UCSPIConn{R: os.Stdin, W: os.Stdout}
210                 nodeIdC := make(chan *nncp.NodeId)
211                 addr := nncp.UCSPITCPRemoteAddr()
212                 if addr == "" {
213                         addr = "PIPE"
214                 }
215                 go performSP(ctx, conn, addr, nice, *noCK, nodeIdC)
216                 nodeId := <-nodeIdC
217                 var autoTossFinish chan struct{}
218                 var autoTossBadCode chan bool
219                 if *autoToss && nodeId != nil {
220                         autoTossFinish, autoTossBadCode = ctx.AutoToss(
221                                 nodeId,
222                                 &nncp.TossOpts{
223                                         Nice:   nice,
224                                         DoSeen: *autoTossDoSeen,
225                                         NoFile: *autoTossNoFile,
226                                         NoFreq: *autoTossNoFreq,
227                                         NoExec: *autoTossNoExec,
228                                         NoTrns: *autoTossNoTrns,
229                                         NoArea: *autoTossNoArea,
230                                         NoACK:  *autoTossNoACK,
231                                 },
232                         )
233                 }
234                 <-nodeIdC // call completion
235                 if *autoToss && nodeId != nil {
236                         close(autoTossFinish)
237                         <-autoTossBadCode
238                 }
239                 conn.Close()
240                 return
241         }
242
243         conns := make(chan net.Conn)
244         if *bind != "" {
245                 cols := strings.Split(*bind, ":")
246                 port, err := strconv.Atoi(cols[len(cols)-1])
247                 if err != nil {
248                         log.Fatalln("Can not parse port:", err)
249                 }
250
251                 if *mcdOnce {
252                         if err = startMCDTx(ctx, port, true); err != nil {
253                                 log.Fatalln("Can not do MCD transmission:", err)
254                         }
255                         return
256                 }
257
258                 ln, err := net.Listen("tcp", *bind)
259                 if err != nil {
260                         log.Fatalln("Can not listen:", err)
261                 }
262                 if err = startMCDTx(ctx, port, false); err != nil {
263                         log.Fatalln("Can not do MCD transmission:", err)
264                 }
265                 ln = netutil.LimitListener(ln, *maxConn)
266                 go func() {
267                         for {
268                                 conn, err := ln.Accept()
269                                 if err != nil {
270                                         log.Fatalln("Can not accept connection on TCP:", err)
271                                 }
272                                 conns <- conn
273                         }
274                 }()
275         }
276
277         if *yggdrasil != "" {
278                 ln, err := nncpYggdrasil.NewListener(ctx.YggdrasilAliases, *yggdrasil)
279                 if err != nil {
280                         log.Fatalln("Can not listen:", err)
281                 }
282                 ln = netutil.LimitListener(ln, *maxConn)
283                 go func() {
284                         for {
285                                 conn, err := ln.Accept()
286                                 if err != nil {
287                                         log.Fatalln("Can not accept connection on Yggdrasil:", err)
288                                 }
289                                 conns <- conn
290                         }
291                 }()
292         }
293
294         for conn := range conns {
295                 ctx.LogD(
296                         "daemon-accepted",
297                         nncp.LEs{{K: "Addr", V: conn.RemoteAddr()}},
298                         func(les nncp.LEs) string {
299                                 return "Accepted connection with " + conn.RemoteAddr().String()
300                         },
301                 )
302                 go func(conn net.Conn) {
303                         nodeIdC := make(chan *nncp.NodeId)
304                         go performSP(ctx, conn, conn.RemoteAddr().String(), nice, *noCK, nodeIdC)
305                         nodeId := <-nodeIdC
306                         var autoTossFinish chan struct{}
307                         var autoTossBadCode chan bool
308                         if *autoToss && nodeId != nil {
309                                 autoTossFinish, autoTossBadCode = ctx.AutoToss(
310                                         nodeId,
311                                         &nncp.TossOpts{
312                                                 Nice:   nice,
313                                                 DoSeen: *autoTossDoSeen,
314                                                 NoFile: *autoTossNoFile,
315                                                 NoFreq: *autoTossNoFreq,
316                                                 NoExec: *autoTossNoExec,
317                                                 NoTrns: *autoTossNoTrns,
318                                                 NoArea: *autoTossNoArea,
319                                                 NoACK:  *autoTossNoACK,
320                                         },
321                                 )
322                         }
323                         <-nodeIdC // call completion
324                         if *autoToss && nodeId != nil {
325                                 close(autoTossFinish)
326                                 <-autoTossBadCode
327                         }
328                         conn.Close()
329                 }(conn)
330
331         }
332 }