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()
810 if state.NotAlive() {
817 state.Ctx.LogD("sp-got-ping", les, func(les LEs) string {
819 "SP with %s (nice %s): got ping",
820 state.Node.Name, NicenessFmt(state.Nice),
823 payload = SPPingMarshalized
825 case payload = <-state.payloads:
828 append(les, LE{"Size", int64(len(payload))}),
829 func(les LEs) string {
831 "SP with %s (nice %s): got payload (%s)",
832 state.Node.Name, NicenessFmt(state.Nice),
833 humanize.IBytes(uint64(len(payload))),
839 if len(state.queueTheir) == 0 {
841 time.Sleep(100 * time.Millisecond)
844 freq := state.queueTheir[0].freq
846 if state.txRate > 0 {
847 time.Sleep(time.Second / time.Duration(state.txRate))
849 pktName := Base32Codec.EncodeToString(freq.Hash[:])
852 LE{"XX", string(TTx)},
854 LE{"Size", int64(freq.Offset)},
856 logMsg := func(les LEs) string {
858 "SP with %s (nice %s): tx/%s (%s)",
859 state.Node.Name, NicenessFmt(state.Nice),
861 humanize.IBytes(freq.Offset),
864 state.Ctx.LogD("sp-queue", lesp, func(les LEs) string {
865 return logMsg(les) + ": queueing"
867 pth := filepath.Join(
869 state.Node.Id.String(),
871 Base32Codec.EncodeToString(freq.Hash[:]),
873 state.fdsLock.RLock()
874 fdAndFullSize, exists := state.fds[pth]
875 state.fdsLock.RUnlock()
877 fd, err := os.Open(pth)
879 state.Ctx.LogE("sp-queue-open", lesp, err, func(les LEs) string {
880 return logMsg(les) + ": opening"
886 state.Ctx.LogE("sp-queue-stat", lesp, err, func(les LEs) string {
887 return logMsg(les) + ": stating"
891 fdAndFullSize = FdAndFullSize{fd: fd, fullSize: fi.Size()}
893 state.fds[pth] = fdAndFullSize
894 state.fdsLock.Unlock()
896 fd := fdAndFullSize.fd
897 fullSize := fdAndFullSize.fullSize
899 if freq.Offset < uint64(fullSize) {
900 state.Ctx.LogD("sp-file-seek", lesp, func(les LEs) string {
901 return logMsg(les) + ": seeking"
903 if _, err = fd.Seek(int64(freq.Offset), io.SeekStart); err != nil {
904 state.Ctx.LogE("sp-file-seek", lesp, err, func(les LEs) string {
905 return logMsg(les) + ": seeking"
909 buf = make([]byte, MaxSPSize-SPHeadOverhead-SPFileOverhead)
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(buf))
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 if len(state.queueTheir) > 0 && *state.queueTheir[0].freq.Hash == *freq.Hash {
951 if ourSize == uint64(fullSize) {
952 state.Ctx.LogD("sp-file-finished", lesp, func(les LEs) string {
953 return logMsg(les) + ": finished"
955 if len(state.queueTheir) > 1 {
956 state.queueTheir = state.queueTheir[1:]
958 state.queueTheir = state.queueTheir[:0]
960 if state.Ctx.ShowPrgrs {
961 delete(state.progressBars, pktName)
964 state.queueTheir[0].freq.Offset += uint64(len(buf))
967 state.Ctx.LogD("sp-file-disappeared", lesp, func(les LEs) string {
968 return logMsg(les) + ": queue disappeared"
973 logMsg := func(les LEs) string {
975 "SP with %s (nice %s): sending %s",
976 state.Node.Name, NicenessFmt(state.Nice),
977 humanize.IBytes(uint64(len(payload))),
980 state.Ctx.LogD("sp-sending", append(les, LE{"Size", int64(len(payload))}), logMsg)
981 conn.SetWriteDeadline(time.Now().Add(DefaultDeadline)) // #nosec G104
982 ct, err := state.csOur.Encrypt(nil, nil, payload)
984 state.Ctx.LogE("sp-encrypting", les, err, logMsg)
987 if err := state.WriteSP(conn, ct, ping); err != nil {
988 state.Ctx.LogE("sp-sending", les, err, logMsg)
998 if state.NotAlive() {
1001 logMsg := func(les LEs) string {
1003 "SP with %s (nice %s): waiting for payload",
1004 state.Node.Name, NicenessFmt(state.Nice),
1007 state.Ctx.LogD("sp-recv-wait", les, logMsg)
1008 conn.SetReadDeadline(time.Now().Add(DefaultDeadline)) // #nosec G104
1009 payload, err := state.ReadSP(conn)
1014 unmarshalErr := err.(*xdr.UnmarshalError)
1015 if os.IsTimeout(unmarshalErr.Err) {
1018 if unmarshalErr.ErrorCode == xdr.ErrIO {
1021 state.Ctx.LogE("sp-recv-wait", les, err, logMsg)
1024 logMsg = func(les LEs) string {
1026 "SP with %s (nice %s): payload (%s)",
1027 state.Node.Name, NicenessFmt(state.Nice),
1028 humanize.IBytes(uint64(len(payload))),
1033 append(les, LE{"Size", int64(len(payload))}),
1034 func(les LEs) string { return logMsg(les) + ": got" },
1036 payload, err = state.csTheir.Decrypt(nil, nil, payload)
1038 state.Ctx.LogE("sp-recv-got", les, err, func(les LEs) string {
1039 return logMsg(les) + ": got"
1045 append(les, LE{"Size", int64(len(payload))}),
1046 func(les LEs) string {
1047 return logMsg(les) + ": processing"
1050 replies, err := state.ProcessSP(payload)
1052 state.Ctx.LogE("sp-recv-process", les, err, func(les LEs) string {
1053 return logMsg(les) + ": processing"
1059 for _, reply := range replies {
1062 append(les[:len(les)-1], LE{"Size", int64(len(reply))}),
1063 func(les LEs) string {
1065 "SP with %s (nice %s): queuing reply (%s)",
1066 state.Node.Name, NicenessFmt(state.Nice),
1067 humanize.IBytes(uint64(len(reply))),
1071 state.payloads <- reply
1075 if state.rxRate > 0 {
1076 time.Sleep(time.Second / time.Duration(state.rxRate))
1082 conn.Close() // #nosec G104
1088 func (state *SPState) Wait() {
1090 close(state.payloads)
1092 state.Duration = time.Now().Sub(state.started)
1094 state.RxSpeed = state.RxBytes
1095 state.TxSpeed = state.TxBytes
1096 rxDuration := int64(state.RxLastSeen.Sub(state.started).Seconds())
1097 txDuration := int64(state.TxLastSeen.Sub(state.started).Seconds())
1099 state.RxSpeed = state.RxBytes / rxDuration
1102 state.TxSpeed = state.TxBytes / txDuration
1104 for _, s := range state.fds {
1107 for pktName := range state.progressBars {
1108 ProgressKill(pktName)
1112 func (state *SPState) ProcessSP(payload []byte) ([][]byte, error) {
1113 les := LEs{{"Node", state.Node.Id}, {"Nice", int(state.Nice)}}
1114 r := bytes.NewReader(payload)
1116 var replies [][]byte
1119 state.Ctx.LogD("sp-process-unmarshal", les, func(les LEs) string {
1121 "SP with %s (nice %s): unmarshaling header",
1122 state.Node.Name, NicenessFmt(state.Nice),
1126 if _, err = xdr.Unmarshal(r, &head); err != nil {
1127 state.Ctx.LogE("sp-process-unmarshal", les, err, func(les LEs) string {
1129 "SP with %s (nice %s): unmarshaling header",
1130 state.Node.Name, NicenessFmt(state.Nice),
1135 if head.Type != SPTypePing {
1136 state.RxLastNonPing = state.RxLastSeen
1142 append(les, LE{"Type", "halt"}), func(les LEs) string {
1144 "SP with %s (nice %s): got HALT",
1145 state.Node.Name, NicenessFmt(state.Nice),
1150 state.queueTheir = nil
1156 append(les, LE{"Type", "ping"}),
1157 func(les LEs) string {
1159 "SP with %s (nice %s): got PING",
1160 state.Node.Name, NicenessFmt(state.Nice),
1167 lesp := append(les, LE{"Type", "info"})
1169 "sp-process-info-unmarshal", lesp,
1170 func(les LEs) string {
1172 "SP with %s (nice %s): unmarshaling INFO",
1173 state.Node.Name, NicenessFmt(state.Nice),
1178 if _, err = xdr.Unmarshal(r, &info); err != nil {
1180 "sp-process-info-unmarshal", lesp, err,
1181 func(les LEs) string {
1183 "SP with %s (nice %s): unmarshaling INFO",
1184 state.Node.Name, NicenessFmt(state.Nice),
1190 pktName := Base32Codec.EncodeToString(info.Hash[:])
1194 LE{"Size", int64(info.Size)},
1195 LE{"PktNice", int(info.Nice)},
1197 logMsg := func(les LEs) string {
1199 "SP with %s (nice %s): INFO %s (%s) nice %s",
1200 state.Node.Name, NicenessFmt(state.Nice),
1202 humanize.IBytes(info.Size),
1203 NicenessFmt(info.Nice),
1206 if !state.listOnly && info.Nice > state.Nice {
1207 state.Ctx.LogD("sp-process-info-too-nice", lesp, func(les LEs) string {
1208 return logMsg(les) + ": too nice"
1212 state.Ctx.LogD("sp-process-info-got", lesp, func(les LEs) string {
1213 return logMsg(les) + ": received"
1215 if !state.listOnly && state.xxOnly == TTx {
1219 state.infosTheir[*info.Hash] = &info
1221 state.Ctx.LogD("sp-process-info-stat", lesp, func(les LEs) string {
1222 return logMsg(les) + ": stating part"
1224 pktPath := filepath.Join(
1226 state.Node.Id.String(),
1228 Base32Codec.EncodeToString(info.Hash[:]),
1230 logMsg = func(les LEs) string {
1232 "Packet %s (%s) (nice %s)",
1234 humanize.IBytes(info.Size),
1235 NicenessFmt(info.Nice),
1238 if _, err = os.Stat(pktPath); err == nil {
1239 state.Ctx.LogI("sp-info-done", lesp, func(les LEs) string {
1240 return logMsg(les) + ": already done"
1242 if !state.listOnly {
1243 replies = append(replies, MarshalSP(SPTypeDone, SPDone{info.Hash}))
1247 if _, err = os.Stat(pktPath + SeenSuffix); err == nil {
1248 state.Ctx.LogI("sp-info-seen", lesp, func(les LEs) string {
1249 return logMsg(les) + ": already seen"
1251 if !state.listOnly {
1252 replies = append(replies, MarshalSP(SPTypeDone, SPDone{info.Hash}))
1256 if _, err = os.Stat(pktPath + NoCKSuffix); err == nil {
1257 state.Ctx.LogI("sp-info-nock", lesp, func(les LEs) string {
1258 return logMsg(les) + ": still not checksummed"
1262 fi, err := os.Stat(pktPath + PartSuffix)
1267 if !state.Ctx.IsEnoughSpace(int64(info.Size) - offset) {
1268 state.Ctx.LogI("sp-info-no-space", lesp, func(les LEs) string {
1269 return logMsg(les) + ": not enough space"
1275 append(lesp, LE{"Offset", offset}),
1276 func(les LEs) string {
1278 "%s: %d%%", logMsg(les), 100*uint64(offset)/info.Size,
1282 if !state.listOnly && (state.onlyPkts == nil || state.onlyPkts[*info.Hash]) {
1283 replies = append(replies, MarshalSP(
1285 SPFreq{info.Hash, uint64(offset)},
1290 lesp := append(les, LE{"Type", "file"})
1291 state.Ctx.LogD("sp-process-file", lesp, func(les LEs) string {
1293 "SP with %s (nice %s): unmarshaling FILE",
1294 state.Node.Name, NicenessFmt(state.Nice),
1298 if _, err = xdr.Unmarshal(r, &file); err != nil {
1299 state.Ctx.LogE("sp-process-file", lesp, err, func(les LEs) string {
1301 "SP with %s (nice %s): unmarshaling FILE",
1302 state.Node.Name, NicenessFmt(state.Nice),
1307 pktName := Base32Codec.EncodeToString(file.Hash[:])
1310 LE{"XX", string(TRx)},
1312 LE{"Size", int64(len(file.Payload))},
1314 logMsg := func(les LEs) string {
1316 "Got packet %s (%s)",
1317 pktName, humanize.IBytes(uint64(len(file.Payload))),
1320 fullsize := int64(0)
1322 infoTheir, ok := state.infosTheir[*file.Hash]
1325 state.Ctx.LogE("sp-file-open", lesp, err, func(les LEs) string {
1326 return logMsg(les) + ": unknown file"
1330 fullsize = int64(infoTheir.Size)
1331 lesp = append(lesp, LE{"FullSize", fullsize})
1332 dirToSync := filepath.Join(
1334 state.Node.Id.String(),
1337 filePath := filepath.Join(dirToSync, pktName)
1338 filePathPart := filePath + PartSuffix
1339 state.Ctx.LogD("sp-file-open", lesp, func(les LEs) string {
1340 return logMsg(les) + ": opening part"
1342 state.fdsLock.RLock()
1343 fdAndFullSize, exists := state.fds[filePathPart]
1344 state.fdsLock.RUnlock()
1345 hasherAndOffset := state.fileHashers[filePath]
1348 fd = fdAndFullSize.fd
1350 fd, err = os.OpenFile(
1352 os.O_RDWR|os.O_CREATE,
1356 state.Ctx.LogE("sp-file-open", lesp, err, func(les LEs) string {
1357 return logMsg(les) + ": opening part"
1361 state.fdsLock.Lock()
1362 state.fds[filePathPart] = FdAndFullSize{fd: fd}
1363 state.fdsLock.Unlock()
1365 hasherAndOffset = &MTHAndOffset{
1366 mth: MTHNew(fullsize, int64(file.Offset)),
1367 offset: file.Offset,
1369 state.fileHashers[filePath] = hasherAndOffset
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 if hasherAndOffset != nil {
1396 if hasherAndOffset.offset == file.Offset {
1397 if _, err = hasherAndOffset.mth.Write(file.Payload); err != nil {
1400 hasherAndOffset.offset += uint64(len(file.Payload))
1403 "sp-file-offset-differs", lesp, errors.New("offset differs"),
1404 func(les LEs) string {
1405 return logMsg(les) + ": deleting hasher"
1408 delete(state.fileHashers, filePath)
1409 hasherAndOffset = nil
1412 ourSize := int64(file.Offset + uint64(len(file.Payload)))
1413 lesp[len(lesp)-2].V = ourSize
1414 if state.Ctx.ShowPrgrs {
1415 state.progressBars[pktName] = struct{}{}
1416 Progress("Rx", lesp)
1418 if fullsize != ourSize {
1421 if state.Ctx.ShowPrgrs {
1422 delete(state.progressBars, pktName)
1424 logMsg = func(les LEs) string {
1426 "Got packet %s %d%% (%s / %s)",
1427 pktName, 100*ourSize/fullsize,
1428 humanize.IBytes(uint64(ourSize)),
1429 humanize.IBytes(uint64(fullsize)),
1434 state.Ctx.LogE("sp-file-sync", lesp, err, func(les LEs) string {
1435 return logMsg(les) + ": syncing"
1437 state.closeFd(filePathPart)
1440 if hasherAndOffset != nil {
1441 delete(state.fileHashers, filePath)
1442 if hasherAndOffset.mth.PrependSize == 0 {
1443 if bytes.Compare(hasherAndOffset.mth.Sum(nil), file.Hash[:]) != 0 {
1445 "sp-file-bad-checksum", lesp,
1446 errors.New("checksum mismatch"),
1449 state.closeFd(filePathPart)
1452 if err = os.Rename(filePathPart, filePath); err != nil {
1453 state.Ctx.LogE("sp-file-rename", lesp, err, func(les LEs) string {
1454 return logMsg(les) + ": renaming"
1456 state.closeFd(filePathPart)
1459 if err = DirSync(dirToSync); err != nil {
1460 state.Ctx.LogE("sp-file-dirsync", lesp, err, func(les LEs) string {
1461 return logMsg(les) + ": dirsyncing"
1463 state.closeFd(filePathPart)
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 {
1480 if _, err = fd.Seek(0, io.SeekStart); err != nil {
1481 state.Ctx.LogE("sp-file-seek", lesp, err, func(les LEs) string {
1482 return logMsg(les) + ": seeking"
1484 state.closeFd(filePathPart)
1487 _, pktEncRaw, err := state.Ctx.HdrRead(fd)
1488 state.closeFd(filePathPart)
1490 state.Ctx.LogE("sp-file-hdr-read", lesp, err, func(les LEs) string {
1491 return logMsg(les) + ": HdrReading"
1495 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)
1518 if hasherAndOffset != nil {
1520 spCheckerTasks <- SPCheckerTask{
1521 nodeId: state.Node.Id,
1523 mth: hasherAndOffset.mth,
1524 done: state.payloads,
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})