2 NNCP -- Node to Node copy, utilities for store-and-forward data exchange
3 Copyright (C) 2016-2022 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/>.
33 xdr "github.com/davecgh/go-xdr/xdr2"
34 "github.com/dustin/go-humanize"
35 "github.com/flynn/noise"
39 MaxSPSize = 1<<16 - 256
44 type MTHAndOffset struct {
49 type SPCheckerTask struct {
60 SPHaltMarshalized []byte
61 SPPingMarshalized []byte
63 NoiseCipherSuite noise.CipherSuite = noise.NewCipherSuite(
65 noise.CipherChaChaPoly,
69 DefaultDeadline = 10 * time.Second
70 PingTimeout = time.Minute
72 spCheckerTasks chan SPCheckerTask
73 SPCheckerWg sync.WaitGroup
74 spCheckerOnce sync.Once
77 type FdAndFullSize struct {
85 SPTypeInfo SPType = iota
86 SPTypeFreq SPType = iota
87 SPTypeFile SPType = iota
88 SPTypeDone SPType = iota
89 SPTypeHalt SPType = iota
90 SPTypePing SPType = iota
123 type FreqWithNice struct {
128 type ConnDeadlined interface {
130 SetReadDeadline(t time.Time) error
131 SetWriteDeadline(t time.Time) error
136 spHead := SPHead{Type: SPTypeHalt}
137 if _, err := xdr.Marshal(&buf, spHead); err != nil {
140 SPHaltMarshalized = make([]byte, SPHeadOverhead)
141 copy(SPHaltMarshalized, buf.Bytes())
144 spHead = SPHead{Type: SPTypePing}
145 if _, err := xdr.Marshal(&buf, spHead); err != nil {
148 SPPingMarshalized = make([]byte, SPHeadOverhead)
149 copy(SPPingMarshalized, buf.Bytes())
152 spInfo := SPInfo{Nice: 123, Size: 123, Hash: new([MTHSize]byte)}
153 if _, err := xdr.Marshal(&buf, spInfo); err != nil {
156 SPInfoOverhead = buf.Len()
159 spFreq := SPFreq{Hash: new([MTHSize]byte), Offset: 123}
160 if _, err := xdr.Marshal(&buf, spFreq); err != nil {
163 SPFreqOverhead = buf.Len()
166 spFile := SPFile{Hash: new([MTHSize]byte), Offset: 123}
167 if _, err := xdr.Marshal(&buf, spFile); err != nil {
170 SPFileOverhead = buf.Len()
171 spCheckerTasks = make(chan SPCheckerTask)
174 func MarshalSP(typ SPType, sp interface{}) []byte {
176 if _, err := xdr.Marshal(&buf, SPHead{typ}); err != nil {
179 if _, err := xdr.Marshal(&buf, sp); err != nil {
185 func payloadsSplit(payloads [][]byte) [][]byte {
186 var outbounds [][]byte
187 outbound := make([]byte, 0, MaxSPSize)
188 for i, payload := range payloads {
189 outbound = append(outbound, payload...)
190 if i+1 < len(payloads) && len(outbound)+len(payloads[i+1]) > MaxSPSize {
191 outbounds = append(outbounds, outbound)
192 outbound = make([]byte, 0, MaxSPSize)
195 if len(outbound) > 0 {
196 outbounds = append(outbounds, outbound)
201 type SPState struct {
206 onlineDeadline time.Duration
207 maxOnlineTime time.Duration
208 hs *noise.HandshakeState
209 csOur *noise.CipherState
210 csTheir *noise.CipherState
213 infosTheir map[[MTHSize]byte]*SPInfo
214 infosOurSeen map[[MTHSize]byte]uint8
215 queueTheir []*FreqWithNice
219 RxLastNonPing time.Time
222 TxLastNonPing time.Time
224 mustFinishAt time.Time
225 Duration time.Duration
235 onlyPkts map[[MTHSize]byte]bool
236 writeSPBuf bytes.Buffer
237 fds map[string]FdAndFullSize
239 fileHashers map[string]*MTHAndOffset
240 progressBars map[string]struct{}
244 func (state *SPState) SetDead() {
249 // Already closed channel, dead
255 for range state.payloads {
259 for range state.pings {
264 func (state *SPState) NotAlive() bool {
273 func (state *SPState) dirUnlock() {
274 state.Ctx.UnlockDir(state.rxLock)
275 state.Ctx.UnlockDir(state.txLock)
278 func (state *SPState) WriteSP(dst io.Writer, payload []byte, ping bool) error {
279 state.writeSPBuf.Reset()
280 n, err := xdr.Marshal(&state.writeSPBuf, SPRaw{
281 Magic: MagicNNCPSv1.B,
287 if n, err = dst.Write(state.writeSPBuf.Bytes()); err == nil {
288 state.TxLastSeen = time.Now()
289 state.TxBytes += int64(n)
291 state.TxLastNonPing = state.TxLastSeen
297 func (state *SPState) ReadSP(src io.Reader) ([]byte, error) {
299 n, err := xdr.UnmarshalLimited(src, &sp, 1<<17)
301 ue := err.(*xdr.UnmarshalError)
302 if ue.Err == io.EOF {
307 state.RxLastSeen = time.Now()
308 state.RxBytes += int64(n)
309 if sp.Magic != MagicNNCPSv1.B {
312 return sp.Payload, nil
315 func (ctx *Ctx) infosOur(nodeId *NodeId, nice uint8, seen *map[[MTHSize]byte]uint8) [][]byte {
318 for job := range ctx.Jobs(nodeId, TTx) {
319 if job.PktEnc.Nice > nice {
322 if _, known := (*seen)[*job.HshValue]; known {
325 totalSize += job.Size
326 infos = append(infos, &SPInfo{
327 Nice: job.PktEnc.Nice,
328 Size: uint64(job.Size),
331 (*seen)[*job.HshValue] = job.PktEnc.Nice
333 sort.Sort(ByNice(infos))
334 var payloads [][]byte
335 for _, info := range infos {
336 payloads = append(payloads, MarshalSP(SPTypeInfo, info))
337 pktName := Base32Codec.EncodeToString(info.Hash[:])
338 ctx.LogD("sp-info-our", LEs{
342 }, func(les LEs) string {
344 "Our info: %s/tx/%s (%s)",
345 ctx.NodeName(nodeId),
347 humanize.IBytes(info.Size),
352 ctx.LogI("sp-infos-tx", LEs{
355 {"Pkts", len(payloads)},
357 }, func(les LEs) string {
359 "We have got for %s: %d packets, %s",
360 ctx.NodeName(nodeId),
362 humanize.IBytes(uint64(totalSize)),
366 return payloadsSplit(payloads)
369 func (state *SPState) StartI(conn ConnDeadlined) error {
370 nodeId := state.Node.Id
371 err := state.Ctx.ensureRxDir(nodeId)
376 if !state.listOnly && (state.xxOnly == "" || state.xxOnly == TRx) {
377 rxLock, err = state.Ctx.LockDir(nodeId, string(TRx))
383 if !state.listOnly && (state.xxOnly == "" || state.xxOnly == TTx) {
384 txLock, err = state.Ctx.LockDir(nodeId, string(TTx))
389 started := time.Now()
390 conf := noise.Config{
391 CipherSuite: NoiseCipherSuite,
392 Pattern: noise.HandshakeIK,
394 StaticKeypair: noise.DHKey{
395 Private: state.Ctx.Self.NoisePrv[:],
396 Public: state.Ctx.Self.NoisePub[:],
398 PeerStatic: state.Node.NoisePub[:],
400 hs, err := noise.NewHandshakeState(conf)
405 state.payloads = make(chan []byte)
406 state.pings = make(chan struct{})
407 state.infosTheir = make(map[[MTHSize]byte]*SPInfo)
408 state.infosOurSeen = make(map[[MTHSize]byte]uint8)
409 state.progressBars = make(map[string]struct{})
410 state.started = started
411 state.rxLock = rxLock
412 state.txLock = txLock
414 var infosPayloads [][]byte
415 if !state.listOnly && (state.xxOnly == "" || state.xxOnly == TTx) {
416 infosPayloads = state.Ctx.infosOur(nodeId, state.Nice, &state.infosOurSeen)
418 var firstPayload []byte
419 if len(infosPayloads) > 0 {
420 firstPayload = infosPayloads[0]
422 // Pad first payload, to hide actual number of existing files
423 for i := 0; i < (MaxSPSize-len(firstPayload))/SPHeadOverhead; i++ {
424 firstPayload = append(firstPayload, SPHaltMarshalized...)
429 buf, _, _, err = state.hs.WriteMessage(nil, firstPayload)
434 les := LEs{{"Node", nodeId}, {"Nice", int(state.Nice)}}
435 state.Ctx.LogD("sp-startI", les, func(les LEs) string {
437 "SP with %s (nice %s): sending first message",
439 NicenessFmt(state.Nice),
442 conn.SetWriteDeadline(time.Now().Add(DefaultDeadline))
443 if err = state.WriteSP(conn, buf, false); err != nil {
444 state.Ctx.LogE("sp-startI", les, err, func(les LEs) string {
446 "SP with %s (nice %s): writing",
448 NicenessFmt(state.Nice),
454 state.Ctx.LogD("sp-startI-wait", les, func(les LEs) string {
456 "SP with %s (nice %s): waiting for first message",
458 NicenessFmt(state.Nice),
461 conn.SetReadDeadline(time.Now().Add(DefaultDeadline))
462 if buf, err = state.ReadSP(conn); err != nil {
463 state.Ctx.LogE("sp-startI-read", les, err, func(les LEs) string {
465 "SP with %s (nice %s): reading",
467 NicenessFmt(state.Nice),
473 payload, state.csOur, state.csTheir, err = state.hs.ReadMessage(nil, buf)
475 state.Ctx.LogE("sp-startI-read", les, err, func(les LEs) string {
477 "SP with %s (nice %s): reading Noise message",
479 NicenessFmt(state.Nice),
485 state.Ctx.LogD("sp-startI-workers", les, func(les LEs) string {
487 "SP with %s (nice %s): starting workers",
489 NicenessFmt(state.Nice),
492 err = state.StartWorkers(conn, infosPayloads, payload)
494 state.Ctx.LogE("sp-startI-workers", les, err, func(les LEs) string {
496 "SP with %s (nice %s): starting workers",
498 NicenessFmt(state.Nice),
506 func (state *SPState) StartR(conn ConnDeadlined) error {
507 started := time.Now()
508 conf := noise.Config{
509 CipherSuite: NoiseCipherSuite,
510 Pattern: noise.HandshakeIK,
512 StaticKeypair: noise.DHKey{
513 Private: state.Ctx.Self.NoisePrv[:],
514 Public: state.Ctx.Self.NoisePub[:],
517 hs, err := noise.NewHandshakeState(conf)
523 state.payloads = make(chan []byte)
524 state.pings = make(chan struct{})
525 state.infosOurSeen = make(map[[MTHSize]byte]uint8)
526 state.infosTheir = make(map[[MTHSize]byte]*SPInfo)
527 state.progressBars = make(map[string]struct{})
528 state.started = started
529 state.xxOnly = xxOnly
533 logMsg := func(les LEs) string {
535 "SP nice %s: waiting for first message",
536 NicenessFmt(state.Nice),
539 les := LEs{{"Nice", int(state.Nice)}}
540 state.Ctx.LogD("sp-startR", les, logMsg)
541 conn.SetReadDeadline(time.Now().Add(DefaultDeadline))
542 if buf, err = state.ReadSP(conn); err != nil {
543 state.Ctx.LogE("sp-startR-read", les, err, logMsg)
546 if payload, _, _, err = state.hs.ReadMessage(nil, buf); err != nil {
547 state.Ctx.LogE("sp-startR-read", les, err, logMsg)
552 for _, n := range state.Ctx.Neigh {
553 if n.NoisePub == nil {
556 if subtle.ConstantTimeCompare(state.hs.PeerStatic(), n.NoisePub[:]) == 1 {
562 peerId := Base32Codec.EncodeToString(state.hs.PeerStatic())
563 err = errors.New("unknown peer: " + peerId)
564 state.Ctx.LogE("sp-startR-unknown", append(les, LE{"Peer", peerId}), err, logMsg)
568 state.rxRate = node.RxRate
569 state.txRate = node.TxRate
570 state.onlineDeadline = node.OnlineDeadline
571 state.maxOnlineTime = node.MaxOnlineTime
572 les = LEs{{"Node", node.Id}, {"Nice", int(state.Nice)}}
574 if err = state.Ctx.ensureRxDir(node.Id); err != nil {
578 if xxOnly == "" || xxOnly == TRx {
579 rxLock, err = state.Ctx.LockDir(node.Id, string(TRx))
584 state.rxLock = rxLock
586 if xxOnly == "" || xxOnly == TTx {
587 txLock, err = state.Ctx.LockDir(node.Id, string(TTx))
592 state.txLock = txLock
594 var infosPayloads [][]byte
595 if xxOnly == "" || xxOnly == TTx {
596 infosPayloads = state.Ctx.infosOur(node.Id, state.Nice, &state.infosOurSeen)
598 var firstPayload []byte
599 if len(infosPayloads) > 0 {
600 firstPayload = infosPayloads[0]
602 // Pad first payload, to hide actual number of existing files
603 for i := 0; i < (MaxSPSize-len(firstPayload))/SPHeadOverhead; i++ {
604 firstPayload = append(firstPayload, SPHaltMarshalized...)
607 state.Ctx.LogD("sp-startR-write", les, func(les LEs) string {
609 "SP with %s (nice %s): sending first message",
610 node.Name, NicenessFmt(state.Nice),
613 buf, state.csTheir, state.csOur, err = state.hs.WriteMessage(nil, firstPayload)
618 conn.SetWriteDeadline(time.Now().Add(DefaultDeadline))
619 if err = state.WriteSP(conn, buf, false); err != nil {
620 state.Ctx.LogE("sp-startR-write", les, err, func(les LEs) string {
622 "SP with %s (nice %s): writing",
623 node.Name, NicenessFmt(state.Nice),
629 state.Ctx.LogD("sp-startR-workers", les, func(les LEs) string {
631 "SP with %s (nice %s): starting workers",
632 node.Name, NicenessFmt(state.Nice),
635 err = state.StartWorkers(conn, infosPayloads, payload)
642 func (state *SPState) closeFd(pth string) {
644 if s, exists := state.fds[pth]; exists {
645 delete(state.fds, pth)
648 state.fdsLock.Unlock()
651 func (state *SPState) StartWorkers(
653 infosPayloads [][]byte,
656 les := LEs{{"Node", state.Node.Id}, {"Nice", int(state.Nice)}}
657 state.fds = make(map[string]FdAndFullSize)
658 state.fileHashers = make(map[string]*MTHAndOffset)
659 state.isDead = make(chan struct{})
660 if state.maxOnlineTime > 0 {
661 state.mustFinishAt = state.started.Add(state.maxOnlineTime)
664 spCheckerOnce.Do(func() { go SPChecker(state.Ctx) })
666 for job := range state.Ctx.JobsNoCK(state.Node.Id) {
667 if job.PktEnc.Nice <= state.Nice {
668 spCheckerTasks <- SPCheckerTask{
669 nodeId: state.Node.Id,
671 done: state.payloads,
678 // Remaining handshake payload sending
679 if len(infosPayloads) > 1 {
682 for _, payload := range infosPayloads[1:] {
684 "sp-queue-remaining",
685 append(les, LE{"Size", int64(len(payload))}),
686 func(les LEs) string {
688 "SP with %s (nice %s): queuing remaining payload (%s)",
689 state.Node.Name, NicenessFmt(state.Nice),
690 humanize.IBytes(uint64(len(payload))),
694 state.payloads <- payload
700 // Processing of first payload and queueing its responses
701 logMsg := func(les LEs) string {
703 "SP with %s (nice %s): processing first payload (%s)",
704 state.Node.Name, NicenessFmt(state.Nice),
705 humanize.IBytes(uint64(len(payload))),
708 state.Ctx.LogD("sp-process", append(les, LE{"Size", int64(len(payload))}), logMsg)
709 replies, err := state.ProcessSP(payload)
711 state.Ctx.LogE("sp-process", les, err, logMsg)
716 for _, reply := range replies {
719 append(les, LE{"Size", int64(len(reply))}),
720 func(les LEs) string {
722 "SP with %s (nice %s): queuing reply (%s)",
723 state.Node.Name, NicenessFmt(state.Nice),
724 humanize.IBytes(uint64(len(payload))),
728 state.payloads <- reply
736 deadlineTicker := time.NewTicker(time.Second)
737 pingTicker := time.NewTicker(PingTimeout)
742 deadlineTicker.Stop()
745 case now := <-deadlineTicker.C:
746 if now.Sub(state.RxLastNonPing) >= state.onlineDeadline &&
747 now.Sub(state.TxLastNonPing) >= state.onlineDeadline {
750 if state.maxOnlineTime > 0 && state.mustFinishAt.Before(now) {
753 if now.Sub(state.RxLastSeen) >= 2*PingTimeout {
760 case now := <-pingTicker.C:
761 if now.After(state.TxLastSeen.Add(PingTimeout)) {
764 state.pings <- struct{}{}
772 // Spool checker and INFOs sender of appearing files
773 if !state.listOnly && (state.xxOnly == "" || state.xxOnly == TTx) {
776 dw, err := state.Ctx.NewDirWatcher(
777 filepath.Join(state.Ctx.Spool, state.Node.Id.String(), string(TTx)),
781 state.Ctx.LogE("sp-queue-dir-watch", les, err, logMsg)
791 for _, payload := range state.Ctx.infosOur(
798 append(les, LE{"Size", int64(len(payload))}),
799 func(les LEs) string {
801 "SP with %s (nice %s): queuing new info (%s)",
802 state.Node.Name, NicenessFmt(state.Nice),
803 humanize.IBytes(uint64(len(payload))),
807 state.payloads <- payload
818 defer state.SetDead()
819 defer state.wg.Done()
820 buf := make([]byte, MaxSPSize-SPHeadOverhead-SPFileOverhead)
822 if state.NotAlive() {
829 state.Ctx.LogD("sp-got-ping", les, func(les LEs) string {
831 "SP with %s (nice %s): got ping",
832 state.Node.Name, NicenessFmt(state.Nice),
835 payload = SPPingMarshalized
837 case payload = <-state.payloads:
840 append(les, LE{"Size", int64(len(payload))}),
841 func(les LEs) string {
843 "SP with %s (nice %s): got payload (%s)",
844 state.Node.Name, NicenessFmt(state.Nice),
845 humanize.IBytes(uint64(len(payload))),
851 if len(state.queueTheir) == 0 {
853 time.Sleep(100 * time.Millisecond)
856 freq := state.queueTheir[0].freq
858 if state.txRate > 0 {
859 time.Sleep(time.Second / time.Duration(state.txRate))
861 pktName := Base32Codec.EncodeToString(freq.Hash[:])
864 LE{"XX", string(TTx)},
866 LE{"Size", int64(freq.Offset)},
868 logMsg := func(les LEs) string {
870 "SP with %s (nice %s): tx/%s (%s)",
871 state.Node.Name, NicenessFmt(state.Nice),
873 humanize.IBytes(freq.Offset),
876 state.Ctx.LogD("sp-queue", lesp, func(les LEs) string {
877 return logMsg(les) + ": queueing"
879 pth := filepath.Join(
881 state.Node.Id.String(),
883 Base32Codec.EncodeToString(freq.Hash[:]),
885 state.fdsLock.RLock()
886 fdAndFullSize, exists := state.fds[pth]
887 state.fdsLock.RUnlock()
889 state.Ctx.LogD("sp-queue-open", lesp, func(les LEs) string {
890 return logMsg(les) + ": opening"
892 fd, err := os.Open(pth)
894 state.Ctx.LogE("sp-queue-open", lesp, err, func(les LEs) string {
895 return logMsg(les) + ": opening"
901 state.Ctx.LogE("sp-queue-stat", lesp, err, func(les LEs) string {
902 return logMsg(les) + ": stating"
906 fdAndFullSize = FdAndFullSize{fd: fd, fullSize: fi.Size()}
908 state.fds[pth] = fdAndFullSize
909 state.fdsLock.Unlock()
911 fd := fdAndFullSize.fd
912 fullSize := fdAndFullSize.fullSize
913 lesp = append(lesp, LE{"FullSize", fullSize})
915 if freq.Offset < uint64(fullSize) {
916 state.Ctx.LogD("sp-file-seek", lesp, func(les LEs) string {
917 return logMsg(les) + ": seeking"
919 if _, err = fd.Seek(int64(freq.Offset), io.SeekStart); err != nil {
920 state.Ctx.LogE("sp-file-seek", lesp, err, func(les LEs) string {
921 return logMsg(les) + ": seeking"
925 n, err := fd.Read(buf)
927 state.Ctx.LogE("sp-file-read", lesp, err, func(les LEs) string {
928 return logMsg(les) + ": reading"
935 LE{"XX", string(TTx)},
937 LE{"Size", int64(n)},
938 LE{"FullSize", fullSize},
940 state.Ctx.LogD("sp-file-read", lesp, func(les LEs) string {
943 logMsg(les), humanize.IBytes(uint64(n)),
949 payload = MarshalSP(SPTypeFile, SPFile{
954 ourSize := freq.Offset + uint64(len(bufRead))
957 LE{"XX", string(TTx)},
959 LE{"Size", int64(ourSize)},
960 LE{"FullSize", fullSize},
962 if state.Ctx.ShowPrgrs {
963 state.progressBars[pktName] = struct{}{}
966 if ourSize == uint64(fullSize) {
968 state.Ctx.LogD("sp-file-finished", lesp, func(les LEs) string {
969 return logMsg(les) + ": finished"
971 if state.Ctx.ShowPrgrs {
972 delete(state.progressBars, pktName)
976 for i, q := range state.queueTheir {
977 if *q.freq.Hash != *freq.Hash {
980 if ourSize == uint64(fullSize) {
981 state.queueTheir = append(
982 state.queueTheir[:i],
983 state.queueTheir[i+1:]...,
986 q.freq.Offset = ourSize
992 logMsg := func(les LEs) string {
994 "SP with %s (nice %s): sending %s",
995 state.Node.Name, NicenessFmt(state.Nice),
996 humanize.IBytes(uint64(len(payload))),
999 state.Ctx.LogD("sp-sending", append(les, LE{"Size", int64(len(payload))}), logMsg)
1000 conn.SetWriteDeadline(time.Now().Add(DefaultDeadline))
1001 ct, err := state.csOur.Encrypt(nil, nil, payload)
1003 state.Ctx.LogE("sp-encrypting", les, err, logMsg)
1006 if err := state.WriteSP(conn, ct, ping); err != nil {
1007 state.Ctx.LogE("sp-sending", les, err, logMsg)
1017 if state.NotAlive() {
1020 logMsg := func(les LEs) string {
1022 "SP with %s (nice %s): waiting for payload",
1023 state.Node.Name, NicenessFmt(state.Nice),
1026 state.Ctx.LogD("sp-recv-wait", les, logMsg)
1027 conn.SetReadDeadline(time.Now().Add(DefaultDeadline))
1028 payload, err := state.ReadSP(conn)
1033 unmarshalErr := err.(*xdr.UnmarshalError)
1034 if os.IsTimeout(unmarshalErr.Err) {
1037 if unmarshalErr.ErrorCode == xdr.ErrIO {
1040 state.Ctx.LogE("sp-recv-wait", les, err, logMsg)
1043 logMsg = func(les LEs) string {
1045 "SP with %s (nice %s): payload (%s)",
1046 state.Node.Name, NicenessFmt(state.Nice),
1047 humanize.IBytes(uint64(len(payload))),
1052 append(les, LE{"Size", int64(len(payload))}),
1053 func(les LEs) string { return logMsg(les) + ": got" },
1055 payload, err = state.csTheir.Decrypt(nil, nil, payload)
1057 state.Ctx.LogE("sp-recv-got", les, err, func(les LEs) string {
1058 return logMsg(les) + ": got"
1064 append(les, LE{"Size", int64(len(payload))}),
1065 func(les LEs) string {
1066 return logMsg(les) + ": processing"
1069 replies, err := state.ProcessSP(payload)
1071 state.Ctx.LogE("sp-recv-process", les, err, func(les LEs) string {
1072 return logMsg(les) + ": processing"
1078 for _, reply := range replies {
1081 append(les[:len(les)-1], LE{"Size", int64(len(reply))}),
1082 func(les LEs) string {
1084 "SP with %s (nice %s): queuing reply (%s)",
1085 state.Node.Name, NicenessFmt(state.Nice),
1086 humanize.IBytes(uint64(len(reply))),
1090 state.payloads <- reply
1094 if state.rxRate > 0 {
1095 time.Sleep(time.Second / time.Duration(state.rxRate))
1107 func (state *SPState) Wait() {
1109 close(state.payloads)
1111 state.Duration = time.Now().Sub(state.started)
1113 state.RxSpeed = state.RxBytes
1114 state.TxSpeed = state.TxBytes
1115 rxDuration := int64(state.RxLastSeen.Sub(state.started).Seconds())
1116 txDuration := int64(state.TxLastSeen.Sub(state.started).Seconds())
1118 state.RxSpeed = state.RxBytes / rxDuration
1121 state.TxSpeed = state.TxBytes / txDuration
1123 for _, s := range state.fds {
1126 for pktName := range state.progressBars {
1127 ProgressKill(pktName)
1131 func (state *SPState) ProcessSP(payload []byte) ([][]byte, error) {
1132 les := LEs{{"Node", state.Node.Id}, {"Nice", int(state.Nice)}}
1133 r := bytes.NewReader(payload)
1135 var replies [][]byte
1138 state.Ctx.LogD("sp-process-unmarshal", les, func(les LEs) string {
1140 "SP with %s (nice %s): unmarshaling header",
1141 state.Node.Name, NicenessFmt(state.Nice),
1145 if _, err = xdr.Unmarshal(r, &head); err != nil {
1146 state.Ctx.LogE("sp-process-unmarshal", les, err, func(les LEs) string {
1148 "SP with %s (nice %s): unmarshaling header",
1149 state.Node.Name, NicenessFmt(state.Nice),
1154 if head.Type != SPTypePing {
1155 state.RxLastNonPing = state.RxLastSeen
1161 append(les, LE{"Type", "halt"}), func(les LEs) string {
1163 "SP with %s (nice %s): got HALT",
1164 state.Node.Name, NicenessFmt(state.Nice),
1169 state.queueTheir = nil
1175 append(les, LE{"Type", "ping"}),
1176 func(les LEs) string {
1178 "SP with %s (nice %s): got PING",
1179 state.Node.Name, NicenessFmt(state.Nice),
1186 lesp := append(les, LE{"Type", "info"})
1188 "sp-process-info-unmarshal", lesp,
1189 func(les LEs) string {
1191 "SP with %s (nice %s): unmarshaling INFO",
1192 state.Node.Name, NicenessFmt(state.Nice),
1197 if _, err = xdr.Unmarshal(r, &info); err != nil {
1199 "sp-process-info-unmarshal", lesp, err,
1200 func(les LEs) string {
1202 "SP with %s (nice %s): unmarshaling INFO",
1203 state.Node.Name, NicenessFmt(state.Nice),
1209 pktName := Base32Codec.EncodeToString(info.Hash[:])
1213 LE{"Size", int64(info.Size)},
1214 LE{"PktNice", int(info.Nice)},
1216 logMsg := func(les LEs) string {
1218 "SP with %s (nice %s): INFO %s (%s) nice %s",
1219 state.Node.Name, NicenessFmt(state.Nice),
1221 humanize.IBytes(info.Size),
1222 NicenessFmt(info.Nice),
1225 if !state.listOnly && info.Nice > state.Nice {
1226 state.Ctx.LogD("sp-process-info-too-nice", lesp, func(les LEs) string {
1227 return logMsg(les) + ": too nice"
1231 state.Ctx.LogD("sp-process-info-got", lesp, func(les LEs) string {
1232 return logMsg(les) + ": received"
1234 if !state.listOnly && state.xxOnly == TTx {
1238 state.infosTheir[*info.Hash] = &info
1240 state.Ctx.LogD("sp-process-info-stat", lesp, func(les LEs) string {
1241 return logMsg(les) + ": stating part"
1243 pktPath := filepath.Join(
1245 state.Node.Id.String(),
1247 Base32Codec.EncodeToString(info.Hash[:]),
1249 logMsg = func(les LEs) string {
1251 "Packet %s (%s) (nice %s)",
1253 humanize.IBytes(info.Size),
1254 NicenessFmt(info.Nice),
1257 if _, err = os.Stat(pktPath); err == nil {
1258 state.Ctx.LogI("sp-info-done", lesp, func(les LEs) string {
1259 return logMsg(les) + ": already done"
1261 if !state.listOnly {
1262 replies = append(replies, MarshalSP(SPTypeDone, SPDone{info.Hash}))
1266 if _, err = os.Stat(filepath.Join(
1267 state.Ctx.Spool, state.Node.Id.String(), string(TRx),
1268 SeenDir, Base32Codec.EncodeToString(info.Hash[:]),
1270 state.Ctx.LogI("sp-info-seen", lesp, func(les LEs) string {
1271 return logMsg(les) + ": already seen"
1273 if !state.listOnly {
1274 replies = append(replies, MarshalSP(SPTypeDone, SPDone{info.Hash}))
1278 if _, err = os.Stat(pktPath + NoCKSuffix); err == nil {
1279 state.Ctx.LogI("sp-info-nock", lesp, func(les LEs) string {
1280 return logMsg(les) + ": still not checksummed"
1284 fi, err := os.Stat(pktPath + PartSuffix)
1289 if !state.Ctx.IsEnoughSpace(int64(info.Size) - offset) {
1290 state.Ctx.LogI("sp-info-no-space", lesp, func(les LEs) string {
1291 return logMsg(les) + ": not enough space"
1297 append(lesp, LE{"Offset", offset}),
1298 func(les LEs) string {
1300 "%s: %d%%", logMsg(les), 100*uint64(offset)/info.Size,
1304 if !state.listOnly && (state.onlyPkts == nil || state.onlyPkts[*info.Hash]) {
1305 replies = append(replies, MarshalSP(
1307 SPFreq{info.Hash, uint64(offset)},
1312 lesp := append(les, LE{"Type", "file"})
1313 state.Ctx.LogD("sp-process-file", lesp, func(les LEs) string {
1315 "SP with %s (nice %s): unmarshaling FILE",
1316 state.Node.Name, NicenessFmt(state.Nice),
1320 if _, err = xdr.Unmarshal(r, &file); err != nil {
1321 state.Ctx.LogE("sp-process-file", lesp, err, func(les LEs) string {
1323 "SP with %s (nice %s): unmarshaling FILE",
1324 state.Node.Name, NicenessFmt(state.Nice),
1329 pktName := Base32Codec.EncodeToString(file.Hash[:])
1332 LE{"XX", string(TRx)},
1334 LE{"Size", int64(len(file.Payload))},
1336 logMsg := func(les LEs) string {
1338 "Got packet %s (%s)",
1339 pktName, humanize.IBytes(uint64(len(file.Payload))),
1342 fullsize := int64(0)
1344 infoTheir := state.infosTheir[*file.Hash]
1346 if infoTheir == nil {
1347 state.Ctx.LogE("sp-file-open", lesp, err, func(les LEs) string {
1348 return logMsg(les) + ": unknown file"
1352 fullsize = int64(infoTheir.Size)
1353 lesp = append(lesp, LE{"FullSize", fullsize})
1354 dirToSync := filepath.Join(
1356 state.Node.Id.String(),
1359 filePath := filepath.Join(dirToSync, pktName)
1360 filePathPart := filePath + PartSuffix
1361 state.Ctx.LogD("sp-file-open", lesp, func(les LEs) string {
1362 return logMsg(les) + ": opening part"
1364 state.fdsLock.RLock()
1365 fdAndFullSize, exists := state.fds[filePathPart]
1366 state.fdsLock.RUnlock()
1367 hasherAndOffset := state.fileHashers[filePath]
1370 fd = fdAndFullSize.fd
1372 fd, err = os.OpenFile(
1374 os.O_RDWR|os.O_CREATE,
1378 state.Ctx.LogE("sp-file-open", lesp, err, func(les LEs) string {
1379 return logMsg(les) + ": opening part"
1383 state.fdsLock.Lock()
1384 state.fds[filePathPart] = FdAndFullSize{fd: fd}
1385 state.fdsLock.Unlock()
1387 hasherAndOffset = &MTHAndOffset{
1388 mth: MTHNew(fullsize, int64(file.Offset)),
1389 offset: file.Offset,
1391 state.fileHashers[filePath] = hasherAndOffset
1396 append(lesp, LE{"Offset", file.Offset}),
1397 func(les LEs) string {
1398 return fmt.Sprintf("%s: seeking %d", logMsg(les), file.Offset)
1400 if _, err = fd.Seek(int64(file.Offset), io.SeekStart); err != nil {
1401 state.Ctx.LogE("sp-file-seek", lesp, err, func(les LEs) string {
1402 return logMsg(les) + ": seeking"
1404 state.closeFd(filePathPart)
1407 state.Ctx.LogD("sp-file-write", lesp, func(les LEs) string {
1408 return logMsg(les) + ": writing"
1410 if _, err = fd.Write(file.Payload); err != nil {
1411 state.Ctx.LogE("sp-file-write", lesp, err, func(les LEs) string {
1412 return logMsg(les) + ": writing"
1414 state.closeFd(filePathPart)
1417 if hasherAndOffset != nil {
1418 if hasherAndOffset.offset == file.Offset {
1419 if _, err = hasherAndOffset.mth.Write(file.Payload); err != nil {
1422 hasherAndOffset.offset += uint64(len(file.Payload))
1425 "sp-file-offset-differs", lesp, errors.New("offset differs"),
1426 func(les LEs) string {
1427 return logMsg(les) + ": deleting hasher"
1430 delete(state.fileHashers, filePath)
1431 hasherAndOffset = nil
1434 ourSize := int64(file.Offset + uint64(len(file.Payload)))
1435 lesp[len(lesp)-2].V = ourSize
1436 if state.Ctx.ShowPrgrs {
1437 state.progressBars[pktName] = struct{}{}
1438 Progress("Rx", lesp)
1440 if fullsize != ourSize {
1443 if state.Ctx.ShowPrgrs {
1444 delete(state.progressBars, pktName)
1446 logMsg = func(les LEs) string {
1448 "Got packet %s %d%% (%s / %s)",
1449 pktName, 100*ourSize/fullsize,
1450 humanize.IBytes(uint64(ourSize)),
1451 humanize.IBytes(uint64(fullsize)),
1456 state.Ctx.LogE("sp-file-sync", lesp, err, func(les LEs) string {
1457 return logMsg(les) + ": syncing"
1459 state.closeFd(filePathPart)
1462 if hasherAndOffset != nil {
1463 delete(state.fileHashers, filePath)
1464 if hasherAndOffset.mth.PreaddSize() == 0 {
1465 if bytes.Compare(hasherAndOffset.mth.Sum(nil), file.Hash[:]) != 0 {
1467 "sp-file-bad-checksum", lesp,
1468 errors.New("checksum mismatch"),
1471 state.closeFd(filePathPart)
1474 if err = os.Rename(filePathPart, filePath); err != nil {
1475 state.Ctx.LogE("sp-file-rename", lesp, err, func(les LEs) string {
1476 return logMsg(les) + ": renaming"
1478 state.closeFd(filePathPart)
1481 if err = DirSync(dirToSync); err != nil {
1482 state.Ctx.LogE("sp-file-dirsync", lesp, err, func(les LEs) string {
1483 return logMsg(les) + ": dirsyncing"
1485 state.closeFd(filePathPart)
1488 state.Ctx.LogI("sp-file-done", lesp, func(les LEs) string {
1489 return logMsg(les) + ": done"
1493 state.payloads <- MarshalSP(SPTypeDone, SPDone{file.Hash})
1497 delete(state.infosTheir, *file.Hash)
1499 if !state.Ctx.HdrUsage {
1502 if _, err = fd.Seek(0, io.SeekStart); err != nil {
1503 state.Ctx.LogE("sp-file-seek", lesp, err, func(les LEs) string {
1504 return logMsg(les) + ": seeking"
1506 state.closeFd(filePathPart)
1509 _, pktEncRaw, err := state.Ctx.HdrRead(fd)
1510 state.closeFd(filePathPart)
1512 state.Ctx.LogE("sp-file-hdr-read", lesp, err, func(les LEs) string {
1513 return logMsg(les) + ": HdrReading"
1517 state.Ctx.HdrWrite(pktEncRaw, filePath)
1521 state.closeFd(filePathPart)
1522 if err = os.Rename(filePathPart, filePath+NoCKSuffix); err != nil {
1523 state.Ctx.LogE("sp-file-rename", lesp, err, func(les LEs) string {
1524 return logMsg(les) + ": renaming"
1528 if err = DirSync(dirToSync); err != nil {
1529 state.Ctx.LogE("sp-file-dirsync", lesp, err, func(les LEs) string {
1530 return logMsg(les) + ": dirsyncing"
1534 state.Ctx.LogI("sp-file-downloaded", lesp, func(les LEs) string {
1535 return logMsg(les) + ": downloaded"
1538 delete(state.infosTheir, *file.Hash)
1542 nodeId: state.Node.Id,
1544 done: state.payloads,
1546 if hasherAndOffset != nil {
1547 t.mth = hasherAndOffset.mth
1553 lesp := append(les, LE{"Type", "done"})
1554 state.Ctx.LogD("sp-process-done-unmarshal", lesp, func(les LEs) string {
1556 "SP with %s (nice %s): unmarshaling DONE",
1557 state.Node.Name, NicenessFmt(state.Nice),
1561 if _, err = xdr.Unmarshal(r, &done); err != nil {
1562 state.Ctx.LogE("sp-process-done-unmarshal", lesp, err, func(les LEs) string {
1564 "SP with %s (nice %s): unmarshaling DONE",
1565 state.Node.Name, NicenessFmt(state.Nice),
1570 pktName := Base32Codec.EncodeToString(done.Hash[:])
1571 lesp = append(lesp, LE{"Pkt", pktName}, LE{"XX", string(TTx)})
1572 logMsg := func(les LEs) string {
1574 "SP with %s (nice %s): DONE: removing %s",
1575 state.Node.Name, NicenessFmt(state.Nice), pktName,
1578 state.Ctx.LogD("sp-done", lesp, logMsg)
1579 pth := filepath.Join(
1581 state.Node.Id.String(),
1585 if err = os.Remove(pth); err == nil {
1586 state.Ctx.LogI("sp-done", lesp, func(les LEs) string {
1587 return fmt.Sprintf("Packet %s is sent", pktName)
1589 if state.Ctx.HdrUsage {
1590 os.Remove(JobPath2Hdr(pth))
1593 state.Ctx.LogE("sp-done", lesp, err, logMsg)
1597 lesp := append(les, LE{"Type", "freq"})
1598 state.Ctx.LogD("sp-process-freq", lesp, func(les LEs) string {
1600 "SP with %s (nice %s): unmarshaling FREQ",
1601 state.Node.Name, NicenessFmt(state.Nice),
1605 if _, err = xdr.Unmarshal(r, &freq); err != nil {
1606 state.Ctx.LogE("sp-process-freq", lesp, err, func(les LEs) string {
1608 "SP with %s (nice %s): unmarshaling FREQ",
1609 state.Node.Name, NicenessFmt(state.Nice),
1614 pktName := Base32Codec.EncodeToString(freq.Hash[:])
1615 lesp = append(lesp, LE{"Pkt", pktName}, LE{"Offset", freq.Offset})
1616 state.Ctx.LogD("sp-process-freq-queueing", lesp, func(les LEs) string {
1618 "SP with %s (nice %s): FREQ %s: queuing",
1619 state.Node.Name, NicenessFmt(state.Nice), pktName,
1622 nice, exists := state.infosOurSeen[*freq.Hash]
1624 if state.onlyPkts == nil || !state.onlyPkts[*freq.Hash] {
1627 var freqWithNice *FreqWithNice
1628 for insertIdx, freqWithNice = range state.queueTheir {
1629 if freqWithNice.nice > nice {
1633 state.queueTheir = append(state.queueTheir, nil)
1634 copy(state.queueTheir[insertIdx+1:], state.queueTheir[insertIdx:])
1635 state.queueTheir[insertIdx] = &FreqWithNice{&freq, nice}
1638 state.Ctx.LogD("sp-process-freq-skip", lesp, func(les LEs) string {
1640 "SP with %s (nice %s): FREQ %s: skipping",
1641 state.Node.Name, NicenessFmt(state.Nice), pktName,
1646 state.Ctx.LogD("sp-process-freq-unknown", lesp, func(les LEs) string {
1648 "SP with %s (nice %s): FREQ %s: unknown",
1649 state.Node.Name, NicenessFmt(state.Nice), pktName,
1656 "sp-process-type-unknown",
1657 append(les, LE{"Type", head.Type}),
1658 errors.New("unknown type"),
1659 func(les LEs) string {
1661 "SP with %s (nice %s): %d",
1662 state.Node.Name, NicenessFmt(state.Nice), head.Type,
1666 return nil, BadPktType
1674 for _, info := range state.infosTheir {
1679 state.Ctx.LogI("sp-infos-rx", LEs{
1680 {"XX", string(TRx)},
1681 {"Node", state.Node.Id},
1683 {"Size", int64(size)},
1684 }, func(les LEs) string {
1686 "%s has got for us: %d packets, %s",
1687 state.Node.Name, pkts, humanize.IBytes(size),
1691 return payloadsSplit(replies), nil
1694 func SPChecker(ctx *Ctx) {
1695 for t := range spCheckerTasks {
1696 pktName := Base32Codec.EncodeToString(t.hsh[:])
1698 {"XX", string(TRx)},
1703 ctx.LogD("sp-checker", les, func(les LEs) string {
1704 return fmt.Sprintf("Checksumming %s/rx/%s", ctx.NodeName(t.nodeId), pktName)
1706 size, err := ctx.CheckNoCK(t.nodeId, t.hsh, t.mth)
1707 les = append(les, LE{"Size", size})
1709 ctx.LogE("sp-checker", les, err, func(les LEs) string {
1711 "Checksumming %s/rx/%s (%s)", ctx.NodeName(t.nodeId), pktName,
1712 humanize.IBytes(uint64(size)),
1718 ctx.LogI("sp-checker-done", les, func(les LEs) string {
1720 "Packet %s is retreived (%s)",
1721 pktName, humanize.IBytes(uint64(size)),
1725 go func(t SPCheckerTask) {
1726 defer func() { recover() }()
1727 t.done <- MarshalSP(SPTypeDone, SPDone{t.hsh})