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) })
663 // Remaining handshake payload sending
664 if len(infosPayloads) > 1 {
667 for _, payload := range infosPayloads[1:] {
669 "sp-queue-remaining",
670 append(les, LE{"Size", int64(len(payload))}),
671 func(les LEs) string {
673 "SP with %s (nice %s): queuing remaining payload (%s)",
674 state.Node.Name, NicenessFmt(state.Nice),
675 humanize.IBytes(uint64(len(payload))),
679 state.payloads <- payload
685 // Processing of first payload and queueing its responses
686 logMsg := func(les LEs) string {
688 "SP with %s (nice %s): processing first payload (%s)",
689 state.Node.Name, NicenessFmt(state.Nice),
690 humanize.IBytes(uint64(len(payload))),
693 state.Ctx.LogD("sp-process", append(les, LE{"Size", int64(len(payload))}), logMsg)
694 replies, err := state.ProcessSP(payload)
696 state.Ctx.LogE("sp-process", les, err, logMsg)
701 for _, reply := range replies {
704 append(les, LE{"Size", int64(len(reply))}),
705 func(les LEs) string {
707 "SP with %s (nice %s): queuing reply (%s)",
708 state.Node.Name, NicenessFmt(state.Nice),
709 humanize.IBytes(uint64(len(payload))),
713 state.payloads <- reply
721 deadlineTicker := time.NewTicker(time.Second)
722 pingTicker := time.NewTicker(PingTimeout)
727 deadlineTicker.Stop()
730 case now := <-deadlineTicker.C:
731 if now.Sub(state.RxLastNonPing) >= state.onlineDeadline &&
732 now.Sub(state.TxLastNonPing) >= state.onlineDeadline {
735 if state.maxOnlineTime > 0 && state.mustFinishAt.Before(now) {
738 if now.Sub(state.RxLastSeen) >= 2*PingTimeout {
744 conn.Close() // #nosec G104
745 case now := <-pingTicker.C:
746 if now.After(state.TxLastSeen.Add(PingTimeout)) {
749 state.pings <- struct{}{}
757 // Spool checker and INFOs sender of appearing files
758 if !state.listOnly && (state.xxOnly == "" || state.xxOnly == TTx) {
761 ticker := time.NewTicker(time.Second)
769 for _, payload := range state.Ctx.infosOur(
776 append(les, LE{"Size", int64(len(payload))}),
777 func(les LEs) string {
779 "SP with %s (nice %s): queuing new info (%s)",
780 state.Node.Name, NicenessFmt(state.Nice),
781 humanize.IBytes(uint64(len(payload))),
785 state.payloads <- payload
796 defer state.SetDead()
797 defer state.wg.Done()
799 if state.NotAlive() {
806 state.Ctx.LogD("sp-got-ping", les, func(les LEs) string {
808 "SP with %s (nice %s): got ping",
809 state.Node.Name, NicenessFmt(state.Nice),
812 payload = SPPingMarshalized
814 case payload = <-state.payloads:
817 append(les, LE{"Size", int64(len(payload))}),
818 func(les LEs) string {
820 "SP with %s (nice %s): got payload (%s)",
821 state.Node.Name, NicenessFmt(state.Nice),
822 humanize.IBytes(uint64(len(payload))),
828 if len(state.queueTheir) == 0 {
830 time.Sleep(100 * time.Millisecond)
833 freq := state.queueTheir[0].freq
835 if state.txRate > 0 {
836 time.Sleep(time.Second / time.Duration(state.txRate))
838 pktName := Base32Codec.EncodeToString(freq.Hash[:])
841 LE{"XX", string(TTx)},
843 LE{"Size", int64(freq.Offset)},
845 logMsg := func(les LEs) string {
847 "SP with %s (nice %s): tx/%s (%s)",
848 state.Node.Name, NicenessFmt(state.Nice),
850 humanize.IBytes(freq.Offset),
853 state.Ctx.LogD("sp-queue", lesp, func(les LEs) string {
854 return logMsg(les) + ": queueing"
856 pth := filepath.Join(
858 state.Node.Id.String(),
860 Base32Codec.EncodeToString(freq.Hash[:]),
862 state.fdsLock.RLock()
863 fdAndFullSize, exists := state.fds[pth]
864 state.fdsLock.RUnlock()
866 fd, err := os.Open(pth)
868 state.Ctx.LogE("sp-queue-open", lesp, err, func(les LEs) string {
869 return logMsg(les) + ": opening"
875 state.Ctx.LogE("sp-queue-stat", lesp, err, func(les LEs) string {
876 return logMsg(les) + ": stating"
880 fdAndFullSize = FdAndFullSize{fd: fd, fullSize: fi.Size()}
882 state.fds[pth] = fdAndFullSize
883 state.fdsLock.Unlock()
885 fd := fdAndFullSize.fd
886 fullSize := fdAndFullSize.fullSize
888 if freq.Offset < uint64(fullSize) {
889 state.Ctx.LogD("sp-file-seek", lesp, func(les LEs) string {
890 return logMsg(les) + ": seeking"
892 if _, err = fd.Seek(int64(freq.Offset), io.SeekStart); err != nil {
893 state.Ctx.LogE("sp-file-seek", lesp, err, func(les LEs) string {
894 return logMsg(les) + ": seeking"
898 buf = make([]byte, MaxSPSize-SPHeadOverhead-SPFileOverhead)
899 n, err := fd.Read(buf)
901 state.Ctx.LogE("sp-file-read", lesp, err, func(les LEs) string {
902 return logMsg(les) + ": reading"
909 LE{"XX", string(TTx)},
911 LE{"Size", int64(n)},
913 state.Ctx.LogD("sp-file-read", lesp, func(les LEs) string {
916 logMsg(les), humanize.IBytes(uint64(n)),
921 payload = MarshalSP(SPTypeFile, SPFile{
926 ourSize := freq.Offset + uint64(len(buf))
929 LE{"XX", string(TTx)},
931 LE{"Size", int64(ourSize)},
932 LE{"FullSize", fullSize},
934 if state.Ctx.ShowPrgrs {
935 state.progressBars[pktName] = struct{}{}
939 if len(state.queueTheir) > 0 && *state.queueTheir[0].freq.Hash == *freq.Hash {
940 if ourSize == uint64(fullSize) {
941 state.Ctx.LogD("sp-file-finished", lesp, func(les LEs) string {
942 return logMsg(les) + ": finished"
944 if len(state.queueTheir) > 1 {
945 state.queueTheir = state.queueTheir[1:]
947 state.queueTheir = state.queueTheir[:0]
949 if state.Ctx.ShowPrgrs {
950 delete(state.progressBars, pktName)
953 state.queueTheir[0].freq.Offset += uint64(len(buf))
956 state.Ctx.LogD("sp-file-disappeared", lesp, func(les LEs) string {
957 return logMsg(les) + ": queue disappeared"
962 logMsg := func(les LEs) string {
964 "SP with %s (nice %s): sending %s",
965 state.Node.Name, NicenessFmt(state.Nice),
966 humanize.IBytes(uint64(len(payload))),
969 state.Ctx.LogD("sp-sending", append(les, LE{"Size", int64(len(payload))}), logMsg)
970 conn.SetWriteDeadline(time.Now().Add(DefaultDeadline)) // #nosec G104
971 ct, err := state.csOur.Encrypt(nil, nil, payload)
973 state.Ctx.LogE("sp-encrypting", les, err, logMsg)
976 if err := state.WriteSP(conn, ct, ping); err != nil {
977 state.Ctx.LogE("sp-sending", les, err, logMsg)
987 if state.NotAlive() {
990 logMsg := func(les LEs) string {
992 "SP with %s (nice %s): waiting for payload",
993 state.Node.Name, NicenessFmt(state.Nice),
996 state.Ctx.LogD("sp-recv-wait", les, logMsg)
997 conn.SetReadDeadline(time.Now().Add(DefaultDeadline)) // #nosec G104
998 payload, err := state.ReadSP(conn)
1003 unmarshalErr := err.(*xdr.UnmarshalError)
1004 if os.IsTimeout(unmarshalErr.Err) {
1007 if unmarshalErr.ErrorCode == xdr.ErrIO {
1010 state.Ctx.LogE("sp-recv-wait", les, err, logMsg)
1013 logMsg = func(les LEs) string {
1015 "SP with %s (nice %s): payload (%s)",
1016 state.Node.Name, NicenessFmt(state.Nice),
1017 humanize.IBytes(uint64(len(payload))),
1022 append(les, LE{"Size", int64(len(payload))}),
1023 func(les LEs) string { return logMsg(les) + ": got" },
1025 payload, err = state.csTheir.Decrypt(nil, nil, payload)
1027 state.Ctx.LogE("sp-recv-got", les, err, func(les LEs) string {
1028 return logMsg(les) + ": got"
1034 append(les, LE{"Size", int64(len(payload))}),
1035 func(les LEs) string {
1036 return logMsg(les) + ": processing"
1039 replies, err := state.ProcessSP(payload)
1041 state.Ctx.LogE("sp-recv-process", les, err, func(les LEs) string {
1042 return logMsg(les) + ": processing"
1048 for _, reply := range replies {
1051 append(les[:len(les)-1], LE{"Size", int64(len(reply))}),
1052 func(les LEs) string {
1054 "SP with %s (nice %s): queuing reply (%s)",
1055 state.Node.Name, NicenessFmt(state.Nice),
1056 humanize.IBytes(uint64(len(reply))),
1060 state.payloads <- reply
1064 if state.rxRate > 0 {
1065 time.Sleep(time.Second / time.Duration(state.rxRate))
1071 conn.Close() // #nosec G104
1077 func (state *SPState) Wait() {
1079 close(state.payloads)
1081 state.Duration = time.Now().Sub(state.started)
1083 state.RxSpeed = state.RxBytes
1084 state.TxSpeed = state.TxBytes
1085 rxDuration := int64(state.RxLastSeen.Sub(state.started).Seconds())
1086 txDuration := int64(state.TxLastSeen.Sub(state.started).Seconds())
1088 state.RxSpeed = state.RxBytes / rxDuration
1091 state.TxSpeed = state.TxBytes / txDuration
1093 for _, s := range state.fds {
1096 for pktName := range state.progressBars {
1097 ProgressKill(pktName)
1101 func (state *SPState) ProcessSP(payload []byte) ([][]byte, error) {
1102 les := LEs{{"Node", state.Node.Id}, {"Nice", int(state.Nice)}}
1103 r := bytes.NewReader(payload)
1105 var replies [][]byte
1108 state.Ctx.LogD("sp-process-unmarshal", les, func(les LEs) string {
1110 "SP with %s (nice %s): unmarshaling header",
1111 state.Node.Name, NicenessFmt(state.Nice),
1115 if _, err = xdr.Unmarshal(r, &head); err != nil {
1116 state.Ctx.LogE("sp-process-unmarshal", les, err, func(les LEs) string {
1118 "SP with %s (nice %s): unmarshaling header",
1119 state.Node.Name, NicenessFmt(state.Nice),
1124 if head.Type != SPTypePing {
1125 state.RxLastNonPing = state.RxLastSeen
1131 append(les, LE{"Type", "halt"}), func(les LEs) string {
1133 "SP with %s (nice %s): got HALT",
1134 state.Node.Name, NicenessFmt(state.Nice),
1139 state.queueTheir = nil
1145 append(les, LE{"Type", "ping"}),
1146 func(les LEs) string {
1148 "SP with %s (nice %s): got PING",
1149 state.Node.Name, NicenessFmt(state.Nice),
1156 lesp := append(les, LE{"Type", "info"})
1158 "sp-process-info-unmarshal", lesp,
1159 func(les LEs) string {
1161 "SP with %s (nice %s): unmarshaling INFO",
1162 state.Node.Name, NicenessFmt(state.Nice),
1167 if _, err = xdr.Unmarshal(r, &info); err != nil {
1169 "sp-process-info-unmarshal", lesp, err,
1170 func(les LEs) string {
1172 "SP with %s (nice %s): unmarshaling INFO",
1173 state.Node.Name, NicenessFmt(state.Nice),
1179 pktName := Base32Codec.EncodeToString(info.Hash[:])
1183 LE{"Size", int64(info.Size)},
1184 LE{"PktNice", int(info.Nice)},
1186 logMsg := func(les LEs) string {
1188 "SP with %s (nice %s): INFO %s (%s) nice %s",
1189 state.Node.Name, NicenessFmt(state.Nice),
1191 humanize.IBytes(info.Size),
1192 NicenessFmt(info.Nice),
1195 if !state.listOnly && info.Nice > state.Nice {
1196 state.Ctx.LogD("sp-process-info-too-nice", lesp, func(les LEs) string {
1197 return logMsg(les) + ": too nice"
1201 state.Ctx.LogD("sp-process-info-got", lesp, func(les LEs) string {
1202 return logMsg(les) + ": received"
1204 if !state.listOnly && state.xxOnly == TTx {
1208 state.infosTheir[*info.Hash] = &info
1210 state.Ctx.LogD("sp-process-info-stat", lesp, func(les LEs) string {
1211 return logMsg(les) + ": stating part"
1213 pktPath := filepath.Join(
1215 state.Node.Id.String(),
1217 Base32Codec.EncodeToString(info.Hash[:]),
1219 logMsg = func(les LEs) string {
1221 "Packet %s (%s) (nice %s)",
1223 humanize.IBytes(info.Size),
1224 NicenessFmt(info.Nice),
1227 if _, err = os.Stat(pktPath); err == nil {
1228 state.Ctx.LogI("sp-info-done", lesp, func(les LEs) string {
1229 return logMsg(les) + ": already done"
1231 if !state.listOnly {
1232 replies = append(replies, MarshalSP(SPTypeDone, SPDone{info.Hash}))
1236 if _, err = os.Stat(pktPath + SeenSuffix); err == nil {
1237 state.Ctx.LogI("sp-info-seen", lesp, func(les LEs) string {
1238 return logMsg(les) + ": already seen"
1240 if !state.listOnly {
1241 replies = append(replies, MarshalSP(SPTypeDone, SPDone{info.Hash}))
1245 if _, err = os.Stat(pktPath + NoCKSuffix); err == nil {
1246 state.Ctx.LogI("sp-info-nock", lesp, func(les LEs) string {
1247 return logMsg(les) + ": still not checksummed"
1251 fi, err := os.Stat(pktPath + PartSuffix)
1256 if !state.Ctx.IsEnoughSpace(int64(info.Size) - offset) {
1257 state.Ctx.LogI("sp-info-no-space", lesp, func(les LEs) string {
1258 return logMsg(les) + ": not enough space"
1264 append(lesp, LE{"Offset", offset}),
1265 func(les LEs) string {
1267 "%s: %d%%", logMsg(les), 100*uint64(offset)/info.Size,
1271 if !state.listOnly && (state.onlyPkts == nil || state.onlyPkts[*info.Hash]) {
1272 replies = append(replies, MarshalSP(
1274 SPFreq{info.Hash, uint64(offset)},
1279 lesp := append(les, LE{"Type", "file"})
1280 state.Ctx.LogD("sp-process-file", lesp, func(les LEs) string {
1282 "SP with %s (nice %s): unmarshaling FILE",
1283 state.Node.Name, NicenessFmt(state.Nice),
1287 if _, err = xdr.Unmarshal(r, &file); err != nil {
1288 state.Ctx.LogE("sp-process-file", lesp, err, func(les LEs) string {
1290 "SP with %s (nice %s): unmarshaling FILE",
1291 state.Node.Name, NicenessFmt(state.Nice),
1296 pktName := Base32Codec.EncodeToString(file.Hash[:])
1299 LE{"XX", string(TRx)},
1301 LE{"Size", int64(len(file.Payload))},
1303 logMsg := func(les LEs) string {
1305 "Got packet %s (%s)",
1306 pktName, humanize.IBytes(uint64(len(file.Payload))),
1309 fullsize := int64(0)
1311 infoTheir, ok := state.infosTheir[*file.Hash]
1314 state.Ctx.LogE("sp-file-open", lesp, err, func(les LEs) string {
1315 return logMsg(les) + ": unknown file"
1319 fullsize = int64(infoTheir.Size)
1320 lesp = append(lesp, LE{"FullSize", fullsize})
1321 dirToSync := filepath.Join(
1323 state.Node.Id.String(),
1326 filePath := filepath.Join(dirToSync, pktName)
1327 filePathPart := filePath + PartSuffix
1328 state.Ctx.LogD("sp-file-open", lesp, func(les LEs) string {
1329 return logMsg(les) + ": opening part"
1331 state.fdsLock.RLock()
1332 fdAndFullSize, exists := state.fds[filePathPart]
1333 state.fdsLock.RUnlock()
1334 hasherAndOffset := state.fileHashers[filePath]
1337 fd = fdAndFullSize.fd
1339 fd, err = os.OpenFile(
1341 os.O_RDWR|os.O_CREATE,
1345 state.Ctx.LogE("sp-file-open", lesp, err, func(les LEs) string {
1346 return logMsg(les) + ": opening part"
1350 state.fdsLock.Lock()
1351 state.fds[filePathPart] = FdAndFullSize{fd: fd}
1352 state.fdsLock.Unlock()
1354 hasherAndOffset = &MTHAndOffset{
1355 mth: MTHNew(fullsize, int64(file.Offset)),
1356 offset: file.Offset,
1358 state.fileHashers[filePath] = hasherAndOffset
1363 append(lesp, LE{"Offset", file.Offset}),
1364 func(les LEs) string {
1365 return fmt.Sprintf("%s: seeking %d", logMsg(les), file.Offset)
1367 if _, err = fd.Seek(int64(file.Offset), io.SeekStart); err != nil {
1368 state.Ctx.LogE("sp-file-seek", lesp, err, func(les LEs) string {
1369 return logMsg(les) + ": seeking"
1371 state.closeFd(filePathPart)
1374 state.Ctx.LogD("sp-file-write", lesp, func(les LEs) string {
1375 return logMsg(les) + ": writing"
1377 if _, err = fd.Write(file.Payload); err != nil {
1378 state.Ctx.LogE("sp-file-write", lesp, err, func(les LEs) string {
1379 return logMsg(les) + ": writing"
1381 state.closeFd(filePathPart)
1384 if hasherAndOffset != nil {
1385 if hasherAndOffset.offset == file.Offset {
1386 if _, err = hasherAndOffset.mth.Write(file.Payload); err != nil {
1389 hasherAndOffset.offset += uint64(len(file.Payload))
1392 "sp-file-offset-differs", lesp, errors.New("offset differs"),
1393 func(les LEs) string {
1394 return logMsg(les) + ": deleting hasher"
1397 delete(state.fileHashers, filePath)
1398 hasherAndOffset = nil
1401 ourSize := int64(file.Offset + uint64(len(file.Payload)))
1402 lesp[len(lesp)-2].V = ourSize
1403 if state.Ctx.ShowPrgrs {
1404 state.progressBars[pktName] = struct{}{}
1405 Progress("Rx", lesp)
1407 if fullsize != ourSize {
1410 if state.Ctx.ShowPrgrs {
1411 delete(state.progressBars, pktName)
1413 logMsg = func(les LEs) string {
1415 "Got packet %s %d%% (%s / %s)",
1416 pktName, 100*ourSize/fullsize,
1417 humanize.IBytes(uint64(ourSize)),
1418 humanize.IBytes(uint64(fullsize)),
1423 state.Ctx.LogE("sp-file-sync", lesp, err, func(les LEs) string {
1424 return logMsg(les) + ": syncing"
1426 state.closeFd(filePathPart)
1429 if hasherAndOffset != nil {
1430 delete(state.fileHashers, filePath)
1431 if hasherAndOffset.mth.PrependSize == 0 {
1432 if bytes.Compare(hasherAndOffset.mth.Sum(nil), file.Hash[:]) != 0 {
1434 "sp-file-bad-checksum", lesp,
1435 errors.New("checksum mismatch"),
1438 state.closeFd(filePathPart)
1441 if err = os.Rename(filePathPart, filePath); err != nil {
1442 state.Ctx.LogE("sp-file-rename", lesp, err, func(les LEs) string {
1443 return logMsg(les) + ": renaming"
1445 state.closeFd(filePathPart)
1448 if err = DirSync(dirToSync); err != nil {
1449 state.Ctx.LogE("sp-file-dirsync", lesp, err, func(les LEs) string {
1450 return logMsg(les) + ": dirsyncing"
1452 state.closeFd(filePathPart)
1455 state.Ctx.LogI("sp-file-done", lesp, func(les LEs) string {
1456 return logMsg(les) + ": done"
1460 state.payloads <- MarshalSP(SPTypeDone, SPDone{file.Hash})
1464 delete(state.infosTheir, *file.Hash)
1466 if !state.Ctx.HdrUsage {
1469 if _, err = fd.Seek(0, io.SeekStart); err != nil {
1470 state.Ctx.LogE("sp-file-seek", lesp, err, func(les LEs) string {
1471 return logMsg(les) + ": seeking"
1473 state.closeFd(filePathPart)
1476 _, pktEncRaw, err := state.Ctx.HdrRead(fd)
1477 state.closeFd(filePathPart)
1479 state.Ctx.LogE("sp-file-hdr-read", lesp, err, func(les LEs) string {
1480 return logMsg(les) + ": HdrReading"
1484 state.Ctx.HdrWrite(pktEncRaw, filePath)
1488 state.closeFd(filePathPart)
1489 if err = os.Rename(filePathPart, filePath+NoCKSuffix); err != nil {
1490 state.Ctx.LogE("sp-file-rename", lesp, err, func(les LEs) string {
1491 return logMsg(les) + ": renaming"
1495 if err = DirSync(dirToSync); err != nil {
1496 state.Ctx.LogE("sp-file-dirsync", lesp, err, func(les LEs) string {
1497 return logMsg(les) + ": dirsyncing"
1501 state.Ctx.LogI("sp-file-downloaded", lesp, func(les LEs) string {
1502 return logMsg(les) + ": downloaded"
1505 delete(state.infosTheir, *file.Hash)
1507 if hasherAndOffset != nil {
1509 spCheckerTasks <- SPCheckerTask{
1510 nodeId: state.Node.Id,
1512 mth: hasherAndOffset.mth,
1513 done: state.payloads,
1519 lesp := append(les, LE{"Type", "done"})
1520 state.Ctx.LogD("sp-process-done-unmarshal", lesp, func(les LEs) string {
1522 "SP with %s (nice %s): unmarshaling DONE",
1523 state.Node.Name, NicenessFmt(state.Nice),
1527 if _, err = xdr.Unmarshal(r, &done); err != nil {
1528 state.Ctx.LogE("sp-process-done-unmarshal", lesp, err, func(les LEs) string {
1530 "SP with %s (nice %s): unmarshaling DONE",
1531 state.Node.Name, NicenessFmt(state.Nice),
1536 pktName := Base32Codec.EncodeToString(done.Hash[:])
1537 lesp = append(lesp, LE{"Pkt", pktName}, LE{"XX", string(TTx)})
1538 logMsg := func(les LEs) string {
1540 "SP with %s (nice %s): DONE: removing %s",
1541 state.Node.Name, NicenessFmt(state.Nice), pktName,
1544 state.Ctx.LogD("sp-done", lesp, logMsg)
1545 pth := filepath.Join(
1547 state.Node.Id.String(),
1551 if err = os.Remove(pth); err == nil {
1552 state.Ctx.LogI("sp-done", lesp, func(les LEs) string {
1553 return fmt.Sprintf("Packet %s is sent", pktName)
1555 if state.Ctx.HdrUsage {
1556 os.Remove(pth + HdrSuffix)
1559 state.Ctx.LogE("sp-done", lesp, err, logMsg)
1563 lesp := append(les, LE{"Type", "freq"})
1564 state.Ctx.LogD("sp-process-freq", lesp, func(les LEs) string {
1566 "SP with %s (nice %s): unmarshaling FREQ",
1567 state.Node.Name, NicenessFmt(state.Nice),
1571 if _, err = xdr.Unmarshal(r, &freq); err != nil {
1572 state.Ctx.LogE("sp-process-freq", lesp, err, func(les LEs) string {
1574 "SP with %s (nice %s): unmarshaling FREQ",
1575 state.Node.Name, NicenessFmt(state.Nice),
1580 pktName := Base32Codec.EncodeToString(freq.Hash[:])
1581 lesp = append(lesp, LE{"Pkt", pktName}, LE{"Offset", freq.Offset})
1582 state.Ctx.LogD("sp-process-freq-queueing", lesp, func(les LEs) string {
1584 "SP with %s (nice %s): FREQ %s: queuing",
1585 state.Node.Name, NicenessFmt(state.Nice), pktName,
1588 nice, exists := state.infosOurSeen[*freq.Hash]
1590 if state.onlyPkts == nil || !state.onlyPkts[*freq.Hash] {
1593 var freqWithNice *FreqWithNice
1594 for insertIdx, freqWithNice = range state.queueTheir {
1595 if freqWithNice.nice > nice {
1599 state.queueTheir = append(state.queueTheir, nil)
1600 copy(state.queueTheir[insertIdx+1:], state.queueTheir[insertIdx:])
1601 state.queueTheir[insertIdx] = &FreqWithNice{&freq, nice}
1604 state.Ctx.LogD("sp-process-freq-skip", lesp, func(les LEs) string {
1606 "SP with %s (nice %s): FREQ %s: skipping",
1607 state.Node.Name, NicenessFmt(state.Nice), pktName,
1612 state.Ctx.LogD("sp-process-freq-unknown", lesp, func(les LEs) string {
1614 "SP with %s (nice %s): FREQ %s: unknown",
1615 state.Node.Name, NicenessFmt(state.Nice), pktName,
1622 "sp-process-type-unknown",
1623 append(les, LE{"Type", head.Type}),
1624 errors.New("unknown type"),
1625 func(les LEs) string {
1627 "SP with %s (nice %s): %d",
1628 state.Node.Name, NicenessFmt(state.Nice), head.Type,
1632 return nil, BadPktType
1640 for _, info := range state.infosTheir {
1645 state.Ctx.LogI("sp-infos-rx", LEs{
1646 {"XX", string(TRx)},
1647 {"Node", state.Node.Id},
1649 {"Size", int64(size)},
1650 }, func(les LEs) string {
1652 "%s has got for us: %d packets, %s",
1653 state.Node.Name, pkts, humanize.IBytes(size),
1657 return payloadsSplit(replies), nil
1660 func SPChecker(ctx *Ctx) {
1661 for t := range spCheckerTasks {
1662 pktName := Base32Codec.EncodeToString(t.hsh[:])
1664 {"XX", string(TRx)},
1669 ctx.LogD("sp-checker", les, func(les LEs) string {
1670 return fmt.Sprintf("Checksumming %s/rx/%s", ctx.NodeName(t.nodeId), pktName)
1672 size, err := ctx.CheckNoCK(t.nodeId, t.hsh, t.mth)
1673 les = append(les, LE{"Size", size})
1675 ctx.LogE("sp-checker", les, err, func(les LEs) string {
1677 "Checksumming %s/rx/%s (%s)", ctx.NodeName(t.nodeId), pktName,
1678 humanize.IBytes(uint64(size)),
1684 ctx.LogI("sp-checker-done", les, func(les LEs) string {
1686 "Packet %s is retreived (%s)",
1687 pktName, humanize.IBytes(uint64(size)),
1691 go func(t SPCheckerTask) {
1692 defer func() { recover() }()
1693 t.done <- MarshalSP(SPTypeDone, SPDone{t.hsh})