]> Cypherpunks.ru repositories - nncp.git/blob - src/cmd/nncp-daemon/main.go
2503ab228def05e48d471d302342bf467ada5534
[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/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                 maxConn   = flag.Int("maxconn", 128, "Maximal number of simultaneous connections")
115                 noCK      = flag.Bool("nock", false, "Do no checksum checking")
116                 mcdOnce   = flag.Bool("mcd-once", false, "Send MCDs once and quit")
117                 spoolPath = flag.String("spool", "", "Override path to spool")
118                 logPath   = flag.String("log", "", "Override path to logfile")
119                 quiet     = flag.Bool("quiet", false, "Print only errors")
120                 showPrgrs = flag.Bool("progress", false, "Force progress showing")
121                 omitPrgrs = flag.Bool("noprogress", false, "Omit progress showing")
122                 debug     = flag.Bool("debug", false, "Print debug messages")
123                 version   = flag.Bool("version", false, "Print version information")
124                 warranty  = flag.Bool("warranty", false, "Print warranty information")
125
126                 autoToss       = flag.Bool("autotoss", false, "Toss after call is finished")
127                 autoTossDoSeen = flag.Bool("autotoss-seen", false, "Create seen/ files during tossing")
128                 autoTossNoFile = flag.Bool("autotoss-nofile", false, "Do not process \"file\" packets during tossing")
129                 autoTossNoFreq = flag.Bool("autotoss-nofreq", false, "Do not process \"freq\" packets during tossing")
130                 autoTossNoExec = flag.Bool("autotoss-noexec", false, "Do not process \"exec\" packets during tossing")
131                 autoTossNoTrns = flag.Bool("autotoss-notrns", false, "Do not process \"trns\" packets during tossing")
132                 autoTossNoArea = flag.Bool("autotoss-noarea", false, "Do not process \"area\" packets during tossing")
133         )
134         log.SetFlags(log.Lshortfile)
135         flag.Usage = usage
136         flag.Parse()
137         if *warranty {
138                 fmt.Println(nncp.Warranty)
139                 return
140         }
141         if *version {
142                 fmt.Println(nncp.VersionGet())
143                 return
144         }
145         nice, err := nncp.NicenessParse(*niceRaw)
146         if err != nil {
147                 log.Fatalln(err)
148         }
149         if *inetd {
150                 *ucspi = true
151         }
152
153         ctx, err := nncp.CtxFromCmdline(
154                 *cfgPath,
155                 *spoolPath,
156                 *logPath,
157                 *quiet,
158                 *showPrgrs,
159                 *omitPrgrs,
160                 *debug,
161         )
162         if err != nil {
163                 log.Fatalln("Error during initialization:", err)
164         }
165         if ctx.Self == nil {
166                 log.Fatalln("Config lacks private keys")
167         }
168         ctx.Umask()
169
170         if *ucspi {
171                 os.Stderr.Close()
172                 conn := &nncp.UCSPIConn{R: os.Stdin, W: os.Stdout}
173                 nodeIdC := make(chan *nncp.NodeId)
174                 addr := nncp.UCSPITCPRemoteAddr()
175                 if addr == "" {
176                         addr = "PIPE"
177                 }
178                 go performSP(ctx, conn, addr, nice, *noCK, nodeIdC)
179                 nodeId := <-nodeIdC
180                 var autoTossFinish chan struct{}
181                 var autoTossBadCode chan bool
182                 if *autoToss && nodeId != nil {
183                         autoTossFinish, autoTossBadCode = ctx.AutoToss(
184                                 nodeId,
185                                 nice,
186                                 *autoTossDoSeen,
187                                 *autoTossNoFile,
188                                 *autoTossNoFreq,
189                                 *autoTossNoExec,
190                                 *autoTossNoTrns,
191                                 *autoTossNoArea,
192                         )
193                 }
194                 <-nodeIdC // call completion
195                 if *autoToss {
196                         close(autoTossFinish)
197                         <-autoTossBadCode
198                 }
199                 conn.Close()
200                 return
201         }
202
203         cols := strings.Split(*bind, ":")
204         port, err := strconv.Atoi(cols[len(cols)-1])
205         if err != nil {
206                 log.Fatalln("Can not parse port:", err)
207         }
208
209         if *mcdOnce {
210                 for ifiName := range ctx.MCDTxIfis {
211                         if err = ctx.MCDTx(ifiName, port, 0); err != nil {
212                                 log.Fatalln("Can not do MCD transmission:", err)
213                         }
214                 }
215                 return
216         }
217
218         ln, err := net.Listen("tcp", *bind)
219         if err != nil {
220                 log.Fatalln("Can not listen:", err)
221         }
222
223         for ifiName, secs := range ctx.MCDTxIfis {
224                 if err = ctx.MCDTx(ifiName, port, time.Duration(secs)*time.Second); err != nil {
225                         log.Fatalln("Can not run MCD transmission:", err)
226                 }
227         }
228
229         ln = netutil.LimitListener(ln, *maxConn)
230         for {
231                 conn, err := ln.Accept()
232                 if err != nil {
233                         log.Fatalln("Can not accept connection:", err)
234                 }
235                 ctx.LogD(
236                         "daemon-accepted",
237                         nncp.LEs{{K: "Addr", V: conn.RemoteAddr()}},
238                         func(les nncp.LEs) string {
239                                 return "Accepted connection with " + conn.RemoteAddr().String()
240                         },
241                 )
242                 go func(conn net.Conn) {
243                         nodeIdC := make(chan *nncp.NodeId)
244                         go performSP(ctx, conn, conn.RemoteAddr().String(), nice, *noCK, nodeIdC)
245                         nodeId := <-nodeIdC
246                         var autoTossFinish chan struct{}
247                         var autoTossBadCode chan bool
248                         if *autoToss && nodeId != nil {
249                                 autoTossFinish, autoTossBadCode = ctx.AutoToss(
250                                         nodeId,
251                                         nice,
252                                         *autoTossDoSeen,
253                                         *autoTossNoFile,
254                                         *autoTossNoFreq,
255                                         *autoTossNoExec,
256                                         *autoTossNoTrns,
257                                         *autoTossNoArea,
258                                 )
259                         }
260                         <-nodeIdC // call completion
261                         if *autoToss {
262                                 close(autoTossFinish)
263                                 <-autoTossBadCode
264                         }
265                         conn.Close()
266                 }(conn)
267         }
268 }