]> Cypherpunks.ru repositories - nncp.git/blob - src/cmd/nncp-daemon/main.go
MCD uses regexp instead of exact interface name
[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         "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.Fprintf(os.Stderr, nncp.UsageHeader())
40         fmt.Fprintf(os.Stderr, "nncp-daemon -- TCP daemon\n\n")
41         fmt.Fprintf(os.Stderr, "Usage: %s [options]\nOptions:\n", os.Args[0])
42         flag.PrintDefaults()
43 }
44
45 func performSP(
46         ctx *nncp.Ctx,
47         conn nncp.ConnDeadlined,
48         addr string,
49         nice uint8,
50         noCK bool,
51         nodeIdC chan *nncp.NodeId,
52 ) {
53         state := nncp.SPState{
54                 Ctx:  ctx,
55                 Nice: nice,
56                 NoCK: noCK,
57         }
58         if err := state.StartR(conn); err == nil {
59                 ctx.LogI(
60                         "call-started",
61                         nncp.LEs{{K: "Node", V: state.Node.Id}},
62                         func(les nncp.LEs) string {
63                                 return fmt.Sprintf("Connection with %s (%s)", state.Node.Name, addr)
64                         },
65                 )
66                 nodeIdC <- state.Node.Id
67                 state.Wait()
68                 ctx.LogI("call-finished", nncp.LEs{
69                         {K: "Node", V: state.Node.Id},
70                         {K: "Duration", V: int64(state.Duration.Seconds())},
71                         {K: "RxBytes", V: state.RxBytes},
72                         {K: "TxBytes", V: state.TxBytes},
73                         {K: "RxSpeed", V: state.RxSpeed},
74                         {K: "TxSpeed", V: state.TxSpeed},
75                 }, func(les nncp.LEs) string {
76                         return fmt.Sprintf(
77                                 "Finished call with %s (%d:%d:%d): %s received (%s/sec), %s transferred (%s/sec)",
78                                 state.Node.Name,
79                                 int(state.Duration.Hours()),
80                                 int(state.Duration.Minutes()),
81                                 int(state.Duration.Seconds())%60,
82                                 humanize.IBytes(uint64(state.RxBytes)),
83                                 humanize.IBytes(uint64(state.RxSpeed)),
84                                 humanize.IBytes(uint64(state.TxBytes)),
85                                 humanize.IBytes(uint64(state.TxSpeed)),
86                         )
87                 })
88         } else {
89                 var nodeId string
90                 var nodeName string
91                 if state.Node == nil {
92                         nodeId = "unknown"
93                         nodeName = "unknown"
94                         nodeIdC <- nil
95                 } else {
96                         nodeId = state.Node.Id.String()
97                         nodeName = state.Node.Name
98                         nodeIdC <- state.Node.Id
99                 }
100                 ctx.LogI(
101                         "call-started",
102                         nncp.LEs{{K: "Node", V: nodeId}},
103                         func(les nncp.LEs) string { return "Connected to " + nodeName },
104                 )
105         }
106         close(nodeIdC)
107 }
108
109 func startMCDTx(ctx *nncp.Ctx, port int, zeroInterval bool) error {
110         ifis, err := net.Interfaces()
111         if err != nil {
112                 return err
113         }
114         for ifiReString, secs := range ctx.MCDTxIfis {
115                 ifiRe, err := regexp.CompilePOSIX(ifiReString)
116                 if err != nil {
117                         return err
118                 }
119                 var interval time.Duration
120                 if !zeroInterval {
121                         interval = time.Duration(secs) * time.Second
122                 }
123                 for _, ifi := range ifis {
124                         if ifiRe.MatchString(ifi.Name) {
125                                 if err = ctx.MCDTx(ifi.Name, port, interval); err != nil {
126                                         return err
127                                 }
128                         }
129                 }
130         }
131         return nil
132 }
133
134 func main() {
135         var (
136                 cfgPath   = flag.String("cfg", nncp.DefaultCfgPath, "Path to configuration file")
137                 niceRaw   = flag.String("nice", nncp.NicenessFmt(255), "Minimal required niceness")
138                 bind      = flag.String("bind", "[::]:5400", "Address to bind to")
139                 ucspi     = flag.Bool("ucspi", false, "Is it started as UCSPI-TCP server")
140                 inetd     = flag.Bool("inetd", false, "Obsolete, use -ucspi")
141                 yggdrasil = flag.String("yggdrasil", "", "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, "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                 autoTossNoArea = flag.Bool("autotoss-noarea", false, "Do not process \"area\" packets during tossing")
161         )
162         log.SetFlags(log.Lshortfile)
163         flag.Usage = usage
164         flag.Parse()
165         if *warranty {
166                 fmt.Println(nncp.Warranty)
167                 return
168         }
169         if *version {
170                 fmt.Println(nncp.VersionGet())
171                 return
172         }
173         nice, err := nncp.NicenessParse(*niceRaw)
174         if err != nil {
175                 log.Fatalln(err)
176         }
177         if *inetd {
178                 *ucspi = true
179         }
180
181         ctx, err := nncp.CtxFromCmdline(
182                 *cfgPath,
183                 *spoolPath,
184                 *logPath,
185                 *quiet,
186                 *showPrgrs,
187                 *omitPrgrs,
188                 *debug,
189         )
190         if err != nil {
191                 log.Fatalln("Error during initialization:", err)
192         }
193         if ctx.Self == nil {
194                 log.Fatalln("Config lacks private keys")
195         }
196         ctx.Umask()
197
198         if *ucspi {
199                 os.Stderr.Close()
200                 conn := &nncp.UCSPIConn{R: os.Stdin, W: os.Stdout}
201                 nodeIdC := make(chan *nncp.NodeId)
202                 addr := nncp.UCSPITCPRemoteAddr()
203                 if addr == "" {
204                         addr = "PIPE"
205                 }
206                 go performSP(ctx, conn, addr, nice, *noCK, nodeIdC)
207                 nodeId := <-nodeIdC
208                 var autoTossFinish chan struct{}
209                 var autoTossBadCode chan bool
210                 if *autoToss && nodeId != nil {
211                         autoTossFinish, autoTossBadCode = ctx.AutoToss(
212                                 nodeId,
213                                 nice,
214                                 *autoTossDoSeen,
215                                 *autoTossNoFile,
216                                 *autoTossNoFreq,
217                                 *autoTossNoExec,
218                                 *autoTossNoTrns,
219                                 *autoTossNoArea,
220                         )
221                 }
222                 <-nodeIdC // call completion
223                 if *autoToss {
224                         close(autoTossFinish)
225                         <-autoTossBadCode
226                 }
227                 conn.Close()
228                 return
229         }
230
231         conns := make(chan net.Conn)
232         if *bind != "" {
233                 cols := strings.Split(*bind, ":")
234                 port, err := strconv.Atoi(cols[len(cols)-1])
235                 if err != nil {
236                         log.Fatalln("Can not parse port:", err)
237                 }
238
239                 if *mcdOnce {
240                         if err = startMCDTx(ctx, port, true); err != nil {
241                                 log.Fatalln("Can not do MCD transmission:", err)
242                         }
243                         return
244                 }
245
246                 ln, err := net.Listen("tcp", *bind)
247                 if err != nil {
248                         log.Fatalln("Can not listen:", err)
249                 }
250                 if err = startMCDTx(ctx, port, false); err != nil {
251                         log.Fatalln("Can not do MCD transmission:", err)
252                 }
253                 ln = netutil.LimitListener(ln, *maxConn)
254                 go func() {
255                         for {
256                                 conn, err := ln.Accept()
257                                 if err != nil {
258                                         log.Fatalln("Can not accept connection on TCP:", err)
259                                 }
260                                 conns <- conn
261                         }
262                 }()
263         }
264
265         if *yggdrasil != "" {
266                 ln, err := nncpYggdrasil.NewListener(ctx.YggdrasilAliases, *yggdrasil)
267                 if err != nil {
268                         log.Fatalln("Can not listen:", err)
269                 }
270                 ln = netutil.LimitListener(ln, *maxConn)
271                 go func() {
272                         for {
273                                 conn, err := ln.Accept()
274                                 if err != nil {
275                                         log.Fatalln("Can not accept connection on Yggdrasil:", err)
276                                 }
277                                 conns <- conn
278                         }
279                 }()
280         }
281
282         for conn := range conns {
283                 ctx.LogD(
284                         "daemon-accepted",
285                         nncp.LEs{{K: "Addr", V: conn.RemoteAddr()}},
286                         func(les nncp.LEs) string {
287                                 return "Accepted connection with " + conn.RemoteAddr().String()
288                         },
289                 )
290                 go func(conn net.Conn) {
291                         nodeIdC := make(chan *nncp.NodeId)
292                         go performSP(ctx, conn, conn.RemoteAddr().String(), nice, *noCK, nodeIdC)
293                         nodeId := <-nodeIdC
294                         var autoTossFinish chan struct{}
295                         var autoTossBadCode chan bool
296                         if *autoToss && nodeId != nil {
297                                 autoTossFinish, autoTossBadCode = ctx.AutoToss(
298                                         nodeId,
299                                         nice,
300                                         *autoTossDoSeen,
301                                         *autoTossNoFile,
302                                         *autoTossNoFreq,
303                                         *autoTossNoExec,
304                                         *autoTossNoTrns,
305                                         *autoTossNoArea,
306                                 )
307                         }
308                         <-nodeIdC // call completion
309                         if *autoToss {
310                                 close(autoTossFinish)
311                                 <-autoTossBadCode
312                         }
313                         conn.Close()
314                 }(conn)
315
316         }
317 }