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 state.Ctx.LogD("sp-queue-open", lesp, func(les LEs) string {
879 return logMsg(les) + ": opening"
881 fd, err := os.Open(pth)
883 state.Ctx.LogE("sp-queue-open", lesp, err, func(les LEs) string {
884 return logMsg(les) + ": opening"
890 state.Ctx.LogE("sp-queue-stat", lesp, err, func(les LEs) string {
891 return logMsg(les) + ": stating"
895 fdAndFullSize = FdAndFullSize{fd: fd, fullSize: fi.Size()}
897 state.fds[pth] = fdAndFullSize
898 state.fdsLock.Unlock()
900 fd := fdAndFullSize.fd
901 fullSize := fdAndFullSize.fullSize
902 lesp = append(lesp, LE{"FullSize", fullSize})
904 if freq.Offset < uint64(fullSize) {
905 state.Ctx.LogD("sp-file-seek", lesp, func(les LEs) string {
906 return logMsg(les) + ": seeking"
908 if _, err = fd.Seek(int64(freq.Offset), io.SeekStart); err != nil {
909 state.Ctx.LogE("sp-file-seek", lesp, err, func(les LEs) string {
910 return logMsg(les) + ": seeking"
914 n, err := fd.Read(buf)
916 state.Ctx.LogE("sp-file-read", lesp, err, func(les LEs) string {
917 return logMsg(les) + ": reading"
924 LE{"XX", string(TTx)},
926 LE{"Size", int64(n)},
927 LE{"FullSize", fullSize},
929 state.Ctx.LogD("sp-file-read", lesp, func(les LEs) string {
932 logMsg(les), humanize.IBytes(uint64(n)),
938 payload = MarshalSP(SPTypeFile, SPFile{
943 ourSize := freq.Offset + uint64(len(bufRead))
946 LE{"XX", string(TTx)},
948 LE{"Size", int64(ourSize)},
949 LE{"FullSize", fullSize},
951 if state.Ctx.ShowPrgrs {
952 state.progressBars[pktName] = struct{}{}
955 if ourSize == uint64(fullSize) {
957 state.Ctx.LogD("sp-file-finished", lesp, func(les LEs) string {
958 return logMsg(les) + ": finished"
960 if state.Ctx.ShowPrgrs {
961 delete(state.progressBars, pktName)
965 for i, q := range state.queueTheir {
966 if *q.freq.Hash != *freq.Hash {
969 if ourSize == uint64(fullSize) {
970 state.queueTheir = append(
971 state.queueTheir[:i],
972 state.queueTheir[i+1:]...,
975 q.freq.Offset = ourSize
981 logMsg := func(les LEs) string {
983 "SP with %s (nice %s): sending %s",
984 state.Node.Name, NicenessFmt(state.Nice),
985 humanize.IBytes(uint64(len(payload))),
988 state.Ctx.LogD("sp-sending", append(les, LE{"Size", int64(len(payload))}), logMsg)
989 conn.SetWriteDeadline(time.Now().Add(DefaultDeadline)) // #nosec G104
990 ct, err := state.csOur.Encrypt(nil, nil, payload)
992 state.Ctx.LogE("sp-encrypting", les, err, logMsg)
995 if err := state.WriteSP(conn, ct, ping); err != nil {
996 state.Ctx.LogE("sp-sending", les, err, logMsg)
1006 if state.NotAlive() {
1009 logMsg := func(les LEs) string {
1011 "SP with %s (nice %s): waiting for payload",
1012 state.Node.Name, NicenessFmt(state.Nice),
1015 state.Ctx.LogD("sp-recv-wait", les, logMsg)
1016 conn.SetReadDeadline(time.Now().Add(DefaultDeadline)) // #nosec G104
1017 payload, err := state.ReadSP(conn)
1022 unmarshalErr := err.(*xdr.UnmarshalError)
1023 if os.IsTimeout(unmarshalErr.Err) {
1026 if unmarshalErr.ErrorCode == xdr.ErrIO {
1029 state.Ctx.LogE("sp-recv-wait", les, err, logMsg)
1032 logMsg = func(les LEs) string {
1034 "SP with %s (nice %s): payload (%s)",
1035 state.Node.Name, NicenessFmt(state.Nice),
1036 humanize.IBytes(uint64(len(payload))),
1041 append(les, LE{"Size", int64(len(payload))}),
1042 func(les LEs) string { return logMsg(les) + ": got" },
1044 payload, err = state.csTheir.Decrypt(nil, nil, payload)
1046 state.Ctx.LogE("sp-recv-got", les, err, func(les LEs) string {
1047 return logMsg(les) + ": got"
1053 append(les, LE{"Size", int64(len(payload))}),
1054 func(les LEs) string {
1055 return logMsg(les) + ": processing"
1058 replies, err := state.ProcessSP(payload)
1060 state.Ctx.LogE("sp-recv-process", les, err, func(les LEs) string {
1061 return logMsg(les) + ": processing"
1067 for _, reply := range replies {
1070 append(les[:len(les)-1], LE{"Size", int64(len(reply))}),
1071 func(les LEs) string {
1073 "SP with %s (nice %s): queuing reply (%s)",
1074 state.Node.Name, NicenessFmt(state.Nice),
1075 humanize.IBytes(uint64(len(reply))),
1079 state.payloads <- reply
1083 if state.rxRate > 0 {
1084 time.Sleep(time.Second / time.Duration(state.rxRate))
1090 conn.Close() // #nosec G104
1096 func (state *SPState) Wait() {
1098 close(state.payloads)
1100 state.Duration = time.Now().Sub(state.started)
1102 state.RxSpeed = state.RxBytes
1103 state.TxSpeed = state.TxBytes
1104 rxDuration := int64(state.RxLastSeen.Sub(state.started).Seconds())
1105 txDuration := int64(state.TxLastSeen.Sub(state.started).Seconds())
1107 state.RxSpeed = state.RxBytes / rxDuration
1110 state.TxSpeed = state.TxBytes / txDuration
1112 for _, s := range state.fds {
1115 for pktName := range state.progressBars {
1116 ProgressKill(pktName)
1120 func (state *SPState) ProcessSP(payload []byte) ([][]byte, error) {
1121 les := LEs{{"Node", state.Node.Id}, {"Nice", int(state.Nice)}}
1122 r := bytes.NewReader(payload)
1124 var replies [][]byte
1127 state.Ctx.LogD("sp-process-unmarshal", les, func(les LEs) string {
1129 "SP with %s (nice %s): unmarshaling header",
1130 state.Node.Name, NicenessFmt(state.Nice),
1134 if _, err = xdr.Unmarshal(r, &head); err != nil {
1135 state.Ctx.LogE("sp-process-unmarshal", les, err, func(les LEs) string {
1137 "SP with %s (nice %s): unmarshaling header",
1138 state.Node.Name, NicenessFmt(state.Nice),
1143 if head.Type != SPTypePing {
1144 state.RxLastNonPing = state.RxLastSeen
1150 append(les, LE{"Type", "halt"}), func(les LEs) string {
1152 "SP with %s (nice %s): got HALT",
1153 state.Node.Name, NicenessFmt(state.Nice),
1158 state.queueTheir = nil
1164 append(les, LE{"Type", "ping"}),
1165 func(les LEs) string {
1167 "SP with %s (nice %s): got PING",
1168 state.Node.Name, NicenessFmt(state.Nice),
1175 lesp := append(les, LE{"Type", "info"})
1177 "sp-process-info-unmarshal", lesp,
1178 func(les LEs) string {
1180 "SP with %s (nice %s): unmarshaling INFO",
1181 state.Node.Name, NicenessFmt(state.Nice),
1186 if _, err = xdr.Unmarshal(r, &info); err != nil {
1188 "sp-process-info-unmarshal", lesp, err,
1189 func(les LEs) string {
1191 "SP with %s (nice %s): unmarshaling INFO",
1192 state.Node.Name, NicenessFmt(state.Nice),
1198 pktName := Base32Codec.EncodeToString(info.Hash[:])
1202 LE{"Size", int64(info.Size)},
1203 LE{"PktNice", int(info.Nice)},
1205 logMsg := func(les LEs) string {
1207 "SP with %s (nice %s): INFO %s (%s) nice %s",
1208 state.Node.Name, NicenessFmt(state.Nice),
1210 humanize.IBytes(info.Size),
1211 NicenessFmt(info.Nice),
1214 if !state.listOnly && info.Nice > state.Nice {
1215 state.Ctx.LogD("sp-process-info-too-nice", lesp, func(les LEs) string {
1216 return logMsg(les) + ": too nice"
1220 state.Ctx.LogD("sp-process-info-got", lesp, func(les LEs) string {
1221 return logMsg(les) + ": received"
1223 if !state.listOnly && state.xxOnly == TTx {
1227 state.infosTheir[*info.Hash] = &info
1229 state.Ctx.LogD("sp-process-info-stat", lesp, func(les LEs) string {
1230 return logMsg(les) + ": stating part"
1232 pktPath := filepath.Join(
1234 state.Node.Id.String(),
1236 Base32Codec.EncodeToString(info.Hash[:]),
1238 logMsg = func(les LEs) string {
1240 "Packet %s (%s) (nice %s)",
1242 humanize.IBytes(info.Size),
1243 NicenessFmt(info.Nice),
1246 if _, err = os.Stat(pktPath); err == nil {
1247 state.Ctx.LogI("sp-info-done", lesp, func(les LEs) string {
1248 return logMsg(les) + ": already done"
1250 if !state.listOnly {
1251 replies = append(replies, MarshalSP(SPTypeDone, SPDone{info.Hash}))
1255 if _, err = os.Stat(pktPath + SeenSuffix); err == nil {
1256 state.Ctx.LogI("sp-info-seen", lesp, func(les LEs) string {
1257 return logMsg(les) + ": already seen"
1259 if !state.listOnly {
1260 replies = append(replies, MarshalSP(SPTypeDone, SPDone{info.Hash}))
1264 if _, err = os.Stat(pktPath + NoCKSuffix); err == nil {
1265 state.Ctx.LogI("sp-info-nock", lesp, func(les LEs) string {
1266 return logMsg(les) + ": still not checksummed"
1270 fi, err := os.Stat(pktPath + PartSuffix)
1275 if !state.Ctx.IsEnoughSpace(int64(info.Size) - offset) {
1276 state.Ctx.LogI("sp-info-no-space", lesp, func(les LEs) string {
1277 return logMsg(les) + ": not enough space"
1283 append(lesp, LE{"Offset", offset}),
1284 func(les LEs) string {
1286 "%s: %d%%", logMsg(les), 100*uint64(offset)/info.Size,
1290 if !state.listOnly && (state.onlyPkts == nil || state.onlyPkts[*info.Hash]) {
1291 replies = append(replies, MarshalSP(
1293 SPFreq{info.Hash, uint64(offset)},
1298 lesp := append(les, LE{"Type", "file"})
1299 state.Ctx.LogD("sp-process-file", lesp, func(les LEs) string {
1301 "SP with %s (nice %s): unmarshaling FILE",
1302 state.Node.Name, NicenessFmt(state.Nice),
1306 if _, err = xdr.Unmarshal(r, &file); err != nil {
1307 state.Ctx.LogE("sp-process-file", lesp, err, func(les LEs) string {
1309 "SP with %s (nice %s): unmarshaling FILE",
1310 state.Node.Name, NicenessFmt(state.Nice),
1315 pktName := Base32Codec.EncodeToString(file.Hash[:])
1318 LE{"XX", string(TRx)},
1320 LE{"Size", int64(len(file.Payload))},
1322 logMsg := func(les LEs) string {
1324 "Got packet %s (%s)",
1325 pktName, humanize.IBytes(uint64(len(file.Payload))),
1328 fullsize := int64(0)
1330 infoTheir := state.infosTheir[*file.Hash]
1332 if infoTheir == nil {
1333 state.Ctx.LogE("sp-file-open", lesp, err, func(les LEs) string {
1334 return logMsg(les) + ": unknown file"
1338 fullsize = int64(infoTheir.Size)
1339 lesp = append(lesp, LE{"FullSize", fullsize})
1340 dirToSync := filepath.Join(
1342 state.Node.Id.String(),
1345 filePath := filepath.Join(dirToSync, pktName)
1346 filePathPart := filePath + PartSuffix
1347 state.Ctx.LogD("sp-file-open", lesp, func(les LEs) string {
1348 return logMsg(les) + ": opening part"
1350 state.fdsLock.RLock()
1351 fdAndFullSize, exists := state.fds[filePathPart]
1352 state.fdsLock.RUnlock()
1353 hasherAndOffset := state.fileHashers[filePath]
1356 fd = fdAndFullSize.fd
1358 fd, err = os.OpenFile(
1360 os.O_RDWR|os.O_CREATE,
1364 state.Ctx.LogE("sp-file-open", lesp, err, func(les LEs) string {
1365 return logMsg(les) + ": opening part"
1369 state.fdsLock.Lock()
1370 state.fds[filePathPart] = FdAndFullSize{fd: fd}
1371 state.fdsLock.Unlock()
1373 hasherAndOffset = &MTHAndOffset{
1374 mth: MTHNew(fullsize, int64(file.Offset)),
1375 offset: file.Offset,
1377 state.fileHashers[filePath] = hasherAndOffset
1382 append(lesp, LE{"Offset", file.Offset}),
1383 func(les LEs) string {
1384 return fmt.Sprintf("%s: seeking %d", logMsg(les), file.Offset)
1386 if _, err = fd.Seek(int64(file.Offset), io.SeekStart); err != nil {
1387 state.Ctx.LogE("sp-file-seek", lesp, err, func(les LEs) string {
1388 return logMsg(les) + ": seeking"
1390 state.closeFd(filePathPart)
1393 state.Ctx.LogD("sp-file-write", lesp, func(les LEs) string {
1394 return logMsg(les) + ": writing"
1396 if _, err = fd.Write(file.Payload); err != nil {
1397 state.Ctx.LogE("sp-file-write", lesp, err, func(les LEs) string {
1398 return logMsg(les) + ": writing"
1400 state.closeFd(filePathPart)
1403 if hasherAndOffset != nil {
1404 if hasherAndOffset.offset == file.Offset {
1405 if _, err = hasherAndOffset.mth.Write(file.Payload); err != nil {
1408 hasherAndOffset.offset += uint64(len(file.Payload))
1411 "sp-file-offset-differs", lesp, errors.New("offset differs"),
1412 func(les LEs) string {
1413 return logMsg(les) + ": deleting hasher"
1416 delete(state.fileHashers, filePath)
1417 hasherAndOffset = nil
1420 ourSize := int64(file.Offset + uint64(len(file.Payload)))
1421 lesp[len(lesp)-2].V = ourSize
1422 if state.Ctx.ShowPrgrs {
1423 state.progressBars[pktName] = struct{}{}
1424 Progress("Rx", lesp)
1426 if fullsize != ourSize {
1429 if state.Ctx.ShowPrgrs {
1430 delete(state.progressBars, pktName)
1432 logMsg = func(les LEs) string {
1434 "Got packet %s %d%% (%s / %s)",
1435 pktName, 100*ourSize/fullsize,
1436 humanize.IBytes(uint64(ourSize)),
1437 humanize.IBytes(uint64(fullsize)),
1442 state.Ctx.LogE("sp-file-sync", lesp, err, func(les LEs) string {
1443 return logMsg(les) + ": syncing"
1445 state.closeFd(filePathPart)
1448 if hasherAndOffset != nil {
1449 delete(state.fileHashers, filePath)
1450 if hasherAndOffset.mth.PreaddSize() == 0 {
1451 if bytes.Compare(hasherAndOffset.mth.Sum(nil), file.Hash[:]) != 0 {
1453 "sp-file-bad-checksum", lesp,
1454 errors.New("checksum mismatch"),
1457 state.closeFd(filePathPart)
1460 if err = os.Rename(filePathPart, filePath); err != nil {
1461 state.Ctx.LogE("sp-file-rename", lesp, err, func(les LEs) string {
1462 return logMsg(les) + ": renaming"
1464 state.closeFd(filePathPart)
1467 if err = DirSync(dirToSync); err != nil {
1468 state.Ctx.LogE("sp-file-dirsync", lesp, err, func(les LEs) string {
1469 return logMsg(les) + ": dirsyncing"
1471 state.closeFd(filePathPart)
1474 state.Ctx.LogI("sp-file-done", lesp, func(les LEs) string {
1475 return logMsg(les) + ": done"
1479 state.payloads <- MarshalSP(SPTypeDone, SPDone{file.Hash})
1483 delete(state.infosTheir, *file.Hash)
1485 if !state.Ctx.HdrUsage {
1488 if _, err = fd.Seek(0, io.SeekStart); err != nil {
1489 state.Ctx.LogE("sp-file-seek", lesp, err, func(les LEs) string {
1490 return logMsg(les) + ": seeking"
1492 state.closeFd(filePathPart)
1495 _, pktEncRaw, err := state.Ctx.HdrRead(fd)
1496 state.closeFd(filePathPart)
1498 state.Ctx.LogE("sp-file-hdr-read", lesp, err, func(les LEs) string {
1499 return logMsg(les) + ": HdrReading"
1503 state.Ctx.HdrWrite(pktEncRaw, filePath)
1507 state.closeFd(filePathPart)
1508 if err = os.Rename(filePathPart, filePath+NoCKSuffix); err != nil {
1509 state.Ctx.LogE("sp-file-rename", lesp, err, func(les LEs) string {
1510 return logMsg(les) + ": renaming"
1514 if err = DirSync(dirToSync); err != nil {
1515 state.Ctx.LogE("sp-file-dirsync", lesp, err, func(les LEs) string {
1516 return logMsg(les) + ": dirsyncing"
1520 state.Ctx.LogI("sp-file-downloaded", lesp, func(les LEs) string {
1521 return logMsg(les) + ": downloaded"
1524 delete(state.infosTheir, *file.Hash)
1528 nodeId: state.Node.Id,
1530 done: state.payloads,
1532 if hasherAndOffset != nil {
1533 t.mth = hasherAndOffset.mth
1539 lesp := append(les, LE{"Type", "done"})
1540 state.Ctx.LogD("sp-process-done-unmarshal", lesp, func(les LEs) string {
1542 "SP with %s (nice %s): unmarshaling DONE",
1543 state.Node.Name, NicenessFmt(state.Nice),
1547 if _, err = xdr.Unmarshal(r, &done); err != nil {
1548 state.Ctx.LogE("sp-process-done-unmarshal", lesp, err, func(les LEs) string {
1550 "SP with %s (nice %s): unmarshaling DONE",
1551 state.Node.Name, NicenessFmt(state.Nice),
1556 pktName := Base32Codec.EncodeToString(done.Hash[:])
1557 lesp = append(lesp, LE{"Pkt", pktName}, LE{"XX", string(TTx)})
1558 logMsg := func(les LEs) string {
1560 "SP with %s (nice %s): DONE: removing %s",
1561 state.Node.Name, NicenessFmt(state.Nice), pktName,
1564 state.Ctx.LogD("sp-done", lesp, logMsg)
1565 pth := filepath.Join(
1567 state.Node.Id.String(),
1571 if err = os.Remove(pth); err == nil {
1572 state.Ctx.LogI("sp-done", lesp, func(les LEs) string {
1573 return fmt.Sprintf("Packet %s is sent", pktName)
1575 if state.Ctx.HdrUsage {
1576 os.Remove(pth + HdrSuffix)
1579 state.Ctx.LogE("sp-done", lesp, err, logMsg)
1583 lesp := append(les, LE{"Type", "freq"})
1584 state.Ctx.LogD("sp-process-freq", lesp, func(les LEs) string {
1586 "SP with %s (nice %s): unmarshaling FREQ",
1587 state.Node.Name, NicenessFmt(state.Nice),
1591 if _, err = xdr.Unmarshal(r, &freq); err != nil {
1592 state.Ctx.LogE("sp-process-freq", lesp, err, func(les LEs) string {
1594 "SP with %s (nice %s): unmarshaling FREQ",
1595 state.Node.Name, NicenessFmt(state.Nice),
1600 pktName := Base32Codec.EncodeToString(freq.Hash[:])
1601 lesp = append(lesp, LE{"Pkt", pktName}, LE{"Offset", freq.Offset})
1602 state.Ctx.LogD("sp-process-freq-queueing", lesp, func(les LEs) string {
1604 "SP with %s (nice %s): FREQ %s: queuing",
1605 state.Node.Name, NicenessFmt(state.Nice), pktName,
1608 nice, exists := state.infosOurSeen[*freq.Hash]
1610 if state.onlyPkts == nil || !state.onlyPkts[*freq.Hash] {
1613 var freqWithNice *FreqWithNice
1614 for insertIdx, freqWithNice = range state.queueTheir {
1615 if freqWithNice.nice > nice {
1619 state.queueTheir = append(state.queueTheir, nil)
1620 copy(state.queueTheir[insertIdx+1:], state.queueTheir[insertIdx:])
1621 state.queueTheir[insertIdx] = &FreqWithNice{&freq, nice}
1624 state.Ctx.LogD("sp-process-freq-skip", lesp, func(les LEs) string {
1626 "SP with %s (nice %s): FREQ %s: skipping",
1627 state.Node.Name, NicenessFmt(state.Nice), pktName,
1632 state.Ctx.LogD("sp-process-freq-unknown", lesp, func(les LEs) string {
1634 "SP with %s (nice %s): FREQ %s: unknown",
1635 state.Node.Name, NicenessFmt(state.Nice), pktName,
1642 "sp-process-type-unknown",
1643 append(les, LE{"Type", head.Type}),
1644 errors.New("unknown type"),
1645 func(les LEs) string {
1647 "SP with %s (nice %s): %d",
1648 state.Node.Name, NicenessFmt(state.Nice), head.Type,
1652 return nil, BadPktType
1660 for _, info := range state.infosTheir {
1665 state.Ctx.LogI("sp-infos-rx", LEs{
1666 {"XX", string(TRx)},
1667 {"Node", state.Node.Id},
1669 {"Size", int64(size)},
1670 }, func(les LEs) string {
1672 "%s has got for us: %d packets, %s",
1673 state.Node.Name, pkts, humanize.IBytes(size),
1677 return payloadsSplit(replies), nil
1680 func SPChecker(ctx *Ctx) {
1681 for t := range spCheckerTasks {
1682 pktName := Base32Codec.EncodeToString(t.hsh[:])
1684 {"XX", string(TRx)},
1689 ctx.LogD("sp-checker", les, func(les LEs) string {
1690 return fmt.Sprintf("Checksumming %s/rx/%s", ctx.NodeName(t.nodeId), pktName)
1692 size, err := ctx.CheckNoCK(t.nodeId, t.hsh, t.mth)
1693 les = append(les, LE{"Size", size})
1695 ctx.LogE("sp-checker", les, err, func(les LEs) string {
1697 "Checksumming %s/rx/%s (%s)", ctx.NodeName(t.nodeId), pktName,
1698 humanize.IBytes(uint64(size)),
1704 ctx.LogI("sp-checker-done", les, func(les LEs) string {
1706 "Packet %s is retreived (%s)",
1707 pktName, humanize.IBytes(uint64(size)),
1711 go func(t SPCheckerTask) {
1712 defer func() { recover() }()
1713 t.done <- MarshalSP(SPTypeDone, SPDone{t.hsh})