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