2 NNCP -- Node to Node copy, utilities for store-and-forward data exchange
3 Copyright (C) 2016-2021 Sergey Matveev <stargrave@stargrave.org>
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.
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.
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/>.
33 xdr "github.com/davecgh/go-xdr/xdr2"
34 "github.com/dustin/go-humanize"
35 "github.com/flynn/noise"
36 "golang.org/x/crypto/blake2b"
40 MaxSPSize = 1<<16 - 256
45 type SPCheckerQueues struct {
46 appeared chan *[32]byte
47 checked chan *[32]byte
51 MagicNNCPLv1 [8]byte = [8]byte{'N', 'N', 'C', 'P', 'S', 0, 0, 1}
56 SPHaltMarshalized []byte
57 SPPingMarshalized []byte
59 NoiseCipherSuite noise.CipherSuite = noise.NewCipherSuite(
61 noise.CipherChaChaPoly,
65 DefaultDeadline = 10 * time.Second
66 PingTimeout = time.Minute
68 spCheckers = make(map[NodeId]*SPCheckerQueues)
71 type FdAndFullSize struct {
76 type HasherAndOffset struct {
84 SPTypeInfo SPType = iota
85 SPTypeFreq SPType = iota
86 SPTypeFile SPType = iota
87 SPTypeDone SPType = iota
88 SPTypeHalt SPType = iota
89 SPTypePing SPType = iota
122 type FreqWithNice struct {
127 type ConnDeadlined interface {
129 SetReadDeadline(t time.Time) error
130 SetWriteDeadline(t time.Time) error
135 spHead := SPHead{Type: SPTypeHalt}
136 if _, err := xdr.Marshal(&buf, spHead); err != nil {
139 SPHaltMarshalized = make([]byte, SPHeadOverhead)
140 copy(SPHaltMarshalized, buf.Bytes())
143 spHead = SPHead{Type: SPTypePing}
144 if _, err := xdr.Marshal(&buf, spHead); err != nil {
147 SPPingMarshalized = make([]byte, SPHeadOverhead)
148 copy(SPPingMarshalized, buf.Bytes())
151 spInfo := SPInfo{Nice: 123, Size: 123, Hash: new([32]byte)}
152 if _, err := xdr.Marshal(&buf, spInfo); err != nil {
155 SPInfoOverhead = buf.Len()
158 spFreq := SPFreq{Hash: new([32]byte), Offset: 123}
159 if _, err := xdr.Marshal(&buf, spFreq); err != nil {
162 SPFreqOverhead = buf.Len()
165 spFile := SPFile{Hash: new([32]byte), Offset: 123}
166 if _, err := xdr.Marshal(&buf, spFile); err != nil {
169 SPFileOverhead = buf.Len()
172 func MarshalSP(typ SPType, sp interface{}) []byte {
174 if _, err := xdr.Marshal(&buf, SPHead{typ}); err != nil {
177 if _, err := xdr.Marshal(&buf, sp); err != nil {
183 func payloadsSplit(payloads [][]byte) [][]byte {
184 var outbounds [][]byte
185 outbound := make([]byte, 0, MaxSPSize)
186 for i, payload := range payloads {
187 outbound = append(outbound, payload...)
188 if i+1 < len(payloads) && len(outbound)+len(payloads[i+1]) > MaxSPSize {
189 outbounds = append(outbounds, outbound)
190 outbound = make([]byte, 0, MaxSPSize)
193 if len(outbound) > 0 {
194 outbounds = append(outbounds, outbound)
199 type SPState struct {
204 onlineDeadline time.Duration
205 maxOnlineTime time.Duration
206 hs *noise.HandshakeState
207 csOur *noise.CipherState
208 csTheir *noise.CipherState
211 infosTheir map[[32]byte]*SPInfo
212 infosOurSeen map[[32]byte]uint8
213 queueTheir []*FreqWithNice
217 RxLastNonPing time.Time
220 TxLastNonPing time.Time
222 mustFinishAt time.Time
223 Duration time.Duration
233 onlyPkts map[[32]byte]bool
234 writeSPBuf bytes.Buffer
235 fds map[string]FdAndFullSize
236 fileHashers map[string]*HasherAndOffset
237 checkerQueues SPCheckerQueues
241 func (state *SPState) SetDead() {
246 // Already closed channel, dead
252 for range state.payloads {
256 for range state.pings {
260 for _, s := range state.fds {
266 func (state *SPState) NotAlive() bool {
275 func (state *SPState) dirUnlock() {
276 state.Ctx.UnlockDir(state.rxLock)
277 state.Ctx.UnlockDir(state.txLock)
280 func SPChecker(ctx *Ctx, nodeId *NodeId, appeared, checked chan *[32]byte) {
281 for hshValue := range appeared {
282 pktName := Base32Codec.EncodeToString(hshValue[:])
288 ctx.LogD("sp-checker", les, func(les LEs) string {
289 return fmt.Sprintf("Checksumming %s/rx/%s", ctx.NodeName(nodeId), pktName)
291 size, err := ctx.CheckNoCK(nodeId, hshValue)
292 les = append(les, LE{"Size", size})
294 ctx.LogE("sp-checker", les, err, func(les LEs) string {
296 "Checksumming %s/rx/%s (%s)", ctx.NodeName(nodeId), pktName,
297 humanize.IBytes(uint64(size)),
302 ctx.LogI("sp-checker-done", les, func(les LEs) string {
304 "Packet %s is retreived (%s)",
305 pktName, humanize.IBytes(uint64(size)),
308 go func(hsh *[32]byte) { checked <- hsh }(hshValue)
312 func (state *SPState) WriteSP(dst io.Writer, payload []byte, ping bool) error {
313 state.writeSPBuf.Reset()
314 n, err := xdr.Marshal(&state.writeSPBuf, SPRaw{
321 if n, err = dst.Write(state.writeSPBuf.Bytes()); err == nil {
322 state.TxLastSeen = time.Now()
323 state.TxBytes += int64(n)
325 state.TxLastNonPing = state.TxLastSeen
331 func (state *SPState) ReadSP(src io.Reader) ([]byte, error) {
333 n, err := xdr.UnmarshalLimited(src, &sp, 1<<17)
335 ue := err.(*xdr.UnmarshalError)
336 if ue.Err == io.EOF {
341 state.RxLastSeen = time.Now()
342 state.RxBytes += int64(n)
343 if sp.Magic != MagicNNCPLv1 {
346 return sp.Payload, nil
349 func (ctx *Ctx) infosOur(nodeId *NodeId, nice uint8, seen *map[[32]byte]uint8) [][]byte {
352 for job := range ctx.Jobs(nodeId, TTx) {
353 if job.PktEnc.Nice > nice {
356 if _, known := (*seen)[*job.HshValue]; known {
359 totalSize += job.Size
360 infos = append(infos, &SPInfo{
361 Nice: job.PktEnc.Nice,
362 Size: uint64(job.Size),
365 (*seen)[*job.HshValue] = job.PktEnc.Nice
367 sort.Sort(ByNice(infos))
368 var payloads [][]byte
369 for _, info := range infos {
370 payloads = append(payloads, MarshalSP(SPTypeInfo, info))
371 pktName := Base32Codec.EncodeToString(info.Hash[:])
372 ctx.LogD("sp-info-our", LEs{
376 }, func(les LEs) string {
378 "Our info: %s/tx/%s (%s)",
379 ctx.NodeName(nodeId),
381 humanize.IBytes(info.Size),
386 ctx.LogI("sp-infos-tx", LEs{
389 {"Pkts", len(payloads)},
391 }, func(les LEs) string {
393 "We have got for %s: %d packets, %s",
394 ctx.NodeName(nodeId),
396 humanize.IBytes(uint64(totalSize)),
400 return payloadsSplit(payloads)
403 func (state *SPState) StartI(conn ConnDeadlined) error {
404 nodeId := state.Node.Id
405 err := state.Ctx.ensureRxDir(nodeId)
410 if !state.listOnly && (state.xxOnly == "" || state.xxOnly == TRx) {
411 rxLock, err = state.Ctx.LockDir(nodeId, string(TRx))
417 if !state.listOnly && (state.xxOnly == "" || state.xxOnly == TTx) {
418 txLock, err = state.Ctx.LockDir(nodeId, string(TTx))
423 started := time.Now()
424 conf := noise.Config{
425 CipherSuite: NoiseCipherSuite,
426 Pattern: noise.HandshakeIK,
428 StaticKeypair: noise.DHKey{
429 Private: state.Ctx.Self.NoisePrv[:],
430 Public: state.Ctx.Self.NoisePub[:],
432 PeerStatic: state.Node.NoisePub[:],
434 hs, err := noise.NewHandshakeState(conf)
439 state.payloads = make(chan []byte)
440 state.pings = make(chan struct{})
441 state.infosTheir = make(map[[32]byte]*SPInfo)
442 state.infosOurSeen = make(map[[32]byte]uint8)
443 state.started = started
444 state.rxLock = rxLock
445 state.txLock = txLock
447 var infosPayloads [][]byte
448 if !state.listOnly && (state.xxOnly == "" || state.xxOnly == TTx) {
449 infosPayloads = state.Ctx.infosOur(nodeId, state.Nice, &state.infosOurSeen)
451 var firstPayload []byte
452 if len(infosPayloads) > 0 {
453 firstPayload = infosPayloads[0]
455 // Pad first payload, to hide actual number of existing files
456 for i := 0; i < (MaxSPSize-len(firstPayload))/SPHeadOverhead; i++ {
457 firstPayload = append(firstPayload, SPHaltMarshalized...)
462 buf, _, _, err = state.hs.WriteMessage(nil, firstPayload)
467 les := LEs{{"Node", nodeId}, {"Nice", int(state.Nice)}}
468 state.Ctx.LogD("sp-startI", les, func(les LEs) string {
470 "SP with %s (nice %s): sending first message",
472 NicenessFmt(state.Nice),
475 conn.SetWriteDeadline(time.Now().Add(DefaultDeadline)) // #nosec G104
476 if err = state.WriteSP(conn, buf, false); err != nil {
477 state.Ctx.LogE("sp-startI", les, err, func(les LEs) string {
479 "SP with %s (nice %s): writing",
481 NicenessFmt(state.Nice),
487 state.Ctx.LogD("sp-startI-wait", les, func(les LEs) string {
489 "SP with %s (nice %s): waiting for first message",
491 NicenessFmt(state.Nice),
494 conn.SetReadDeadline(time.Now().Add(DefaultDeadline)) // #nosec G104
495 if buf, err = state.ReadSP(conn); err != nil {
496 state.Ctx.LogE("sp-startI-read", les, err, func(les LEs) string {
498 "SP with %s (nice %s): reading",
500 NicenessFmt(state.Nice),
506 payload, state.csOur, state.csTheir, err = state.hs.ReadMessage(nil, buf)
508 state.Ctx.LogE("sp-startI-read", les, err, func(les LEs) string {
510 "SP with %s (nice %s): reading Noise message",
512 NicenessFmt(state.Nice),
518 state.Ctx.LogD("sp-startI-workers", les, func(les LEs) string {
520 "SP with %s (nice %s): starting workers",
522 NicenessFmt(state.Nice),
525 err = state.StartWorkers(conn, infosPayloads, payload)
527 state.Ctx.LogE("sp-startI-workers", les, err, func(les LEs) string {
529 "SP with %s (nice %s): starting workers",
531 NicenessFmt(state.Nice),
539 func (state *SPState) StartR(conn ConnDeadlined) error {
540 started := time.Now()
541 conf := noise.Config{
542 CipherSuite: NoiseCipherSuite,
543 Pattern: noise.HandshakeIK,
545 StaticKeypair: noise.DHKey{
546 Private: state.Ctx.Self.NoisePrv[:],
547 Public: state.Ctx.Self.NoisePub[:],
550 hs, err := noise.NewHandshakeState(conf)
556 state.payloads = make(chan []byte)
557 state.pings = make(chan struct{})
558 state.infosOurSeen = make(map[[32]byte]uint8)
559 state.infosTheir = make(map[[32]byte]*SPInfo)
560 state.started = started
561 state.xxOnly = xxOnly
565 logMsg := func(les LEs) string {
567 "SP nice %s: waiting for first message",
568 NicenessFmt(state.Nice),
571 les := LEs{{"Nice", int(state.Nice)}}
572 state.Ctx.LogD("sp-startR", les, logMsg)
573 conn.SetReadDeadline(time.Now().Add(DefaultDeadline)) // #nosec G104
574 if buf, err = state.ReadSP(conn); err != nil {
575 state.Ctx.LogE("sp-startR-read", les, err, logMsg)
578 if payload, _, _, err = state.hs.ReadMessage(nil, buf); err != nil {
579 state.Ctx.LogE("sp-startR-read", les, err, logMsg)
584 for _, n := range state.Ctx.Neigh {
585 if subtle.ConstantTimeCompare(state.hs.PeerStatic(), n.NoisePub[:]) == 1 {
591 peerId := Base32Codec.EncodeToString(state.hs.PeerStatic())
592 err = errors.New("unknown peer: " + peerId)
593 state.Ctx.LogE("sp-startR-unknown", append(les, LE{"Peer", peerId}), err, logMsg)
597 state.rxRate = node.RxRate
598 state.txRate = node.TxRate
599 state.onlineDeadline = node.OnlineDeadline
600 state.maxOnlineTime = node.MaxOnlineTime
601 les = LEs{{"Node", node.Id}, {"Nice", int(state.Nice)}}
603 if err = state.Ctx.ensureRxDir(node.Id); err != nil {
607 if xxOnly == "" || xxOnly == TRx {
608 rxLock, err = state.Ctx.LockDir(node.Id, string(TRx))
613 state.rxLock = rxLock
615 if xxOnly == "" || xxOnly == TTx {
616 txLock, err = state.Ctx.LockDir(node.Id, string(TTx))
621 state.txLock = txLock
623 var infosPayloads [][]byte
624 if xxOnly == "" || xxOnly == TTx {
625 infosPayloads = state.Ctx.infosOur(node.Id, state.Nice, &state.infosOurSeen)
627 var firstPayload []byte
628 if len(infosPayloads) > 0 {
629 firstPayload = infosPayloads[0]
631 // Pad first payload, to hide actual number of existing files
632 for i := 0; i < (MaxSPSize-len(firstPayload))/SPHeadOverhead; i++ {
633 firstPayload = append(firstPayload, SPHaltMarshalized...)
636 state.Ctx.LogD("sp-startR-write", les, func(les LEs) string {
638 "SP with %s (nice %s): sending first message",
639 node.Name, NicenessFmt(state.Nice),
642 buf, state.csTheir, state.csOur, err = state.hs.WriteMessage(nil, firstPayload)
647 conn.SetWriteDeadline(time.Now().Add(DefaultDeadline)) // #nosec G104
648 if err = state.WriteSP(conn, buf, false); err != nil {
649 state.Ctx.LogE("sp-startR-write", les, err, func(les LEs) string {
651 "SP with %s (nice %s): writing",
652 node.Name, NicenessFmt(state.Nice),
658 state.Ctx.LogD("sp-startR-workers", les, func(les LEs) string {
660 "SP with %s (nice %s): starting workers",
661 node.Name, NicenessFmt(state.Nice),
664 err = state.StartWorkers(conn, infosPayloads, payload)
671 func (state *SPState) closeFd(pth string) {
672 s, exists := state.fds[pth]
673 delete(state.fds, pth)
679 func (state *SPState) StartWorkers(
681 infosPayloads [][]byte,
684 les := LEs{{"Node", state.Node.Id}, {"Nice", int(state.Nice)}}
685 state.fds = make(map[string]FdAndFullSize)
686 state.fileHashers = make(map[string]*HasherAndOffset)
687 state.isDead = make(chan struct{})
688 if state.maxOnlineTime > 0 {
689 state.mustFinishAt = state.started.Add(state.maxOnlineTime)
694 queues := spCheckers[*state.Node.Id]
696 queues = &SPCheckerQueues{
697 appeared: make(chan *[32]byte),
698 checked: make(chan *[32]byte),
700 spCheckers[*state.Node.Id] = queues
701 go SPChecker(state.Ctx, state.Node.Id, queues.appeared, queues.checked)
703 state.checkerQueues = *queues
705 for job := range state.Ctx.JobsNoCK(state.Node.Id) {
706 if job.PktEnc.Nice <= state.Nice {
707 state.checkerQueues.appeared <- job.HshValue
713 defer state.wg.Done()
718 case hsh := <-state.checkerQueues.checked:
719 state.payloads <- MarshalSP(SPTypeDone, SPDone{hsh})
725 // Remaining handshake payload sending
726 if len(infosPayloads) > 1 {
729 for _, payload := range infosPayloads[1:] {
731 "sp-queue-remaining",
732 append(les, LE{"Size", len(payload)}),
733 func(les LEs) string {
735 "SP with %s (nice %s): queuing remaining payload (%s)",
736 state.Node.Name, NicenessFmt(state.Nice),
737 humanize.IBytes(uint64(len(payload))),
741 state.payloads <- payload
747 // Processing of first payload and queueing its responses
748 logMsg := func(les LEs) string {
750 "SP with %s (nice %s): processing first payload (%s)",
751 state.Node.Name, NicenessFmt(state.Nice),
752 humanize.IBytes(uint64(len(payload))),
755 state.Ctx.LogD("sp-process", append(les, LE{"Size", len(payload)}), logMsg)
756 replies, err := state.ProcessSP(payload)
758 state.Ctx.LogE("sp-process", les, err, logMsg)
763 for _, reply := range replies {
766 append(les, LE{"Size", len(reply)}),
767 func(les LEs) string {
769 "SP with %s (nice %s): queuing reply (%s)",
770 state.Node.Name, NicenessFmt(state.Nice),
771 humanize.IBytes(uint64(len(payload))),
775 state.payloads <- reply
783 deadlineTicker := time.NewTicker(time.Second)
784 pingTicker := time.NewTicker(PingTimeout)
789 deadlineTicker.Stop()
792 case now := <-deadlineTicker.C:
793 if (now.Sub(state.RxLastNonPing) >= state.onlineDeadline &&
794 now.Sub(state.TxLastNonPing) >= state.onlineDeadline) ||
795 (state.maxOnlineTime > 0 && state.mustFinishAt.Before(now)) ||
796 (now.Sub(state.RxLastSeen) >= 2*PingTimeout) {
798 conn.Close() // #nosec G104
800 case now := <-pingTicker.C:
801 if now.After(state.TxLastSeen.Add(PingTimeout)) {
804 state.pings <- struct{}{}
812 // Spool checker and INFOs sender of appearing files
813 if !state.listOnly && (state.xxOnly == "" || state.xxOnly == TTx) {
816 ticker := time.NewTicker(time.Second)
824 for _, payload := range state.Ctx.infosOur(
831 append(les, LE{"Size", len(payload)}),
832 func(les LEs) string {
834 "SP with %s (nice %s): queuing new info (%s)",
835 state.Node.Name, NicenessFmt(state.Nice),
836 humanize.IBytes(uint64(len(payload))),
840 state.payloads <- payload
851 defer state.SetDead()
852 defer state.wg.Done()
854 if state.NotAlive() {
861 state.Ctx.LogD("sp-got-ping", les, func(les LEs) string {
863 "SP with %s (nice %s): got ping",
864 state.Node.Name, NicenessFmt(state.Nice),
867 payload = SPPingMarshalized
869 case payload = <-state.payloads:
872 append(les, LE{"Size", len(payload)}),
873 func(les LEs) string {
875 "SP with %s (nice %s): got payload (%s)",
876 state.Node.Name, NicenessFmt(state.Nice),
877 humanize.IBytes(uint64(len(payload))),
883 if len(state.queueTheir) == 0 {
885 time.Sleep(100 * time.Millisecond)
888 freq := state.queueTheir[0].freq
890 if state.txRate > 0 {
891 time.Sleep(time.Second / time.Duration(state.txRate))
893 pktName := Base32Codec.EncodeToString(freq.Hash[:])
896 LE{"XX", string(TTx)},
898 LE{"Size", int64(freq.Offset)},
900 logMsg := func(les LEs) string {
902 "SP with %s (nice %s): tx/%s (%s)",
903 state.Node.Name, NicenessFmt(state.Nice),
905 humanize.IBytes(freq.Offset),
908 state.Ctx.LogD("sp-queue", lesp, func(les LEs) string {
909 return logMsg(les) + ": queueing"
911 pth := filepath.Join(
913 state.Node.Id.String(),
915 Base32Codec.EncodeToString(freq.Hash[:]),
917 fdAndFullSize, exists := state.fds[pth]
919 fd, err := os.Open(pth)
921 state.Ctx.LogE("sp-queue-open", lesp, err, func(les LEs) string {
922 return logMsg(les) + ": opening"
928 state.Ctx.LogE("sp-queue-stat", lesp, err, func(les LEs) string {
929 return logMsg(les) + ": stating"
933 fdAndFullSize = FdAndFullSize{fd: fd, fullSize: fi.Size()}
934 state.fds[pth] = fdAndFullSize
936 fd := fdAndFullSize.fd
937 fullSize := fdAndFullSize.fullSize
939 if freq.Offset < uint64(fullSize) {
940 state.Ctx.LogD("sp-file-seek", lesp, func(les LEs) string {
941 return logMsg(les) + ": seeking"
943 if _, err = fd.Seek(int64(freq.Offset), io.SeekStart); err != nil {
944 state.Ctx.LogE("sp-file-seek", lesp, err, func(les LEs) string {
945 return logMsg(les) + ": seeking"
949 buf = make([]byte, MaxSPSize-SPHeadOverhead-SPFileOverhead)
950 n, err := fd.Read(buf)
952 state.Ctx.LogE("sp-file-read", lesp, err, func(les LEs) string {
953 return logMsg(les) + ": reading"
960 append(lesp, LE{"Size", n}),
961 func(les LEs) string {
964 logMsg(les), humanize.IBytes(uint64(n)),
970 payload = MarshalSP(SPTypeFile, SPFile{
975 ourSize := freq.Offset + uint64(len(buf))
976 lesp = append(lesp, LE{"Size", int64(ourSize)}, LE{"FullSize", fullSize})
977 if state.Ctx.ShowPrgrs {
981 if len(state.queueTheir) > 0 && *state.queueTheir[0].freq.Hash == *freq.Hash {
982 if ourSize == uint64(fullSize) {
983 state.Ctx.LogD("sp-file-finished", lesp, func(les LEs) string {
984 return logMsg(les) + ": finished"
986 if len(state.queueTheir) > 1 {
987 state.queueTheir = state.queueTheir[1:]
989 state.queueTheir = state.queueTheir[:0]
992 state.queueTheir[0].freq.Offset += uint64(len(buf))
995 state.Ctx.LogD("sp-file-disappeared", lesp, func(les LEs) string {
996 return logMsg(les) + ": queue disappeared"
1001 logMsg := func(les LEs) string {
1003 "SP with %s (nice %s): sending %s",
1004 state.Node.Name, NicenessFmt(state.Nice),
1005 humanize.IBytes(uint64(len(payload))),
1008 state.Ctx.LogD("sp-sending", append(les, LE{"Size", len(payload)}), logMsg)
1009 conn.SetWriteDeadline(time.Now().Add(DefaultDeadline)) // #nosec G104
1010 if err := state.WriteSP(conn, state.csOur.Encrypt(nil, nil, payload), ping); err != nil {
1011 state.Ctx.LogE("sp-sending", les, err, logMsg)
1021 if state.NotAlive() {
1024 logMsg := func(les LEs) string {
1026 "SP with %s (nice %s): waiting for payload",
1027 state.Node.Name, NicenessFmt(state.Nice),
1030 state.Ctx.LogD("sp-recv-wait", les, logMsg)
1031 conn.SetReadDeadline(time.Now().Add(DefaultDeadline)) // #nosec G104
1032 payload, err := state.ReadSP(conn)
1037 unmarshalErr := err.(*xdr.UnmarshalError)
1038 if os.IsTimeout(unmarshalErr.Err) {
1041 if unmarshalErr.ErrorCode == xdr.ErrIO {
1044 state.Ctx.LogE("sp-recv-wait", les, err, logMsg)
1047 logMsg = func(les LEs) string {
1049 "SP with %s (nice %s): payload (%s)",
1050 state.Node.Name, NicenessFmt(state.Nice),
1051 humanize.IBytes(uint64(len(payload))),
1056 append(les, LE{"Size", len(payload)}),
1057 func(les LEs) string { return logMsg(les) + ": got" },
1059 payload, err = state.csTheir.Decrypt(nil, nil, payload)
1061 state.Ctx.LogE("sp-recv-got", les, err, func(les LEs) string {
1062 return logMsg(les) + ": got"
1068 append(les, LE{"Size", len(payload)}),
1069 func(les LEs) string {
1070 return logMsg(les) + ": processing"
1073 replies, err := state.ProcessSP(payload)
1075 state.Ctx.LogE("sp-recv-process", les, err, func(les LEs) string {
1076 return logMsg(les) + ": processing"
1082 for _, reply := range replies {
1085 append(les[:len(les)-1], LE{"Size", len(reply)}),
1086 func(les LEs) string {
1088 "SP with %s (nice %s): queuing reply (%s)",
1089 state.Node.Name, NicenessFmt(state.Nice),
1090 humanize.IBytes(uint64(len(reply))),
1094 state.payloads <- reply
1098 if state.rxRate > 0 {
1099 time.Sleep(time.Second / time.Duration(state.rxRate))
1105 conn.Close() // #nosec G104
1111 func (state *SPState) Wait() {
1113 close(state.payloads)
1116 state.Duration = time.Now().Sub(state.started)
1117 state.RxSpeed = state.RxBytes
1118 state.TxSpeed = state.TxBytes
1119 rxDuration := int64(state.RxLastSeen.Sub(state.started).Seconds())
1120 txDuration := int64(state.TxLastSeen.Sub(state.started).Seconds())
1122 state.RxSpeed = state.RxBytes / rxDuration
1125 state.TxSpeed = state.TxBytes / txDuration
1129 func (state *SPState) ProcessSP(payload []byte) ([][]byte, error) {
1130 les := LEs{{"Node", state.Node.Id}, {"Nice", int(state.Nice)}}
1131 r := bytes.NewReader(payload)
1133 var replies [][]byte
1136 state.Ctx.LogD("sp-process-unmarshal", les, func(les LEs) string {
1138 "SP with %s (nice %s): unmarshaling header",
1139 state.Node.Name, NicenessFmt(state.Nice),
1143 if _, err = xdr.Unmarshal(r, &head); err != nil {
1144 state.Ctx.LogE("sp-process-unmarshal", les, err, func(les LEs) string {
1146 "SP with %s (nice %s): unmarshaling header",
1147 state.Node.Name, NicenessFmt(state.Nice),
1152 if head.Type != SPTypePing {
1153 state.RxLastNonPing = state.RxLastSeen
1159 append(les, LE{"Type", "halt"}), func(les LEs) string {
1161 "SP with %s (nice %s): got HALT",
1162 state.Node.Name, NicenessFmt(state.Nice),
1167 state.queueTheir = nil
1173 append(les, LE{"Type", "ping"}),
1174 func(les LEs) string {
1176 "SP with %s (nice %s): got PING",
1177 state.Node.Name, NicenessFmt(state.Nice),
1184 lesp := append(les, LE{"Type", "info"})
1186 "sp-process-info-unmarshal", lesp,
1187 func(les LEs) string {
1189 "SP with %s (nice %s): unmarshaling INFO",
1190 state.Node.Name, NicenessFmt(state.Nice),
1195 if _, err = xdr.Unmarshal(r, &info); err != nil {
1197 "sp-process-info-unmarshal", lesp, err,
1198 func(les LEs) string {
1200 "SP with %s (nice %s): unmarshaling INFO",
1201 state.Node.Name, NicenessFmt(state.Nice),
1207 pktName := Base32Codec.EncodeToString(info.Hash[:])
1211 LE{"Size", int64(info.Size)},
1212 LE{"PktNice", int(info.Nice)},
1214 logMsg := func(les LEs) string {
1216 "SP with %s (nice %s): INFO %s (%s) nice %s",
1217 state.Node.Name, NicenessFmt(state.Nice),
1219 humanize.IBytes(info.Size),
1220 NicenessFmt(info.Nice),
1223 if !state.listOnly && info.Nice > state.Nice {
1224 state.Ctx.LogD("sp-process-info-too-nice", lesp, func(les LEs) string {
1225 return logMsg(les) + ": too nice"
1229 state.Ctx.LogD("sp-process-info-got", lesp, func(les LEs) string {
1230 return logMsg(les) + ": received"
1232 if !state.listOnly && state.xxOnly == TTx {
1236 state.infosTheir[*info.Hash] = &info
1238 state.Ctx.LogD("sp-process-info-stat", lesp, func(les LEs) string {
1239 return logMsg(les) + ": stating part"
1241 pktPath := filepath.Join(
1243 state.Node.Id.String(),
1245 Base32Codec.EncodeToString(info.Hash[:]),
1247 logMsg = func(les LEs) string {
1249 "Packet %s (%s) (nice %s)",
1251 humanize.IBytes(info.Size),
1252 NicenessFmt(info.Nice),
1255 if _, err = os.Stat(pktPath); err == nil {
1256 state.Ctx.LogI("sp-info-done", lesp, func(les LEs) string {
1257 return logMsg(les) + ": already done"
1259 if !state.listOnly {
1260 replies = append(replies, MarshalSP(SPTypeDone, SPDone{info.Hash}))
1264 if _, err = os.Stat(pktPath + SeenSuffix); err == nil {
1265 state.Ctx.LogI("sp-info-seen", lesp, func(les LEs) string {
1266 return logMsg(les) + ": already seen"
1268 if !state.listOnly {
1269 replies = append(replies, MarshalSP(SPTypeDone, SPDone{info.Hash}))
1273 if _, err = os.Stat(pktPath + NoCKSuffix); err == nil {
1274 state.Ctx.LogI("sp-info-nock", lesp, func(les LEs) string {
1275 return logMsg(les) + ": still not checksummed"
1279 fi, err := os.Stat(pktPath + PartSuffix)
1284 if !state.Ctx.IsEnoughSpace(int64(info.Size) - offset) {
1285 state.Ctx.LogI("sp-info-no-space", lesp, func(les LEs) string {
1286 return logMsg(les) + ": not enough space"
1292 append(lesp, LE{"Offset", offset}),
1293 func(les LEs) string {
1295 "%s: %d%%", logMsg(les), 100*uint64(offset)/info.Size,
1299 if !state.listOnly && (state.onlyPkts == nil || state.onlyPkts[*info.Hash]) {
1300 replies = append(replies, MarshalSP(
1302 SPFreq{info.Hash, uint64(offset)},
1307 lesp := append(les, LE{"Type", "file"})
1308 state.Ctx.LogD("sp-process-file", lesp, func(les LEs) string {
1310 "SP with %s (nice %s): unmarshaling FILE",
1311 state.Node.Name, NicenessFmt(state.Nice),
1315 if _, err = xdr.Unmarshal(r, &file); err != nil {
1316 state.Ctx.LogE("sp-process-file", lesp, err, func(les LEs) string {
1318 "SP with %s (nice %s): unmarshaling FILE",
1319 state.Node.Name, NicenessFmt(state.Nice),
1324 pktName := Base32Codec.EncodeToString(file.Hash[:])
1327 LE{"XX", string(TRx)},
1329 LE{"Size", len(file.Payload)},
1331 logMsg := func(les LEs) string {
1333 "Got packet %s (%s)",
1334 pktName, humanize.IBytes(uint64(len(file.Payload))),
1337 dirToSync := filepath.Join(
1339 state.Node.Id.String(),
1342 filePath := filepath.Join(dirToSync, pktName)
1343 filePathPart := filePath + PartSuffix
1344 state.Ctx.LogD("sp-file-open", lesp, func(les LEs) string {
1345 return logMsg(les) + ": opening part"
1347 fdAndFullSize, exists := state.fds[filePathPart]
1350 fd = fdAndFullSize.fd
1352 fd, err = os.OpenFile(
1354 os.O_RDWR|os.O_CREATE,
1358 state.Ctx.LogE("sp-file-open", lesp, err, func(les LEs) string {
1359 return logMsg(les) + ": opening part"
1363 state.fds[filePathPart] = FdAndFullSize{fd: fd}
1364 if file.Offset == 0 {
1365 h, err := blake2b.New256(nil)
1369 state.fileHashers[filePath] = &HasherAndOffset{h: h}
1374 append(lesp, LE{"Offset", file.Offset}),
1375 func(les LEs) string {
1376 return fmt.Sprintf("%s: seeking %d", logMsg(les), file.Offset)
1378 if _, err = fd.Seek(int64(file.Offset), io.SeekStart); err != nil {
1379 state.Ctx.LogE("sp-file-seek", lesp, err, func(les LEs) string {
1380 return logMsg(les) + ": seeking"
1382 state.closeFd(filePathPart)
1385 state.Ctx.LogD("sp-file-write", lesp, func(les LEs) string {
1386 return logMsg(les) + ": writing"
1388 if _, err = fd.Write(file.Payload); err != nil {
1389 state.Ctx.LogE("sp-file-write", lesp, err, func(les LEs) string {
1390 return logMsg(les) + ": writing"
1392 state.closeFd(filePathPart)
1395 hasherAndOffset, hasherExists := state.fileHashers[filePath]
1397 if hasherAndOffset.offset == file.Offset {
1398 if _, err = hasherAndOffset.h.Write(file.Payload); err != nil {
1401 hasherAndOffset.offset += uint64(len(file.Payload))
1404 "sp-file-offset-differs", lesp,
1405 func(les LEs) string {
1406 return logMsg(les) + ": offset differs, deleting hasher"
1409 delete(state.fileHashers, filePath)
1410 hasherExists = false
1413 ourSize := int64(file.Offset + uint64(len(file.Payload)))
1414 lesp[len(lesp)-1].V = ourSize
1415 fullsize := int64(0)
1417 infoTheir, ok := state.infosTheir[*file.Hash]
1420 fullsize = int64(infoTheir.Size)
1422 lesp = append(lesp, LE{"FullSize", fullsize})
1423 if state.Ctx.ShowPrgrs {
1424 Progress("Rx", lesp)
1426 if fullsize != ourSize {
1429 logMsg = func(les LEs) string {
1431 "Got packet %s %d%% (%s / %s)",
1432 pktName, 100*ourSize/fullsize,
1433 humanize.IBytes(uint64(ourSize)),
1434 humanize.IBytes(uint64(fullsize)),
1439 state.Ctx.LogE("sp-file-sync", lesp, err, func(les LEs) string {
1440 return logMsg(les) + ": syncing"
1442 state.closeFd(filePathPart)
1446 if bytes.Compare(hasherAndOffset.h.Sum(nil), file.Hash[:]) != 0 {
1448 "sp-file-bad-checksum", lesp,
1449 errors.New("checksum mismatch"),
1454 if err = os.Rename(filePathPart, filePath); err != nil {
1455 state.Ctx.LogE("sp-file-rename", lesp, err, func(les LEs) string {
1456 return logMsg(les) + ": renaming"
1460 if err = DirSync(dirToSync); err != nil {
1461 state.Ctx.LogE("sp-file-dirsync", lesp, err, func(les LEs) string {
1462 return logMsg(les) + ": dirsyncing"
1466 state.Ctx.LogI("sp-file-done", lesp, func(les LEs) string {
1467 return logMsg(les) + ": done"
1471 state.payloads <- MarshalSP(SPTypeDone, SPDone{file.Hash})
1475 delete(state.infosTheir, *file.Hash)
1477 if !state.Ctx.HdrUsage {
1478 state.closeFd(filePathPart)
1481 if _, err = fd.Seek(0, io.SeekStart); err != nil {
1482 state.Ctx.LogE("sp-file-seek", lesp, err, func(les LEs) string {
1483 return logMsg(les) + ": seeking"
1485 state.closeFd(filePathPart)
1488 _, pktEncRaw, err := state.Ctx.HdrRead(fd)
1489 state.closeFd(filePathPart)
1491 state.Ctx.LogE("sp-file-hdr-read", lesp, err, func(les LEs) string {
1492 return logMsg(les) + ": HdrReading"
1496 state.Ctx.HdrWrite(pktEncRaw, filePath)
1499 state.closeFd(filePathPart)
1500 if err = os.Rename(filePathPart, filePath+NoCKSuffix); err != nil {
1501 state.Ctx.LogE("sp-file-rename", lesp, err, func(les LEs) string {
1502 return logMsg(les) + ": renaming"
1506 if err = DirSync(dirToSync); err != nil {
1507 state.Ctx.LogE("sp-file-dirsync", lesp, err, func(les LEs) string {
1508 return logMsg(les) + ": dirsyncing"
1512 state.Ctx.LogI("sp-file-downloaded", lesp, func(les LEs) string {
1513 return logMsg(les) + ": downloaded"
1516 delete(state.infosTheir, *file.Hash)
1519 state.checkerQueues.appeared <- file.Hash
1523 lesp := append(les, LE{"Type", "done"})
1524 state.Ctx.LogD("sp-process-done-unmarshal", lesp, func(les LEs) string {
1526 "SP with %s (nice %s): unmarshaling DONE",
1527 state.Node.Name, NicenessFmt(state.Nice),
1531 if _, err = xdr.Unmarshal(r, &done); err != nil {
1532 state.Ctx.LogE("sp-process-done-unmarshal", lesp, err, func(les LEs) string {
1534 "SP with %s (nice %s): unmarshaling DONE",
1535 state.Node.Name, NicenessFmt(state.Nice),
1540 pktName := Base32Codec.EncodeToString(done.Hash[:])
1541 lesp = append(lesp, LE{"Pkt", pktName}, LE{"XX", string(TTx)})
1542 logMsg := func(les LEs) string {
1544 "SP with %s (nice %s): DONE: removing %s",
1545 state.Node.Name, NicenessFmt(state.Nice), pktName,
1548 state.Ctx.LogD("sp-done", lesp, logMsg)
1549 pth := filepath.Join(
1551 state.Node.Id.String(),
1555 if err = os.Remove(pth); err == nil {
1556 state.Ctx.LogI("sp-done", lesp, func(les LEs) string {
1557 return fmt.Sprintf("Packet %s is sent", pktName)
1559 if state.Ctx.HdrUsage {
1560 os.Remove(pth + HdrSuffix)
1563 state.Ctx.LogE("sp-done", lesp, err, logMsg)
1567 lesp := append(les, LE{"Type", "freq"})
1568 state.Ctx.LogD("sp-process-freq", lesp, func(les LEs) string {
1570 "SP with %s (nice %s): unmarshaling FREQ",
1571 state.Node.Name, NicenessFmt(state.Nice),
1575 if _, err = xdr.Unmarshal(r, &freq); err != nil {
1576 state.Ctx.LogE("sp-process-freq", lesp, err, func(les LEs) string {
1578 "SP with %s (nice %s): unmarshaling FREQ",
1579 state.Node.Name, NicenessFmt(state.Nice),
1584 pktName := Base32Codec.EncodeToString(freq.Hash[:])
1585 lesp = append(lesp, LE{"Pkt", pktName}, LE{"Offset", freq.Offset})
1586 state.Ctx.LogD("sp-process-freq-queueing", lesp, func(les LEs) string {
1588 "SP with %s (nice %s): FREQ %s: queuing",
1589 state.Node.Name, NicenessFmt(state.Nice), pktName,
1592 nice, exists := state.infosOurSeen[*freq.Hash]
1594 if state.onlyPkts == nil || !state.onlyPkts[*freq.Hash] {
1597 var freqWithNice *FreqWithNice
1598 for insertIdx, freqWithNice = range state.queueTheir {
1599 if freqWithNice.nice > nice {
1603 state.queueTheir = append(state.queueTheir, nil)
1604 copy(state.queueTheir[insertIdx+1:], state.queueTheir[insertIdx:])
1605 state.queueTheir[insertIdx] = &FreqWithNice{&freq, nice}
1608 state.Ctx.LogD("sp-process-freq-skip", lesp, func(les LEs) string {
1610 "SP with %s (nice %s): FREQ %s: skipping",
1611 state.Node.Name, NicenessFmt(state.Nice), pktName,
1616 state.Ctx.LogD("sp-process-freq-unknown", lesp, func(les LEs) string {
1618 "SP with %s (nice %s): FREQ %s: unknown",
1619 state.Node.Name, NicenessFmt(state.Nice), pktName,
1626 "sp-process-type-unknown",
1627 append(les, LE{"Type", head.Type}),
1628 errors.New("unknown type"),
1629 func(les LEs) string {
1631 "SP with %s (nice %s): %d",
1632 state.Node.Name, NicenessFmt(state.Nice), head.Type,
1636 return nil, BadPktType
1644 for _, info := range state.infosTheir {
1649 state.Ctx.LogI("sp-infos-rx", LEs{
1650 {"XX", string(TRx)},
1651 {"Node", state.Node.Id},
1653 {"Size", int64(size)},
1654 }, func(les LEs) string {
1656 "%s has got for us: %d packets, %s",
1657 state.Node.Name, pkts, humanize.IBytes(size),
1661 return payloadsSplit(replies), nil