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 {
56 MagicNNCPLv1 [8]byte = [8]byte{'N', 'N', 'C', 'P', 'S', 0, 0, 1}
61 SPHaltMarshalized []byte
62 SPPingMarshalized []byte
64 NoiseCipherSuite noise.CipherSuite = noise.NewCipherSuite(
66 noise.CipherChaChaPoly,
70 DefaultDeadline = 10 * time.Second
71 PingTimeout = time.Minute
73 spCheckerTasks chan SPCheckerTask
74 SPCheckerWg sync.WaitGroup
75 spCheckerOnce sync.Once
78 type FdAndFullSize struct {
86 SPTypeInfo SPType = iota
87 SPTypeFreq SPType = iota
88 SPTypeFile SPType = iota
89 SPTypeDone SPType = iota
90 SPTypeHalt SPType = iota
91 SPTypePing SPType = iota
124 type FreqWithNice struct {
129 type ConnDeadlined interface {
131 SetReadDeadline(t time.Time) error
132 SetWriteDeadline(t time.Time) error
137 spHead := SPHead{Type: SPTypeHalt}
138 if _, err := xdr.Marshal(&buf, spHead); err != nil {
141 SPHaltMarshalized = make([]byte, SPHeadOverhead)
142 copy(SPHaltMarshalized, buf.Bytes())
145 spHead = SPHead{Type: SPTypePing}
146 if _, err := xdr.Marshal(&buf, spHead); err != nil {
149 SPPingMarshalized = make([]byte, SPHeadOverhead)
150 copy(SPPingMarshalized, buf.Bytes())
153 spInfo := SPInfo{Nice: 123, Size: 123, Hash: new([MTHSize]byte)}
154 if _, err := xdr.Marshal(&buf, spInfo); err != nil {
157 SPInfoOverhead = buf.Len()
160 spFreq := SPFreq{Hash: new([MTHSize]byte), Offset: 123}
161 if _, err := xdr.Marshal(&buf, spFreq); err != nil {
164 SPFreqOverhead = buf.Len()
167 spFile := SPFile{Hash: new([MTHSize]byte), Offset: 123}
168 if _, err := xdr.Marshal(&buf, spFile); err != nil {
171 SPFileOverhead = buf.Len()
172 spCheckerTasks = make(chan SPCheckerTask)
175 func MarshalSP(typ SPType, sp interface{}) []byte {
177 if _, err := xdr.Marshal(&buf, SPHead{typ}); err != nil {
180 if _, err := xdr.Marshal(&buf, sp); err != nil {
186 func payloadsSplit(payloads [][]byte) [][]byte {
187 var outbounds [][]byte
188 outbound := make([]byte, 0, MaxSPSize)
189 for i, payload := range payloads {
190 outbound = append(outbound, payload...)
191 if i+1 < len(payloads) && len(outbound)+len(payloads[i+1]) > MaxSPSize {
192 outbounds = append(outbounds, outbound)
193 outbound = make([]byte, 0, MaxSPSize)
196 if len(outbound) > 0 {
197 outbounds = append(outbounds, outbound)
202 type SPState struct {
207 onlineDeadline time.Duration
208 maxOnlineTime time.Duration
209 hs *noise.HandshakeState
210 csOur *noise.CipherState
211 csTheir *noise.CipherState
214 infosTheir map[[MTHSize]byte]*SPInfo
215 infosOurSeen map[[MTHSize]byte]uint8
216 queueTheir []*FreqWithNice
220 RxLastNonPing time.Time
223 TxLastNonPing time.Time
225 mustFinishAt time.Time
226 Duration time.Duration
236 onlyPkts map[[MTHSize]byte]bool
237 writeSPBuf bytes.Buffer
238 fds map[string]FdAndFullSize
240 fileHashers map[string]*MTHAndOffset
241 progressBars map[string]struct{}
245 func (state *SPState) SetDead() {
250 // Already closed channel, dead
256 for range state.payloads {
260 for range state.pings {
265 func (state *SPState) NotAlive() bool {
274 func (state *SPState) dirUnlock() {
275 state.Ctx.UnlockDir(state.rxLock)
276 state.Ctx.UnlockDir(state.txLock)
279 func (state *SPState) WriteSP(dst io.Writer, payload []byte, ping bool) error {
280 state.writeSPBuf.Reset()
281 n, err := xdr.Marshal(&state.writeSPBuf, SPRaw{
288 if n, err = dst.Write(state.writeSPBuf.Bytes()); err == nil {
289 state.TxLastSeen = time.Now()
290 state.TxBytes += int64(n)
292 state.TxLastNonPing = state.TxLastSeen
298 func (state *SPState) ReadSP(src io.Reader) ([]byte, error) {
300 n, err := xdr.UnmarshalLimited(src, &sp, 1<<17)
302 ue := err.(*xdr.UnmarshalError)
303 if ue.Err == io.EOF {
308 state.RxLastSeen = time.Now()
309 state.RxBytes += int64(n)
310 if sp.Magic != MagicNNCPLv1 {
313 return sp.Payload, nil
316 func (ctx *Ctx) infosOur(nodeId *NodeId, nice uint8, seen *map[[MTHSize]byte]uint8) [][]byte {
319 for job := range ctx.Jobs(nodeId, TTx) {
320 if job.PktEnc.Nice > nice {
323 if _, known := (*seen)[*job.HshValue]; known {
326 totalSize += job.Size
327 infos = append(infos, &SPInfo{
328 Nice: job.PktEnc.Nice,
329 Size: uint64(job.Size),
332 (*seen)[*job.HshValue] = job.PktEnc.Nice
334 sort.Sort(ByNice(infos))
335 var payloads [][]byte
336 for _, info := range infos {
337 payloads = append(payloads, MarshalSP(SPTypeInfo, info))
338 pktName := Base32Codec.EncodeToString(info.Hash[:])
339 ctx.LogD("sp-info-our", LEs{
343 }, func(les LEs) string {
345 "Our info: %s/tx/%s (%s)",
346 ctx.NodeName(nodeId),
348 humanize.IBytes(info.Size),
353 ctx.LogI("sp-infos-tx", LEs{
356 {"Pkts", len(payloads)},
358 }, func(les LEs) string {
360 "We have got for %s: %d packets, %s",
361 ctx.NodeName(nodeId),
363 humanize.IBytes(uint64(totalSize)),
367 return payloadsSplit(payloads)
370 func (state *SPState) StartI(conn ConnDeadlined) error {
371 nodeId := state.Node.Id
372 err := state.Ctx.ensureRxDir(nodeId)
377 if !state.listOnly && (state.xxOnly == "" || state.xxOnly == TRx) {
378 rxLock, err = state.Ctx.LockDir(nodeId, string(TRx))
384 if !state.listOnly && (state.xxOnly == "" || state.xxOnly == TTx) {
385 txLock, err = state.Ctx.LockDir(nodeId, string(TTx))
390 started := time.Now()
391 conf := noise.Config{
392 CipherSuite: NoiseCipherSuite,
393 Pattern: noise.HandshakeIK,
395 StaticKeypair: noise.DHKey{
396 Private: state.Ctx.Self.NoisePrv[:],
397 Public: state.Ctx.Self.NoisePub[:],
399 PeerStatic: state.Node.NoisePub[:],
401 hs, err := noise.NewHandshakeState(conf)
406 state.payloads = make(chan []byte)
407 state.pings = make(chan struct{})
408 state.infosTheir = make(map[[MTHSize]byte]*SPInfo)
409 state.infosOurSeen = make(map[[MTHSize]byte]uint8)
410 state.progressBars = make(map[string]struct{})
411 state.started = started
412 state.rxLock = rxLock
413 state.txLock = txLock
415 var infosPayloads [][]byte
416 if !state.listOnly && (state.xxOnly == "" || state.xxOnly == TTx) {
417 infosPayloads = state.Ctx.infosOur(nodeId, state.Nice, &state.infosOurSeen)
419 var firstPayload []byte
420 if len(infosPayloads) > 0 {
421 firstPayload = infosPayloads[0]
423 // Pad first payload, to hide actual number of existing files
424 for i := 0; i < (MaxSPSize-len(firstPayload))/SPHeadOverhead; i++ {
425 firstPayload = append(firstPayload, SPHaltMarshalized...)
430 buf, _, _, err = state.hs.WriteMessage(nil, firstPayload)
435 les := LEs{{"Node", nodeId}, {"Nice", int(state.Nice)}}
436 state.Ctx.LogD("sp-startI", les, func(les LEs) string {
438 "SP with %s (nice %s): sending first message",
440 NicenessFmt(state.Nice),
443 conn.SetWriteDeadline(time.Now().Add(DefaultDeadline)) // #nosec G104
444 if err = state.WriteSP(conn, buf, false); err != nil {
445 state.Ctx.LogE("sp-startI", les, err, func(les LEs) string {
447 "SP with %s (nice %s): writing",
449 NicenessFmt(state.Nice),
455 state.Ctx.LogD("sp-startI-wait", les, func(les LEs) string {
457 "SP with %s (nice %s): waiting for first message",
459 NicenessFmt(state.Nice),
462 conn.SetReadDeadline(time.Now().Add(DefaultDeadline)) // #nosec G104
463 if buf, err = state.ReadSP(conn); err != nil {
464 state.Ctx.LogE("sp-startI-read", les, err, func(les LEs) string {
466 "SP with %s (nice %s): reading",
468 NicenessFmt(state.Nice),
474 payload, state.csOur, state.csTheir, err = state.hs.ReadMessage(nil, buf)
476 state.Ctx.LogE("sp-startI-read", les, err, func(les LEs) string {
478 "SP with %s (nice %s): reading Noise message",
480 NicenessFmt(state.Nice),
486 state.Ctx.LogD("sp-startI-workers", les, func(les LEs) string {
488 "SP with %s (nice %s): starting workers",
490 NicenessFmt(state.Nice),
493 err = state.StartWorkers(conn, infosPayloads, payload)
495 state.Ctx.LogE("sp-startI-workers", les, err, func(les LEs) string {
497 "SP with %s (nice %s): starting workers",
499 NicenessFmt(state.Nice),
507 func (state *SPState) StartR(conn ConnDeadlined) error {
508 started := time.Now()
509 conf := noise.Config{
510 CipherSuite: NoiseCipherSuite,
511 Pattern: noise.HandshakeIK,
513 StaticKeypair: noise.DHKey{
514 Private: state.Ctx.Self.NoisePrv[:],
515 Public: state.Ctx.Self.NoisePub[:],
518 hs, err := noise.NewHandshakeState(conf)
524 state.payloads = make(chan []byte)
525 state.pings = make(chan struct{})
526 state.infosOurSeen = make(map[[MTHSize]byte]uint8)
527 state.infosTheir = make(map[[MTHSize]byte]*SPInfo)
528 state.progressBars = make(map[string]struct{})
529 state.started = started
530 state.xxOnly = xxOnly
534 logMsg := func(les LEs) string {
536 "SP nice %s: waiting for first message",
537 NicenessFmt(state.Nice),
540 les := LEs{{"Nice", int(state.Nice)}}
541 state.Ctx.LogD("sp-startR", les, logMsg)
542 conn.SetReadDeadline(time.Now().Add(DefaultDeadline)) // #nosec G104
543 if buf, err = state.ReadSP(conn); err != nil {
544 state.Ctx.LogE("sp-startR-read", les, err, logMsg)
547 if payload, _, _, err = state.hs.ReadMessage(nil, buf); err != nil {
548 state.Ctx.LogE("sp-startR-read", les, err, logMsg)
553 for _, n := range state.Ctx.Neigh {
554 if subtle.ConstantTimeCompare(state.hs.PeerStatic(), n.NoisePub[:]) == 1 {
560 peerId := Base32Codec.EncodeToString(state.hs.PeerStatic())
561 err = errors.New("unknown peer: " + peerId)
562 state.Ctx.LogE("sp-startR-unknown", append(les, LE{"Peer", peerId}), err, logMsg)
566 state.rxRate = node.RxRate
567 state.txRate = node.TxRate
568 state.onlineDeadline = node.OnlineDeadline
569 state.maxOnlineTime = node.MaxOnlineTime
570 les = LEs{{"Node", node.Id}, {"Nice", int(state.Nice)}}
572 if err = state.Ctx.ensureRxDir(node.Id); err != nil {
576 if xxOnly == "" || xxOnly == TRx {
577 rxLock, err = state.Ctx.LockDir(node.Id, string(TRx))
582 state.rxLock = rxLock
584 if xxOnly == "" || xxOnly == TTx {
585 txLock, err = state.Ctx.LockDir(node.Id, string(TTx))
590 state.txLock = txLock
592 var infosPayloads [][]byte
593 if xxOnly == "" || xxOnly == TTx {
594 infosPayloads = state.Ctx.infosOur(node.Id, state.Nice, &state.infosOurSeen)
596 var firstPayload []byte
597 if len(infosPayloads) > 0 {
598 firstPayload = infosPayloads[0]
600 // Pad first payload, to hide actual number of existing files
601 for i := 0; i < (MaxSPSize-len(firstPayload))/SPHeadOverhead; i++ {
602 firstPayload = append(firstPayload, SPHaltMarshalized...)
605 state.Ctx.LogD("sp-startR-write", les, func(les LEs) string {
607 "SP with %s (nice %s): sending first message",
608 node.Name, NicenessFmt(state.Nice),
611 buf, state.csTheir, state.csOur, err = state.hs.WriteMessage(nil, firstPayload)
616 conn.SetWriteDeadline(time.Now().Add(DefaultDeadline)) // #nosec G104
617 if err = state.WriteSP(conn, buf, false); err != nil {
618 state.Ctx.LogE("sp-startR-write", les, err, func(les LEs) string {
620 "SP with %s (nice %s): writing",
621 node.Name, NicenessFmt(state.Nice),
627 state.Ctx.LogD("sp-startR-workers", les, func(les LEs) string {
629 "SP with %s (nice %s): starting workers",
630 node.Name, NicenessFmt(state.Nice),
633 err = state.StartWorkers(conn, infosPayloads, payload)
640 func (state *SPState) closeFd(pth string) {
642 if s, exists := state.fds[pth]; exists {
643 delete(state.fds, pth)
646 state.fdsLock.Unlock()
649 func (state *SPState) StartWorkers(
651 infosPayloads [][]byte,
654 les := LEs{{"Node", state.Node.Id}, {"Nice", int(state.Nice)}}
655 state.fds = make(map[string]FdAndFullSize)
656 state.fileHashers = make(map[string]*MTHAndOffset)
657 state.isDead = make(chan struct{})
658 if state.maxOnlineTime > 0 {
659 state.mustFinishAt = state.started.Add(state.maxOnlineTime)
662 spCheckerOnce.Do(func() { go SPChecker(state.Ctx) })
665 // Remaining handshake payload sending
666 if len(infosPayloads) > 1 {
669 for _, payload := range infosPayloads[1:] {
671 "sp-queue-remaining",
672 append(les, LE{"Size", int64(len(payload))}),
673 func(les LEs) string {
675 "SP with %s (nice %s): queuing remaining payload (%s)",
676 state.Node.Name, NicenessFmt(state.Nice),
677 humanize.IBytes(uint64(len(payload))),
681 state.payloads <- payload
687 // Processing of first payload and queueing its responses
688 logMsg := func(les LEs) string {
690 "SP with %s (nice %s): processing first payload (%s)",
691 state.Node.Name, NicenessFmt(state.Nice),
692 humanize.IBytes(uint64(len(payload))),
695 state.Ctx.LogD("sp-process", append(les, LE{"Size", int64(len(payload))}), logMsg)
696 replies, err := state.ProcessSP(payload)
698 state.Ctx.LogE("sp-process", les, err, logMsg)
703 for _, reply := range replies {
706 append(les, LE{"Size", int64(len(reply))}),
707 func(les LEs) string {
709 "SP with %s (nice %s): queuing reply (%s)",
710 state.Node.Name, NicenessFmt(state.Nice),
711 humanize.IBytes(uint64(len(payload))),
715 state.payloads <- reply
723 deadlineTicker := time.NewTicker(time.Second)
724 pingTicker := time.NewTicker(PingTimeout)
729 deadlineTicker.Stop()
732 case now := <-deadlineTicker.C:
733 if now.Sub(state.RxLastNonPing) >= state.onlineDeadline &&
734 now.Sub(state.TxLastNonPing) >= state.onlineDeadline {
737 if state.maxOnlineTime > 0 && state.mustFinishAt.Before(now) {
740 if now.Sub(state.RxLastSeen) >= 2*PingTimeout {
746 conn.Close() // #nosec G104
747 case now := <-pingTicker.C:
748 if now.After(state.TxLastSeen.Add(PingTimeout)) {
751 state.pings <- struct{}{}
759 // Spool checker and INFOs sender of appearing files
760 if !state.listOnly && (state.xxOnly == "" || state.xxOnly == TTx) {
763 ticker := time.NewTicker(time.Second)
771 for _, payload := range state.Ctx.infosOur(
778 append(les, LE{"Size", int64(len(payload))}),
779 func(les LEs) string {
781 "SP with %s (nice %s): queuing new info (%s)",
782 state.Node.Name, NicenessFmt(state.Nice),
783 humanize.IBytes(uint64(len(payload))),
787 state.payloads <- payload
798 defer state.SetDead()
799 defer state.wg.Done()
801 if state.NotAlive() {
808 state.Ctx.LogD("sp-got-ping", les, func(les LEs) string {
810 "SP with %s (nice %s): got ping",
811 state.Node.Name, NicenessFmt(state.Nice),
814 payload = SPPingMarshalized
816 case payload = <-state.payloads:
819 append(les, LE{"Size", int64(len(payload))}),
820 func(les LEs) string {
822 "SP with %s (nice %s): got payload (%s)",
823 state.Node.Name, NicenessFmt(state.Nice),
824 humanize.IBytes(uint64(len(payload))),
830 if len(state.queueTheir) == 0 {
832 time.Sleep(100 * time.Millisecond)
835 freq := state.queueTheir[0].freq
837 if state.txRate > 0 {
838 time.Sleep(time.Second / time.Duration(state.txRate))
840 pktName := Base32Codec.EncodeToString(freq.Hash[:])
843 LE{"XX", string(TTx)},
845 LE{"Size", int64(freq.Offset)},
847 logMsg := func(les LEs) string {
849 "SP with %s (nice %s): tx/%s (%s)",
850 state.Node.Name, NicenessFmt(state.Nice),
852 humanize.IBytes(freq.Offset),
855 state.Ctx.LogD("sp-queue", lesp, func(les LEs) string {
856 return logMsg(les) + ": queueing"
858 pth := filepath.Join(
860 state.Node.Id.String(),
862 Base32Codec.EncodeToString(freq.Hash[:]),
864 state.fdsLock.RLock()
865 fdAndFullSize, exists := state.fds[pth]
866 state.fdsLock.RUnlock()
868 fd, err := os.Open(pth)
870 state.Ctx.LogE("sp-queue-open", lesp, err, func(les LEs) string {
871 return logMsg(les) + ": opening"
877 state.Ctx.LogE("sp-queue-stat", lesp, err, func(les LEs) string {
878 return logMsg(les) + ": stating"
882 fdAndFullSize = FdAndFullSize{fd: fd, fullSize: fi.Size()}
884 state.fds[pth] = fdAndFullSize
885 state.fdsLock.Unlock()
887 fd := fdAndFullSize.fd
888 fullSize := fdAndFullSize.fullSize
890 if freq.Offset < uint64(fullSize) {
891 state.Ctx.LogD("sp-file-seek", lesp, func(les LEs) string {
892 return logMsg(les) + ": seeking"
894 if _, err = fd.Seek(int64(freq.Offset), io.SeekStart); err != nil {
895 state.Ctx.LogE("sp-file-seek", lesp, err, func(les LEs) string {
896 return logMsg(les) + ": seeking"
900 buf = make([]byte, MaxSPSize-SPHeadOverhead-SPFileOverhead)
901 n, err := fd.Read(buf)
903 state.Ctx.LogE("sp-file-read", lesp, err, func(les LEs) string {
904 return logMsg(les) + ": reading"
911 LE{"XX", string(TTx)},
913 LE{"Size", int64(n)},
915 state.Ctx.LogD("sp-file-read", lesp, func(les LEs) string {
918 logMsg(les), humanize.IBytes(uint64(n)),
923 payload = MarshalSP(SPTypeFile, SPFile{
928 ourSize := freq.Offset + uint64(len(buf))
931 LE{"XX", string(TTx)},
933 LE{"Size", int64(ourSize)},
934 LE{"FullSize", fullSize},
936 if state.Ctx.ShowPrgrs {
937 state.progressBars[pktName] = struct{}{}
941 if len(state.queueTheir) > 0 && *state.queueTheir[0].freq.Hash == *freq.Hash {
942 if ourSize == uint64(fullSize) {
943 state.Ctx.LogD("sp-file-finished", lesp, func(les LEs) string {
944 return logMsg(les) + ": finished"
946 if len(state.queueTheir) > 1 {
947 state.queueTheir = state.queueTheir[1:]
949 state.queueTheir = state.queueTheir[:0]
951 if state.Ctx.ShowPrgrs {
952 delete(state.progressBars, pktName)
955 state.queueTheir[0].freq.Offset += uint64(len(buf))
958 state.Ctx.LogD("sp-file-disappeared", lesp, func(les LEs) string {
959 return logMsg(les) + ": queue disappeared"
964 logMsg := func(les LEs) string {
966 "SP with %s (nice %s): sending %s",
967 state.Node.Name, NicenessFmt(state.Nice),
968 humanize.IBytes(uint64(len(payload))),
971 state.Ctx.LogD("sp-sending", append(les, LE{"Size", int64(len(payload))}), logMsg)
972 conn.SetWriteDeadline(time.Now().Add(DefaultDeadline)) // #nosec G104
973 ct, err := state.csOur.Encrypt(nil, nil, payload)
975 state.Ctx.LogE("sp-encrypting", les, err, logMsg)
978 if err := state.WriteSP(conn, ct, ping); err != nil {
979 state.Ctx.LogE("sp-sending", les, err, logMsg)
989 if state.NotAlive() {
992 logMsg := func(les LEs) string {
994 "SP with %s (nice %s): waiting for payload",
995 state.Node.Name, NicenessFmt(state.Nice),
998 state.Ctx.LogD("sp-recv-wait", les, logMsg)
999 conn.SetReadDeadline(time.Now().Add(DefaultDeadline)) // #nosec G104
1000 payload, err := state.ReadSP(conn)
1005 unmarshalErr := err.(*xdr.UnmarshalError)
1006 if os.IsTimeout(unmarshalErr.Err) {
1009 if unmarshalErr.ErrorCode == xdr.ErrIO {
1012 state.Ctx.LogE("sp-recv-wait", les, err, logMsg)
1015 logMsg = func(les LEs) string {
1017 "SP with %s (nice %s): payload (%s)",
1018 state.Node.Name, NicenessFmt(state.Nice),
1019 humanize.IBytes(uint64(len(payload))),
1024 append(les, LE{"Size", int64(len(payload))}),
1025 func(les LEs) string { return logMsg(les) + ": got" },
1027 payload, err = state.csTheir.Decrypt(nil, nil, payload)
1029 state.Ctx.LogE("sp-recv-got", les, err, func(les LEs) string {
1030 return logMsg(les) + ": got"
1036 append(les, LE{"Size", int64(len(payload))}),
1037 func(les LEs) string {
1038 return logMsg(les) + ": processing"
1041 replies, err := state.ProcessSP(payload)
1043 state.Ctx.LogE("sp-recv-process", les, err, func(les LEs) string {
1044 return logMsg(les) + ": processing"
1050 for _, reply := range replies {
1053 append(les[:len(les)-1], LE{"Size", int64(len(reply))}),
1054 func(les LEs) string {
1056 "SP with %s (nice %s): queuing reply (%s)",
1057 state.Node.Name, NicenessFmt(state.Nice),
1058 humanize.IBytes(uint64(len(reply))),
1062 state.payloads <- reply
1066 if state.rxRate > 0 {
1067 time.Sleep(time.Second / time.Duration(state.rxRate))
1073 conn.Close() // #nosec G104
1079 func (state *SPState) Wait() {
1081 close(state.payloads)
1083 state.Duration = time.Now().Sub(state.started)
1085 state.RxSpeed = state.RxBytes
1086 state.TxSpeed = state.TxBytes
1087 rxDuration := int64(state.RxLastSeen.Sub(state.started).Seconds())
1088 txDuration := int64(state.TxLastSeen.Sub(state.started).Seconds())
1090 state.RxSpeed = state.RxBytes / rxDuration
1093 state.TxSpeed = state.TxBytes / txDuration
1095 for _, s := range state.fds {
1098 for pktName := range state.progressBars {
1099 ProgressKill(pktName)
1103 func (state *SPState) ProcessSP(payload []byte) ([][]byte, error) {
1104 les := LEs{{"Node", state.Node.Id}, {"Nice", int(state.Nice)}}
1105 r := bytes.NewReader(payload)
1107 var replies [][]byte
1110 state.Ctx.LogD("sp-process-unmarshal", les, func(les LEs) string {
1112 "SP with %s (nice %s): unmarshaling header",
1113 state.Node.Name, NicenessFmt(state.Nice),
1117 if _, err = xdr.Unmarshal(r, &head); err != nil {
1118 state.Ctx.LogE("sp-process-unmarshal", les, err, func(les LEs) string {
1120 "SP with %s (nice %s): unmarshaling header",
1121 state.Node.Name, NicenessFmt(state.Nice),
1126 if head.Type != SPTypePing {
1127 state.RxLastNonPing = state.RxLastSeen
1133 append(les, LE{"Type", "halt"}), func(les LEs) string {
1135 "SP with %s (nice %s): got HALT",
1136 state.Node.Name, NicenessFmt(state.Nice),
1141 state.queueTheir = nil
1147 append(les, LE{"Type", "ping"}),
1148 func(les LEs) string {
1150 "SP with %s (nice %s): got PING",
1151 state.Node.Name, NicenessFmt(state.Nice),
1158 lesp := append(les, LE{"Type", "info"})
1160 "sp-process-info-unmarshal", lesp,
1161 func(les LEs) string {
1163 "SP with %s (nice %s): unmarshaling INFO",
1164 state.Node.Name, NicenessFmt(state.Nice),
1169 if _, err = xdr.Unmarshal(r, &info); err != nil {
1171 "sp-process-info-unmarshal", lesp, err,
1172 func(les LEs) string {
1174 "SP with %s (nice %s): unmarshaling INFO",
1175 state.Node.Name, NicenessFmt(state.Nice),
1181 pktName := Base32Codec.EncodeToString(info.Hash[:])
1185 LE{"Size", int64(info.Size)},
1186 LE{"PktNice", int(info.Nice)},
1188 logMsg := func(les LEs) string {
1190 "SP with %s (nice %s): INFO %s (%s) nice %s",
1191 state.Node.Name, NicenessFmt(state.Nice),
1193 humanize.IBytes(info.Size),
1194 NicenessFmt(info.Nice),
1197 if !state.listOnly && info.Nice > state.Nice {
1198 state.Ctx.LogD("sp-process-info-too-nice", lesp, func(les LEs) string {
1199 return logMsg(les) + ": too nice"
1203 state.Ctx.LogD("sp-process-info-got", lesp, func(les LEs) string {
1204 return logMsg(les) + ": received"
1206 if !state.listOnly && state.xxOnly == TTx {
1210 state.infosTheir[*info.Hash] = &info
1212 state.Ctx.LogD("sp-process-info-stat", lesp, func(les LEs) string {
1213 return logMsg(les) + ": stating part"
1215 pktPath := filepath.Join(
1217 state.Node.Id.String(),
1219 Base32Codec.EncodeToString(info.Hash[:]),
1221 logMsg = func(les LEs) string {
1223 "Packet %s (%s) (nice %s)",
1225 humanize.IBytes(info.Size),
1226 NicenessFmt(info.Nice),
1229 if _, err = os.Stat(pktPath); err == nil {
1230 state.Ctx.LogI("sp-info-done", lesp, func(les LEs) string {
1231 return logMsg(les) + ": already done"
1233 if !state.listOnly {
1234 replies = append(replies, MarshalSP(SPTypeDone, SPDone{info.Hash}))
1238 if _, err = os.Stat(pktPath + SeenSuffix); err == nil {
1239 state.Ctx.LogI("sp-info-seen", lesp, func(les LEs) string {
1240 return logMsg(les) + ": already seen"
1242 if !state.listOnly {
1243 replies = append(replies, MarshalSP(SPTypeDone, SPDone{info.Hash}))
1247 if _, err = os.Stat(pktPath + NoCKSuffix); err == nil {
1248 state.Ctx.LogI("sp-info-nock", lesp, func(les LEs) string {
1249 return logMsg(les) + ": still not checksummed"
1253 fi, err := os.Stat(pktPath + PartSuffix)
1258 if !state.Ctx.IsEnoughSpace(int64(info.Size) - offset) {
1259 state.Ctx.LogI("sp-info-no-space", lesp, func(les LEs) string {
1260 return logMsg(les) + ": not enough space"
1266 append(lesp, LE{"Offset", offset}),
1267 func(les LEs) string {
1269 "%s: %d%%", logMsg(les), 100*uint64(offset)/info.Size,
1273 if !state.listOnly && (state.onlyPkts == nil || state.onlyPkts[*info.Hash]) {
1274 replies = append(replies, MarshalSP(
1276 SPFreq{info.Hash, uint64(offset)},
1281 lesp := append(les, LE{"Type", "file"})
1282 state.Ctx.LogD("sp-process-file", lesp, func(les LEs) string {
1284 "SP with %s (nice %s): unmarshaling FILE",
1285 state.Node.Name, NicenessFmt(state.Nice),
1289 if _, err = xdr.Unmarshal(r, &file); err != nil {
1290 state.Ctx.LogE("sp-process-file", lesp, err, func(les LEs) string {
1292 "SP with %s (nice %s): unmarshaling FILE",
1293 state.Node.Name, NicenessFmt(state.Nice),
1298 pktName := Base32Codec.EncodeToString(file.Hash[:])
1301 LE{"XX", string(TRx)},
1303 LE{"Size", int64(len(file.Payload))},
1305 logMsg := func(les LEs) string {
1307 "Got packet %s (%s)",
1308 pktName, humanize.IBytes(uint64(len(file.Payload))),
1311 fullsize := int64(0)
1313 infoTheir, ok := state.infosTheir[*file.Hash]
1316 state.Ctx.LogE("sp-file-open", lesp, err, func(les LEs) string {
1317 return logMsg(les) + ": unknown file"
1321 fullsize = int64(infoTheir.Size)
1322 lesp = append(lesp, LE{"FullSize", fullsize})
1323 dirToSync := filepath.Join(
1325 state.Node.Id.String(),
1328 filePath := filepath.Join(dirToSync, pktName)
1329 filePathPart := filePath + PartSuffix
1330 state.Ctx.LogD("sp-file-open", lesp, func(les LEs) string {
1331 return logMsg(les) + ": opening part"
1333 state.fdsLock.RLock()
1334 fdAndFullSize, exists := state.fds[filePathPart]
1335 state.fdsLock.RUnlock()
1336 hasherAndOffset := state.fileHashers[filePath]
1339 fd = fdAndFullSize.fd
1341 fd, err = os.OpenFile(
1343 os.O_RDWR|os.O_CREATE,
1347 state.Ctx.LogE("sp-file-open", lesp, err, func(les LEs) string {
1348 return logMsg(les) + ": opening part"
1352 state.fdsLock.Lock()
1353 state.fds[filePathPart] = FdAndFullSize{fd: fd}
1354 state.fdsLock.Unlock()
1356 hasherAndOffset = &MTHAndOffset{
1357 mth: MTHNew(fullsize, int64(file.Offset)),
1358 offset: file.Offset,
1360 state.fileHashers[filePath] = hasherAndOffset
1365 append(lesp, LE{"Offset", file.Offset}),
1366 func(les LEs) string {
1367 return fmt.Sprintf("%s: seeking %d", logMsg(les), file.Offset)
1369 if _, err = fd.Seek(int64(file.Offset), io.SeekStart); err != nil {
1370 state.Ctx.LogE("sp-file-seek", lesp, err, func(les LEs) string {
1371 return logMsg(les) + ": seeking"
1373 state.closeFd(filePathPart)
1376 state.Ctx.LogD("sp-file-write", lesp, func(les LEs) string {
1377 return logMsg(les) + ": writing"
1379 if _, err = fd.Write(file.Payload); err != nil {
1380 state.Ctx.LogE("sp-file-write", lesp, err, func(les LEs) string {
1381 return logMsg(les) + ": writing"
1383 state.closeFd(filePathPart)
1386 if hasherAndOffset != nil {
1387 if hasherAndOffset.offset == file.Offset {
1388 if _, err = hasherAndOffset.mth.Write(file.Payload); err != nil {
1391 hasherAndOffset.offset += uint64(len(file.Payload))
1394 "sp-file-offset-differs", lesp, errors.New("offset differs"),
1395 func(les LEs) string {
1396 return logMsg(les) + ": deleting hasher"
1399 delete(state.fileHashers, filePath)
1400 hasherAndOffset = nil
1403 ourSize := int64(file.Offset + uint64(len(file.Payload)))
1404 lesp[len(lesp)-2].V = ourSize
1405 if state.Ctx.ShowPrgrs {
1406 state.progressBars[pktName] = struct{}{}
1407 Progress("Rx", lesp)
1409 if fullsize != ourSize {
1412 if state.Ctx.ShowPrgrs {
1413 delete(state.progressBars, pktName)
1415 logMsg = func(les LEs) string {
1417 "Got packet %s %d%% (%s / %s)",
1418 pktName, 100*ourSize/fullsize,
1419 humanize.IBytes(uint64(ourSize)),
1420 humanize.IBytes(uint64(fullsize)),
1425 state.Ctx.LogE("sp-file-sync", lesp, err, func(les LEs) string {
1426 return logMsg(les) + ": syncing"
1428 state.closeFd(filePathPart)
1431 if hasherAndOffset != nil {
1432 delete(state.fileHashers, filePath)
1433 if hasherAndOffset.mth.PrependSize == 0 {
1434 if bytes.Compare(hasherAndOffset.mth.Sum(nil), file.Hash[:]) != 0 {
1436 "sp-file-bad-checksum", lesp,
1437 errors.New("checksum mismatch"),
1440 state.closeFd(filePathPart)
1443 if err = os.Rename(filePathPart, filePath); err != nil {
1444 state.Ctx.LogE("sp-file-rename", lesp, err, func(les LEs) string {
1445 return logMsg(les) + ": renaming"
1447 state.closeFd(filePathPart)
1450 if err = DirSync(dirToSync); err != nil {
1451 state.Ctx.LogE("sp-file-dirsync", lesp, err, func(les LEs) string {
1452 return logMsg(les) + ": dirsyncing"
1454 state.closeFd(filePathPart)
1457 state.Ctx.LogI("sp-file-done", lesp, func(les LEs) string {
1458 return logMsg(les) + ": done"
1462 state.payloads <- MarshalSP(SPTypeDone, SPDone{file.Hash})
1466 delete(state.infosTheir, *file.Hash)
1468 if !state.Ctx.HdrUsage {
1471 if _, err = fd.Seek(0, io.SeekStart); err != nil {
1472 state.Ctx.LogE("sp-file-seek", lesp, err, func(les LEs) string {
1473 return logMsg(les) + ": seeking"
1475 state.closeFd(filePathPart)
1478 _, pktEncRaw, err := state.Ctx.HdrRead(fd)
1479 state.closeFd(filePathPart)
1481 state.Ctx.LogE("sp-file-hdr-read", lesp, err, func(les LEs) string {
1482 return logMsg(les) + ": HdrReading"
1486 state.Ctx.HdrWrite(pktEncRaw, filePath)
1490 state.closeFd(filePathPart)
1491 if err = os.Rename(filePathPart, filePath+NoCKSuffix); err != nil {
1492 state.Ctx.LogE("sp-file-rename", lesp, err, func(les LEs) string {
1493 return logMsg(les) + ": renaming"
1497 if err = DirSync(dirToSync); err != nil {
1498 state.Ctx.LogE("sp-file-dirsync", lesp, err, func(les LEs) string {
1499 return logMsg(les) + ": dirsyncing"
1503 state.Ctx.LogI("sp-file-downloaded", lesp, func(les LEs) string {
1504 return logMsg(les) + ": downloaded"
1507 delete(state.infosTheir, *file.Hash)
1509 if hasherAndOffset != nil {
1511 spCheckerTasks <- SPCheckerTask{
1512 nodeId: state.Node.Id,
1514 mth: hasherAndOffset.mth,
1515 done: state.payloads,
1521 lesp := append(les, LE{"Type", "done"})
1522 state.Ctx.LogD("sp-process-done-unmarshal", lesp, func(les LEs) string {
1524 "SP with %s (nice %s): unmarshaling DONE",
1525 state.Node.Name, NicenessFmt(state.Nice),
1529 if _, err = xdr.Unmarshal(r, &done); err != nil {
1530 state.Ctx.LogE("sp-process-done-unmarshal", lesp, err, func(les LEs) string {
1532 "SP with %s (nice %s): unmarshaling DONE",
1533 state.Node.Name, NicenessFmt(state.Nice),
1538 pktName := Base32Codec.EncodeToString(done.Hash[:])
1539 lesp = append(lesp, LE{"Pkt", pktName}, LE{"XX", string(TTx)})
1540 logMsg := func(les LEs) string {
1542 "SP with %s (nice %s): DONE: removing %s",
1543 state.Node.Name, NicenessFmt(state.Nice), pktName,
1546 state.Ctx.LogD("sp-done", lesp, logMsg)
1547 pth := filepath.Join(
1549 state.Node.Id.String(),
1553 if err = os.Remove(pth); err == nil {
1554 state.Ctx.LogI("sp-done", lesp, func(les LEs) string {
1555 return fmt.Sprintf("Packet %s is sent", pktName)
1557 if state.Ctx.HdrUsage {
1558 os.Remove(pth + HdrSuffix)
1561 state.Ctx.LogE("sp-done", lesp, err, logMsg)
1565 lesp := append(les, LE{"Type", "freq"})
1566 state.Ctx.LogD("sp-process-freq", lesp, func(les LEs) string {
1568 "SP with %s (nice %s): unmarshaling FREQ",
1569 state.Node.Name, NicenessFmt(state.Nice),
1573 if _, err = xdr.Unmarshal(r, &freq); err != nil {
1574 state.Ctx.LogE("sp-process-freq", lesp, err, func(les LEs) string {
1576 "SP with %s (nice %s): unmarshaling FREQ",
1577 state.Node.Name, NicenessFmt(state.Nice),
1582 pktName := Base32Codec.EncodeToString(freq.Hash[:])
1583 lesp = append(lesp, LE{"Pkt", pktName}, LE{"Offset", freq.Offset})
1584 state.Ctx.LogD("sp-process-freq-queueing", lesp, func(les LEs) string {
1586 "SP with %s (nice %s): FREQ %s: queuing",
1587 state.Node.Name, NicenessFmt(state.Nice), pktName,
1590 nice, exists := state.infosOurSeen[*freq.Hash]
1592 if state.onlyPkts == nil || !state.onlyPkts[*freq.Hash] {
1595 var freqWithNice *FreqWithNice
1596 for insertIdx, freqWithNice = range state.queueTheir {
1597 if freqWithNice.nice > nice {
1601 state.queueTheir = append(state.queueTheir, nil)
1602 copy(state.queueTheir[insertIdx+1:], state.queueTheir[insertIdx:])
1603 state.queueTheir[insertIdx] = &FreqWithNice{&freq, nice}
1606 state.Ctx.LogD("sp-process-freq-skip", lesp, func(les LEs) string {
1608 "SP with %s (nice %s): FREQ %s: skipping",
1609 state.Node.Name, NicenessFmt(state.Nice), pktName,
1614 state.Ctx.LogD("sp-process-freq-unknown", lesp, func(les LEs) string {
1616 "SP with %s (nice %s): FREQ %s: unknown",
1617 state.Node.Name, NicenessFmt(state.Nice), pktName,
1624 "sp-process-type-unknown",
1625 append(les, LE{"Type", head.Type}),
1626 errors.New("unknown type"),
1627 func(les LEs) string {
1629 "SP with %s (nice %s): %d",
1630 state.Node.Name, NicenessFmt(state.Nice), head.Type,
1634 return nil, BadPktType
1642 for _, info := range state.infosTheir {
1647 state.Ctx.LogI("sp-infos-rx", LEs{
1648 {"XX", string(TRx)},
1649 {"Node", state.Node.Id},
1651 {"Size", int64(size)},
1652 }, func(les LEs) string {
1654 "%s has got for us: %d packets, %s",
1655 state.Node.Name, pkts, humanize.IBytes(size),
1659 return payloadsSplit(replies), nil
1662 func SPChecker(ctx *Ctx) {
1663 for t := range spCheckerTasks {
1664 pktName := Base32Codec.EncodeToString(t.hsh[:])
1666 {"XX", string(TRx)},
1671 ctx.LogD("sp-checker", les, func(les LEs) string {
1672 return fmt.Sprintf("Checksumming %s/rx/%s", ctx.NodeName(t.nodeId), pktName)
1674 size, err := ctx.CheckNoCK(t.nodeId, t.hsh, t.mth)
1675 les = append(les, LE{"Size", size})
1677 ctx.LogE("sp-checker", les, err, func(les LEs) string {
1679 "Checksumming %s/rx/%s (%s)", ctx.NodeName(t.nodeId), pktName,
1680 humanize.IBytes(uint64(size)),
1686 ctx.LogI("sp-checker-done", les, func(les LEs) string {
1688 "Packet %s is retreived (%s)",
1689 pktName, humanize.IBytes(uint64(size)),
1693 go func(t SPCheckerTask) {
1694 defer func() { recover() }()
1695 t.done <- MarshalSP(SPTypeDone, SPDone{t.hsh})