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/>.
32 xdr "github.com/davecgh/go-xdr/xdr2"
33 "github.com/dustin/go-humanize"
34 "github.com/flynn/noise"
38 MaxSPSize = 1<<16 - 256
43 type MTHAndOffset struct {
48 type SPCheckerTask struct {
59 SPHaltMarshalized []byte
60 SPPingMarshalized []byte
62 NoiseCipherSuite noise.CipherSuite = noise.NewCipherSuite(
64 noise.CipherChaChaPoly,
68 DefaultDeadline = 10 * time.Second
69 PingTimeout = time.Minute
71 spCheckerTasks chan SPCheckerTask
72 SPCheckerWg sync.WaitGroup
73 spCheckerOnce sync.Once
76 type FdAndFullSize 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([MTHSize]byte)}
152 if _, err := xdr.Marshal(&buf, spInfo); err != nil {
155 SPInfoOverhead = buf.Len()
158 spFreq := SPFreq{Hash: new([MTHSize]byte), Offset: 123}
159 if _, err := xdr.Marshal(&buf, spFreq); err != nil {
162 SPFreqOverhead = buf.Len()
165 spFile := SPFile{Hash: new([MTHSize]byte), Offset: 123}
166 if _, err := xdr.Marshal(&buf, spFile); err != nil {
169 SPFileOverhead = buf.Len()
170 spCheckerTasks = make(chan SPCheckerTask)
173 func MarshalSP(typ SPType, sp interface{}) []byte {
175 if _, err := xdr.Marshal(&buf, SPHead{typ}); err != nil {
178 if _, err := xdr.Marshal(&buf, sp); err != nil {
184 func payloadsSplit(payloads [][]byte) [][]byte {
185 var outbounds [][]byte
186 outbound := make([]byte, 0, MaxSPSize)
187 for i, payload := range payloads {
188 outbound = append(outbound, payload...)
189 if i+1 < len(payloads) && len(outbound)+len(payloads[i+1]) > MaxSPSize {
190 outbounds = append(outbounds, outbound)
191 outbound = make([]byte, 0, MaxSPSize)
194 if len(outbound) > 0 {
195 outbounds = append(outbounds, outbound)
200 type SPState struct {
205 onlineDeadline time.Duration
206 maxOnlineTime time.Duration
207 hs *noise.HandshakeState
208 csOur *noise.CipherState
209 csTheir *noise.CipherState
212 infosTheir map[[MTHSize]byte]*SPInfo
213 infosOurSeen map[[MTHSize]byte]uint8
214 queueTheir []*FreqWithNice
218 RxLastNonPing time.Time
221 TxLastNonPing time.Time
223 mustFinishAt time.Time
224 Duration time.Duration
234 onlyPkts map[[MTHSize]byte]bool
235 writeSPBuf bytes.Buffer
236 fds map[string]FdAndFullSize
238 fileHashers map[string]*MTHAndOffset
239 progressBars map[string]struct{}
243 func (state *SPState) SetDead() {
248 // Already closed channel, dead
254 for range state.payloads {
258 for range state.pings {
263 func (state *SPState) NotAlive() bool {
272 func (state *SPState) dirUnlock() {
273 state.Ctx.UnlockDir(state.rxLock)
274 state.Ctx.UnlockDir(state.txLock)
277 func (state *SPState) WriteSP(dst io.Writer, payload []byte, ping bool) error {
278 state.writeSPBuf.Reset()
279 n, err := xdr.Marshal(&state.writeSPBuf, SPRaw{
280 Magic: MagicNNCPSv1.B,
286 if n, err = dst.Write(state.writeSPBuf.Bytes()); err == nil {
287 state.TxLastSeen = time.Now()
288 state.TxBytes += int64(n)
290 state.TxLastNonPing = state.TxLastSeen
296 func (state *SPState) ReadSP(src io.Reader) ([]byte, error) {
298 n, err := xdr.UnmarshalLimited(src, &sp, 1<<17)
300 ue := err.(*xdr.UnmarshalError)
301 if ue.Err == io.EOF {
306 state.RxLastSeen = time.Now()
307 state.RxBytes += int64(n)
308 if sp.Magic != MagicNNCPSv1.B {
311 return sp.Payload, nil
314 func (ctx *Ctx) infosOur(nodeId *NodeId, nice uint8, seen *map[[MTHSize]byte]uint8) [][]byte {
317 for job := range ctx.Jobs(nodeId, TTx) {
318 if job.PktEnc.Nice > nice {
321 if _, known := (*seen)[*job.HshValue]; known {
324 totalSize += job.Size
325 infos = append(infos, &SPInfo{
326 Nice: job.PktEnc.Nice,
327 Size: uint64(job.Size),
330 (*seen)[*job.HshValue] = job.PktEnc.Nice
332 sort.Sort(ByNice(infos))
333 var payloads [][]byte
334 for _, info := range infos {
335 payloads = append(payloads, MarshalSP(SPTypeInfo, info))
336 pktName := Base32Codec.EncodeToString(info.Hash[:])
337 ctx.LogD("sp-info-our", LEs{
341 }, func(les LEs) string {
343 "Our info: %s/tx/%s (%s)",
344 ctx.NodeName(nodeId),
346 humanize.IBytes(info.Size),
351 ctx.LogI("sp-infos-tx", LEs{
354 {"Pkts", len(payloads)},
356 }, func(les LEs) string {
358 "We have got for %s: %d packets, %s",
359 ctx.NodeName(nodeId),
361 humanize.IBytes(uint64(totalSize)),
365 return payloadsSplit(payloads)
368 func (state *SPState) StartI(conn ConnDeadlined) error {
369 nodeId := state.Node.Id
370 err := state.Ctx.ensureRxDir(nodeId)
375 if !state.listOnly && (state.xxOnly == "" || state.xxOnly == TRx) {
376 rxLock, err = state.Ctx.LockDir(nodeId, string(TRx))
382 if !state.listOnly && (state.xxOnly == "" || state.xxOnly == TTx) {
383 txLock, err = state.Ctx.LockDir(nodeId, string(TTx))
388 started := time.Now()
389 conf := noise.Config{
390 CipherSuite: NoiseCipherSuite,
391 Pattern: noise.HandshakeIK,
393 StaticKeypair: noise.DHKey{
394 Private: state.Ctx.Self.NoisePrv[:],
395 Public: state.Ctx.Self.NoisePub[:],
397 PeerStatic: state.Node.NoisePub[:],
399 hs, err := noise.NewHandshakeState(conf)
404 state.payloads = make(chan []byte)
405 state.pings = make(chan struct{})
406 state.infosTheir = make(map[[MTHSize]byte]*SPInfo)
407 state.infosOurSeen = make(map[[MTHSize]byte]uint8)
408 state.progressBars = make(map[string]struct{})
409 state.started = started
410 state.rxLock = rxLock
411 state.txLock = txLock
413 var infosPayloads [][]byte
414 if !state.listOnly && (state.xxOnly == "" || state.xxOnly == TTx) {
415 infosPayloads = state.Ctx.infosOur(nodeId, state.Nice, &state.infosOurSeen)
417 var firstPayload []byte
418 if len(infosPayloads) > 0 {
419 firstPayload = infosPayloads[0]
421 // Pad first payload, to hide actual number of existing files
422 for i := 0; i < (MaxSPSize-len(firstPayload))/SPHeadOverhead; i++ {
423 firstPayload = append(firstPayload, SPHaltMarshalized...)
428 buf, _, _, err = state.hs.WriteMessage(nil, firstPayload)
433 les := LEs{{"Node", nodeId}, {"Nice", int(state.Nice)}}
434 state.Ctx.LogD("sp-startI", les, func(les LEs) string {
436 "SP with %s (nice %s): sending first message",
438 NicenessFmt(state.Nice),
441 conn.SetWriteDeadline(time.Now().Add(DefaultDeadline)) // #nosec G104
442 if err = state.WriteSP(conn, buf, false); err != nil {
443 state.Ctx.LogE("sp-startI", les, err, func(les LEs) string {
445 "SP with %s (nice %s): writing",
447 NicenessFmt(state.Nice),
453 state.Ctx.LogD("sp-startI-wait", les, func(les LEs) string {
455 "SP with %s (nice %s): waiting for first message",
457 NicenessFmt(state.Nice),
460 conn.SetReadDeadline(time.Now().Add(DefaultDeadline)) // #nosec G104
461 if buf, err = state.ReadSP(conn); err != nil {
462 state.Ctx.LogE("sp-startI-read", les, err, func(les LEs) string {
464 "SP with %s (nice %s): reading",
466 NicenessFmt(state.Nice),
472 payload, state.csOur, state.csTheir, err = state.hs.ReadMessage(nil, buf)
474 state.Ctx.LogE("sp-startI-read", les, err, func(les LEs) string {
476 "SP with %s (nice %s): reading Noise message",
478 NicenessFmt(state.Nice),
484 state.Ctx.LogD("sp-startI-workers", les, func(les LEs) string {
486 "SP with %s (nice %s): starting workers",
488 NicenessFmt(state.Nice),
491 err = state.StartWorkers(conn, infosPayloads, payload)
493 state.Ctx.LogE("sp-startI-workers", les, err, func(les LEs) string {
495 "SP with %s (nice %s): starting workers",
497 NicenessFmt(state.Nice),
505 func (state *SPState) StartR(conn ConnDeadlined) error {
506 started := time.Now()
507 conf := noise.Config{
508 CipherSuite: NoiseCipherSuite,
509 Pattern: noise.HandshakeIK,
511 StaticKeypair: noise.DHKey{
512 Private: state.Ctx.Self.NoisePrv[:],
513 Public: state.Ctx.Self.NoisePub[:],
516 hs, err := noise.NewHandshakeState(conf)
522 state.payloads = make(chan []byte)
523 state.pings = make(chan struct{})
524 state.infosOurSeen = make(map[[MTHSize]byte]uint8)
525 state.infosTheir = make(map[[MTHSize]byte]*SPInfo)
526 state.progressBars = make(map[string]struct{})
527 state.started = started
528 state.xxOnly = xxOnly
532 logMsg := func(les LEs) string {
534 "SP nice %s: waiting for first message",
535 NicenessFmt(state.Nice),
538 les := LEs{{"Nice", int(state.Nice)}}
539 state.Ctx.LogD("sp-startR", les, logMsg)
540 conn.SetReadDeadline(time.Now().Add(DefaultDeadline)) // #nosec G104
541 if buf, err = state.ReadSP(conn); err != nil {
542 state.Ctx.LogE("sp-startR-read", les, err, logMsg)
545 if payload, _, _, err = state.hs.ReadMessage(nil, buf); err != nil {
546 state.Ctx.LogE("sp-startR-read", les, err, logMsg)
551 for _, n := range state.Ctx.Neigh {
552 if subtle.ConstantTimeCompare(state.hs.PeerStatic(), n.NoisePub[:]) == 1 {
558 peerId := Base32Codec.EncodeToString(state.hs.PeerStatic())
559 err = errors.New("unknown peer: " + peerId)
560 state.Ctx.LogE("sp-startR-unknown", append(les, LE{"Peer", peerId}), err, logMsg)
564 state.rxRate = node.RxRate
565 state.txRate = node.TxRate
566 state.onlineDeadline = node.OnlineDeadline
567 state.maxOnlineTime = node.MaxOnlineTime
568 les = LEs{{"Node", node.Id}, {"Nice", int(state.Nice)}}
570 if err = state.Ctx.ensureRxDir(node.Id); err != nil {
574 if xxOnly == "" || xxOnly == TRx {
575 rxLock, err = state.Ctx.LockDir(node.Id, string(TRx))
580 state.rxLock = rxLock
582 if xxOnly == "" || xxOnly == TTx {
583 txLock, err = state.Ctx.LockDir(node.Id, string(TTx))
588 state.txLock = txLock
590 var infosPayloads [][]byte
591 if xxOnly == "" || xxOnly == TTx {
592 infosPayloads = state.Ctx.infosOur(node.Id, state.Nice, &state.infosOurSeen)
594 var firstPayload []byte
595 if len(infosPayloads) > 0 {
596 firstPayload = infosPayloads[0]
598 // Pad first payload, to hide actual number of existing files
599 for i := 0; i < (MaxSPSize-len(firstPayload))/SPHeadOverhead; i++ {
600 firstPayload = append(firstPayload, SPHaltMarshalized...)
603 state.Ctx.LogD("sp-startR-write", les, func(les LEs) string {
605 "SP with %s (nice %s): sending first message",
606 node.Name, NicenessFmt(state.Nice),
609 buf, state.csTheir, state.csOur, err = state.hs.WriteMessage(nil, firstPayload)
614 conn.SetWriteDeadline(time.Now().Add(DefaultDeadline)) // #nosec G104
615 if err = state.WriteSP(conn, buf, false); err != nil {
616 state.Ctx.LogE("sp-startR-write", les, err, func(les LEs) string {
618 "SP with %s (nice %s): writing",
619 node.Name, NicenessFmt(state.Nice),
625 state.Ctx.LogD("sp-startR-workers", les, func(les LEs) string {
627 "SP with %s (nice %s): starting workers",
628 node.Name, NicenessFmt(state.Nice),
631 err = state.StartWorkers(conn, infosPayloads, payload)
638 func (state *SPState) closeFd(pth string) {
640 if s, exists := state.fds[pth]; exists {
641 delete(state.fds, pth)
644 state.fdsLock.Unlock()
647 func (state *SPState) StartWorkers(
649 infosPayloads [][]byte,
652 les := LEs{{"Node", state.Node.Id}, {"Nice", int(state.Nice)}}
653 state.fds = make(map[string]FdAndFullSize)
654 state.fileHashers = make(map[string]*MTHAndOffset)
655 state.isDead = make(chan struct{})
656 if state.maxOnlineTime > 0 {
657 state.mustFinishAt = state.started.Add(state.maxOnlineTime)
660 spCheckerOnce.Do(func() { go SPChecker(state.Ctx) })
662 for job := range state.Ctx.JobsNoCK(state.Node.Id) {
663 if job.PktEnc.Nice <= state.Nice {
664 spCheckerTasks <- SPCheckerTask{
665 nodeId: state.Node.Id,
667 done: state.payloads,
674 // Remaining handshake payload sending
675 if len(infosPayloads) > 1 {
678 for _, payload := range infosPayloads[1:] {
680 "sp-queue-remaining",
681 append(les, LE{"Size", int64(len(payload))}),
682 func(les LEs) string {
684 "SP with %s (nice %s): queuing remaining payload (%s)",
685 state.Node.Name, NicenessFmt(state.Nice),
686 humanize.IBytes(uint64(len(payload))),
690 state.payloads <- payload
696 // Processing of first payload and queueing its responses
697 logMsg := func(les LEs) string {
699 "SP with %s (nice %s): processing first payload (%s)",
700 state.Node.Name, NicenessFmt(state.Nice),
701 humanize.IBytes(uint64(len(payload))),
704 state.Ctx.LogD("sp-process", append(les, LE{"Size", int64(len(payload))}), logMsg)
705 replies, err := state.ProcessSP(payload)
707 state.Ctx.LogE("sp-process", les, err, logMsg)
712 for _, reply := range replies {
715 append(les, LE{"Size", int64(len(reply))}),
716 func(les LEs) string {
718 "SP with %s (nice %s): queuing reply (%s)",
719 state.Node.Name, NicenessFmt(state.Nice),
720 humanize.IBytes(uint64(len(payload))),
724 state.payloads <- reply
732 deadlineTicker := time.NewTicker(time.Second)
733 pingTicker := time.NewTicker(PingTimeout)
738 deadlineTicker.Stop()
741 case now := <-deadlineTicker.C:
742 if now.Sub(state.RxLastNonPing) >= state.onlineDeadline &&
743 now.Sub(state.TxLastNonPing) >= state.onlineDeadline {
746 if state.maxOnlineTime > 0 && state.mustFinishAt.Before(now) {
749 if now.Sub(state.RxLastSeen) >= 2*PingTimeout {
755 conn.Close() // #nosec G104
756 case now := <-pingTicker.C:
757 if now.After(state.TxLastSeen.Add(PingTimeout)) {
760 state.pings <- struct{}{}
768 // Spool checker and INFOs sender of appearing files
769 if !state.listOnly && (state.xxOnly == "" || state.xxOnly == TTx) {
772 ticker := time.NewTicker(time.Second)
780 for _, payload := range state.Ctx.infosOur(
787 append(les, LE{"Size", int64(len(payload))}),
788 func(les LEs) string {
790 "SP with %s (nice %s): queuing new info (%s)",
791 state.Node.Name, NicenessFmt(state.Nice),
792 humanize.IBytes(uint64(len(payload))),
796 state.payloads <- payload
807 defer state.SetDead()
808 defer state.wg.Done()
809 buf := make([]byte, MaxSPSize-SPHeadOverhead-SPFileOverhead)
811 if state.NotAlive() {
818 state.Ctx.LogD("sp-got-ping", les, func(les LEs) string {
820 "SP with %s (nice %s): got ping",
821 state.Node.Name, NicenessFmt(state.Nice),
824 payload = SPPingMarshalized
826 case payload = <-state.payloads:
829 append(les, LE{"Size", int64(len(payload))}),
830 func(les LEs) string {
832 "SP with %s (nice %s): got payload (%s)",
833 state.Node.Name, NicenessFmt(state.Nice),
834 humanize.IBytes(uint64(len(payload))),
840 if len(state.queueTheir) == 0 {
842 time.Sleep(100 * time.Millisecond)
845 freq := state.queueTheir[0].freq
847 if state.txRate > 0 {
848 time.Sleep(time.Second / time.Duration(state.txRate))
850 pktName := Base32Codec.EncodeToString(freq.Hash[:])
853 LE{"XX", string(TTx)},
855 LE{"Size", int64(freq.Offset)},
857 logMsg := func(les LEs) string {
859 "SP with %s (nice %s): tx/%s (%s)",
860 state.Node.Name, NicenessFmt(state.Nice),
862 humanize.IBytes(freq.Offset),
865 state.Ctx.LogD("sp-queue", lesp, func(les LEs) string {
866 return logMsg(les) + ": queueing"
868 pth := filepath.Join(
870 state.Node.Id.String(),
872 Base32Codec.EncodeToString(freq.Hash[:]),
874 state.fdsLock.RLock()
875 fdAndFullSize, exists := state.fds[pth]
876 state.fdsLock.RUnlock()
878 fd, err := os.Open(pth)
880 state.Ctx.LogE("sp-queue-open", lesp, err, func(les LEs) string {
881 return logMsg(les) + ": opening"
887 state.Ctx.LogE("sp-queue-stat", lesp, err, func(les LEs) string {
888 return logMsg(les) + ": stating"
892 fdAndFullSize = FdAndFullSize{fd: fd, fullSize: fi.Size()}
894 state.fds[pth] = fdAndFullSize
895 state.fdsLock.Unlock()
897 fd := fdAndFullSize.fd
898 fullSize := fdAndFullSize.fullSize
900 if freq.Offset < uint64(fullSize) {
901 state.Ctx.LogD("sp-file-seek", lesp, func(les LEs) string {
902 return logMsg(les) + ": seeking"
904 if _, err = fd.Seek(int64(freq.Offset), io.SeekStart); err != nil {
905 state.Ctx.LogE("sp-file-seek", lesp, err, func(les LEs) string {
906 return logMsg(les) + ": seeking"
910 n, err := fd.Read(buf)
912 state.Ctx.LogE("sp-file-read", lesp, err, func(les LEs) string {
913 return logMsg(les) + ": reading"
920 LE{"XX", string(TTx)},
922 LE{"Size", int64(n)},
924 state.Ctx.LogD("sp-file-read", lesp, func(les LEs) string {
927 logMsg(les), humanize.IBytes(uint64(n)),
932 payload = MarshalSP(SPTypeFile, SPFile{
937 ourSize := freq.Offset + uint64(len(bufRead))
940 LE{"XX", string(TTx)},
942 LE{"Size", int64(ourSize)},
943 LE{"FullSize", fullSize},
945 if state.Ctx.ShowPrgrs {
946 state.progressBars[pktName] = struct{}{}
950 for i, q := range state.queueTheir {
951 if *q.freq.Hash != *freq.Hash {
954 if ourSize == uint64(fullSize) {
955 state.Ctx.LogD("sp-file-finished", lesp, func(les LEs) string {
956 return logMsg(les) + ": finished"
958 state.queueTheir = append(
959 state.queueTheir[:i],
960 state.queueTheir[i+1:]...,
962 if state.Ctx.ShowPrgrs {
963 delete(state.progressBars, pktName)
966 q.freq.Offset = ourSize
972 logMsg := func(les LEs) string {
974 "SP with %s (nice %s): sending %s",
975 state.Node.Name, NicenessFmt(state.Nice),
976 humanize.IBytes(uint64(len(payload))),
979 state.Ctx.LogD("sp-sending", append(les, LE{"Size", int64(len(payload))}), logMsg)
980 conn.SetWriteDeadline(time.Now().Add(DefaultDeadline)) // #nosec G104
981 ct, err := state.csOur.Encrypt(nil, nil, payload)
983 state.Ctx.LogE("sp-encrypting", les, err, logMsg)
986 if err := state.WriteSP(conn, ct, ping); err != nil {
987 state.Ctx.LogE("sp-sending", les, err, logMsg)
997 if state.NotAlive() {
1000 logMsg := func(les LEs) string {
1002 "SP with %s (nice %s): waiting for payload",
1003 state.Node.Name, NicenessFmt(state.Nice),
1006 state.Ctx.LogD("sp-recv-wait", les, logMsg)
1007 conn.SetReadDeadline(time.Now().Add(DefaultDeadline)) // #nosec G104
1008 payload, err := state.ReadSP(conn)
1013 unmarshalErr := err.(*xdr.UnmarshalError)
1014 if os.IsTimeout(unmarshalErr.Err) {
1017 if unmarshalErr.ErrorCode == xdr.ErrIO {
1020 state.Ctx.LogE("sp-recv-wait", les, err, logMsg)
1023 logMsg = func(les LEs) string {
1025 "SP with %s (nice %s): payload (%s)",
1026 state.Node.Name, NicenessFmt(state.Nice),
1027 humanize.IBytes(uint64(len(payload))),
1032 append(les, LE{"Size", int64(len(payload))}),
1033 func(les LEs) string { return logMsg(les) + ": got" },
1035 payload, err = state.csTheir.Decrypt(nil, nil, payload)
1037 state.Ctx.LogE("sp-recv-got", les, err, func(les LEs) string {
1038 return logMsg(les) + ": got"
1044 append(les, LE{"Size", int64(len(payload))}),
1045 func(les LEs) string {
1046 return logMsg(les) + ": processing"
1049 replies, err := state.ProcessSP(payload)
1051 state.Ctx.LogE("sp-recv-process", les, err, func(les LEs) string {
1052 return logMsg(les) + ": processing"
1058 for _, reply := range replies {
1061 append(les[:len(les)-1], LE{"Size", int64(len(reply))}),
1062 func(les LEs) string {
1064 "SP with %s (nice %s): queuing reply (%s)",
1065 state.Node.Name, NicenessFmt(state.Nice),
1066 humanize.IBytes(uint64(len(reply))),
1070 state.payloads <- reply
1074 if state.rxRate > 0 {
1075 time.Sleep(time.Second / time.Duration(state.rxRate))
1081 conn.Close() // #nosec G104
1087 func (state *SPState) Wait() {
1089 close(state.payloads)
1091 state.Duration = time.Now().Sub(state.started)
1093 state.RxSpeed = state.RxBytes
1094 state.TxSpeed = state.TxBytes
1095 rxDuration := int64(state.RxLastSeen.Sub(state.started).Seconds())
1096 txDuration := int64(state.TxLastSeen.Sub(state.started).Seconds())
1098 state.RxSpeed = state.RxBytes / rxDuration
1101 state.TxSpeed = state.TxBytes / txDuration
1103 for _, s := range state.fds {
1106 for pktName := range state.progressBars {
1107 ProgressKill(pktName)
1111 func (state *SPState) ProcessSP(payload []byte) ([][]byte, error) {
1112 les := LEs{{"Node", state.Node.Id}, {"Nice", int(state.Nice)}}
1113 r := bytes.NewReader(payload)
1115 var replies [][]byte
1118 state.Ctx.LogD("sp-process-unmarshal", les, func(les LEs) string {
1120 "SP with %s (nice %s): unmarshaling header",
1121 state.Node.Name, NicenessFmt(state.Nice),
1125 if _, err = xdr.Unmarshal(r, &head); err != nil {
1126 state.Ctx.LogE("sp-process-unmarshal", les, err, func(les LEs) string {
1128 "SP with %s (nice %s): unmarshaling header",
1129 state.Node.Name, NicenessFmt(state.Nice),
1134 if head.Type != SPTypePing {
1135 state.RxLastNonPing = state.RxLastSeen
1141 append(les, LE{"Type", "halt"}), func(les LEs) string {
1143 "SP with %s (nice %s): got HALT",
1144 state.Node.Name, NicenessFmt(state.Nice),
1149 state.queueTheir = nil
1155 append(les, LE{"Type", "ping"}),
1156 func(les LEs) string {
1158 "SP with %s (nice %s): got PING",
1159 state.Node.Name, NicenessFmt(state.Nice),
1166 lesp := append(les, LE{"Type", "info"})
1168 "sp-process-info-unmarshal", lesp,
1169 func(les LEs) string {
1171 "SP with %s (nice %s): unmarshaling INFO",
1172 state.Node.Name, NicenessFmt(state.Nice),
1177 if _, err = xdr.Unmarshal(r, &info); err != nil {
1179 "sp-process-info-unmarshal", lesp, err,
1180 func(les LEs) string {
1182 "SP with %s (nice %s): unmarshaling INFO",
1183 state.Node.Name, NicenessFmt(state.Nice),
1189 pktName := Base32Codec.EncodeToString(info.Hash[:])
1193 LE{"Size", int64(info.Size)},
1194 LE{"PktNice", int(info.Nice)},
1196 logMsg := func(les LEs) string {
1198 "SP with %s (nice %s): INFO %s (%s) nice %s",
1199 state.Node.Name, NicenessFmt(state.Nice),
1201 humanize.IBytes(info.Size),
1202 NicenessFmt(info.Nice),
1205 if !state.listOnly && info.Nice > state.Nice {
1206 state.Ctx.LogD("sp-process-info-too-nice", lesp, func(les LEs) string {
1207 return logMsg(les) + ": too nice"
1211 state.Ctx.LogD("sp-process-info-got", lesp, func(les LEs) string {
1212 return logMsg(les) + ": received"
1214 if !state.listOnly && state.xxOnly == TTx {
1218 state.infosTheir[*info.Hash] = &info
1220 state.Ctx.LogD("sp-process-info-stat", lesp, func(les LEs) string {
1221 return logMsg(les) + ": stating part"
1223 pktPath := filepath.Join(
1225 state.Node.Id.String(),
1227 Base32Codec.EncodeToString(info.Hash[:]),
1229 logMsg = func(les LEs) string {
1231 "Packet %s (%s) (nice %s)",
1233 humanize.IBytes(info.Size),
1234 NicenessFmt(info.Nice),
1237 if _, err = os.Stat(pktPath); err == nil {
1238 state.Ctx.LogI("sp-info-done", lesp, func(les LEs) string {
1239 return logMsg(les) + ": already done"
1241 if !state.listOnly {
1242 replies = append(replies, MarshalSP(SPTypeDone, SPDone{info.Hash}))
1246 if _, err = os.Stat(pktPath + SeenSuffix); err == nil {
1247 state.Ctx.LogI("sp-info-seen", lesp, func(les LEs) string {
1248 return logMsg(les) + ": already seen"
1250 if !state.listOnly {
1251 replies = append(replies, MarshalSP(SPTypeDone, SPDone{info.Hash}))
1255 if _, err = os.Stat(pktPath + NoCKSuffix); err == nil {
1256 state.Ctx.LogI("sp-info-nock", lesp, func(les LEs) string {
1257 return logMsg(les) + ": still not checksummed"
1261 fi, err := os.Stat(pktPath + PartSuffix)
1266 if !state.Ctx.IsEnoughSpace(int64(info.Size) - offset) {
1267 state.Ctx.LogI("sp-info-no-space", lesp, func(les LEs) string {
1268 return logMsg(les) + ": not enough space"
1274 append(lesp, LE{"Offset", offset}),
1275 func(les LEs) string {
1277 "%s: %d%%", logMsg(les), 100*uint64(offset)/info.Size,
1281 if !state.listOnly && (state.onlyPkts == nil || state.onlyPkts[*info.Hash]) {
1282 replies = append(replies, MarshalSP(
1284 SPFreq{info.Hash, uint64(offset)},
1289 lesp := append(les, LE{"Type", "file"})
1290 state.Ctx.LogD("sp-process-file", lesp, func(les LEs) string {
1292 "SP with %s (nice %s): unmarshaling FILE",
1293 state.Node.Name, NicenessFmt(state.Nice),
1297 if _, err = xdr.Unmarshal(r, &file); err != nil {
1298 state.Ctx.LogE("sp-process-file", lesp, err, func(les LEs) string {
1300 "SP with %s (nice %s): unmarshaling FILE",
1301 state.Node.Name, NicenessFmt(state.Nice),
1306 pktName := Base32Codec.EncodeToString(file.Hash[:])
1309 LE{"XX", string(TRx)},
1311 LE{"Size", int64(len(file.Payload))},
1313 logMsg := func(les LEs) string {
1315 "Got packet %s (%s)",
1316 pktName, humanize.IBytes(uint64(len(file.Payload))),
1319 fullsize := int64(0)
1321 infoTheir, ok := state.infosTheir[*file.Hash]
1324 state.Ctx.LogE("sp-file-open", lesp, err, func(les LEs) string {
1325 return logMsg(les) + ": unknown file"
1329 fullsize = int64(infoTheir.Size)
1330 lesp = append(lesp, LE{"FullSize", fullsize})
1331 dirToSync := filepath.Join(
1333 state.Node.Id.String(),
1336 filePath := filepath.Join(dirToSync, pktName)
1337 filePathPart := filePath + PartSuffix
1338 state.Ctx.LogD("sp-file-open", lesp, func(les LEs) string {
1339 return logMsg(les) + ": opening part"
1341 state.fdsLock.RLock()
1342 fdAndFullSize, exists := state.fds[filePathPart]
1343 state.fdsLock.RUnlock()
1344 hasherAndOffset := state.fileHashers[filePath]
1347 fd = fdAndFullSize.fd
1349 fd, err = os.OpenFile(
1351 os.O_RDWR|os.O_CREATE,
1355 state.Ctx.LogE("sp-file-open", lesp, err, func(les LEs) string {
1356 return logMsg(les) + ": opening part"
1360 state.fdsLock.Lock()
1361 state.fds[filePathPart] = FdAndFullSize{fd: fd}
1362 state.fdsLock.Unlock()
1364 hasherAndOffset = &MTHAndOffset{
1365 mth: MTHNew(fullsize, int64(file.Offset)),
1366 offset: file.Offset,
1368 state.fileHashers[filePath] = hasherAndOffset
1373 append(lesp, LE{"Offset", file.Offset}),
1374 func(les LEs) string {
1375 return fmt.Sprintf("%s: seeking %d", logMsg(les), file.Offset)
1377 if _, err = fd.Seek(int64(file.Offset), io.SeekStart); err != nil {
1378 state.Ctx.LogE("sp-file-seek", lesp, err, func(les LEs) string {
1379 return logMsg(les) + ": seeking"
1381 state.closeFd(filePathPart)
1384 state.Ctx.LogD("sp-file-write", lesp, func(les LEs) string {
1385 return logMsg(les) + ": writing"
1387 if _, err = fd.Write(file.Payload); err != nil {
1388 state.Ctx.LogE("sp-file-write", lesp, err, func(les LEs) string {
1389 return logMsg(les) + ": writing"
1391 state.closeFd(filePathPart)
1394 if hasherAndOffset != nil {
1395 if hasherAndOffset.offset == file.Offset {
1396 if _, err = hasherAndOffset.mth.Write(file.Payload); err != nil {
1399 hasherAndOffset.offset += uint64(len(file.Payload))
1402 "sp-file-offset-differs", lesp, errors.New("offset differs"),
1403 func(les LEs) string {
1404 return logMsg(les) + ": deleting hasher"
1407 delete(state.fileHashers, filePath)
1408 hasherAndOffset = nil
1411 ourSize := int64(file.Offset + uint64(len(file.Payload)))
1412 lesp[len(lesp)-2].V = ourSize
1413 if state.Ctx.ShowPrgrs {
1414 state.progressBars[pktName] = struct{}{}
1415 Progress("Rx", lesp)
1417 if fullsize != ourSize {
1420 if state.Ctx.ShowPrgrs {
1421 delete(state.progressBars, pktName)
1423 logMsg = func(les LEs) string {
1425 "Got packet %s %d%% (%s / %s)",
1426 pktName, 100*ourSize/fullsize,
1427 humanize.IBytes(uint64(ourSize)),
1428 humanize.IBytes(uint64(fullsize)),
1433 state.Ctx.LogE("sp-file-sync", lesp, err, func(les LEs) string {
1434 return logMsg(les) + ": syncing"
1436 state.closeFd(filePathPart)
1439 if hasherAndOffset != nil {
1440 delete(state.fileHashers, filePath)
1441 if hasherAndOffset.mth.PrependSize() == 0 {
1442 if bytes.Compare(hasherAndOffset.mth.Sum(nil), file.Hash[:]) != 0 {
1444 "sp-file-bad-checksum", lesp,
1445 errors.New("checksum mismatch"),
1448 state.closeFd(filePathPart)
1451 if err = os.Rename(filePathPart, filePath); err != nil {
1452 state.Ctx.LogE("sp-file-rename", lesp, err, func(les LEs) string {
1453 return logMsg(les) + ": renaming"
1455 state.closeFd(filePathPart)
1458 if err = DirSync(dirToSync); err != nil {
1459 state.Ctx.LogE("sp-file-dirsync", lesp, err, func(les LEs) string {
1460 return logMsg(les) + ": dirsyncing"
1462 state.closeFd(filePathPart)
1465 state.Ctx.LogI("sp-file-done", lesp, func(les LEs) string {
1466 return logMsg(les) + ": done"
1470 state.payloads <- MarshalSP(SPTypeDone, SPDone{file.Hash})
1474 delete(state.infosTheir, *file.Hash)
1476 if !state.Ctx.HdrUsage {
1479 if _, err = fd.Seek(0, io.SeekStart); err != nil {
1480 state.Ctx.LogE("sp-file-seek", lesp, err, func(les LEs) string {
1481 return logMsg(les) + ": seeking"
1483 state.closeFd(filePathPart)
1486 _, pktEncRaw, err := state.Ctx.HdrRead(fd)
1487 state.closeFd(filePathPart)
1489 state.Ctx.LogE("sp-file-hdr-read", lesp, err, func(les LEs) string {
1490 return logMsg(les) + ": HdrReading"
1494 state.Ctx.HdrWrite(pktEncRaw, filePath)
1498 state.closeFd(filePathPart)
1499 if err = os.Rename(filePathPart, filePath+NoCKSuffix); err != nil {
1500 state.Ctx.LogE("sp-file-rename", lesp, err, func(les LEs) string {
1501 return logMsg(les) + ": renaming"
1505 if err = DirSync(dirToSync); err != nil {
1506 state.Ctx.LogE("sp-file-dirsync", lesp, err, func(les LEs) string {
1507 return logMsg(les) + ": dirsyncing"
1511 state.Ctx.LogI("sp-file-downloaded", lesp, func(les LEs) string {
1512 return logMsg(les) + ": downloaded"
1515 delete(state.infosTheir, *file.Hash)
1519 nodeId: state.Node.Id,
1521 done: state.payloads,
1523 if hasherAndOffset != nil {
1524 t.mth = hasherAndOffset.mth
1530 lesp := append(les, LE{"Type", "done"})
1531 state.Ctx.LogD("sp-process-done-unmarshal", lesp, func(les LEs) string {
1533 "SP with %s (nice %s): unmarshaling DONE",
1534 state.Node.Name, NicenessFmt(state.Nice),
1538 if _, err = xdr.Unmarshal(r, &done); err != nil {
1539 state.Ctx.LogE("sp-process-done-unmarshal", lesp, err, func(les LEs) string {
1541 "SP with %s (nice %s): unmarshaling DONE",
1542 state.Node.Name, NicenessFmt(state.Nice),
1547 pktName := Base32Codec.EncodeToString(done.Hash[:])
1548 lesp = append(lesp, LE{"Pkt", pktName}, LE{"XX", string(TTx)})
1549 logMsg := func(les LEs) string {
1551 "SP with %s (nice %s): DONE: removing %s",
1552 state.Node.Name, NicenessFmt(state.Nice), pktName,
1555 state.Ctx.LogD("sp-done", lesp, logMsg)
1556 pth := filepath.Join(
1558 state.Node.Id.String(),
1562 if err = os.Remove(pth); err == nil {
1563 state.Ctx.LogI("sp-done", lesp, func(les LEs) string {
1564 return fmt.Sprintf("Packet %s is sent", pktName)
1566 if state.Ctx.HdrUsage {
1567 os.Remove(pth + HdrSuffix)
1570 state.Ctx.LogE("sp-done", lesp, err, logMsg)
1574 lesp := append(les, LE{"Type", "freq"})
1575 state.Ctx.LogD("sp-process-freq", lesp, func(les LEs) string {
1577 "SP with %s (nice %s): unmarshaling FREQ",
1578 state.Node.Name, NicenessFmt(state.Nice),
1582 if _, err = xdr.Unmarshal(r, &freq); err != nil {
1583 state.Ctx.LogE("sp-process-freq", lesp, err, func(les LEs) string {
1585 "SP with %s (nice %s): unmarshaling FREQ",
1586 state.Node.Name, NicenessFmt(state.Nice),
1591 pktName := Base32Codec.EncodeToString(freq.Hash[:])
1592 lesp = append(lesp, LE{"Pkt", pktName}, LE{"Offset", freq.Offset})
1593 state.Ctx.LogD("sp-process-freq-queueing", lesp, func(les LEs) string {
1595 "SP with %s (nice %s): FREQ %s: queuing",
1596 state.Node.Name, NicenessFmt(state.Nice), pktName,
1599 nice, exists := state.infosOurSeen[*freq.Hash]
1601 if state.onlyPkts == nil || !state.onlyPkts[*freq.Hash] {
1604 var freqWithNice *FreqWithNice
1605 for insertIdx, freqWithNice = range state.queueTheir {
1606 if freqWithNice.nice > nice {
1610 state.queueTheir = append(state.queueTheir, nil)
1611 copy(state.queueTheir[insertIdx+1:], state.queueTheir[insertIdx:])
1612 state.queueTheir[insertIdx] = &FreqWithNice{&freq, nice}
1615 state.Ctx.LogD("sp-process-freq-skip", lesp, func(les LEs) string {
1617 "SP with %s (nice %s): FREQ %s: skipping",
1618 state.Node.Name, NicenessFmt(state.Nice), pktName,
1623 state.Ctx.LogD("sp-process-freq-unknown", lesp, func(les LEs) string {
1625 "SP with %s (nice %s): FREQ %s: unknown",
1626 state.Node.Name, NicenessFmt(state.Nice), pktName,
1633 "sp-process-type-unknown",
1634 append(les, LE{"Type", head.Type}),
1635 errors.New("unknown type"),
1636 func(les LEs) string {
1638 "SP with %s (nice %s): %d",
1639 state.Node.Name, NicenessFmt(state.Nice), head.Type,
1643 return nil, BadPktType
1651 for _, info := range state.infosTheir {
1656 state.Ctx.LogI("sp-infos-rx", LEs{
1657 {"XX", string(TRx)},
1658 {"Node", state.Node.Id},
1660 {"Size", int64(size)},
1661 }, func(les LEs) string {
1663 "%s has got for us: %d packets, %s",
1664 state.Node.Name, pkts, humanize.IBytes(size),
1668 return payloadsSplit(replies), nil
1671 func SPChecker(ctx *Ctx) {
1672 for t := range spCheckerTasks {
1673 pktName := Base32Codec.EncodeToString(t.hsh[:])
1675 {"XX", string(TRx)},
1680 ctx.LogD("sp-checker", les, func(les LEs) string {
1681 return fmt.Sprintf("Checksumming %s/rx/%s", ctx.NodeName(t.nodeId), pktName)
1683 size, err := ctx.CheckNoCK(t.nodeId, t.hsh, t.mth)
1684 les = append(les, LE{"Size", size})
1686 ctx.LogE("sp-checker", les, err, func(les LEs) string {
1688 "Checksumming %s/rx/%s (%s)", ctx.NodeName(t.nodeId), pktName,
1689 humanize.IBytes(uint64(size)),
1695 ctx.LogI("sp-checker-done", les, func(les LEs) string {
1697 "Packet %s is retreived (%s)",
1698 pktName, humanize.IBytes(uint64(size)),
1702 go func(t SPCheckerTask) {
1703 defer func() { recover() }()
1704 t.done <- MarshalSP(SPTypeDone, SPDone{t.hsh})