2 NNCP -- Node to Node copy, utilities for store-and-forward data exchange
3 Copyright (C) 2016-2023 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/>.
34 xdr "github.com/davecgh/go-xdr/xdr2"
35 "github.com/dustin/go-humanize"
36 "github.com/flynn/noise"
40 MaxSPSize = 1<<16 - 256
43 CfgDeadline = "NNCPDEADLINE"
46 type MTHAndOffset struct {
51 type SPCheckerTask struct {
62 SPHaltMarshalized []byte
63 SPPingMarshalized []byte
65 NoiseCipherSuite noise.CipherSuite = noise.NewCipherSuite(
67 noise.CipherChaChaPoly,
71 DefaultDeadline = 10 * time.Second
72 PingTimeout = time.Minute
74 spCheckerTasks chan SPCheckerTask
75 SPCheckerWg sync.WaitGroup
76 spCheckerOnce sync.Once
79 type FdAndFullSize struct {
87 SPTypeInfo SPType = iota
88 SPTypeFreq SPType = iota
89 SPTypeFile SPType = iota
90 SPTypeDone SPType = iota
91 SPTypeHalt SPType = iota
92 SPTypePing SPType = iota
125 type FreqWithNice struct {
130 type ConnDeadlined interface {
132 SetReadDeadline(t time.Time) error
133 SetWriteDeadline(t time.Time) error
137 if v := os.Getenv(CfgDeadline); v != "" {
138 i, err := strconv.Atoi(v)
140 log.Fatalln("Can not convert", CfgDeadline, "to integer:", err)
142 DefaultDeadline = time.Duration(i) * time.Second
146 spHead := SPHead{Type: SPTypeHalt}
147 if _, err := xdr.Marshal(&buf, spHead); err != nil {
150 SPHaltMarshalized = make([]byte, SPHeadOverhead)
151 copy(SPHaltMarshalized, buf.Bytes())
154 spHead = SPHead{Type: SPTypePing}
155 if _, err := xdr.Marshal(&buf, spHead); err != nil {
158 SPPingMarshalized = make([]byte, SPHeadOverhead)
159 copy(SPPingMarshalized, buf.Bytes())
162 spInfo := SPInfo{Nice: 123, Size: 123, Hash: new([MTHSize]byte)}
163 if _, err := xdr.Marshal(&buf, spInfo); err != nil {
166 SPInfoOverhead = buf.Len()
169 spFreq := SPFreq{Hash: new([MTHSize]byte), Offset: 123}
170 if _, err := xdr.Marshal(&buf, spFreq); err != nil {
173 SPFreqOverhead = buf.Len()
176 spFile := SPFile{Hash: new([MTHSize]byte), Offset: 123}
177 if _, err := xdr.Marshal(&buf, spFile); err != nil {
180 SPFileOverhead = buf.Len()
181 spCheckerTasks = make(chan SPCheckerTask)
184 func MarshalSP(typ SPType, sp interface{}) []byte {
186 if _, err := xdr.Marshal(&buf, SPHead{typ}); err != nil {
189 if _, err := xdr.Marshal(&buf, sp); err != nil {
195 func payloadsSplit(payloads [][]byte) [][]byte {
196 var outbounds [][]byte
197 outbound := make([]byte, 0, MaxSPSize)
198 for i, payload := range payloads {
199 outbound = append(outbound, payload...)
200 if i+1 < len(payloads) && len(outbound)+len(payloads[i+1]) > MaxSPSize {
201 outbounds = append(outbounds, outbound)
202 outbound = make([]byte, 0, MaxSPSize)
205 if len(outbound) > 0 {
206 outbounds = append(outbounds, outbound)
211 type SPState struct {
216 onlineDeadline time.Duration
217 maxOnlineTime time.Duration
218 hs *noise.HandshakeState
219 csOur *noise.CipherState
220 csTheir *noise.CipherState
223 infosTheir map[[MTHSize]byte]*SPInfo
224 infosOurSeen map[[MTHSize]byte]uint8
225 queueTheir []*FreqWithNice
229 RxLastNonPing time.Time
232 TxLastNonPing time.Time
234 mustFinishAt time.Time
235 Duration time.Duration
245 onlyPkts map[[MTHSize]byte]bool
246 writeSPBuf bytes.Buffer
247 fds map[string]FdAndFullSize
249 fileHashers map[string]*MTHAndOffset
250 progressBars map[string]struct{}
254 func (state *SPState) SetDead() {
259 // Already closed channel, dead
265 for range state.payloads {
269 for range state.pings {
274 func (state *SPState) NotAlive() bool {
283 func (state *SPState) dirUnlock() {
284 state.Ctx.UnlockDir(state.rxLock)
285 state.Ctx.UnlockDir(state.txLock)
288 func (state *SPState) WriteSP(dst io.Writer, payload []byte, ping bool) error {
289 state.writeSPBuf.Reset()
290 if _, err := xdr.Marshal(&state.writeSPBuf, SPRaw{
291 Magic: MagicNNCPSv1.B,
296 n, err := dst.Write(state.writeSPBuf.Bytes())
300 state.TxLastSeen = time.Now()
301 state.TxBytes += int64(n)
303 state.TxLastNonPing = state.TxLastSeen
308 func (state *SPState) ReadSP(src io.Reader) ([]byte, error) {
310 n, err := xdr.UnmarshalLimited(src, &sp, 1<<17)
312 ue := err.(*xdr.UnmarshalError)
313 if ue.Err == io.EOF {
318 state.RxLastSeen = time.Now()
319 state.RxBytes += int64(n)
320 if sp.Magic != MagicNNCPSv1.B {
323 return sp.Payload, nil
326 func (ctx *Ctx) infosOur(nodeId *NodeId, nice uint8, seen *map[[MTHSize]byte]uint8) [][]byte {
329 for job := range ctx.Jobs(nodeId, TTx) {
330 if job.PktEnc.Nice > nice {
333 if _, known := (*seen)[*job.HshValue]; known {
336 totalSize += job.Size
337 infos = append(infos, &SPInfo{
338 Nice: job.PktEnc.Nice,
339 Size: uint64(job.Size),
342 (*seen)[*job.HshValue] = job.PktEnc.Nice
344 sort.Sort(ByNice(infos))
345 var payloads [][]byte
346 for _, info := range infos {
347 payloads = append(payloads, MarshalSP(SPTypeInfo, info))
348 pktName := Base32Codec.EncodeToString(info.Hash[:])
349 ctx.LogD("sp-info-our", LEs{
353 }, func(les LEs) string {
355 "Our info: %s/tx/%s (%s)",
356 ctx.NodeName(nodeId),
358 humanize.IBytes(info.Size),
363 ctx.LogI("sp-infos-tx", LEs{
366 {"Pkts", len(payloads)},
368 }, func(les LEs) string {
370 "We have got for %s: %d packets, %s",
371 ctx.NodeName(nodeId),
373 humanize.IBytes(uint64(totalSize)),
377 return payloadsSplit(payloads)
380 func (state *SPState) StartI(conn ConnDeadlined) error {
381 nodeId := state.Node.Id
382 err := state.Ctx.ensureRxDir(nodeId)
387 if !state.listOnly && (state.xxOnly == "" || state.xxOnly == TRx) {
388 rxLock, err = state.Ctx.LockDir(nodeId, string(TRx))
394 if !state.listOnly && (state.xxOnly == "" || state.xxOnly == TTx) {
395 txLock, err = state.Ctx.LockDir(nodeId, string(TTx))
400 started := time.Now()
401 conf := noise.Config{
402 CipherSuite: NoiseCipherSuite,
403 Pattern: noise.HandshakeIK,
405 StaticKeypair: noise.DHKey{
406 Private: state.Ctx.Self.NoisePrv[:],
407 Public: state.Ctx.Self.NoisePub[:],
409 PeerStatic: state.Node.NoisePub[:],
411 hs, err := noise.NewHandshakeState(conf)
416 state.payloads = make(chan []byte)
417 state.pings = make(chan struct{})
418 state.infosTheir = make(map[[MTHSize]byte]*SPInfo)
419 state.infosOurSeen = make(map[[MTHSize]byte]uint8)
420 state.progressBars = make(map[string]struct{})
421 state.started = started
422 state.rxLock = rxLock
423 state.txLock = txLock
425 var infosPayloads [][]byte
426 if !state.listOnly && (state.xxOnly == "" || state.xxOnly == TTx) {
427 infosPayloads = state.Ctx.infosOur(nodeId, state.Nice, &state.infosOurSeen)
429 var firstPayload []byte
430 if len(infosPayloads) > 0 {
431 firstPayload = infosPayloads[0]
433 // Pad first payload, to hide actual number of existing files
434 for i := 0; i < (MaxSPSize-len(firstPayload))/SPHeadOverhead; i++ {
435 firstPayload = append(firstPayload, SPHaltMarshalized...)
440 buf, _, _, err = state.hs.WriteMessage(nil, firstPayload)
445 les := LEs{{"Node", nodeId}, {"Nice", int(state.Nice)}}
446 state.Ctx.LogD("sp-startI", les, func(les LEs) string {
448 "SP with %s (nice %s): sending first message",
450 NicenessFmt(state.Nice),
453 conn.SetWriteDeadline(time.Now().Add(DefaultDeadline))
454 if err = state.WriteSP(conn, buf, false); err != nil {
455 state.Ctx.LogE("sp-startI", les, err, func(les LEs) string {
457 "SP with %s (nice %s): writing",
459 NicenessFmt(state.Nice),
465 state.Ctx.LogD("sp-startI-wait", les, func(les LEs) string {
467 "SP with %s (nice %s): waiting for first message",
469 NicenessFmt(state.Nice),
472 conn.SetReadDeadline(time.Now().Add(DefaultDeadline))
473 if buf, err = state.ReadSP(conn); err != nil {
474 state.Ctx.LogE("sp-startI-read", les, err, func(les LEs) string {
476 "SP with %s (nice %s): reading",
478 NicenessFmt(state.Nice),
484 payload, state.csOur, state.csTheir, err = state.hs.ReadMessage(nil, buf)
486 state.Ctx.LogE("sp-startI-read", les, err, func(les LEs) string {
488 "SP with %s (nice %s): reading Noise message",
490 NicenessFmt(state.Nice),
496 state.Ctx.LogD("sp-startI-workers", les, func(les LEs) string {
498 "SP with %s (nice %s): starting workers",
500 NicenessFmt(state.Nice),
503 err = state.StartWorkers(conn, infosPayloads, payload)
505 state.Ctx.LogE("sp-startI-workers", les, err, func(les LEs) string {
507 "SP with %s (nice %s): starting workers",
509 NicenessFmt(state.Nice),
517 func (state *SPState) StartR(conn ConnDeadlined) error {
518 started := time.Now()
519 conf := noise.Config{
520 CipherSuite: NoiseCipherSuite,
521 Pattern: noise.HandshakeIK,
523 StaticKeypair: noise.DHKey{
524 Private: state.Ctx.Self.NoisePrv[:],
525 Public: state.Ctx.Self.NoisePub[:],
528 hs, err := noise.NewHandshakeState(conf)
534 state.payloads = make(chan []byte)
535 state.pings = make(chan struct{})
536 state.infosOurSeen = make(map[[MTHSize]byte]uint8)
537 state.infosTheir = make(map[[MTHSize]byte]*SPInfo)
538 state.progressBars = make(map[string]struct{})
539 state.started = started
540 state.xxOnly = xxOnly
544 logMsg := func(les LEs) string {
546 "SP nice %s: waiting for first message",
547 NicenessFmt(state.Nice),
550 les := LEs{{"Nice", int(state.Nice)}}
551 state.Ctx.LogD("sp-startR", les, logMsg)
552 conn.SetReadDeadline(time.Now().Add(DefaultDeadline))
553 if buf, err = state.ReadSP(conn); err != nil {
554 state.Ctx.LogE("sp-startR-read", les, err, logMsg)
557 if payload, _, _, err = state.hs.ReadMessage(nil, buf); err != nil {
558 state.Ctx.LogE("sp-startR-read", les, err, logMsg)
563 for _, n := range state.Ctx.Neigh {
564 if n.NoisePub == nil {
567 if subtle.ConstantTimeCompare(state.hs.PeerStatic(), n.NoisePub[:]) == 1 {
573 peerId := Base32Codec.EncodeToString(state.hs.PeerStatic())
574 err = errors.New("unknown peer: " + peerId)
575 state.Ctx.LogE("sp-startR-unknown", append(les, LE{"Peer", peerId}), err, logMsg)
579 state.rxRate = node.RxRate
580 state.txRate = node.TxRate
581 state.onlineDeadline = node.OnlineDeadline
582 state.maxOnlineTime = node.MaxOnlineTime
583 les = LEs{{"Node", node.Id}, {"Nice", int(state.Nice)}}
585 if err = state.Ctx.ensureRxDir(node.Id); err != nil {
589 if xxOnly == "" || xxOnly == TRx {
590 rxLock, err = state.Ctx.LockDir(node.Id, string(TRx))
595 state.rxLock = rxLock
597 if xxOnly == "" || xxOnly == TTx {
598 txLock, err = state.Ctx.LockDir(node.Id, string(TTx))
603 state.txLock = txLock
605 var infosPayloads [][]byte
606 if xxOnly == "" || xxOnly == TTx {
607 infosPayloads = state.Ctx.infosOur(node.Id, state.Nice, &state.infosOurSeen)
609 var firstPayload []byte
610 if len(infosPayloads) > 0 {
611 firstPayload = infosPayloads[0]
613 // Pad first payload, to hide actual number of existing files
614 for i := 0; i < (MaxSPSize-len(firstPayload))/SPHeadOverhead; i++ {
615 firstPayload = append(firstPayload, SPHaltMarshalized...)
618 state.Ctx.LogD("sp-startR-write", les, func(les LEs) string {
620 "SP with %s (nice %s): sending first message",
621 node.Name, NicenessFmt(state.Nice),
624 buf, state.csTheir, state.csOur, err = state.hs.WriteMessage(nil, firstPayload)
629 conn.SetWriteDeadline(time.Now().Add(DefaultDeadline))
630 if err = state.WriteSP(conn, buf, false); err != nil {
631 state.Ctx.LogE("sp-startR-write", les, err, func(les LEs) string {
633 "SP with %s (nice %s): writing",
634 node.Name, NicenessFmt(state.Nice),
640 state.Ctx.LogD("sp-startR-workers", les, func(les LEs) string {
642 "SP with %s (nice %s): starting workers",
643 node.Name, NicenessFmt(state.Nice),
646 err = state.StartWorkers(conn, infosPayloads, payload)
653 func (state *SPState) closeFd(pth string) {
655 if s, exists := state.fds[pth]; exists {
656 delete(state.fds, pth)
659 state.fdsLock.Unlock()
662 func (state *SPState) StartWorkers(
664 infosPayloads [][]byte,
667 les := LEs{{"Node", state.Node.Id}, {"Nice", int(state.Nice)}}
668 state.fds = make(map[string]FdAndFullSize)
669 state.fileHashers = make(map[string]*MTHAndOffset)
670 state.isDead = make(chan struct{})
671 if state.maxOnlineTime > 0 {
672 state.mustFinishAt = state.started.Add(state.maxOnlineTime)
675 spCheckerOnce.Do(func() { go SPChecker(state.Ctx) })
677 for job := range state.Ctx.JobsNoCK(state.Node.Id) {
678 if job.PktEnc.Nice <= state.Nice {
679 spCheckerTasks <- SPCheckerTask{
680 nodeId: state.Node.Id,
682 done: state.payloads,
689 // Remaining handshake payload sending
690 if len(infosPayloads) > 1 {
693 for _, payload := range infosPayloads[1:] {
695 "sp-queue-remaining",
696 append(les, LE{"Size", int64(len(payload))}),
697 func(les LEs) string {
699 "SP with %s (nice %s): queuing remaining payload (%s)",
700 state.Node.Name, NicenessFmt(state.Nice),
701 humanize.IBytes(uint64(len(payload))),
705 state.payloads <- payload
711 // Processing of first payload and queueing its responses
712 logMsg := func(les LEs) string {
714 "SP with %s (nice %s): processing first payload (%s)",
715 state.Node.Name, NicenessFmt(state.Nice),
716 humanize.IBytes(uint64(len(payload))),
719 state.Ctx.LogD("sp-process", append(les, LE{"Size", int64(len(payload))}), logMsg)
720 replies, err := state.ProcessSP(payload)
722 state.Ctx.LogE("sp-process", les, err, logMsg)
727 for _, reply := range replies {
730 append(les, LE{"Size", int64(len(reply))}),
731 func(les LEs) string {
733 "SP with %s (nice %s): queuing reply (%s)",
734 state.Node.Name, NicenessFmt(state.Nice),
735 humanize.IBytes(uint64(len(payload))),
739 state.payloads <- reply
747 deadlineTicker := time.NewTicker(time.Second)
748 pingTicker := time.NewTicker(PingTimeout)
753 deadlineTicker.Stop()
756 case now := <-deadlineTicker.C:
757 if now.Sub(state.RxLastNonPing) >= state.onlineDeadline &&
758 now.Sub(state.TxLastNonPing) >= state.onlineDeadline {
761 if state.maxOnlineTime > 0 && state.mustFinishAt.Before(now) {
764 if now.Sub(state.RxLastSeen) >= 2*PingTimeout {
771 case now := <-pingTicker.C:
772 if now.After(state.TxLastSeen.Add(PingTimeout)) {
775 state.pings <- struct{}{}
783 // Spool checker and INFOs sender of appearing files
784 if !state.listOnly && (state.xxOnly == "" || state.xxOnly == TTx) {
787 dw, err := state.Ctx.NewDirWatcher(
788 filepath.Join(state.Ctx.Spool, state.Node.Id.String(), string(TTx)),
792 state.Ctx.LogE("sp-queue-dir-watch", les, err, logMsg)
802 for _, payload := range state.Ctx.infosOur(
809 append(les, LE{"Size", int64(len(payload))}),
810 func(les LEs) string {
812 "SP with %s (nice %s): queuing new info (%s)",
813 state.Node.Name, NicenessFmt(state.Nice),
814 humanize.IBytes(uint64(len(payload))),
818 state.payloads <- payload
829 defer state.SetDead()
830 defer state.wg.Done()
831 buf := make([]byte, MaxSPSize-SPHeadOverhead-SPFileOverhead)
833 if state.NotAlive() {
840 state.Ctx.LogD("sp-got-ping", les, func(les LEs) string {
842 "SP with %s (nice %s): got ping",
843 state.Node.Name, NicenessFmt(state.Nice),
846 payload = SPPingMarshalized
848 case payload = <-state.payloads:
851 append(les, LE{"Size", int64(len(payload))}),
852 func(les LEs) string {
854 "SP with %s (nice %s): got payload (%s)",
855 state.Node.Name, NicenessFmt(state.Nice),
856 humanize.IBytes(uint64(len(payload))),
862 if len(state.queueTheir) == 0 {
864 time.Sleep(100 * time.Millisecond)
867 freq := state.queueTheir[0].freq
869 if state.txRate > 0 {
870 time.Sleep(time.Second / time.Duration(state.txRate))
872 pktName := Base32Codec.EncodeToString(freq.Hash[:])
875 LE{"XX", string(TTx)},
877 LE{"Size", int64(freq.Offset)},
879 logMsg := func(les LEs) string {
881 "SP with %s (nice %s): tx/%s (%s)",
882 state.Node.Name, NicenessFmt(state.Nice),
884 humanize.IBytes(freq.Offset),
887 state.Ctx.LogD("sp-queue", lesp, func(les LEs) string {
888 return logMsg(les) + ": queueing"
890 pth := filepath.Join(
892 state.Node.Id.String(),
894 Base32Codec.EncodeToString(freq.Hash[:]),
896 state.fdsLock.RLock()
897 fdAndFullSize, exists := state.fds[pth]
898 state.fdsLock.RUnlock()
900 state.Ctx.LogD("sp-queue-open", lesp, func(les LEs) string {
901 return logMsg(les) + ": opening"
903 fd, err := os.Open(pth)
905 state.Ctx.LogE("sp-queue-open", lesp, err, func(les LEs) string {
906 return logMsg(les) + ": opening"
912 state.Ctx.LogE("sp-queue-stat", lesp, err, func(les LEs) string {
913 return logMsg(les) + ": stating"
917 fdAndFullSize = FdAndFullSize{fd: fd, fullSize: fi.Size()}
919 state.fds[pth] = fdAndFullSize
920 state.fdsLock.Unlock()
922 fd := fdAndFullSize.fd
923 fullSize := fdAndFullSize.fullSize
924 lesp = append(lesp, LE{"FullSize", fullSize})
926 if freq.Offset < uint64(fullSize) {
927 state.Ctx.LogD("sp-file-seek", lesp, func(les LEs) string {
928 return logMsg(les) + ": seeking"
930 if _, err = fd.Seek(int64(freq.Offset), io.SeekStart); err != nil {
931 state.Ctx.LogE("sp-file-seek", lesp, err, func(les LEs) string {
932 return logMsg(les) + ": seeking"
936 n, err := fd.Read(buf)
938 state.Ctx.LogE("sp-file-read", lesp, err, func(les LEs) string {
939 return logMsg(les) + ": reading"
946 LE{"XX", string(TTx)},
948 LE{"Size", int64(n)},
949 LE{"FullSize", fullSize},
951 state.Ctx.LogD("sp-file-read", lesp, func(les LEs) string {
954 logMsg(les), humanize.IBytes(uint64(n)),
960 payload = MarshalSP(SPTypeFile, SPFile{
965 ourSize := freq.Offset + uint64(len(bufRead))
968 LE{"XX", string(TTx)},
970 LE{"Size", int64(ourSize)},
971 LE{"FullSize", fullSize},
973 if state.Ctx.ShowPrgrs {
974 state.progressBars[pktName] = struct{}{}
977 if ourSize == uint64(fullSize) {
979 state.Ctx.LogD("sp-file-finished", lesp, func(les LEs) string {
980 return logMsg(les) + ": finished"
982 if state.Ctx.ShowPrgrs {
983 delete(state.progressBars, pktName)
987 for i, q := range state.queueTheir {
988 if *q.freq.Hash != *freq.Hash {
991 if ourSize == uint64(fullSize) {
992 state.queueTheir = append(
993 state.queueTheir[:i],
994 state.queueTheir[i+1:]...,
997 q.freq.Offset = ourSize
1003 logMsg := func(les LEs) string {
1005 "SP with %s (nice %s): sending %s",
1006 state.Node.Name, NicenessFmt(state.Nice),
1007 humanize.IBytes(uint64(len(payload))),
1010 state.Ctx.LogD("sp-sending", append(les, LE{"Size", int64(len(payload))}), logMsg)
1011 conn.SetWriteDeadline(time.Now().Add(DefaultDeadline))
1012 ct, err := state.csOur.Encrypt(nil, nil, payload)
1014 state.Ctx.LogE("sp-encrypting", les, err, logMsg)
1017 if err := state.WriteSP(conn, ct, ping); err != nil {
1018 state.Ctx.LogE("sp-sending", les, err, logMsg)
1028 if state.NotAlive() {
1031 logMsg := func(les LEs) string {
1033 "SP with %s (nice %s): waiting for payload",
1034 state.Node.Name, NicenessFmt(state.Nice),
1037 state.Ctx.LogD("sp-recv-wait", les, logMsg)
1038 conn.SetReadDeadline(time.Now().Add(DefaultDeadline))
1039 payload, err := state.ReadSP(conn)
1044 unmarshalErr := err.(*xdr.UnmarshalError)
1045 if os.IsTimeout(unmarshalErr.Err) {
1048 if unmarshalErr.ErrorCode == xdr.ErrIO {
1051 state.Ctx.LogE("sp-recv-wait", les, err, logMsg)
1054 logMsg = func(les LEs) string {
1056 "SP with %s (nice %s): payload (%s)",
1057 state.Node.Name, NicenessFmt(state.Nice),
1058 humanize.IBytes(uint64(len(payload))),
1063 append(les, LE{"Size", int64(len(payload))}),
1064 func(les LEs) string { return logMsg(les) + ": got" },
1066 payload, err = state.csTheir.Decrypt(nil, nil, payload)
1068 state.Ctx.LogE("sp-recv-got", les, err, func(les LEs) string {
1069 return logMsg(les) + ": got"
1075 append(les, LE{"Size", int64(len(payload))}),
1076 func(les LEs) string {
1077 return logMsg(les) + ": processing"
1080 replies, err := state.ProcessSP(payload)
1082 state.Ctx.LogE("sp-recv-process", les, err, func(les LEs) string {
1083 return logMsg(les) + ": processing"
1089 for _, reply := range replies {
1092 append(les[:len(les)-1], LE{"Size", int64(len(reply))}),
1093 func(les LEs) string {
1095 "SP with %s (nice %s): queuing reply (%s)",
1096 state.Node.Name, NicenessFmt(state.Nice),
1097 humanize.IBytes(uint64(len(reply))),
1101 state.payloads <- reply
1105 if state.rxRate > 0 {
1106 time.Sleep(time.Second / time.Duration(state.rxRate))
1118 func (state *SPState) Wait() bool {
1120 close(state.payloads)
1122 state.Duration = time.Since(state.started)
1124 state.RxSpeed = state.RxBytes
1125 state.TxSpeed = state.TxBytes
1126 rxDuration := int64(state.RxLastSeen.Sub(state.started).Seconds())
1127 txDuration := int64(state.TxLastSeen.Sub(state.started).Seconds())
1129 state.RxSpeed = state.RxBytes / rxDuration
1132 state.TxSpeed = state.TxBytes / txDuration
1134 nothingLeft := len(state.queueTheir) == 0
1135 for _, s := range state.fds {
1139 for pktName := range state.progressBars {
1140 ProgressKill(pktName)
1145 func (state *SPState) ProcessSP(payload []byte) ([][]byte, error) {
1146 les := LEs{{"Node", state.Node.Id}, {"Nice", int(state.Nice)}}
1147 r := bytes.NewReader(payload)
1149 var replies [][]byte
1152 state.Ctx.LogD("sp-process-unmarshal", les, func(les LEs) string {
1154 "SP with %s (nice %s): unmarshaling header",
1155 state.Node.Name, NicenessFmt(state.Nice),
1159 if _, err = xdr.Unmarshal(r, &head); err != nil {
1160 state.Ctx.LogE("sp-process-unmarshal", les, err, func(les LEs) string {
1162 "SP with %s (nice %s): unmarshaling header",
1163 state.Node.Name, NicenessFmt(state.Nice),
1168 if head.Type != SPTypePing {
1169 state.RxLastNonPing = state.RxLastSeen
1175 append(les, LE{"Type", "halt"}), func(les LEs) string {
1177 "SP with %s (nice %s): got HALT",
1178 state.Node.Name, NicenessFmt(state.Nice),
1183 state.queueTheir = nil
1189 append(les, LE{"Type", "ping"}),
1190 func(les LEs) string {
1192 "SP with %s (nice %s): got PING",
1193 state.Node.Name, NicenessFmt(state.Nice),
1200 lesp := append(les, LE{"Type", "info"})
1202 "sp-process-info-unmarshal", lesp,
1203 func(les LEs) string {
1205 "SP with %s (nice %s): unmarshaling INFO",
1206 state.Node.Name, NicenessFmt(state.Nice),
1211 if _, err = xdr.Unmarshal(r, &info); err != nil {
1213 "sp-process-info-unmarshal", lesp, err,
1214 func(les LEs) string {
1216 "SP with %s (nice %s): unmarshaling INFO",
1217 state.Node.Name, NicenessFmt(state.Nice),
1223 pktName := Base32Codec.EncodeToString(info.Hash[:])
1227 LE{"Size", int64(info.Size)},
1228 LE{"PktNice", int(info.Nice)},
1230 logMsg := func(les LEs) string {
1232 "SP with %s (nice %s): INFO %s (%s) nice %s",
1233 state.Node.Name, NicenessFmt(state.Nice),
1235 humanize.IBytes(info.Size),
1236 NicenessFmt(info.Nice),
1239 if !state.listOnly && info.Nice > state.Nice {
1240 state.Ctx.LogD("sp-process-info-too-nice", lesp, func(les LEs) string {
1241 return logMsg(les) + ": too nice"
1245 state.Ctx.LogD("sp-process-info-got", lesp, func(les LEs) string {
1246 return logMsg(les) + ": received"
1248 if !state.listOnly && state.xxOnly == TTx {
1252 state.infosTheir[*info.Hash] = &info
1254 state.Ctx.LogD("sp-process-info-stat", lesp, func(les LEs) string {
1255 return logMsg(les) + ": stating part"
1257 pktPath := filepath.Join(
1259 state.Node.Id.String(),
1261 Base32Codec.EncodeToString(info.Hash[:]),
1263 logMsg = func(les LEs) string {
1265 "Packet %s (%s) (nice %s)",
1267 humanize.IBytes(info.Size),
1268 NicenessFmt(info.Nice),
1271 if _, err = os.Stat(pktPath); err == nil {
1272 state.Ctx.LogI("sp-info-done", lesp, func(les LEs) string {
1273 return logMsg(les) + ": already done"
1275 if !state.listOnly {
1276 replies = append(replies, MarshalSP(SPTypeDone, SPDone{info.Hash}))
1280 if _, err = os.Stat(filepath.Join(
1281 state.Ctx.Spool, state.Node.Id.String(), string(TRx),
1282 SeenDir, Base32Codec.EncodeToString(info.Hash[:]),
1284 state.Ctx.LogI("sp-info-seen", lesp, func(les LEs) string {
1285 return logMsg(les) + ": already seen"
1287 if !state.listOnly {
1288 replies = append(replies, MarshalSP(SPTypeDone, SPDone{info.Hash}))
1292 if _, err = os.Stat(pktPath + NoCKSuffix); err == nil {
1293 state.Ctx.LogI("sp-info-nock", lesp, func(les LEs) string {
1294 return logMsg(les) + ": still not checksummed"
1298 fi, err := os.Stat(pktPath + PartSuffix)
1303 if !state.Ctx.IsEnoughSpace(int64(info.Size) - offset) {
1304 state.Ctx.LogI("sp-info-no-space", lesp, func(les LEs) string {
1305 return logMsg(les) + ": not enough space"
1311 append(lesp, LE{"Offset", offset}),
1312 func(les LEs) string {
1314 "%s: %d%%", logMsg(les), 100*uint64(offset)/info.Size,
1318 if !state.listOnly && (state.onlyPkts == nil || state.onlyPkts[*info.Hash]) {
1319 replies = append(replies, MarshalSP(
1321 SPFreq{info.Hash, uint64(offset)},
1326 lesp := append(les, LE{"Type", "file"})
1327 state.Ctx.LogD("sp-process-file", lesp, func(les LEs) string {
1329 "SP with %s (nice %s): unmarshaling FILE",
1330 state.Node.Name, NicenessFmt(state.Nice),
1334 if _, err = xdr.Unmarshal(r, &file); err != nil {
1335 state.Ctx.LogE("sp-process-file", lesp, err, func(les LEs) string {
1337 "SP with %s (nice %s): unmarshaling FILE",
1338 state.Node.Name, NicenessFmt(state.Nice),
1343 pktName := Base32Codec.EncodeToString(file.Hash[:])
1346 LE{"XX", string(TRx)},
1348 LE{"Size", int64(len(file.Payload))},
1350 logMsg := func(les LEs) string {
1352 "Got packet %s (%s)",
1353 pktName, humanize.IBytes(uint64(len(file.Payload))),
1356 fullsize := int64(0)
1358 infoTheir := state.infosTheir[*file.Hash]
1360 if infoTheir == nil {
1361 state.Ctx.LogE("sp-file-open", lesp, err, func(les LEs) string {
1362 return logMsg(les) + ": unknown file"
1366 fullsize = int64(infoTheir.Size)
1367 lesp = append(lesp, LE{"FullSize", fullsize})
1368 dirToSync := filepath.Join(
1370 state.Node.Id.String(),
1373 filePath := filepath.Join(dirToSync, pktName)
1374 filePathPart := filePath + PartSuffix
1375 state.Ctx.LogD("sp-file-open", lesp, func(les LEs) string {
1376 return logMsg(les) + ": opening part"
1378 state.fdsLock.RLock()
1379 fdAndFullSize, exists := state.fds[filePathPart]
1380 state.fdsLock.RUnlock()
1381 hasherAndOffset := state.fileHashers[filePath]
1384 fd = fdAndFullSize.fd
1386 fd, err = os.OpenFile(
1388 os.O_RDWR|os.O_CREATE,
1392 state.Ctx.LogE("sp-file-open", lesp, err, func(les LEs) string {
1393 return logMsg(les) + ": opening part"
1397 state.fdsLock.Lock()
1398 state.fds[filePathPart] = FdAndFullSize{fd: fd}
1399 state.fdsLock.Unlock()
1401 hasherAndOffset = &MTHAndOffset{
1402 mth: MTHNew(fullsize, int64(file.Offset)),
1403 offset: file.Offset,
1405 state.fileHashers[filePath] = hasherAndOffset
1410 append(lesp, LE{"Offset", file.Offset}),
1411 func(les LEs) string {
1412 return fmt.Sprintf("%s: seeking %d", logMsg(les), file.Offset)
1414 if _, err = fd.Seek(int64(file.Offset), io.SeekStart); err != nil {
1415 state.Ctx.LogE("sp-file-seek", lesp, err, func(les LEs) string {
1416 return logMsg(les) + ": seeking"
1418 state.closeFd(filePathPart)
1421 state.Ctx.LogD("sp-file-write", lesp, func(les LEs) string {
1422 return logMsg(les) + ": writing"
1424 if _, err = fd.Write(file.Payload); err != nil {
1425 state.Ctx.LogE("sp-file-write", lesp, err, func(les LEs) string {
1426 return logMsg(les) + ": writing"
1428 state.closeFd(filePathPart)
1431 if hasherAndOffset != nil {
1432 if hasherAndOffset.offset == file.Offset {
1433 if _, err = hasherAndOffset.mth.Write(file.Payload); err != nil {
1436 hasherAndOffset.offset += uint64(len(file.Payload))
1439 "sp-file-offset-differs", lesp, errors.New("offset differs"),
1440 func(les LEs) string {
1441 return logMsg(les) + ": deleting hasher"
1444 delete(state.fileHashers, filePath)
1445 hasherAndOffset = nil
1448 ourSize := int64(file.Offset + uint64(len(file.Payload)))
1449 lesp[len(lesp)-2].V = ourSize
1450 if state.Ctx.ShowPrgrs {
1451 state.progressBars[pktName] = struct{}{}
1452 Progress("Rx", lesp)
1454 if fullsize != ourSize {
1457 if state.Ctx.ShowPrgrs {
1458 delete(state.progressBars, pktName)
1460 logMsg = func(les LEs) string {
1462 "Got packet %s %d%% (%s / %s)",
1463 pktName, 100*ourSize/fullsize,
1464 humanize.IBytes(uint64(ourSize)),
1465 humanize.IBytes(uint64(fullsize)),
1471 state.Ctx.LogE("sp-file-sync", lesp, err, func(les LEs) string {
1472 return logMsg(les) + ": syncing"
1474 state.closeFd(filePathPart)
1478 if hasherAndOffset != nil {
1479 delete(state.fileHashers, filePath)
1480 if hasherAndOffset.mth.PreaddSize() == 0 {
1481 if !bytes.Equal(hasherAndOffset.mth.Sum(nil), file.Hash[:]) {
1483 "sp-file-bad-checksum", lesp,
1484 errors.New("checksum mismatch"),
1487 state.closeFd(filePathPart)
1490 if err = os.Rename(filePathPart, filePath); err != nil {
1491 state.Ctx.LogE("sp-file-rename", lesp, err, func(les LEs) string {
1492 return logMsg(les) + ": renaming"
1494 state.closeFd(filePathPart)
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"
1501 state.closeFd(filePathPart)
1504 state.Ctx.LogI("sp-file-done", lesp, func(les LEs) string {
1505 return logMsg(les) + ": done"
1509 state.payloads <- MarshalSP(SPTypeDone, SPDone{file.Hash})
1513 delete(state.infosTheir, *file.Hash)
1515 if !state.Ctx.HdrUsage {
1518 if _, err = fd.Seek(0, io.SeekStart); err != nil {
1519 state.Ctx.LogE("sp-file-seek", lesp, err, func(les LEs) string {
1520 return logMsg(les) + ": seeking"
1522 state.closeFd(filePathPart)
1525 _, pktEncRaw, err := state.Ctx.HdrRead(fd)
1526 state.closeFd(filePathPart)
1528 state.Ctx.LogE("sp-file-hdr-read", lesp, err, func(les LEs) string {
1529 return logMsg(les) + ": HdrReading"
1533 state.Ctx.HdrWrite(pktEncRaw, filePath)
1537 state.closeFd(filePathPart)
1538 if err = os.Rename(filePathPart, filePath+NoCKSuffix); err != nil {
1539 state.Ctx.LogE("sp-file-rename", lesp, err, func(les LEs) string {
1540 return logMsg(les) + ": renaming"
1544 if err = DirSync(dirToSync); err != nil {
1545 state.Ctx.LogE("sp-file-dirsync", lesp, err, func(les LEs) string {
1546 return logMsg(les) + ": dirsyncing"
1550 state.Ctx.LogI("sp-file-downloaded", lesp, func(les LEs) string {
1551 return logMsg(les) + ": downloaded"
1554 delete(state.infosTheir, *file.Hash)
1558 nodeId: state.Node.Id,
1560 done: state.payloads,
1562 if hasherAndOffset != nil {
1563 t.mth = hasherAndOffset.mth
1569 lesp := append(les, LE{"Type", "done"})
1570 state.Ctx.LogD("sp-process-done-unmarshal", lesp, func(les LEs) string {
1572 "SP with %s (nice %s): unmarshaling DONE",
1573 state.Node.Name, NicenessFmt(state.Nice),
1577 if _, err = xdr.Unmarshal(r, &done); err != nil {
1578 state.Ctx.LogE("sp-process-done-unmarshal", lesp, err, func(les LEs) string {
1580 "SP with %s (nice %s): unmarshaling DONE",
1581 state.Node.Name, NicenessFmt(state.Nice),
1586 pktName := Base32Codec.EncodeToString(done.Hash[:])
1587 lesp = append(lesp, LE{"Pkt", pktName}, LE{"XX", string(TTx)})
1588 logMsg := func(les LEs) string {
1590 "SP with %s (nice %s): DONE: removing %s",
1591 state.Node.Name, NicenessFmt(state.Nice), pktName,
1594 state.Ctx.LogD("sp-done", lesp, logMsg)
1595 pth := filepath.Join(
1597 state.Node.Id.String(),
1601 if err = os.Remove(pth); err == nil {
1602 state.Ctx.LogI("sp-done", lesp, func(les LEs) string {
1603 return fmt.Sprintf("Packet %s is sent", pktName)
1605 if state.Ctx.HdrUsage {
1606 os.Remove(JobPath2Hdr(pth))
1609 state.Ctx.LogE("sp-done", lesp, err, logMsg)
1613 lesp := append(les, LE{"Type", "freq"})
1614 state.Ctx.LogD("sp-process-freq", lesp, func(les LEs) string {
1616 "SP with %s (nice %s): unmarshaling FREQ",
1617 state.Node.Name, NicenessFmt(state.Nice),
1621 if _, err = xdr.Unmarshal(r, &freq); err != nil {
1622 state.Ctx.LogE("sp-process-freq", lesp, err, func(les LEs) string {
1624 "SP with %s (nice %s): unmarshaling FREQ",
1625 state.Node.Name, NicenessFmt(state.Nice),
1630 pktName := Base32Codec.EncodeToString(freq.Hash[:])
1631 lesp = append(lesp, LE{"Pkt", pktName}, LE{"Offset", freq.Offset})
1632 state.Ctx.LogD("sp-process-freq-queueing", lesp, func(les LEs) string {
1634 "SP with %s (nice %s): FREQ %s: queuing",
1635 state.Node.Name, NicenessFmt(state.Nice), pktName,
1638 nice, exists := state.infosOurSeen[*freq.Hash]
1640 if state.onlyPkts == nil || !state.onlyPkts[*freq.Hash] {
1643 var freqWithNice *FreqWithNice
1644 for insertIdx, freqWithNice = range state.queueTheir {
1645 if freqWithNice.nice > nice {
1649 state.queueTheir = append(state.queueTheir, nil)
1650 copy(state.queueTheir[insertIdx+1:], state.queueTheir[insertIdx:])
1651 state.queueTheir[insertIdx] = &FreqWithNice{&freq, nice}
1654 state.Ctx.LogD("sp-process-freq-skip", lesp, func(les LEs) string {
1656 "SP with %s (nice %s): FREQ %s: skipping",
1657 state.Node.Name, NicenessFmt(state.Nice), pktName,
1662 state.Ctx.LogD("sp-process-freq-unknown", lesp, func(les LEs) string {
1664 "SP with %s (nice %s): FREQ %s: unknown",
1665 state.Node.Name, NicenessFmt(state.Nice), pktName,
1672 "sp-process-type-unknown",
1673 append(les, LE{"Type", head.Type}),
1674 errors.New("unknown type"),
1675 func(les LEs) string {
1677 "SP with %s (nice %s): %d",
1678 state.Node.Name, NicenessFmt(state.Nice), head.Type,
1682 return nil, BadPktType
1690 for _, info := range state.infosTheir {
1695 state.Ctx.LogI("sp-infos-rx", LEs{
1696 {"XX", string(TRx)},
1697 {"Node", state.Node.Id},
1699 {"Size", int64(size)},
1700 }, func(les LEs) string {
1702 "%s has got for us: %d packets, %s",
1703 state.Node.Name, pkts, humanize.IBytes(size),
1707 return payloadsSplit(replies), nil
1710 func SPChecker(ctx *Ctx) {
1711 for t := range spCheckerTasks {
1712 pktName := Base32Codec.EncodeToString(t.hsh[:])
1714 {"XX", string(TRx)},
1719 ctx.LogD("sp-checker", les, func(les LEs) string {
1720 return fmt.Sprintf("Checksumming %s/rx/%s", ctx.NodeName(t.nodeId), pktName)
1722 size, err := ctx.CheckNoCK(t.nodeId, t.hsh, t.mth)
1723 les = append(les, LE{"Size", size})
1725 ctx.LogE("sp-checker", les, err, func(les LEs) string {
1727 "Checksumming %s/rx/%s (%s)", ctx.NodeName(t.nodeId), pktName,
1728 humanize.IBytes(uint64(size)),
1734 ctx.LogI("sp-checker-done", les, func(les LEs) string {
1736 "Packet %s is retreived (%s)",
1737 pktName, humanize.IBytes(uint64(size)),
1741 go func(t SPCheckerTask) {
1742 defer func() { recover() }()
1743 t.done <- MarshalSP(SPTypeDone, SPDone{t.hsh})