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))
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))
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))
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 n.NoisePub == nil {
555 if subtle.ConstantTimeCompare(state.hs.PeerStatic(), n.NoisePub[:]) == 1 {
561 peerId := Base32Codec.EncodeToString(state.hs.PeerStatic())
562 err = errors.New("unknown peer: " + peerId)
563 state.Ctx.LogE("sp-startR-unknown", append(les, LE{"Peer", peerId}), err, logMsg)
567 state.rxRate = node.RxRate
568 state.txRate = node.TxRate
569 state.onlineDeadline = node.OnlineDeadline
570 state.maxOnlineTime = node.MaxOnlineTime
571 les = LEs{{"Node", node.Id}, {"Nice", int(state.Nice)}}
573 if err = state.Ctx.ensureRxDir(node.Id); err != nil {
577 if xxOnly == "" || xxOnly == TRx {
578 rxLock, err = state.Ctx.LockDir(node.Id, string(TRx))
583 state.rxLock = rxLock
585 if xxOnly == "" || xxOnly == TTx {
586 txLock, err = state.Ctx.LockDir(node.Id, string(TTx))
591 state.txLock = txLock
593 var infosPayloads [][]byte
594 if xxOnly == "" || xxOnly == TTx {
595 infosPayloads = state.Ctx.infosOur(node.Id, state.Nice, &state.infosOurSeen)
597 var firstPayload []byte
598 if len(infosPayloads) > 0 {
599 firstPayload = infosPayloads[0]
601 // Pad first payload, to hide actual number of existing files
602 for i := 0; i < (MaxSPSize-len(firstPayload))/SPHeadOverhead; i++ {
603 firstPayload = append(firstPayload, SPHaltMarshalized...)
606 state.Ctx.LogD("sp-startR-write", les, func(les LEs) string {
608 "SP with %s (nice %s): sending first message",
609 node.Name, NicenessFmt(state.Nice),
612 buf, state.csTheir, state.csOur, err = state.hs.WriteMessage(nil, firstPayload)
617 conn.SetWriteDeadline(time.Now().Add(DefaultDeadline))
618 if err = state.WriteSP(conn, buf, false); err != nil {
619 state.Ctx.LogE("sp-startR-write", les, err, func(les LEs) string {
621 "SP with %s (nice %s): writing",
622 node.Name, NicenessFmt(state.Nice),
628 state.Ctx.LogD("sp-startR-workers", les, func(les LEs) string {
630 "SP with %s (nice %s): starting workers",
631 node.Name, NicenessFmt(state.Nice),
634 err = state.StartWorkers(conn, infosPayloads, payload)
641 func (state *SPState) closeFd(pth string) {
643 if s, exists := state.fds[pth]; exists {
644 delete(state.fds, pth)
647 state.fdsLock.Unlock()
650 func (state *SPState) StartWorkers(
652 infosPayloads [][]byte,
655 les := LEs{{"Node", state.Node.Id}, {"Nice", int(state.Nice)}}
656 state.fds = make(map[string]FdAndFullSize)
657 state.fileHashers = make(map[string]*MTHAndOffset)
658 state.isDead = make(chan struct{})
659 if state.maxOnlineTime > 0 {
660 state.mustFinishAt = state.started.Add(state.maxOnlineTime)
663 spCheckerOnce.Do(func() { go SPChecker(state.Ctx) })
665 for job := range state.Ctx.JobsNoCK(state.Node.Id) {
666 if job.PktEnc.Nice <= state.Nice {
667 spCheckerTasks <- SPCheckerTask{
668 nodeId: state.Node.Id,
670 done: state.payloads,
677 // Remaining handshake payload sending
678 if len(infosPayloads) > 1 {
681 for _, payload := range infosPayloads[1:] {
683 "sp-queue-remaining",
684 append(les, LE{"Size", int64(len(payload))}),
685 func(les LEs) string {
687 "SP with %s (nice %s): queuing remaining payload (%s)",
688 state.Node.Name, NicenessFmt(state.Nice),
689 humanize.IBytes(uint64(len(payload))),
693 state.payloads <- payload
699 // Processing of first payload and queueing its responses
700 logMsg := func(les LEs) string {
702 "SP with %s (nice %s): processing first payload (%s)",
703 state.Node.Name, NicenessFmt(state.Nice),
704 humanize.IBytes(uint64(len(payload))),
707 state.Ctx.LogD("sp-process", append(les, LE{"Size", int64(len(payload))}), logMsg)
708 replies, err := state.ProcessSP(payload)
710 state.Ctx.LogE("sp-process", les, err, logMsg)
715 for _, reply := range replies {
718 append(les, LE{"Size", int64(len(reply))}),
719 func(les LEs) string {
721 "SP with %s (nice %s): queuing reply (%s)",
722 state.Node.Name, NicenessFmt(state.Nice),
723 humanize.IBytes(uint64(len(payload))),
727 state.payloads <- reply
735 deadlineTicker := time.NewTicker(time.Second)
736 pingTicker := time.NewTicker(PingTimeout)
741 deadlineTicker.Stop()
744 case now := <-deadlineTicker.C:
745 if now.Sub(state.RxLastNonPing) >= state.onlineDeadline &&
746 now.Sub(state.TxLastNonPing) >= state.onlineDeadline {
749 if state.maxOnlineTime > 0 && state.mustFinishAt.Before(now) {
752 if now.Sub(state.RxLastSeen) >= 2*PingTimeout {
759 case now := <-pingTicker.C:
760 if now.After(state.TxLastSeen.Add(PingTimeout)) {
763 state.pings <- struct{}{}
771 // Spool checker and INFOs sender of appearing files
772 if !state.listOnly && (state.xxOnly == "" || state.xxOnly == TTx) {
775 ticker := time.NewTicker(time.Second)
783 for _, payload := range state.Ctx.infosOur(
790 append(les, LE{"Size", int64(len(payload))}),
791 func(les LEs) string {
793 "SP with %s (nice %s): queuing new info (%s)",
794 state.Node.Name, NicenessFmt(state.Nice),
795 humanize.IBytes(uint64(len(payload))),
799 state.payloads <- payload
810 defer state.SetDead()
811 defer state.wg.Done()
812 buf := make([]byte, MaxSPSize-SPHeadOverhead-SPFileOverhead)
814 if state.NotAlive() {
821 state.Ctx.LogD("sp-got-ping", les, func(les LEs) string {
823 "SP with %s (nice %s): got ping",
824 state.Node.Name, NicenessFmt(state.Nice),
827 payload = SPPingMarshalized
829 case payload = <-state.payloads:
832 append(les, LE{"Size", int64(len(payload))}),
833 func(les LEs) string {
835 "SP with %s (nice %s): got payload (%s)",
836 state.Node.Name, NicenessFmt(state.Nice),
837 humanize.IBytes(uint64(len(payload))),
843 if len(state.queueTheir) == 0 {
845 time.Sleep(100 * time.Millisecond)
848 freq := state.queueTheir[0].freq
850 if state.txRate > 0 {
851 time.Sleep(time.Second / time.Duration(state.txRate))
853 pktName := Base32Codec.EncodeToString(freq.Hash[:])
856 LE{"XX", string(TTx)},
858 LE{"Size", int64(freq.Offset)},
860 logMsg := func(les LEs) string {
862 "SP with %s (nice %s): tx/%s (%s)",
863 state.Node.Name, NicenessFmt(state.Nice),
865 humanize.IBytes(freq.Offset),
868 state.Ctx.LogD("sp-queue", lesp, func(les LEs) string {
869 return logMsg(les) + ": queueing"
871 pth := filepath.Join(
873 state.Node.Id.String(),
875 Base32Codec.EncodeToString(freq.Hash[:]),
877 state.fdsLock.RLock()
878 fdAndFullSize, exists := state.fds[pth]
879 state.fdsLock.RUnlock()
881 state.Ctx.LogD("sp-queue-open", lesp, func(les LEs) string {
882 return logMsg(les) + ": opening"
884 fd, err := os.Open(pth)
886 state.Ctx.LogE("sp-queue-open", lesp, err, func(les LEs) string {
887 return logMsg(les) + ": opening"
893 state.Ctx.LogE("sp-queue-stat", lesp, err, func(les LEs) string {
894 return logMsg(les) + ": stating"
898 fdAndFullSize = FdAndFullSize{fd: fd, fullSize: fi.Size()}
900 state.fds[pth] = fdAndFullSize
901 state.fdsLock.Unlock()
903 fd := fdAndFullSize.fd
904 fullSize := fdAndFullSize.fullSize
905 lesp = append(lesp, LE{"FullSize", fullSize})
907 if freq.Offset < uint64(fullSize) {
908 state.Ctx.LogD("sp-file-seek", lesp, func(les LEs) string {
909 return logMsg(les) + ": seeking"
911 if _, err = fd.Seek(int64(freq.Offset), io.SeekStart); err != nil {
912 state.Ctx.LogE("sp-file-seek", lesp, err, func(les LEs) string {
913 return logMsg(les) + ": seeking"
917 n, err := fd.Read(buf)
919 state.Ctx.LogE("sp-file-read", lesp, err, func(les LEs) string {
920 return logMsg(les) + ": reading"
927 LE{"XX", string(TTx)},
929 LE{"Size", int64(n)},
930 LE{"FullSize", fullSize},
932 state.Ctx.LogD("sp-file-read", lesp, func(les LEs) string {
935 logMsg(les), humanize.IBytes(uint64(n)),
941 payload = MarshalSP(SPTypeFile, SPFile{
946 ourSize := freq.Offset + uint64(len(bufRead))
949 LE{"XX", string(TTx)},
951 LE{"Size", int64(ourSize)},
952 LE{"FullSize", fullSize},
954 if state.Ctx.ShowPrgrs {
955 state.progressBars[pktName] = struct{}{}
958 if ourSize == uint64(fullSize) {
960 state.Ctx.LogD("sp-file-finished", lesp, func(les LEs) string {
961 return logMsg(les) + ": finished"
963 if state.Ctx.ShowPrgrs {
964 delete(state.progressBars, pktName)
968 for i, q := range state.queueTheir {
969 if *q.freq.Hash != *freq.Hash {
972 if ourSize == uint64(fullSize) {
973 state.queueTheir = append(
974 state.queueTheir[:i],
975 state.queueTheir[i+1:]...,
978 q.freq.Offset = ourSize
984 logMsg := func(les LEs) string {
986 "SP with %s (nice %s): sending %s",
987 state.Node.Name, NicenessFmt(state.Nice),
988 humanize.IBytes(uint64(len(payload))),
991 state.Ctx.LogD("sp-sending", append(les, LE{"Size", int64(len(payload))}), logMsg)
992 conn.SetWriteDeadline(time.Now().Add(DefaultDeadline))
993 ct, err := state.csOur.Encrypt(nil, nil, payload)
995 state.Ctx.LogE("sp-encrypting", les, err, logMsg)
998 if err := state.WriteSP(conn, ct, ping); err != nil {
999 state.Ctx.LogE("sp-sending", les, err, logMsg)
1009 if state.NotAlive() {
1012 logMsg := func(les LEs) string {
1014 "SP with %s (nice %s): waiting for payload",
1015 state.Node.Name, NicenessFmt(state.Nice),
1018 state.Ctx.LogD("sp-recv-wait", les, logMsg)
1019 conn.SetReadDeadline(time.Now().Add(DefaultDeadline))
1020 payload, err := state.ReadSP(conn)
1025 unmarshalErr := err.(*xdr.UnmarshalError)
1026 if os.IsTimeout(unmarshalErr.Err) {
1029 if unmarshalErr.ErrorCode == xdr.ErrIO {
1032 state.Ctx.LogE("sp-recv-wait", les, err, logMsg)
1035 logMsg = func(les LEs) string {
1037 "SP with %s (nice %s): payload (%s)",
1038 state.Node.Name, NicenessFmt(state.Nice),
1039 humanize.IBytes(uint64(len(payload))),
1044 append(les, LE{"Size", int64(len(payload))}),
1045 func(les LEs) string { return logMsg(les) + ": got" },
1047 payload, err = state.csTheir.Decrypt(nil, nil, payload)
1049 state.Ctx.LogE("sp-recv-got", les, err, func(les LEs) string {
1050 return logMsg(les) + ": got"
1056 append(les, LE{"Size", int64(len(payload))}),
1057 func(les LEs) string {
1058 return logMsg(les) + ": processing"
1061 replies, err := state.ProcessSP(payload)
1063 state.Ctx.LogE("sp-recv-process", les, err, func(les LEs) string {
1064 return logMsg(les) + ": processing"
1070 for _, reply := range replies {
1073 append(les[:len(les)-1], LE{"Size", int64(len(reply))}),
1074 func(les LEs) string {
1076 "SP with %s (nice %s): queuing reply (%s)",
1077 state.Node.Name, NicenessFmt(state.Nice),
1078 humanize.IBytes(uint64(len(reply))),
1082 state.payloads <- reply
1086 if state.rxRate > 0 {
1087 time.Sleep(time.Second / time.Duration(state.rxRate))
1099 func (state *SPState) Wait() {
1101 close(state.payloads)
1103 state.Duration = time.Now().Sub(state.started)
1105 state.RxSpeed = state.RxBytes
1106 state.TxSpeed = state.TxBytes
1107 rxDuration := int64(state.RxLastSeen.Sub(state.started).Seconds())
1108 txDuration := int64(state.TxLastSeen.Sub(state.started).Seconds())
1110 state.RxSpeed = state.RxBytes / rxDuration
1113 state.TxSpeed = state.TxBytes / txDuration
1115 for _, s := range state.fds {
1118 for pktName := range state.progressBars {
1119 ProgressKill(pktName)
1123 func (state *SPState) ProcessSP(payload []byte) ([][]byte, error) {
1124 les := LEs{{"Node", state.Node.Id}, {"Nice", int(state.Nice)}}
1125 r := bytes.NewReader(payload)
1127 var replies [][]byte
1130 state.Ctx.LogD("sp-process-unmarshal", les, func(les LEs) string {
1132 "SP with %s (nice %s): unmarshaling header",
1133 state.Node.Name, NicenessFmt(state.Nice),
1137 if _, err = xdr.Unmarshal(r, &head); err != nil {
1138 state.Ctx.LogE("sp-process-unmarshal", les, err, func(les LEs) string {
1140 "SP with %s (nice %s): unmarshaling header",
1141 state.Node.Name, NicenessFmt(state.Nice),
1146 if head.Type != SPTypePing {
1147 state.RxLastNonPing = state.RxLastSeen
1153 append(les, LE{"Type", "halt"}), func(les LEs) string {
1155 "SP with %s (nice %s): got HALT",
1156 state.Node.Name, NicenessFmt(state.Nice),
1161 state.queueTheir = nil
1167 append(les, LE{"Type", "ping"}),
1168 func(les LEs) string {
1170 "SP with %s (nice %s): got PING",
1171 state.Node.Name, NicenessFmt(state.Nice),
1178 lesp := append(les, LE{"Type", "info"})
1180 "sp-process-info-unmarshal", lesp,
1181 func(les LEs) string {
1183 "SP with %s (nice %s): unmarshaling INFO",
1184 state.Node.Name, NicenessFmt(state.Nice),
1189 if _, err = xdr.Unmarshal(r, &info); err != nil {
1191 "sp-process-info-unmarshal", lesp, err,
1192 func(les LEs) string {
1194 "SP with %s (nice %s): unmarshaling INFO",
1195 state.Node.Name, NicenessFmt(state.Nice),
1201 pktName := Base32Codec.EncodeToString(info.Hash[:])
1205 LE{"Size", int64(info.Size)},
1206 LE{"PktNice", int(info.Nice)},
1208 logMsg := func(les LEs) string {
1210 "SP with %s (nice %s): INFO %s (%s) nice %s",
1211 state.Node.Name, NicenessFmt(state.Nice),
1213 humanize.IBytes(info.Size),
1214 NicenessFmt(info.Nice),
1217 if !state.listOnly && info.Nice > state.Nice {
1218 state.Ctx.LogD("sp-process-info-too-nice", lesp, func(les LEs) string {
1219 return logMsg(les) + ": too nice"
1223 state.Ctx.LogD("sp-process-info-got", lesp, func(les LEs) string {
1224 return logMsg(les) + ": received"
1226 if !state.listOnly && state.xxOnly == TTx {
1230 state.infosTheir[*info.Hash] = &info
1232 state.Ctx.LogD("sp-process-info-stat", lesp, func(les LEs) string {
1233 return logMsg(les) + ": stating part"
1235 pktPath := filepath.Join(
1237 state.Node.Id.String(),
1239 Base32Codec.EncodeToString(info.Hash[:]),
1241 logMsg = func(les LEs) string {
1243 "Packet %s (%s) (nice %s)",
1245 humanize.IBytes(info.Size),
1246 NicenessFmt(info.Nice),
1249 if _, err = os.Stat(pktPath); err == nil {
1250 state.Ctx.LogI("sp-info-done", lesp, func(les LEs) string {
1251 return logMsg(les) + ": already done"
1253 if !state.listOnly {
1254 replies = append(replies, MarshalSP(SPTypeDone, SPDone{info.Hash}))
1258 if _, err = os.Stat(pktPath + SeenSuffix); err == nil {
1259 state.Ctx.LogI("sp-info-seen", lesp, func(les LEs) string {
1260 return logMsg(les) + ": already seen"
1262 if !state.listOnly {
1263 replies = append(replies, MarshalSP(SPTypeDone, SPDone{info.Hash}))
1267 if _, err = os.Stat(pktPath + NoCKSuffix); err == nil {
1268 state.Ctx.LogI("sp-info-nock", lesp, func(les LEs) string {
1269 return logMsg(les) + ": still not checksummed"
1273 fi, err := os.Stat(pktPath + PartSuffix)
1278 if !state.Ctx.IsEnoughSpace(int64(info.Size) - offset) {
1279 state.Ctx.LogI("sp-info-no-space", lesp, func(les LEs) string {
1280 return logMsg(les) + ": not enough space"
1286 append(lesp, LE{"Offset", offset}),
1287 func(les LEs) string {
1289 "%s: %d%%", logMsg(les), 100*uint64(offset)/info.Size,
1293 if !state.listOnly && (state.onlyPkts == nil || state.onlyPkts[*info.Hash]) {
1294 replies = append(replies, MarshalSP(
1296 SPFreq{info.Hash, uint64(offset)},
1301 lesp := append(les, LE{"Type", "file"})
1302 state.Ctx.LogD("sp-process-file", lesp, func(les LEs) string {
1304 "SP with %s (nice %s): unmarshaling FILE",
1305 state.Node.Name, NicenessFmt(state.Nice),
1309 if _, err = xdr.Unmarshal(r, &file); err != nil {
1310 state.Ctx.LogE("sp-process-file", lesp, err, func(les LEs) string {
1312 "SP with %s (nice %s): unmarshaling FILE",
1313 state.Node.Name, NicenessFmt(state.Nice),
1318 pktName := Base32Codec.EncodeToString(file.Hash[:])
1321 LE{"XX", string(TRx)},
1323 LE{"Size", int64(len(file.Payload))},
1325 logMsg := func(les LEs) string {
1327 "Got packet %s (%s)",
1328 pktName, humanize.IBytes(uint64(len(file.Payload))),
1331 fullsize := int64(0)
1333 infoTheir := state.infosTheir[*file.Hash]
1335 if infoTheir == nil {
1336 state.Ctx.LogE("sp-file-open", lesp, err, func(les LEs) string {
1337 return logMsg(les) + ": unknown file"
1341 fullsize = int64(infoTheir.Size)
1342 lesp = append(lesp, LE{"FullSize", fullsize})
1343 dirToSync := filepath.Join(
1345 state.Node.Id.String(),
1348 filePath := filepath.Join(dirToSync, pktName)
1349 filePathPart := filePath + PartSuffix
1350 state.Ctx.LogD("sp-file-open", lesp, func(les LEs) string {
1351 return logMsg(les) + ": opening part"
1353 state.fdsLock.RLock()
1354 fdAndFullSize, exists := state.fds[filePathPart]
1355 state.fdsLock.RUnlock()
1356 hasherAndOffset := state.fileHashers[filePath]
1359 fd = fdAndFullSize.fd
1361 fd, err = os.OpenFile(
1363 os.O_RDWR|os.O_CREATE,
1367 state.Ctx.LogE("sp-file-open", lesp, err, func(les LEs) string {
1368 return logMsg(les) + ": opening part"
1372 state.fdsLock.Lock()
1373 state.fds[filePathPart] = FdAndFullSize{fd: fd}
1374 state.fdsLock.Unlock()
1376 hasherAndOffset = &MTHAndOffset{
1377 mth: MTHNew(fullsize, int64(file.Offset)),
1378 offset: file.Offset,
1380 state.fileHashers[filePath] = hasherAndOffset
1385 append(lesp, LE{"Offset", file.Offset}),
1386 func(les LEs) string {
1387 return fmt.Sprintf("%s: seeking %d", logMsg(les), file.Offset)
1389 if _, err = fd.Seek(int64(file.Offset), io.SeekStart); err != nil {
1390 state.Ctx.LogE("sp-file-seek", lesp, err, func(les LEs) string {
1391 return logMsg(les) + ": seeking"
1393 state.closeFd(filePathPart)
1396 state.Ctx.LogD("sp-file-write", lesp, func(les LEs) string {
1397 return logMsg(les) + ": writing"
1399 if _, err = fd.Write(file.Payload); err != nil {
1400 state.Ctx.LogE("sp-file-write", lesp, err, func(les LEs) string {
1401 return logMsg(les) + ": writing"
1403 state.closeFd(filePathPart)
1406 if hasherAndOffset != nil {
1407 if hasherAndOffset.offset == file.Offset {
1408 if _, err = hasherAndOffset.mth.Write(file.Payload); err != nil {
1411 hasherAndOffset.offset += uint64(len(file.Payload))
1414 "sp-file-offset-differs", lesp, errors.New("offset differs"),
1415 func(les LEs) string {
1416 return logMsg(les) + ": deleting hasher"
1419 delete(state.fileHashers, filePath)
1420 hasherAndOffset = nil
1423 ourSize := int64(file.Offset + uint64(len(file.Payload)))
1424 lesp[len(lesp)-2].V = ourSize
1425 if state.Ctx.ShowPrgrs {
1426 state.progressBars[pktName] = struct{}{}
1427 Progress("Rx", lesp)
1429 if fullsize != ourSize {
1432 if state.Ctx.ShowPrgrs {
1433 delete(state.progressBars, pktName)
1435 logMsg = func(les LEs) string {
1437 "Got packet %s %d%% (%s / %s)",
1438 pktName, 100*ourSize/fullsize,
1439 humanize.IBytes(uint64(ourSize)),
1440 humanize.IBytes(uint64(fullsize)),
1445 state.Ctx.LogE("sp-file-sync", lesp, err, func(les LEs) string {
1446 return logMsg(les) + ": syncing"
1448 state.closeFd(filePathPart)
1451 if hasherAndOffset != nil {
1452 delete(state.fileHashers, filePath)
1453 if hasherAndOffset.mth.PreaddSize() == 0 {
1454 if bytes.Compare(hasherAndOffset.mth.Sum(nil), file.Hash[:]) != 0 {
1456 "sp-file-bad-checksum", lesp,
1457 errors.New("checksum mismatch"),
1460 state.closeFd(filePathPart)
1463 if err = os.Rename(filePathPart, filePath); err != nil {
1464 state.Ctx.LogE("sp-file-rename", lesp, err, func(les LEs) string {
1465 return logMsg(les) + ": renaming"
1467 state.closeFd(filePathPart)
1470 if err = DirSync(dirToSync); err != nil {
1471 state.Ctx.LogE("sp-file-dirsync", lesp, err, func(les LEs) string {
1472 return logMsg(les) + ": dirsyncing"
1474 state.closeFd(filePathPart)
1477 state.Ctx.LogI("sp-file-done", lesp, func(les LEs) string {
1478 return logMsg(les) + ": done"
1482 state.payloads <- MarshalSP(SPTypeDone, SPDone{file.Hash})
1486 delete(state.infosTheir, *file.Hash)
1488 if !state.Ctx.HdrUsage {
1491 if _, err = fd.Seek(0, io.SeekStart); err != nil {
1492 state.Ctx.LogE("sp-file-seek", lesp, err, func(les LEs) string {
1493 return logMsg(les) + ": seeking"
1495 state.closeFd(filePathPart)
1498 _, pktEncRaw, err := state.Ctx.HdrRead(fd)
1499 state.closeFd(filePathPart)
1501 state.Ctx.LogE("sp-file-hdr-read", lesp, err, func(les LEs) string {
1502 return logMsg(les) + ": HdrReading"
1506 state.Ctx.HdrWrite(pktEncRaw, filePath)
1510 state.closeFd(filePathPart)
1511 if err = os.Rename(filePathPart, filePath+NoCKSuffix); err != nil {
1512 state.Ctx.LogE("sp-file-rename", lesp, err, func(les LEs) string {
1513 return logMsg(les) + ": renaming"
1517 if err = DirSync(dirToSync); err != nil {
1518 state.Ctx.LogE("sp-file-dirsync", lesp, err, func(les LEs) string {
1519 return logMsg(les) + ": dirsyncing"
1523 state.Ctx.LogI("sp-file-downloaded", lesp, func(les LEs) string {
1524 return logMsg(les) + ": downloaded"
1527 delete(state.infosTheir, *file.Hash)
1531 nodeId: state.Node.Id,
1533 done: state.payloads,
1535 if hasherAndOffset != nil {
1536 t.mth = hasherAndOffset.mth
1542 lesp := append(les, LE{"Type", "done"})
1543 state.Ctx.LogD("sp-process-done-unmarshal", lesp, func(les LEs) string {
1545 "SP with %s (nice %s): unmarshaling DONE",
1546 state.Node.Name, NicenessFmt(state.Nice),
1550 if _, err = xdr.Unmarshal(r, &done); err != nil {
1551 state.Ctx.LogE("sp-process-done-unmarshal", lesp, err, func(les LEs) string {
1553 "SP with %s (nice %s): unmarshaling DONE",
1554 state.Node.Name, NicenessFmt(state.Nice),
1559 pktName := Base32Codec.EncodeToString(done.Hash[:])
1560 lesp = append(lesp, LE{"Pkt", pktName}, LE{"XX", string(TTx)})
1561 logMsg := func(les LEs) string {
1563 "SP with %s (nice %s): DONE: removing %s",
1564 state.Node.Name, NicenessFmt(state.Nice), pktName,
1567 state.Ctx.LogD("sp-done", lesp, logMsg)
1568 pth := filepath.Join(
1570 state.Node.Id.String(),
1574 if err = os.Remove(pth); err == nil {
1575 state.Ctx.LogI("sp-done", lesp, func(les LEs) string {
1576 return fmt.Sprintf("Packet %s is sent", pktName)
1578 if state.Ctx.HdrUsage {
1579 os.Remove(pth + HdrSuffix)
1582 state.Ctx.LogE("sp-done", lesp, err, logMsg)
1586 lesp := append(les, LE{"Type", "freq"})
1587 state.Ctx.LogD("sp-process-freq", lesp, func(les LEs) string {
1589 "SP with %s (nice %s): unmarshaling FREQ",
1590 state.Node.Name, NicenessFmt(state.Nice),
1594 if _, err = xdr.Unmarshal(r, &freq); err != nil {
1595 state.Ctx.LogE("sp-process-freq", lesp, err, func(les LEs) string {
1597 "SP with %s (nice %s): unmarshaling FREQ",
1598 state.Node.Name, NicenessFmt(state.Nice),
1603 pktName := Base32Codec.EncodeToString(freq.Hash[:])
1604 lesp = append(lesp, LE{"Pkt", pktName}, LE{"Offset", freq.Offset})
1605 state.Ctx.LogD("sp-process-freq-queueing", lesp, func(les LEs) string {
1607 "SP with %s (nice %s): FREQ %s: queuing",
1608 state.Node.Name, NicenessFmt(state.Nice), pktName,
1611 nice, exists := state.infosOurSeen[*freq.Hash]
1613 if state.onlyPkts == nil || !state.onlyPkts[*freq.Hash] {
1616 var freqWithNice *FreqWithNice
1617 for insertIdx, freqWithNice = range state.queueTheir {
1618 if freqWithNice.nice > nice {
1622 state.queueTheir = append(state.queueTheir, nil)
1623 copy(state.queueTheir[insertIdx+1:], state.queueTheir[insertIdx:])
1624 state.queueTheir[insertIdx] = &FreqWithNice{&freq, nice}
1627 state.Ctx.LogD("sp-process-freq-skip", lesp, func(les LEs) string {
1629 "SP with %s (nice %s): FREQ %s: skipping",
1630 state.Node.Name, NicenessFmt(state.Nice), pktName,
1635 state.Ctx.LogD("sp-process-freq-unknown", lesp, func(les LEs) string {
1637 "SP with %s (nice %s): FREQ %s: unknown",
1638 state.Node.Name, NicenessFmt(state.Nice), pktName,
1645 "sp-process-type-unknown",
1646 append(les, LE{"Type", head.Type}),
1647 errors.New("unknown type"),
1648 func(les LEs) string {
1650 "SP with %s (nice %s): %d",
1651 state.Node.Name, NicenessFmt(state.Nice), head.Type,
1655 return nil, BadPktType
1663 for _, info := range state.infosTheir {
1668 state.Ctx.LogI("sp-infos-rx", LEs{
1669 {"XX", string(TRx)},
1670 {"Node", state.Node.Id},
1672 {"Size", int64(size)},
1673 }, func(les LEs) string {
1675 "%s has got for us: %d packets, %s",
1676 state.Node.Name, pkts, humanize.IBytes(size),
1680 return payloadsSplit(replies), nil
1683 func SPChecker(ctx *Ctx) {
1684 for t := range spCheckerTasks {
1685 pktName := Base32Codec.EncodeToString(t.hsh[:])
1687 {"XX", string(TRx)},
1692 ctx.LogD("sp-checker", les, func(les LEs) string {
1693 return fmt.Sprintf("Checksumming %s/rx/%s", ctx.NodeName(t.nodeId), pktName)
1695 size, err := ctx.CheckNoCK(t.nodeId, t.hsh, t.mth)
1696 les = append(les, LE{"Size", size})
1698 ctx.LogE("sp-checker", les, err, func(les LEs) string {
1700 "Checksumming %s/rx/%s (%s)", ctx.NodeName(t.nodeId), pktName,
1701 humanize.IBytes(uint64(size)),
1707 ctx.LogI("sp-checker-done", les, func(les LEs) string {
1709 "Packet %s is retreived (%s)",
1710 pktName, humanize.IBytes(uint64(size)),
1714 go func(t SPCheckerTask) {
1715 defer func() { recover() }()
1716 t.done <- MarshalSP(SPTypeDone, SPDone{t.hsh})