]> Cypherpunks.ru repositories - nncp.git/blobdiff - src/cmd/nncp-daemon/main.go
MCD uses regexp instead of exact interface name
[nncp.git] / src / cmd / nncp-daemon / main.go
index 2e55cd654ef23ce88b9d904271a9c8e6c37c4776..5fd6f6d0353f5cc0e7e5e5212234e9bd4def05ea 100644 (file)
@@ -1,6 +1,6 @@
 /*
 NNCP -- Node to Node copy, utilities for store-and-forward data exchange
-Copyright (C) 2016-2019 Sergey Matveev <stargrave@stargrave.org>
+Copyright (C) 2016-2022 Sergey Matveev <stargrave@stargrave.org>
 
 This program is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
@@ -24,10 +24,14 @@ import (
        "log"
        "net"
        "os"
+       "regexp"
        "strconv"
+       "strings"
        "time"
 
-       "go.cypherpunks.ru/nncp/v4"
+       "github.com/dustin/go-humanize"
+       "go.cypherpunks.ru/nncp/v8"
+       nncpYggdrasil "go.cypherpunks.ru/nncp/v8/yggdrasil"
        "golang.org/x/net/netutil"
 )
 
@@ -38,50 +42,93 @@ func usage() {
        flag.PrintDefaults()
 }
 
-type InetdConn struct {
-       r *os.File
-       w *os.File
-}
-
-func (ic *InetdConn) Read(p []byte) (n int, err error) {
-       return ic.r.Read(p)
-}
-
-func (ic *InetdConn) Write(p []byte) (n int, err error) {
-       return ic.w.Write(p)
-}
-
-func (ic *InetdConn) SetReadDeadline(t time.Time) error {
-       return ic.r.SetReadDeadline(t)
-}
-
-func (ic *InetdConn) SetWriteDeadline(t time.Time) error {
-       return ic.w.SetWriteDeadline(t)
-}
-
-func performSP(ctx *nncp.Ctx, conn nncp.ConnDeadlined, nice uint8) {
+func performSP(
+       ctx *nncp.Ctx,
+       conn nncp.ConnDeadlined,
+       addr string,
+       nice uint8,
+       noCK bool,
+       nodeIdC chan *nncp.NodeId,
+) {
        state := nncp.SPState{
                Ctx:  ctx,
                Nice: nice,
+               NoCK: noCK,
        }
        if err := state.StartR(conn); err == nil {
-               ctx.LogI("call-start", nncp.SDS{"node": state.Node.Id}, "connected")
+               ctx.LogI(
+                       "call-started",
+                       nncp.LEs{{K: "Node", V: state.Node.Id}},
+                       func(les nncp.LEs) string {
+                               return fmt.Sprintf("Connection with %s (%s)", state.Node.Name, addr)
+                       },
+               )
+               nodeIdC <- state.Node.Id
                state.Wait()
-               ctx.LogI("call-finish", nncp.SDS{
-                       "node":     state.Node.Id,
-                       "duration": strconv.FormatInt(int64(state.Duration.Seconds()), 10),
-                       "rxbytes":  strconv.FormatInt(state.RxBytes, 10),
-                       "txbytes":  strconv.FormatInt(state.TxBytes, 10),
-                       "rxspeed":  strconv.FormatInt(state.RxSpeed, 10),
-                       "txspeed":  strconv.FormatInt(state.TxSpeed, 10),
-               }, "")
+               ctx.LogI("call-finished", nncp.LEs{
+                       {K: "Node", V: state.Node.Id},
+                       {K: "Duration", V: int64(state.Duration.Seconds())},
+                       {K: "RxBytes", V: state.RxBytes},
+                       {K: "TxBytes", V: state.TxBytes},
+                       {K: "RxSpeed", V: state.RxSpeed},
+                       {K: "TxSpeed", V: state.TxSpeed},
+               }, func(les nncp.LEs) string {
+                       return fmt.Sprintf(
+                               "Finished call with %s (%d:%d:%d): %s received (%s/sec), %s transferred (%s/sec)",
+                               state.Node.Name,
+                               int(state.Duration.Hours()),
+                               int(state.Duration.Minutes()),
+                               int(state.Duration.Seconds())%60,
+                               humanize.IBytes(uint64(state.RxBytes)),
+                               humanize.IBytes(uint64(state.RxSpeed)),
+                               humanize.IBytes(uint64(state.TxBytes)),
+                               humanize.IBytes(uint64(state.TxSpeed)),
+                       )
+               })
        } else {
-               nodeId := "unknown"
-               if state.Node != nil {
+               var nodeId string
+               var nodeName string
+               if state.Node == nil {
+                       nodeId = "unknown"
+                       nodeName = "unknown"
+                       nodeIdC <- nil
+               } else {
                        nodeId = state.Node.Id.String()
+                       nodeName = state.Node.Name
+                       nodeIdC <- state.Node.Id
                }
-               ctx.LogE("call-start", nncp.SDS{"node": nodeId, "err": err}, "")
+               ctx.LogI(
+                       "call-started",
+                       nncp.LEs{{K: "Node", V: nodeId}},
+                       func(les nncp.LEs) string { return "Connected to " + nodeName },
+               )
        }
+       close(nodeIdC)
+}
+
+func startMCDTx(ctx *nncp.Ctx, port int, zeroInterval bool) error {
+       ifis, err := net.Interfaces()
+       if err != nil {
+               return err
+       }
+       for ifiReString, secs := range ctx.MCDTxIfis {
+               ifiRe, err := regexp.CompilePOSIX(ifiReString)
+               if err != nil {
+                       return err
+               }
+               var interval time.Duration
+               if !zeroInterval {
+                       interval = time.Duration(secs) * time.Second
+               }
+               for _, ifi := range ifis {
+                       if ifiRe.MatchString(ifi.Name) {
+                               if err = ctx.MCDTx(ifi.Name, port, interval); err != nil {
+                                       return err
+                               }
+                       }
+               }
+       }
+       return nil
 }
 
 func main() {
@@ -89,15 +136,30 @@ func main() {
                cfgPath   = flag.String("cfg", nncp.DefaultCfgPath, "Path to configuration file")
                niceRaw   = flag.String("nice", nncp.NicenessFmt(255), "Minimal required niceness")
                bind      = flag.String("bind", "[::]:5400", "Address to bind to")
-               inetd     = flag.Bool("inetd", false, "Is it started as inetd service")
+               ucspi     = flag.Bool("ucspi", false, "Is it started as UCSPI-TCP server")
+               inetd     = flag.Bool("inetd", false, "Obsolete, use -ucspi")
+               yggdrasil = flag.String("yggdrasil", "", "Start Yggdrasil listener: yggdrasils://PRV[:PORT]?[bind=BIND][&pub=PUB][&peer=PEER][&mcast=REGEX[:PORT]]")
                maxConn   = flag.Int("maxconn", 128, "Maximal number of simultaneous connections")
+               noCK      = flag.Bool("nock", false, "Do no checksum checking")
+               mcdOnce   = flag.Bool("mcd-once", false, "Send MCDs once and quit")
                spoolPath = flag.String("spool", "", "Override path to spool")
                logPath   = flag.String("log", "", "Override path to logfile")
                quiet     = flag.Bool("quiet", false, "Print only errors")
+               showPrgrs = flag.Bool("progress", false, "Force progress showing")
+               omitPrgrs = flag.Bool("noprogress", false, "Omit progress showing")
                debug     = flag.Bool("debug", false, "Print debug messages")
                version   = flag.Bool("version", false, "Print version information")
                warranty  = flag.Bool("warranty", false, "Print warranty information")
+
+               autoToss       = flag.Bool("autotoss", false, "Toss after call is finished")
+               autoTossDoSeen = flag.Bool("autotoss-seen", false, "Create seen/ files during tossing")
+               autoTossNoFile = flag.Bool("autotoss-nofile", false, "Do not process \"file\" packets during tossing")
+               autoTossNoFreq = flag.Bool("autotoss-nofreq", false, "Do not process \"freq\" packets during tossing")
+               autoTossNoExec = flag.Bool("autotoss-noexec", false, "Do not process \"exec\" packets during tossing")
+               autoTossNoTrns = flag.Bool("autotoss-notrns", false, "Do not process \"trns\" packets during tossing")
+               autoTossNoArea = flag.Bool("autotoss-noarea", false, "Do not process \"area\" packets during tossing")
        )
+       log.SetFlags(log.Lshortfile)
        flag.Usage = usage
        flag.Parse()
        if *warranty {
@@ -112,36 +174,144 @@ func main() {
        if err != nil {
                log.Fatalln(err)
        }
+       if *inetd {
+               *ucspi = true
+       }
 
-       ctx, err := nncp.CtxFromCmdline(*cfgPath, *spoolPath, *logPath, *quiet, *debug)
+       ctx, err := nncp.CtxFromCmdline(
+               *cfgPath,
+               *spoolPath,
+               *logPath,
+               *quiet,
+               *showPrgrs,
+               *omitPrgrs,
+               *debug,
+       )
        if err != nil {
                log.Fatalln("Error during initialization:", err)
        }
        if ctx.Self == nil {
                log.Fatalln("Config lacks private keys")
        }
+       ctx.Umask()
 
-       if *inetd {
+       if *ucspi {
                os.Stderr.Close()
-               conn := &InetdConn{os.Stdin, os.Stdout}
-               performSP(ctx, conn, nice)
+               conn := &nncp.UCSPIConn{R: os.Stdin, W: os.Stdout}
+               nodeIdC := make(chan *nncp.NodeId)
+               addr := nncp.UCSPITCPRemoteAddr()
+               if addr == "" {
+                       addr = "PIPE"
+               }
+               go performSP(ctx, conn, addr, nice, *noCK, nodeIdC)
+               nodeId := <-nodeIdC
+               var autoTossFinish chan struct{}
+               var autoTossBadCode chan bool
+               if *autoToss && nodeId != nil {
+                       autoTossFinish, autoTossBadCode = ctx.AutoToss(
+                               nodeId,
+                               nice,
+                               *autoTossDoSeen,
+                               *autoTossNoFile,
+                               *autoTossNoFreq,
+                               *autoTossNoExec,
+                               *autoTossNoTrns,
+                               *autoTossNoArea,
+                       )
+               }
+               <-nodeIdC // call completion
+               if *autoToss {
+                       close(autoTossFinish)
+                       <-autoTossBadCode
+               }
+               conn.Close()
                return
        }
 
-       ln, err := net.Listen("tcp", *bind)
-       if err != nil {
-               log.Fatalln("Can not listen:", err)
+       conns := make(chan net.Conn)
+       if *bind != "" {
+               cols := strings.Split(*bind, ":")
+               port, err := strconv.Atoi(cols[len(cols)-1])
+               if err != nil {
+                       log.Fatalln("Can not parse port:", err)
+               }
+
+               if *mcdOnce {
+                       if err = startMCDTx(ctx, port, true); err != nil {
+                               log.Fatalln("Can not do MCD transmission:", err)
+                       }
+                       return
+               }
+
+               ln, err := net.Listen("tcp", *bind)
+               if err != nil {
+                       log.Fatalln("Can not listen:", err)
+               }
+               if err = startMCDTx(ctx, port, false); err != nil {
+                       log.Fatalln("Can not do MCD transmission:", err)
+               }
+               ln = netutil.LimitListener(ln, *maxConn)
+               go func() {
+                       for {
+                               conn, err := ln.Accept()
+                               if err != nil {
+                                       log.Fatalln("Can not accept connection on TCP:", err)
+                               }
+                               conns <- conn
+                       }
+               }()
        }
-       ln = netutil.LimitListener(ln, *maxConn)
-       for {
-               conn, err := ln.Accept()
+
+       if *yggdrasil != "" {
+               ln, err := nncpYggdrasil.NewListener(ctx.YggdrasilAliases, *yggdrasil)
                if err != nil {
-                       log.Fatalln("Can not accept connection:", err)
+                       log.Fatalln("Can not listen:", err)
                }
-               ctx.LogD("daemon", nncp.SDS{"addr": conn.RemoteAddr()}, "accepted")
+               ln = netutil.LimitListener(ln, *maxConn)
+               go func() {
+                       for {
+                               conn, err := ln.Accept()
+                               if err != nil {
+                                       log.Fatalln("Can not accept connection on Yggdrasil:", err)
+                               }
+                               conns <- conn
+                       }
+               }()
+       }
+
+       for conn := range conns {
+               ctx.LogD(
+                       "daemon-accepted",
+                       nncp.LEs{{K: "Addr", V: conn.RemoteAddr()}},
+                       func(les nncp.LEs) string {
+                               return "Accepted connection with " + conn.RemoteAddr().String()
+                       },
+               )
                go func(conn net.Conn) {
-                       performSP(ctx, conn, nice)
+                       nodeIdC := make(chan *nncp.NodeId)
+                       go performSP(ctx, conn, conn.RemoteAddr().String(), nice, *noCK, nodeIdC)
+                       nodeId := <-nodeIdC
+                       var autoTossFinish chan struct{}
+                       var autoTossBadCode chan bool
+                       if *autoToss && nodeId != nil {
+                               autoTossFinish, autoTossBadCode = ctx.AutoToss(
+                                       nodeId,
+                                       nice,
+                                       *autoTossDoSeen,
+                                       *autoTossNoFile,
+                                       *autoTossNoFreq,
+                                       *autoTossNoExec,
+                                       *autoTossNoTrns,
+                                       *autoTossNoArea,
+                               )
+                       }
+                       <-nodeIdC // call completion
+                       if *autoToss {
+                               close(autoTossFinish)
+                               <-autoTossBadCode
+                       }
                        conn.Close()
                }(conn)
+
        }
 }