1 // NNCP -- Node to Node copy, utilities for store-and-forward data exchange
2 // Copyright (C) 2016-2024 Sergey Matveev <stargrave@stargrave.org>
4 // This program is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, version 3 of the License.
8 // This program is distributed in the hope that it will be useful,
9 // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 // GNU General Public License for more details.
13 // You should have received a copy of the GNU General Public License
14 // 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
41 CfgDeadline = "NNCPDEADLINE"
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
135 if v := os.Getenv(CfgDeadline); v != "" {
136 i, err := strconv.Atoi(v)
138 log.Fatalln("Can not convert", CfgDeadline, "to integer:", err)
140 DefaultDeadline = time.Duration(i) * time.Second
144 spHead := SPHead{Type: SPTypeHalt}
145 if _, err := xdr.Marshal(&buf, spHead); err != nil {
148 SPHaltMarshalized = make([]byte, SPHeadOverhead)
149 copy(SPHaltMarshalized, buf.Bytes())
152 spHead = SPHead{Type: SPTypePing}
153 if _, err := xdr.Marshal(&buf, spHead); err != nil {
156 SPPingMarshalized = make([]byte, SPHeadOverhead)
157 copy(SPPingMarshalized, buf.Bytes())
160 spInfo := SPInfo{Nice: 123, Size: 123, Hash: new([MTHSize]byte)}
161 if _, err := xdr.Marshal(&buf, spInfo); err != nil {
164 SPInfoOverhead = buf.Len()
167 spFreq := SPFreq{Hash: new([MTHSize]byte), Offset: 123}
168 if _, err := xdr.Marshal(&buf, spFreq); err != nil {
171 SPFreqOverhead = buf.Len()
174 spFile := SPFile{Hash: new([MTHSize]byte), Offset: 123}
175 if _, err := xdr.Marshal(&buf, spFile); err != nil {
178 SPFileOverhead = buf.Len()
179 spCheckerTasks = make(chan SPCheckerTask)
182 func MarshalSP(typ SPType, sp interface{}) []byte {
184 if _, err := xdr.Marshal(&buf, SPHead{typ}); err != nil {
187 if _, err := xdr.Marshal(&buf, sp); err != nil {
193 func payloadsSplit(payloads [][]byte) [][]byte {
194 var outbounds [][]byte
195 outbound := make([]byte, 0, MaxSPSize)
196 for i, payload := range payloads {
197 outbound = append(outbound, payload...)
198 if i+1 < len(payloads) && len(outbound)+len(payloads[i+1]) > MaxSPSize {
199 outbounds = append(outbounds, outbound)
200 outbound = make([]byte, 0, MaxSPSize)
203 if len(outbound) > 0 {
204 outbounds = append(outbounds, outbound)
209 type SPState struct {
214 onlineDeadline time.Duration
215 maxOnlineTime time.Duration
216 hs *noise.HandshakeState
217 csOur *noise.CipherState
218 csTheir *noise.CipherState
221 infosTheir map[[MTHSize]byte]*SPInfo
222 infosOurSeen map[[MTHSize]byte]uint8
223 queueTheir []*FreqWithNice
227 RxLastNonPing time.Time
230 TxLastNonPing time.Time
232 mustFinishAt time.Time
233 Duration time.Duration
243 onlyPkts map[[MTHSize]byte]bool
244 writeSPBuf bytes.Buffer
245 fds map[string]FdAndFullSize
247 fileHashers map[string]*MTHAndOffset
248 progressBars map[string]struct{}
252 func (state *SPState) SetDead() {
257 // Already closed channel, dead
263 for range state.payloads {
267 for range state.pings {
272 func (state *SPState) NotAlive() bool {
281 func (state *SPState) dirUnlock() {
282 state.Ctx.UnlockDir(state.rxLock)
283 state.Ctx.UnlockDir(state.txLock)
286 func (state *SPState) WriteSP(dst io.Writer, payload []byte, ping bool) error {
287 state.writeSPBuf.Reset()
288 if _, err := xdr.Marshal(&state.writeSPBuf, SPRaw{
289 Magic: MagicNNCPSv1.B,
294 n, err := dst.Write(state.writeSPBuf.Bytes())
298 state.TxLastSeen = time.Now()
299 state.TxBytes += int64(n)
301 state.TxLastNonPing = state.TxLastSeen
306 func (state *SPState) ReadSP(src io.Reader) ([]byte, error) {
308 n, err := xdr.UnmarshalLimited(src, &sp, 1<<17)
310 ue := err.(*xdr.UnmarshalError)
311 if ue.Err == io.EOF {
316 state.RxLastSeen = time.Now()
317 state.RxBytes += int64(n)
318 if sp.Magic != MagicNNCPSv1.B {
321 return sp.Payload, nil
324 func (ctx *Ctx) infosOur(nodeId *NodeId, nice uint8, seen *map[[MTHSize]byte]uint8) [][]byte {
327 for job := range ctx.Jobs(nodeId, TTx) {
328 if job.PktEnc.Nice > nice {
331 if _, known := (*seen)[*job.HshValue]; known {
334 totalSize += job.Size
335 infos = append(infos, &SPInfo{
336 Nice: job.PktEnc.Nice,
337 Size: uint64(job.Size),
340 (*seen)[*job.HshValue] = job.PktEnc.Nice
342 sort.Sort(ByNice(infos))
343 var payloads [][]byte
344 for _, info := range infos {
345 payloads = append(payloads, MarshalSP(SPTypeInfo, info))
346 pktName := Base32Codec.EncodeToString(info.Hash[:])
347 ctx.LogD("sp-info-our", LEs{
351 }, func(les LEs) string {
353 "Our info: %s/tx/%s (%s)",
354 ctx.NodeName(nodeId),
356 humanize.IBytes(info.Size),
361 ctx.LogI("sp-infos-tx", LEs{
364 {"Pkts", len(payloads)},
366 }, func(les LEs) string {
368 "We have got for %s: %d packets, %s",
369 ctx.NodeName(nodeId),
371 humanize.IBytes(uint64(totalSize)),
375 return payloadsSplit(payloads)
378 func (state *SPState) StartI(conn ConnDeadlined) error {
379 nodeId := state.Node.Id
380 err := state.Ctx.ensureRxDir(nodeId)
385 if !state.listOnly && (state.xxOnly == "" || state.xxOnly == TRx) {
386 rxLock, err = state.Ctx.LockDir(nodeId, string(TRx))
392 if !state.listOnly && (state.xxOnly == "" || state.xxOnly == TTx) {
393 txLock, err = state.Ctx.LockDir(nodeId, string(TTx))
398 started := time.Now()
399 conf := noise.Config{
400 CipherSuite: NoiseCipherSuite,
401 Pattern: noise.HandshakeIK,
403 StaticKeypair: noise.DHKey{
404 Private: state.Ctx.Self.NoisePrv[:],
405 Public: state.Ctx.Self.NoisePub[:],
407 PeerStatic: state.Node.NoisePub[:],
409 hs, err := noise.NewHandshakeState(conf)
414 state.payloads = make(chan []byte)
415 state.pings = make(chan struct{})
416 state.infosTheir = make(map[[MTHSize]byte]*SPInfo)
417 state.infosOurSeen = make(map[[MTHSize]byte]uint8)
418 state.progressBars = make(map[string]struct{})
419 state.started = started
420 state.rxLock = rxLock
421 state.txLock = txLock
423 var infosPayloads [][]byte
424 if !state.listOnly && (state.xxOnly == "" || state.xxOnly == TTx) {
425 infosPayloads = state.Ctx.infosOur(nodeId, state.Nice, &state.infosOurSeen)
427 var firstPayload []byte
428 if len(infosPayloads) > 0 {
429 firstPayload = infosPayloads[0]
431 // Pad first payload, to hide actual number of existing files
432 for i := 0; i < (MaxSPSize-len(firstPayload))/SPHeadOverhead; i++ {
433 firstPayload = append(firstPayload, SPHaltMarshalized...)
438 buf, _, _, err = state.hs.WriteMessage(nil, firstPayload)
443 les := LEs{{"Node", nodeId}, {"Nice", int(state.Nice)}}
444 state.Ctx.LogD("sp-startI", les, func(les LEs) string {
446 "SP with %s (nice %s): sending first message",
448 NicenessFmt(state.Nice),
451 conn.SetWriteDeadline(time.Now().Add(DefaultDeadline))
452 if err = state.WriteSP(conn, buf, false); err != nil {
453 state.Ctx.LogE("sp-startI", les, err, func(les LEs) string {
455 "SP with %s (nice %s): writing",
457 NicenessFmt(state.Nice),
463 state.Ctx.LogD("sp-startI-wait", les, func(les LEs) string {
465 "SP with %s (nice %s): waiting for first message",
467 NicenessFmt(state.Nice),
470 conn.SetReadDeadline(time.Now().Add(DefaultDeadline))
471 if buf, err = state.ReadSP(conn); err != nil {
472 state.Ctx.LogE("sp-startI-read", les, err, func(les LEs) string {
474 "SP with %s (nice %s): reading",
476 NicenessFmt(state.Nice),
482 payload, state.csOur, state.csTheir, err = state.hs.ReadMessage(nil, buf)
484 state.Ctx.LogE("sp-startI-read", les, err, func(les LEs) string {
486 "SP with %s (nice %s): reading Noise message",
488 NicenessFmt(state.Nice),
494 state.Ctx.LogD("sp-startI-workers", les, func(les LEs) string {
496 "SP with %s (nice %s): starting workers",
498 NicenessFmt(state.Nice),
501 err = state.StartWorkers(conn, infosPayloads, payload)
503 state.Ctx.LogE("sp-startI-workers", les, err, func(les LEs) string {
505 "SP with %s (nice %s): starting workers",
507 NicenessFmt(state.Nice),
515 func (state *SPState) StartR(conn ConnDeadlined) error {
516 started := time.Now()
517 conf := noise.Config{
518 CipherSuite: NoiseCipherSuite,
519 Pattern: noise.HandshakeIK,
521 StaticKeypair: noise.DHKey{
522 Private: state.Ctx.Self.NoisePrv[:],
523 Public: state.Ctx.Self.NoisePub[:],
526 hs, err := noise.NewHandshakeState(conf)
532 state.payloads = make(chan []byte)
533 state.pings = make(chan struct{})
534 state.infosOurSeen = make(map[[MTHSize]byte]uint8)
535 state.infosTheir = make(map[[MTHSize]byte]*SPInfo)
536 state.progressBars = make(map[string]struct{})
537 state.started = started
538 state.xxOnly = xxOnly
542 logMsg := func(les LEs) string {
544 "SP nice %s: waiting for first message",
545 NicenessFmt(state.Nice),
548 les := LEs{{"Nice", int(state.Nice)}}
549 state.Ctx.LogD("sp-startR", les, logMsg)
550 conn.SetReadDeadline(time.Now().Add(DefaultDeadline))
551 if buf, err = state.ReadSP(conn); err != nil {
552 state.Ctx.LogE("sp-startR-read", les, err, logMsg)
555 if payload, _, _, err = state.hs.ReadMessage(nil, buf); err != nil {
556 state.Ctx.LogE("sp-startR-read", les, err, logMsg)
561 for _, n := range state.Ctx.Neigh {
562 if n.NoisePub == nil {
565 if subtle.ConstantTimeCompare(state.hs.PeerStatic(), n.NoisePub[:]) == 1 {
571 peerId := Base32Codec.EncodeToString(state.hs.PeerStatic())
572 err = errors.New("unknown peer: " + peerId)
573 state.Ctx.LogE("sp-startR-unknown", append(les, LE{"Peer", peerId}), err, logMsg)
577 state.rxRate = node.RxRate
578 state.txRate = node.TxRate
579 state.onlineDeadline = node.OnlineDeadline
580 state.maxOnlineTime = node.MaxOnlineTime
581 les = LEs{{"Node", node.Id}, {"Nice", int(state.Nice)}}
583 if err = state.Ctx.ensureRxDir(node.Id); err != nil {
587 if xxOnly == "" || xxOnly == TRx {
588 rxLock, err = state.Ctx.LockDir(node.Id, string(TRx))
593 state.rxLock = rxLock
595 if xxOnly == "" || xxOnly == TTx {
596 txLock, err = state.Ctx.LockDir(node.Id, string(TTx))
601 state.txLock = txLock
603 var infosPayloads [][]byte
604 if xxOnly == "" || xxOnly == TTx {
605 infosPayloads = state.Ctx.infosOur(node.Id, state.Nice, &state.infosOurSeen)
607 var firstPayload []byte
608 if len(infosPayloads) > 0 {
609 firstPayload = infosPayloads[0]
611 // Pad first payload, to hide actual number of existing files
612 for i := 0; i < (MaxSPSize-len(firstPayload))/SPHeadOverhead; i++ {
613 firstPayload = append(firstPayload, SPHaltMarshalized...)
616 state.Ctx.LogD("sp-startR-write", les, func(les LEs) string {
618 "SP with %s (nice %s): sending first message",
619 node.Name, NicenessFmt(state.Nice),
622 buf, state.csTheir, state.csOur, err = state.hs.WriteMessage(nil, firstPayload)
627 conn.SetWriteDeadline(time.Now().Add(DefaultDeadline))
628 if err = state.WriteSP(conn, buf, false); err != nil {
629 state.Ctx.LogE("sp-startR-write", les, err, func(les LEs) string {
631 "SP with %s (nice %s): writing",
632 node.Name, NicenessFmt(state.Nice),
638 state.Ctx.LogD("sp-startR-workers", les, func(les LEs) string {
640 "SP with %s (nice %s): starting workers",
641 node.Name, NicenessFmt(state.Nice),
644 err = state.StartWorkers(conn, infosPayloads, payload)
651 func (state *SPState) closeFd(pth string) {
653 if s, exists := state.fds[pth]; exists {
654 delete(state.fds, pth)
657 state.fdsLock.Unlock()
660 func (state *SPState) StartWorkers(
662 infosPayloads [][]byte,
665 les := LEs{{"Node", state.Node.Id}, {"Nice", int(state.Nice)}}
666 state.fds = make(map[string]FdAndFullSize)
667 state.fileHashers = make(map[string]*MTHAndOffset)
668 state.isDead = make(chan struct{})
669 if state.maxOnlineTime > 0 {
670 state.mustFinishAt = state.started.Add(state.maxOnlineTime)
673 spCheckerOnce.Do(func() { go SPChecker(state.Ctx) })
675 for job := range state.Ctx.JobsNoCK(state.Node.Id) {
676 if job.PktEnc.Nice <= state.Nice {
677 spCheckerTasks <- SPCheckerTask{
678 nodeId: state.Node.Id,
680 done: state.payloads,
687 // Remaining handshake payload sending
688 if len(infosPayloads) > 1 {
691 for _, payload := range infosPayloads[1:] {
693 "sp-queue-remaining",
694 append(les, LE{"Size", int64(len(payload))}),
695 func(les LEs) string {
697 "SP with %s (nice %s): queuing remaining payload (%s)",
698 state.Node.Name, NicenessFmt(state.Nice),
699 humanize.IBytes(uint64(len(payload))),
703 state.payloads <- payload
709 // Processing of first payload and queueing its responses
710 logMsg := func(les LEs) string {
712 "SP with %s (nice %s): processing first payload (%s)",
713 state.Node.Name, NicenessFmt(state.Nice),
714 humanize.IBytes(uint64(len(payload))),
717 state.Ctx.LogD("sp-process", append(les, LE{"Size", int64(len(payload))}), logMsg)
718 replies, err := state.ProcessSP(payload)
720 state.Ctx.LogE("sp-process", les, err, logMsg)
725 for _, reply := range replies {
728 append(les, LE{"Size", int64(len(reply))}),
729 func(les LEs) string {
731 "SP with %s (nice %s): queuing reply (%s)",
732 state.Node.Name, NicenessFmt(state.Nice),
733 humanize.IBytes(uint64(len(payload))),
737 state.payloads <- reply
745 deadlineTicker := time.NewTicker(time.Second)
746 pingTicker := time.NewTicker(PingTimeout)
751 deadlineTicker.Stop()
754 case now := <-deadlineTicker.C:
755 if now.Sub(state.RxLastNonPing) >= state.onlineDeadline &&
756 now.Sub(state.TxLastNonPing) >= state.onlineDeadline {
759 if state.maxOnlineTime > 0 && state.mustFinishAt.Before(now) {
762 if now.Sub(state.RxLastSeen) >= 2*PingTimeout {
769 case now := <-pingTicker.C:
770 if now.After(state.TxLastSeen.Add(PingTimeout)) {
773 state.pings <- struct{}{}
781 // Spool checker and INFOs sender of appearing files
782 if !state.listOnly && (state.xxOnly == "" || state.xxOnly == TTx) {
785 dw, err := state.Ctx.NewDirWatcher(
786 filepath.Join(state.Ctx.Spool, state.Node.Id.String(), string(TTx)),
790 state.Ctx.LogE("sp-queue-dir-watch", les, err, logMsg)
800 for _, payload := range state.Ctx.infosOur(
807 append(les, LE{"Size", int64(len(payload))}),
808 func(les LEs) string {
810 "SP with %s (nice %s): queuing new info (%s)",
811 state.Node.Name, NicenessFmt(state.Nice),
812 humanize.IBytes(uint64(len(payload))),
816 state.payloads <- payload
827 defer state.SetDead()
828 defer state.wg.Done()
829 buf := make([]byte, MaxSPSize-SPHeadOverhead-SPFileOverhead)
831 if state.NotAlive() {
838 state.Ctx.LogD("sp-got-ping", les, func(les LEs) string {
840 "SP with %s (nice %s): got ping",
841 state.Node.Name, NicenessFmt(state.Nice),
844 payload = SPPingMarshalized
846 case payload = <-state.payloads:
849 append(les, LE{"Size", int64(len(payload))}),
850 func(les LEs) string {
852 "SP with %s (nice %s): got payload (%s)",
853 state.Node.Name, NicenessFmt(state.Nice),
854 humanize.IBytes(uint64(len(payload))),
860 if len(state.queueTheir) == 0 {
862 time.Sleep(100 * time.Millisecond)
865 freq := state.queueTheir[0].freq
867 if state.txRate > 0 {
868 time.Sleep(time.Second / time.Duration(state.txRate))
870 pktName := Base32Codec.EncodeToString(freq.Hash[:])
873 LE{"XX", string(TTx)},
875 LE{"Size", int64(freq.Offset)},
877 logMsg := func(les LEs) string {
879 "SP with %s (nice %s): tx/%s (%s)",
880 state.Node.Name, NicenessFmt(state.Nice),
882 humanize.IBytes(freq.Offset),
885 state.Ctx.LogD("sp-queue", lesp, func(les LEs) string {
886 return logMsg(les) + ": queueing"
888 pth := filepath.Join(
890 state.Node.Id.String(),
892 Base32Codec.EncodeToString(freq.Hash[:]),
894 state.fdsLock.RLock()
895 fdAndFullSize, exists := state.fds[pth]
896 state.fdsLock.RUnlock()
898 state.Ctx.LogD("sp-queue-open", lesp, func(les LEs) string {
899 return logMsg(les) + ": opening"
901 fd, err := os.Open(pth)
903 state.Ctx.LogE("sp-queue-open", lesp, err, func(les LEs) string {
904 return logMsg(les) + ": opening"
910 state.Ctx.LogE("sp-queue-stat", lesp, err, func(les LEs) string {
911 return logMsg(les) + ": stating"
915 fdAndFullSize = FdAndFullSize{fd: fd, fullSize: fi.Size()}
917 state.fds[pth] = fdAndFullSize
918 state.fdsLock.Unlock()
920 fd := fdAndFullSize.fd
921 fullSize := fdAndFullSize.fullSize
922 lesp = append(lesp, LE{"FullSize", fullSize})
924 if freq.Offset < uint64(fullSize) {
925 state.Ctx.LogD("sp-file-seek", lesp, func(les LEs) string {
926 return logMsg(les) + ": seeking"
928 if _, err = fd.Seek(int64(freq.Offset), io.SeekStart); err != nil {
929 state.Ctx.LogE("sp-file-seek", lesp, err, func(les LEs) string {
930 return logMsg(les) + ": seeking"
934 n, err := fd.Read(buf)
936 state.Ctx.LogE("sp-file-read", lesp, err, func(les LEs) string {
937 return logMsg(les) + ": reading"
944 LE{"XX", string(TTx)},
946 LE{"Size", int64(n)},
947 LE{"FullSize", fullSize},
949 state.Ctx.LogD("sp-file-read", lesp, func(les LEs) string {
952 logMsg(les), humanize.IBytes(uint64(n)),
958 payload = MarshalSP(SPTypeFile, SPFile{
963 ourSize := freq.Offset + uint64(len(bufRead))
966 LE{"XX", string(TTx)},
968 LE{"Size", int64(ourSize)},
969 LE{"FullSize", fullSize},
971 if state.Ctx.ShowPrgrs {
972 state.progressBars[pktName] = struct{}{}
975 if ourSize == uint64(fullSize) {
977 state.Ctx.LogD("sp-file-finished", lesp, func(les LEs) string {
978 return logMsg(les) + ": finished"
980 if state.Ctx.ShowPrgrs {
981 delete(state.progressBars, pktName)
985 for i, q := range state.queueTheir {
986 if *q.freq.Hash != *freq.Hash {
989 if ourSize == uint64(fullSize) {
990 state.queueTheir = append(
991 state.queueTheir[:i],
992 state.queueTheir[i+1:]...,
995 q.freq.Offset = ourSize
1001 logMsg := func(les LEs) string {
1003 "SP with %s (nice %s): sending %s",
1004 state.Node.Name, NicenessFmt(state.Nice),
1005 humanize.IBytes(uint64(len(payload))),
1008 state.Ctx.LogD("sp-sending", append(les, LE{"Size", int64(len(payload))}), logMsg)
1009 conn.SetWriteDeadline(time.Now().Add(DefaultDeadline))
1010 ct, err := state.csOur.Encrypt(nil, nil, payload)
1012 state.Ctx.LogE("sp-encrypting", les, err, logMsg)
1015 if err := state.WriteSP(conn, ct, ping); err != nil {
1016 state.Ctx.LogE("sp-sending", les, err, logMsg)
1026 if state.NotAlive() {
1029 logMsg := func(les LEs) string {
1031 "SP with %s (nice %s): waiting for payload",
1032 state.Node.Name, NicenessFmt(state.Nice),
1035 state.Ctx.LogD("sp-recv-wait", les, logMsg)
1036 conn.SetReadDeadline(time.Now().Add(DefaultDeadline))
1037 payload, err := state.ReadSP(conn)
1042 unmarshalErr := err.(*xdr.UnmarshalError)
1043 if os.IsTimeout(unmarshalErr.Err) {
1046 if unmarshalErr.ErrorCode == xdr.ErrIO {
1049 state.Ctx.LogE("sp-recv-wait", les, err, logMsg)
1052 logMsg = func(les LEs) string {
1054 "SP with %s (nice %s): payload (%s)",
1055 state.Node.Name, NicenessFmt(state.Nice),
1056 humanize.IBytes(uint64(len(payload))),
1061 append(les, LE{"Size", int64(len(payload))}),
1062 func(les LEs) string { return logMsg(les) + ": got" },
1064 payload, err = state.csTheir.Decrypt(nil, nil, payload)
1066 state.Ctx.LogE("sp-recv-got", les, err, func(les LEs) string {
1067 return logMsg(les) + ": got"
1073 append(les, LE{"Size", int64(len(payload))}),
1074 func(les LEs) string {
1075 return logMsg(les) + ": processing"
1078 replies, err := state.ProcessSP(payload)
1080 state.Ctx.LogE("sp-recv-process", les, err, func(les LEs) string {
1081 return logMsg(les) + ": processing"
1087 for _, reply := range replies {
1090 append(les[:len(les)-1], LE{"Size", int64(len(reply))}),
1091 func(les LEs) string {
1093 "SP with %s (nice %s): queuing reply (%s)",
1094 state.Node.Name, NicenessFmt(state.Nice),
1095 humanize.IBytes(uint64(len(reply))),
1099 state.payloads <- reply
1103 if state.rxRate > 0 {
1104 time.Sleep(time.Second / time.Duration(state.rxRate))
1116 func (state *SPState) Wait() bool {
1118 close(state.payloads)
1120 state.Duration = time.Since(state.started)
1122 state.RxSpeed = state.RxBytes
1123 state.TxSpeed = state.TxBytes
1124 rxDuration := int64(state.RxLastSeen.Sub(state.started).Seconds())
1125 txDuration := int64(state.TxLastSeen.Sub(state.started).Seconds())
1127 state.RxSpeed = state.RxBytes / rxDuration
1130 state.TxSpeed = state.TxBytes / txDuration
1132 nothingLeft := len(state.queueTheir) == 0
1133 for _, s := range state.fds {
1137 for pktName := range state.progressBars {
1138 ProgressKill(pktName)
1143 func (state *SPState) ProcessSP(payload []byte) ([][]byte, error) {
1144 les := LEs{{"Node", state.Node.Id}, {"Nice", int(state.Nice)}}
1145 r := bytes.NewReader(payload)
1147 var replies [][]byte
1150 state.Ctx.LogD("sp-process-unmarshal", les, func(les LEs) string {
1152 "SP with %s (nice %s): unmarshaling header",
1153 state.Node.Name, NicenessFmt(state.Nice),
1157 if _, err = xdr.Unmarshal(r, &head); err != nil {
1158 state.Ctx.LogE("sp-process-unmarshal", les, err, func(les LEs) string {
1160 "SP with %s (nice %s): unmarshaling header",
1161 state.Node.Name, NicenessFmt(state.Nice),
1166 if head.Type != SPTypePing {
1167 state.RxLastNonPing = state.RxLastSeen
1173 append(les, LE{"Type", "halt"}), func(les LEs) string {
1175 "SP with %s (nice %s): got HALT",
1176 state.Node.Name, NicenessFmt(state.Nice),
1181 state.queueTheir = nil
1187 append(les, LE{"Type", "ping"}),
1188 func(les LEs) string {
1190 "SP with %s (nice %s): got PING",
1191 state.Node.Name, NicenessFmt(state.Nice),
1198 lesp := append(les, LE{"Type", "info"})
1200 "sp-process-info-unmarshal", lesp,
1201 func(les LEs) string {
1203 "SP with %s (nice %s): unmarshaling INFO",
1204 state.Node.Name, NicenessFmt(state.Nice),
1209 if _, err = xdr.Unmarshal(r, &info); err != nil {
1211 "sp-process-info-unmarshal", lesp, err,
1212 func(les LEs) string {
1214 "SP with %s (nice %s): unmarshaling INFO",
1215 state.Node.Name, NicenessFmt(state.Nice),
1221 pktName := Base32Codec.EncodeToString(info.Hash[:])
1225 LE{"Size", int64(info.Size)},
1226 LE{"PktNice", int(info.Nice)},
1228 logMsg := func(les LEs) string {
1230 "SP with %s (nice %s): INFO %s (%s) nice %s",
1231 state.Node.Name, NicenessFmt(state.Nice),
1233 humanize.IBytes(info.Size),
1234 NicenessFmt(info.Nice),
1237 if !state.listOnly && info.Nice > state.Nice {
1238 state.Ctx.LogD("sp-process-info-too-nice", lesp, func(les LEs) string {
1239 return logMsg(les) + ": too nice"
1243 state.Ctx.LogD("sp-process-info-got", lesp, func(les LEs) string {
1244 return logMsg(les) + ": received"
1246 if !state.listOnly && state.xxOnly == TTx {
1250 state.infosTheir[*info.Hash] = &info
1252 state.Ctx.LogD("sp-process-info-stat", lesp, func(les LEs) string {
1253 return logMsg(les) + ": stating part"
1255 pktPath := filepath.Join(
1257 state.Node.Id.String(),
1259 Base32Codec.EncodeToString(info.Hash[:]),
1261 logMsg = func(les LEs) string {
1263 "Packet %s (%s) (nice %s)",
1265 humanize.IBytes(info.Size),
1266 NicenessFmt(info.Nice),
1269 if _, err = os.Stat(pktPath); err == nil {
1270 state.Ctx.LogI("sp-info-done", lesp, func(les LEs) string {
1271 return logMsg(les) + ": already done"
1273 if !state.listOnly {
1274 replies = append(replies, MarshalSP(SPTypeDone, SPDone{info.Hash}))
1278 if _, err = os.Stat(filepath.Join(
1279 state.Ctx.Spool, state.Node.Id.String(), string(TRx),
1280 SeenDir, Base32Codec.EncodeToString(info.Hash[:]),
1282 state.Ctx.LogI("sp-info-seen", lesp, func(les LEs) string {
1283 return logMsg(les) + ": already seen"
1285 if !state.listOnly {
1286 replies = append(replies, MarshalSP(SPTypeDone, SPDone{info.Hash}))
1290 if _, err = os.Stat(pktPath + NoCKSuffix); err == nil {
1291 state.Ctx.LogI("sp-info-nock", lesp, func(les LEs) string {
1292 return logMsg(les) + ": still not checksummed"
1296 fi, err := os.Stat(pktPath + PartSuffix)
1301 if !state.Ctx.IsEnoughSpace(int64(info.Size) - offset) {
1302 state.Ctx.LogI("sp-info-no-space", lesp, func(les LEs) string {
1303 return logMsg(les) + ": not enough space"
1309 append(lesp, LE{"Offset", offset}),
1310 func(les LEs) string {
1312 "%s: %d%%", logMsg(les), 100*uint64(offset)/info.Size,
1316 if !state.listOnly && (state.onlyPkts == nil || state.onlyPkts[*info.Hash]) {
1317 replies = append(replies, MarshalSP(
1319 SPFreq{info.Hash, uint64(offset)},
1324 lesp := append(les, LE{"Type", "file"})
1325 state.Ctx.LogD("sp-process-file", lesp, func(les LEs) string {
1327 "SP with %s (nice %s): unmarshaling FILE",
1328 state.Node.Name, NicenessFmt(state.Nice),
1332 if _, err = xdr.Unmarshal(r, &file); err != nil {
1333 state.Ctx.LogE("sp-process-file", lesp, err, func(les LEs) string {
1335 "SP with %s (nice %s): unmarshaling FILE",
1336 state.Node.Name, NicenessFmt(state.Nice),
1341 pktName := Base32Codec.EncodeToString(file.Hash[:])
1344 LE{"XX", string(TRx)},
1346 LE{"Size", int64(len(file.Payload))},
1348 logMsg := func(les LEs) string {
1350 "Got packet %s (%s)",
1351 pktName, humanize.IBytes(uint64(len(file.Payload))),
1354 fullsize := int64(0)
1356 infoTheir := state.infosTheir[*file.Hash]
1358 if infoTheir == nil {
1359 state.Ctx.LogE("sp-file-open", lesp, err, func(les LEs) string {
1360 return logMsg(les) + ": unknown file"
1364 fullsize = int64(infoTheir.Size)
1365 lesp = append(lesp, LE{"FullSize", fullsize})
1366 dirToSync := filepath.Join(
1368 state.Node.Id.String(),
1371 filePath := filepath.Join(dirToSync, pktName)
1372 filePathPart := filePath + PartSuffix
1373 state.Ctx.LogD("sp-file-open", lesp, func(les LEs) string {
1374 return logMsg(les) + ": opening part"
1376 state.fdsLock.RLock()
1377 fdAndFullSize, exists := state.fds[filePathPart]
1378 state.fdsLock.RUnlock()
1379 hasherAndOffset := state.fileHashers[filePath]
1382 fd = fdAndFullSize.fd
1384 fd, err = os.OpenFile(
1386 os.O_RDWR|os.O_CREATE,
1390 state.Ctx.LogE("sp-file-open", lesp, err, func(les LEs) string {
1391 return logMsg(les) + ": opening part"
1395 state.fdsLock.Lock()
1396 state.fds[filePathPart] = FdAndFullSize{fd: fd}
1397 state.fdsLock.Unlock()
1399 hasherAndOffset = &MTHAndOffset{
1400 mth: MTHNew(fullsize, int64(file.Offset)),
1401 offset: file.Offset,
1403 state.fileHashers[filePath] = hasherAndOffset
1408 append(lesp, LE{"Offset", file.Offset}),
1409 func(les LEs) string {
1410 return fmt.Sprintf("%s: seeking %d", logMsg(les), file.Offset)
1412 if _, err = fd.Seek(int64(file.Offset), io.SeekStart); err != nil {
1413 state.Ctx.LogE("sp-file-seek", lesp, err, func(les LEs) string {
1414 return logMsg(les) + ": seeking"
1416 state.closeFd(filePathPart)
1419 state.Ctx.LogD("sp-file-write", lesp, func(les LEs) string {
1420 return logMsg(les) + ": writing"
1422 if _, err = fd.Write(file.Payload); err != nil {
1423 state.Ctx.LogE("sp-file-write", lesp, err, func(les LEs) string {
1424 return logMsg(les) + ": writing"
1426 state.closeFd(filePathPart)
1429 if hasherAndOffset != nil {
1430 if hasherAndOffset.offset == file.Offset {
1431 if _, err = hasherAndOffset.mth.Write(file.Payload); err != nil {
1434 hasherAndOffset.offset += uint64(len(file.Payload))
1437 "sp-file-offset-differs", lesp, errors.New("offset differs"),
1438 func(les LEs) string {
1439 return logMsg(les) + ": deleting hasher"
1442 delete(state.fileHashers, filePath)
1443 hasherAndOffset = nil
1446 ourSize := int64(file.Offset + uint64(len(file.Payload)))
1447 lesp[len(lesp)-2].V = ourSize
1448 if state.Ctx.ShowPrgrs {
1449 state.progressBars[pktName] = struct{}{}
1450 Progress("Rx", lesp)
1452 if fullsize != ourSize {
1455 if state.Ctx.ShowPrgrs {
1456 delete(state.progressBars, pktName)
1458 logMsg = func(les LEs) string {
1460 "Got packet %s %d%% (%s / %s)",
1461 pktName, 100*ourSize/fullsize,
1462 humanize.IBytes(uint64(ourSize)),
1463 humanize.IBytes(uint64(fullsize)),
1469 state.Ctx.LogE("sp-file-sync", lesp, err, func(les LEs) string {
1470 return logMsg(les) + ": syncing"
1472 state.closeFd(filePathPart)
1476 if hasherAndOffset != nil {
1477 delete(state.fileHashers, filePath)
1478 if hasherAndOffset.mth.PreaddSize() == 0 {
1479 if !bytes.Equal(hasherAndOffset.mth.Sum(nil), file.Hash[:]) {
1481 "sp-file-bad-checksum", lesp,
1482 errors.New("checksum mismatch"),
1485 state.closeFd(filePathPart)
1488 if err = os.Rename(filePathPart, filePath); err != nil {
1489 state.Ctx.LogE("sp-file-rename", lesp, err, func(les LEs) string {
1490 return logMsg(les) + ": renaming"
1492 state.closeFd(filePathPart)
1495 if err = DirSync(dirToSync); err != nil {
1496 state.Ctx.LogE("sp-file-dirsync", lesp, err, func(les LEs) string {
1497 return logMsg(les) + ": dirsyncing"
1499 state.closeFd(filePathPart)
1502 state.Ctx.LogI("sp-file-done", lesp, func(les LEs) string {
1503 return logMsg(les) + ": done"
1507 state.payloads <- MarshalSP(SPTypeDone, SPDone{file.Hash})
1511 delete(state.infosTheir, *file.Hash)
1513 if !state.Ctx.HdrUsage {
1516 if _, err = fd.Seek(0, io.SeekStart); err != nil {
1517 state.Ctx.LogE("sp-file-seek", lesp, err, func(les LEs) string {
1518 return logMsg(les) + ": seeking"
1520 state.closeFd(filePathPart)
1523 _, pktEncRaw, err := state.Ctx.HdrRead(fd)
1524 state.closeFd(filePathPart)
1526 state.Ctx.LogE("sp-file-hdr-read", lesp, err, func(les LEs) string {
1527 return logMsg(les) + ": HdrReading"
1531 state.Ctx.HdrWrite(pktEncRaw, filePath)
1535 state.closeFd(filePathPart)
1536 if err = os.Rename(filePathPart, filePath+NoCKSuffix); err != nil {
1537 state.Ctx.LogE("sp-file-rename", lesp, err, func(les LEs) string {
1538 return logMsg(les) + ": renaming"
1542 if err = DirSync(dirToSync); err != nil {
1543 state.Ctx.LogE("sp-file-dirsync", lesp, err, func(les LEs) string {
1544 return logMsg(les) + ": dirsyncing"
1548 state.Ctx.LogI("sp-file-downloaded", lesp, func(les LEs) string {
1549 return logMsg(les) + ": downloaded"
1552 delete(state.infosTheir, *file.Hash)
1556 nodeId: state.Node.Id,
1558 done: state.payloads,
1560 if hasherAndOffset != nil {
1561 t.mth = hasherAndOffset.mth
1567 lesp := append(les, LE{"Type", "done"})
1568 state.Ctx.LogD("sp-process-done-unmarshal", lesp, func(les LEs) string {
1570 "SP with %s (nice %s): unmarshaling DONE",
1571 state.Node.Name, NicenessFmt(state.Nice),
1575 if _, err = xdr.Unmarshal(r, &done); err != nil {
1576 state.Ctx.LogE("sp-process-done-unmarshal", lesp, err, func(les LEs) string {
1578 "SP with %s (nice %s): unmarshaling DONE",
1579 state.Node.Name, NicenessFmt(state.Nice),
1584 pktName := Base32Codec.EncodeToString(done.Hash[:])
1585 lesp = append(lesp, LE{"Pkt", pktName}, LE{"XX", string(TTx)})
1586 logMsg := func(les LEs) string {
1588 "SP with %s (nice %s): DONE: removing %s",
1589 state.Node.Name, NicenessFmt(state.Nice), pktName,
1592 state.Ctx.LogD("sp-done", lesp, logMsg)
1593 pth := filepath.Join(
1595 state.Node.Id.String(),
1599 if err = os.Remove(pth); err == nil {
1600 state.Ctx.LogI("sp-done", lesp, func(les LEs) string {
1601 return fmt.Sprintf("Packet %s is sent", pktName)
1603 if state.Ctx.HdrUsage {
1604 os.Remove(JobPath2Hdr(pth))
1607 state.Ctx.LogE("sp-done", lesp, err, logMsg)
1611 lesp := append(les, LE{"Type", "freq"})
1612 state.Ctx.LogD("sp-process-freq", lesp, func(les LEs) string {
1614 "SP with %s (nice %s): unmarshaling FREQ",
1615 state.Node.Name, NicenessFmt(state.Nice),
1619 if _, err = xdr.Unmarshal(r, &freq); err != nil {
1620 state.Ctx.LogE("sp-process-freq", lesp, err, func(les LEs) string {
1622 "SP with %s (nice %s): unmarshaling FREQ",
1623 state.Node.Name, NicenessFmt(state.Nice),
1628 pktName := Base32Codec.EncodeToString(freq.Hash[:])
1629 lesp = append(lesp, LE{"Pkt", pktName}, LE{"Offset", freq.Offset})
1630 state.Ctx.LogD("sp-process-freq-queueing", lesp, func(les LEs) string {
1632 "SP with %s (nice %s): FREQ %s: queuing",
1633 state.Node.Name, NicenessFmt(state.Nice), pktName,
1636 nice, exists := state.infosOurSeen[*freq.Hash]
1638 if state.onlyPkts == nil || !state.onlyPkts[*freq.Hash] {
1641 var freqWithNice *FreqWithNice
1642 for insertIdx, freqWithNice = range state.queueTheir {
1643 if freqWithNice.nice > nice {
1647 state.queueTheir = append(state.queueTheir, nil)
1648 copy(state.queueTheir[insertIdx+1:], state.queueTheir[insertIdx:])
1649 state.queueTheir[insertIdx] = &FreqWithNice{&freq, nice}
1652 state.Ctx.LogD("sp-process-freq-skip", lesp, func(les LEs) string {
1654 "SP with %s (nice %s): FREQ %s: skipping",
1655 state.Node.Name, NicenessFmt(state.Nice), pktName,
1660 state.Ctx.LogD("sp-process-freq-unknown", lesp, func(les LEs) string {
1662 "SP with %s (nice %s): FREQ %s: unknown",
1663 state.Node.Name, NicenessFmt(state.Nice), pktName,
1670 "sp-process-type-unknown",
1671 append(les, LE{"Type", head.Type}),
1672 errors.New("unknown type"),
1673 func(les LEs) string {
1675 "SP with %s (nice %s): %d",
1676 state.Node.Name, NicenessFmt(state.Nice), head.Type,
1680 return nil, BadPktType
1688 for _, info := range state.infosTheir {
1693 state.Ctx.LogI("sp-infos-rx", LEs{
1694 {"XX", string(TRx)},
1695 {"Node", state.Node.Id},
1697 {"Size", int64(size)},
1698 }, func(les LEs) string {
1700 "%s has got for us: %d packets, %s",
1701 state.Node.Name, pkts, humanize.IBytes(size),
1705 return payloadsSplit(replies), nil
1708 func SPChecker(ctx *Ctx) {
1709 for t := range spCheckerTasks {
1710 pktName := Base32Codec.EncodeToString(t.hsh[:])
1712 {"XX", string(TRx)},
1717 ctx.LogD("sp-checker", les, func(les LEs) string {
1718 return fmt.Sprintf("Checksumming %s/rx/%s", ctx.NodeName(t.nodeId), pktName)
1720 size, err := ctx.CheckNoCK(t.nodeId, t.hsh, t.mth)
1721 les = append(les, LE{"Size", size})
1723 ctx.LogE("sp-checker", les, err, func(les LEs) string {
1725 "Checksumming %s/rx/%s (%s)", ctx.NodeName(t.nodeId), pktName,
1726 humanize.IBytes(uint64(size)),
1732 ctx.LogI("sp-checker-done", les, func(les LEs) string {
1734 "Packet %s is retreived (%s)",
1735 pktName, humanize.IBytes(uint64(size)),
1739 go func(t SPCheckerTask) {
1740 defer func() { recover() }()
1741 t.done <- MarshalSP(SPTypeDone, SPDone{t.hsh})