package hotline
import (
+ "bufio"
+ "bytes"
"context"
"encoding/binary"
"errors"
"fmt"
+ "github.com/go-playground/validator/v10"
"go.uber.org/zap"
+ "gopkg.in/yaml.v3"
"io"
+ "io/fs"
"io/ioutil"
"math/big"
"math/rand"
"path"
"path/filepath"
"runtime/debug"
- "sort"
"strings"
"sync"
"time"
-
- "gopkg.in/yaml.v2"
)
+type contextKey string
+
+var contextKeyReq = contextKey("req")
+
+type requestCtx struct {
+ remoteAddr string
+ login string
+ name string
+}
+
const (
userIdleSeconds = 300 // time in seconds before an inactive user is marked idle
idleCheckInterval = 10 // time in seconds to check for idle users
trackerUpdateFrequency = 300 // time in seconds between tracker re-registration
)
+var nostalgiaVersion = []byte{0, 0, 2, 0x2c} // version ID used by the Nostalgia client
+
type Server struct {
Port int
Accounts map[string]*Account
Agreement []byte
Clients map[uint16]*ClientConn
- FlatNews []byte
ThreadedNews *ThreadedNews
FileTransfers map[uint32]*FileTransfer
Config *Config
Logger *zap.SugaredLogger
PrivateChats map[uint32]*PrivateChat
NextGuestID *uint16
- TrackerPassID []byte
+ TrackerPassID [4]byte
Stats *Stats
- APIListener net.Listener
- FileListener net.Listener
-
- // newsReader io.Reader
- // newsWriter io.WriteCloser
+ FS FileStore // Storage backend to use for File storage
outbox chan Transaction
+ mux sync.Mutex
- mux sync.Mutex
flatNewsMux sync.Mutex
+ FlatNews []byte
}
type PrivateChat struct {
}
func (s *Server) ListenAndServe(ctx context.Context, cancelRoot context.CancelFunc) error {
- s.Logger.Infow("Hotline server started", "version", VERSION)
+ s.Logger.Infow("Hotline server started",
+ "version", VERSION,
+ "API port", fmt.Sprintf(":%v", s.Port),
+ "Transfer port", fmt.Sprintf(":%v", s.Port+1),
+ )
+
var wg sync.WaitGroup
wg.Add(1)
- go func() { s.Logger.Fatal(s.Serve(ctx, cancelRoot, s.APIListener)) }()
+ go func() {
+ ln, err := net.Listen("tcp", fmt.Sprintf("%s:%v", "", s.Port))
+ if err != nil {
+ s.Logger.Fatal(err)
+ }
+
+ s.Logger.Fatal(s.Serve(ctx, ln))
+ }()
wg.Add(1)
- go func() { s.Logger.Fatal(s.ServeFileTransfers(s.FileListener)) }()
+ go func() {
+ ln, err := net.Listen("tcp", fmt.Sprintf("%s:%v", "", s.Port+1))
+ if err != nil {
+ s.Logger.Fatal(err)
+
+ }
+
+ s.Logger.Fatal(s.ServeFileTransfers(ctx, ln))
+ }()
wg.Wait()
return nil
}
-func (s *Server) APIPort() int {
- return s.APIListener.Addr().(*net.TCPAddr).Port
-}
-
-func (s *Server) ServeFileTransfers(ln net.Listener) error {
- s.Logger.Infow("Hotline file transfer server started", "Addr", fmt.Sprintf(":%v", s.Port+1))
-
+func (s *Server) ServeFileTransfers(ctx context.Context, ln net.Listener) error {
for {
conn, err := ln.Accept()
if err != nil {
}
go func() {
- if err := s.TransferFile(conn); err != nil {
+ defer func() { _ = conn.Close() }()
+
+ err = s.handleFileTransfer(
+ context.WithValue(ctx, contextKeyReq, requestCtx{
+ remoteAddr: conn.RemoteAddr().String(),
+ }),
+ conn,
+ )
+
+ if err != nil {
s.Logger.Errorw("file transfer error", "reason", err)
}
}()
"IsReply", t.IsReply,
"type", handler.Name,
"sentBytes", n,
- "remoteAddr", client.Connection.RemoteAddr(),
+ "remoteAddr", client.RemoteAddr,
)
return nil
}
-func (s *Server) Serve(ctx context.Context, cancelRoot context.CancelFunc, ln net.Listener) error {
- s.Logger.Infow("Hotline server started", "Addr", fmt.Sprintf(":%v", s.Port))
-
+func (s *Server) Serve(ctx context.Context, ln net.Listener) error {
for {
conn, err := ln.Accept()
if err != nil {
}
}()
go func() {
- if err := s.handleNewConnection(conn); err != nil {
+ if err := s.handleNewConnection(ctx, conn, conn.RemoteAddr().String()); err != nil {
+ s.Logger.Infow("New client connection established", "RemoteAddr", conn.RemoteAddr())
if err == io.EOF {
s.Logger.Infow("Client disconnected", "RemoteAddr", conn.RemoteAddr())
} else {
)
// NewServer constructs a new Server from a config dir
-func NewServer(configDir, netInterface string, netPort int, logger *zap.SugaredLogger) (*Server, error) {
+func NewServer(configDir string, netPort int, logger *zap.SugaredLogger, FS FileStore) (*Server, error) {
server := Server{
Port: netPort,
Accounts: make(map[string]*Account),
outbox: make(chan Transaction),
Stats: &Stats{StartTime: time.Now()},
ThreadedNews: &ThreadedNews{},
- TrackerPassID: make([]byte, 4),
- }
-
- ln, err := net.Listen("tcp", fmt.Sprintf("%s:%v", netInterface, netPort))
- if err != nil {
- return nil, err
- }
- server.APIListener = ln
-
- if netPort != 0 {
- netPort += 1
+ FS: FS,
}
- ln2, err := net.Listen("tcp", fmt.Sprintf("%s:%v", netInterface, netPort))
- server.FileListener = ln2
- if err != nil {
- return nil, err
- }
+ var err error
// generate a new random passID for tracker registration
- if _, err := rand.Read(server.TrackerPassID); err != nil {
+ if _, err := rand.Read(server.TrackerPassID[:]); err != nil {
return nil, err
}
- server.Logger.Debugw("Loading Agreement", "path", configDir+agreementFile)
- if server.Agreement, err = os.ReadFile(configDir + agreementFile); err != nil {
+ server.Agreement, err = os.ReadFile(configDir + agreementFile)
+ if err != nil {
return nil, err
}
*server.NextGuestID = 1
if server.Config.EnableTrackerRegistration {
+ server.Logger.Infow(
+ "Tracker registration enabled",
+ "frequency", fmt.Sprintf("%vs", trackerUpdateFrequency),
+ "trackers", server.Config.Trackers,
+ )
+
go func() {
for {
- tr := TrackerRegistration{
- Port: []byte{0x15, 0x7c},
+ tr := &TrackerRegistration{
UserCount: server.userCount(),
- PassID: server.TrackerPassID,
+ PassID: server.TrackerPassID[:],
Name: server.Config.Name,
Description: server.Config.Description,
}
+ binary.BigEndian.PutUint16(tr.Port[:], uint16(server.Port))
for _, t := range server.Config.Trackers {
- server.Logger.Infof("Registering with tracker %v", t)
-
if err := register(t, tr); err != nil {
server.Logger.Errorw("unable to register with tracker %v", "error", err)
}
+ server.Logger.Infow("Sent Tracker registration", "data", tr)
}
time.Sleep(trackerUpdateFrequency * time.Second)
return err
}
-func (s *Server) NewClientConn(conn net.Conn) *ClientConn {
+func (s *Server) NewClientConn(conn net.Conn, remoteAddr string) *ClientConn {
s.mux.Lock()
defer s.mux.Unlock()
AutoReply: []byte{},
Transfers: make(map[int][]*FileTransfer),
Agreed: false,
+ RemoteAddr: remoteAddr,
}
*s.NextGuestID++
ID := *s.NextGuestID
}
s.Accounts[login] = &account
- return ioutil.WriteFile(s.ConfigDir+"Users/"+login+".yaml", out, 0666)
+ return s.FS.WriteFile(s.ConfigDir+"Users/"+login+".yaml", out, 0666)
+}
+
+func (s *Server) UpdateUser(login, newLogin, name, password string, access []byte) error {
+ s.mux.Lock()
+ defer s.mux.Unlock()
+
+ // update renames the user login
+ if login != newLogin {
+ err := os.Rename(s.ConfigDir+"Users/"+login+".yaml", s.ConfigDir+"Users/"+newLogin+".yaml")
+ if err != nil {
+ return err
+ }
+ s.Accounts[newLogin] = s.Accounts[login]
+ delete(s.Accounts, login)
+ }
+
+ account := s.Accounts[newLogin]
+ account.Access = &access
+ account.Name = name
+ account.Password = password
+
+ out, err := yaml.Marshal(&account)
+ if err != nil {
+ return err
+ }
+ if err := os.WriteFile(s.ConfigDir+"Users/"+newLogin+".yaml", out, 0666); err != nil {
+ return err
+ }
+
+ return nil
}
// DeleteUser deletes the user account
delete(s.Accounts, login)
- return FS.Remove(s.ConfigDir + "Users/" + login + ".yaml")
+ return s.FS.Remove(s.ConfigDir + "Users/" + login + ".yaml")
}
func (s *Server) connectedUsers() []Field {
return err
}
decoder := yaml.NewDecoder(fh)
- decoder.SetStrict(true)
return decoder.Decode(s.ThreadedNews)
}
}
for _, file := range matches {
- fh, err := FS.Open(file)
+ fh, err := s.FS.Open(file)
if err != nil {
return err
}
account := Account{}
decoder := yaml.NewDecoder(fh)
- decoder.SetStrict(true)
if err := decoder.Decode(&account); err != nil {
return err
}
}
func (s *Server) loadConfig(path string) error {
- fh, err := FS.Open(path)
+ fh, err := s.FS.Open(path)
if err != nil {
return err
}
decoder := yaml.NewDecoder(fh)
- decoder.SetStrict(true)
err = decoder.Decode(s.Config)
if err != nil {
return err
}
+
+ validate := validator.New()
+ err = validate.Struct(s.Config)
+ if err != nil {
+ return err
+ }
return nil
}
minTransactionLen = 22 // minimum length of any transaction
)
-// handleNewConnection takes a new net.Conn and performs the initial login sequence
-func (s *Server) handleNewConnection(conn net.Conn) error {
- handshakeBuf := make([]byte, 12) // handshakes are always 12 bytes in length
- if _, err := conn.Read(handshakeBuf); err != nil {
- return err
+// dontPanic recovers and logs panics instead of crashing
+// TODO: remove this after known issues are fixed
+func dontPanic(logger *zap.SugaredLogger) {
+ if r := recover(); r != nil {
+ fmt.Println("stacktrace from panic: \n" + string(debug.Stack()))
+ logger.Errorw("PANIC", "err", r, "trace", string(debug.Stack()))
}
- if err := Handshake(conn, handshakeBuf[:12]); err != nil {
+}
+
+// handleNewConnection takes a new net.Conn and performs the initial login sequence
+func (s *Server) handleNewConnection(ctx context.Context, conn net.Conn, remoteAddr string) error {
+ defer dontPanic(s.Logger)
+
+ if err := Handshake(conn); err != nil {
return err
}
buf := make([]byte, 1024)
+ // TODO: fix potential short read with io.ReadFull
readLen, err := conn.Read(buf)
if readLen < minTransactionLen {
return err
return err
}
- c := s.NewClientConn(conn)
+ c := s.NewClientConn(conn, remoteAddr)
defer c.Disconnect()
- defer func() {
- if r := recover(); r != nil {
- fmt.Println("stacktrace from panic: \n" + string(debug.Stack()))
- c.Server.Logger.Errorw("PANIC", "err", r, "trace", string(debug.Stack()))
- c.Disconnect()
- }
- }()
encodedLogin := clientLogin.GetField(fieldUserLogin).Data
encodedPassword := clientLogin.GetField(fieldUserPassword).Data
*c.Flags = []byte{0, 2}
}
- s.Logger.Infow("Client connection received", "login", login, "version", *c.Version, "RemoteAddr", conn.RemoteAddr().String())
+ s.Logger.Infow("Client connection received", "login", login, "version", *c.Version, "RemoteAddr", remoteAddr)
s.outbox <- c.NewReply(clientLogin,
NewField(fieldVersion, []byte{0x00, 0xbe}),
// Show agreement to client
c.Server.outbox <- *NewTransaction(tranShowAgreement, c.ID, NewField(fieldData, s.Agreement))
- // assume simplified hotline v1.2.3 login flow that does not require agreement
- if *c.Version == nil {
+ // Used simplified hotline v1.2.3 login flow for clients that do not send login info in tranAgreed
+ if *c.Version == nil || bytes.Equal(*c.Version, nostalgiaVersion) {
c.Agreed = true
c.notifyOthers(
c.Server.Logger.Errorw("Error handling transaction", "err", err)
}
- // iterate over all of the transactions that were parsed from the byte slice and handle them
+ // iterate over all the transactions that were parsed from the byte slice and handle them
for _, t := range transactions {
if err := c.handleTransaction(&t); err != nil {
c.Server.Logger.Errorw("Error handling transaction", "err", err)
}
// NewTransactionRef generates a random ID for the file transfer. The Hotline client includes this ID
-// in the file transfer request payload, and the file transfer server will use it to map the request
+// in the transfer request payload, and the file transfer server will use it to map the request
// to a transfer
func (s *Server) NewTransactionRef() []byte {
transactionRef := make([]byte, 4)
const dlFldrActionResumeFile = 2
const dlFldrActionNextFile = 3
-func (s *Server) TransferFile(conn net.Conn) error {
- defer func() { _ = conn.Close() }()
+// handleFileTransfer receives a client net.Conn from the file transfer server, performs the requested transfer type, then closes the connection
+func (s *Server) handleFileTransfer(ctx context.Context, rwc io.ReadWriter) error {
+ defer dontPanic(s.Logger)
txBuf := make([]byte, 16)
- _, err := conn.Read(txBuf)
- if err != nil {
+ if _, err := io.ReadFull(rwc, txBuf); err != nil {
return err
}
var t transfer
- _, err = t.Write(txBuf)
- if err != nil {
+ if _, err := t.Write(txBuf); err != nil {
return err
}
transferRefNum := binary.BigEndian.Uint32(t.ReferenceNumber[:])
- fileTransfer := s.FileTransfers[transferRefNum]
+ defer func() {
+ s.mux.Lock()
+ delete(s.FileTransfers, transferRefNum)
+ s.mux.Unlock()
+ }()
+
+ s.mux.Lock()
+ fileTransfer, ok := s.FileTransfers[transferRefNum]
+ s.mux.Unlock()
+ if !ok {
+ return errors.New("invalid transaction ID")
+ }
+
+ rLogger := s.Logger.With(
+ "remoteAddr", ctx.Value(contextKeyReq).(requestCtx).remoteAddr,
+ "xferID", transferRefNum,
+ )
switch fileTransfer.Type {
case FileDownload:
+ s.Stats.DownloadCounter += 1
+
fullFilePath, err := readPath(s.Config.FileRoot, fileTransfer.FilePath, fileTransfer.FileName)
if err != nil {
return err
}
- ffo, err := NewFlattenedFileObject(
- s.Config.FileRoot,
- fileTransfer.FilePath,
- fileTransfer.FileName,
- )
+ var dataOffset int64
+ if fileTransfer.fileResumeData != nil {
+ dataOffset = int64(binary.BigEndian.Uint32(fileTransfer.fileResumeData.ForkInfoList[0].DataSize[:]))
+ }
+
+ fw, err := newFileWrapper(s.FS, fullFilePath, 0)
if err != nil {
return err
}
- s.Logger.Infow("File download started", "filePath", fullFilePath, "transactionRef", fileTransfer.ReferenceNumber, "RemoteAddr", conn.RemoteAddr().String())
+ rLogger.Infow("File download started", "filePath", fullFilePath, "transactionRef", fileTransfer.ReferenceNumber)
- // Start by sending flat file object to client
- if _, err := conn.Write(ffo.BinaryMarshal()); err != nil {
- return err
+ wr := bufio.NewWriterSize(rwc, 1460)
+
+ // if file transfer options are included, that means this is a "quick preview" request from a 1.5+ client
+ if fileTransfer.options == nil {
+ // Start by sending flat file object to client
+ if _, err := wr.Write(fw.ffo.BinaryMarshal()); err != nil {
+ return err
+ }
}
- file, err := FS.Open(fullFilePath)
+ file, err := fw.dataForkReader()
if err != nil {
return err
}
- sendBuffer := make([]byte, 1048576)
- for {
- var bytesRead int
- if bytesRead, err = file.Read(sendBuffer); err == io.EOF {
- break
- }
-
- fileTransfer.BytesSent += bytesRead
+ if err := sendFile(wr, file, int(dataOffset)); err != nil {
+ return err
+ }
- delete(s.FileTransfers, transferRefNum)
+ if err := wr.Flush(); err != nil {
+ return err
+ }
- if _, err := conn.Write(sendBuffer[:bytesRead]); err != nil {
+ // if the client requested to resume transfer, do not send the resource fork, or it will be appended into the fileWrapper data
+ if fileTransfer.fileResumeData == nil {
+ err = binary.Write(wr, binary.BigEndian, fw.rsrcForkHeader())
+ if err != nil {
+ return err
+ }
+ if err := wr.Flush(); err != nil {
return err
}
}
- case FileUpload:
- const buffSize = 1460
-
- uploadBuf := make([]byte, buffSize)
- _, err := conn.Read(uploadBuf)
+ rFile, err := fw.rsrcForkFile()
if err != nil {
- return err
+ return nil
}
- ffo := ReadFlattenedFileObject(uploadBuf)
- payloadLen := len(ffo.BinaryMarshal())
- fileSize := int(binary.BigEndian.Uint32(ffo.FlatFileDataForkHeader.DataSize))
+ err = sendFile(wr, rFile, int(dataOffset))
- destinationFile := s.Config.FileRoot + ReadFilePath(fileTransfer.FilePath) + "/" + string(fileTransfer.FileName)
- s.Logger.Infow(
- "File upload started",
- "transactionRef", fileTransfer.ReferenceNumber,
- "RemoteAddr", conn.RemoteAddr().String(),
- "size", fileSize,
- "dstFile", destinationFile,
- )
+ if err := wr.Flush(); err != nil {
+ return err
+ }
+
+ case FileUpload:
+ s.Stats.UploadCounter += 1
- newFile, err := os.Create(destinationFile)
+ destinationFile, err := readPath(s.Config.FileRoot, fileTransfer.FilePath, fileTransfer.FileName)
if err != nil {
return err
}
- defer func() { _ = newFile.Close() }()
+ var file *os.File
+
+ // A file upload has three possible cases:
+ // 1) Upload a new file
+ // 2) Resume a partially transferred file
+ // 3) Replace a fully uploaded file
+ // We have to infer which case applies by inspecting what is already on the filesystem
- if _, err := newFile.Write(uploadBuf[payloadLen:]); err != nil {
+ // 1) Check for existing file:
+ _, err = os.Stat(destinationFile)
+ if err == nil {
+ // If found, that means this upload is intended to replace the file
+ if err = os.Remove(destinationFile); err != nil {
+ return err
+ }
+ file, err = os.Create(destinationFile + incompleteFileSuffix)
+ }
+ if errors.Is(err, fs.ErrNotExist) {
+ // If not found, open or create a new .incomplete file
+ file, err = os.OpenFile(destinationFile+incompleteFileSuffix, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0644)
+ if err != nil {
+ return err
+ }
+ }
+
+ f, err := newFileWrapper(s.FS, destinationFile, 0)
+ if err != nil {
return err
}
- receivedBytes := buffSize - payloadLen
- for {
- if (fileSize - receivedBytes) < buffSize {
- s.Logger.Infow(
- "File upload complete",
- "transactionRef", fileTransfer.ReferenceNumber,
- "RemoteAddr", conn.RemoteAddr().String(),
- "size", fileSize,
- "dstFile", destinationFile,
- )
+ defer func() { _ = file.Close() }()
- if _, err := io.CopyN(newFile, conn, int64(fileSize-receivedBytes)); err != nil {
- return fmt.Errorf("file transfer failed: %s", err)
- }
- return nil
+ s.Logger.Infow("File upload started", "transactionRef", fileTransfer.ReferenceNumber, "dstFile", destinationFile)
+
+ rForkWriter := io.Discard
+ iForkWriter := io.Discard
+ if s.Config.PreserveResourceForks {
+ rForkWriter, err = f.rsrcForkWriter()
+ if err != nil {
+ return err
}
- // Copy N bytes from conn to upload file
- n, err := io.CopyN(newFile, conn, buffSize)
+ iForkWriter, err = f.infoForkWriter()
if err != nil {
return err
}
- receivedBytes += int(n)
}
+
+ if err := receiveFile(rwc, file, rForkWriter, iForkWriter); err != nil {
+ return err
+ }
+
+ if err := s.FS.Rename(destinationFile+".incomplete", destinationFile); err != nil {
+ return err
+ }
+
+ s.Logger.Infow("File upload complete", "transactionRef", fileTransfer.ReferenceNumber, "dstFile", destinationFile)
case FolderDownload:
// Folder Download flow:
// 1. Get filePath from the transfer
// 2. Iterate over files
- // 3. For each file:
- // Send file header to client
+ // 3. For each fileWrapper:
+ // Send fileWrapper header to client
// The client can reply in 3 ways:
//
- // 1. If type is an odd number (unknown type?), or file download for the current file is completed:
- // client sends []byte{0x00, 0x03} to tell the server to continue to the next file
+ // 1. If type is an odd number (unknown type?), or fileWrapper download for the current fileWrapper is completed:
+ // client sends []byte{0x00, 0x03} to tell the server to continue to the next fileWrapper
//
- // 2. If download of a file is to be resumed:
+ // 2. If download of a fileWrapper is to be resumed:
// client sends:
// []byte{0x00, 0x02} // download folder action
// [2]byte // Resume data size
- // []byte file resume data (see myField_FileResumeData)
+ // []byte fileWrapper resume data (see myField_FileResumeData)
//
- // 3. Otherwise download of the file is requested and client sends []byte{0x00, 0x01}
+ // 3. Otherwise, download of the fileWrapper is requested and client sends []byte{0x00, 0x01}
//
// When download is requested (case 2 or 3), server replies with:
- // [4]byte - file size
+ // [4]byte - fileWrapper size
// []byte - Flattened File Object
//
- // After every file download, client could request next file with:
+ // After every fileWrapper download, client could request next fileWrapper with:
// []byte{0x00, 0x03}
//
// This notifies the server to send the next item header
basePathLen := len(fullFilePath)
- readBuffer := make([]byte, 1024)
+ s.Logger.Infow("Start folder download", "path", fullFilePath, "ReferenceNumber", fileTransfer.ReferenceNumber)
- s.Logger.Infow("Start folder download", "path", fullFilePath, "ReferenceNumber", fileTransfer.ReferenceNumber, "RemoteAddr", conn.RemoteAddr())
+ nextAction := make([]byte, 2)
+ if _, err := io.ReadFull(rwc, nextAction); err != nil {
+ return err
+ }
i := 0
- _ = filepath.Walk(fullFilePath+"/", func(path string, info os.FileInfo, _ error) error {
+ err = filepath.Walk(fullFilePath+"/", func(path string, info os.FileInfo, err error) error {
+ s.Stats.DownloadCounter += 1
i += 1
- subPath := path[basePathLen:]
- s.Logger.Infow("Sending fileheader", "i", i, "path", path, "fullFilePath", fullFilePath, "subPath", subPath, "IsDir", info.IsDir())
- fileHeader := NewFileHeader(subPath, info.IsDir())
+ if err != nil {
+ return err
+ }
+
+ // skip dot files
+ if strings.HasPrefix(info.Name(), ".") {
+ return nil
+ }
+
+ hlFile, err := newFileWrapper(s.FS, path, 0)
+ if err != nil {
+ return err
+ }
+
+ subPath := path[basePathLen+1:]
+ s.Logger.Infow("Sending fileheader", "i", i, "path", path, "fullFilePath", fullFilePath, "subPath", subPath, "IsDir", info.IsDir())
if i == 1 {
return nil
}
- // Send the file header to client
- if _, err := conn.Write(fileHeader.Payload()); err != nil {
+ fileHeader := NewFileHeader(subPath, info.IsDir())
+
+ // Send the fileWrapper header to client
+ if _, err := rwc.Write(fileHeader.Payload()); err != nil {
s.Logger.Errorf("error sending file header: %v", err)
return err
}
// Read the client's Next Action request
- // TODO: Remove hardcoded behavior and switch behaviors based on the next action send
- if _, err := conn.Read(readBuffer); err != nil {
+ if _, err := io.ReadFull(rwc, nextAction); err != nil {
return err
}
- s.Logger.Infow("Client folder download action", "action", fmt.Sprintf("%X", readBuffer[0:2]))
+ s.Logger.Infow("Client folder download action", "action", fmt.Sprintf("%X", nextAction[0:2]))
- if info.IsDir() {
+ var dataOffset int64
+
+ switch nextAction[1] {
+ case dlFldrActionResumeFile:
+ // get size of resumeData
+ resumeDataByteLen := make([]byte, 2)
+ if _, err := io.ReadFull(rwc, resumeDataByteLen); err != nil {
+ return err
+ }
+
+ resumeDataLen := binary.BigEndian.Uint16(resumeDataByteLen)
+ resumeDataBytes := make([]byte, resumeDataLen)
+ if _, err := io.ReadFull(rwc, resumeDataBytes); err != nil {
+ return err
+ }
+
+ var frd FileResumeData
+ if err := frd.UnmarshalBinary(resumeDataBytes); err != nil {
+ return err
+ }
+ dataOffset = int64(binary.BigEndian.Uint32(frd.ForkInfoList[0].DataSize[:]))
+ case dlFldrActionNextFile:
+ // client asked to skip this file
return nil
}
- splitPath := strings.Split(path, "/")
-
- ffo, err := NewFlattenedFileObject(
- strings.Join(splitPath[:len(splitPath)-1], "/"),
- nil,
- []byte(info.Name()),
- )
- if err != nil {
- return err
+ if info.IsDir() {
+ return nil
}
+
s.Logger.Infow("File download started",
"fileName", info.Name(),
"transactionRef", fileTransfer.ReferenceNumber,
- "RemoteAddr", conn.RemoteAddr().String(),
- "TransferSize", fmt.Sprintf("%x", ffo.TransferSize()),
+ "TransferSize", fmt.Sprintf("%x", hlFile.ffo.TransferSize(dataOffset)),
)
// Send file size to client
- if _, err := conn.Write(ffo.TransferSize()); err != nil {
+ if _, err := rwc.Write(hlFile.ffo.TransferSize(dataOffset)); err != nil {
s.Logger.Error(err)
return err
}
- // Send file bytes to client
- if _, err := conn.Write(ffo.BinaryMarshal()); err != nil {
+ // Send ffo bytes to client
+ if _, err := rwc.Write(hlFile.ffo.BinaryMarshal()); err != nil {
s.Logger.Error(err)
return err
}
- file, err := FS.Open(path)
+ file, err := s.FS.Open(path)
if err != nil {
return err
}
- sendBuffer := make([]byte, 1048576)
- totalBytesSent := len(ffo.BinaryMarshal())
+ // wr := bufio.NewWriterSize(rwc, 1460)
+ err = sendFile(rwc, file, int(dataOffset))
+ if err != nil {
+ return err
+ }
- for {
- bytesRead, err := file.Read(sendBuffer)
- if err == io.EOF {
- // Read the client's Next Action request
- // TODO: Remove hardcoded behavior and switch behaviors based on the next action send
- if _, err := conn.Read(readBuffer); err != nil {
- s.Logger.Errorf("error reading next action: %v", err)
- return err
- }
- break
+ if nextAction[1] != 2 && hlFile.ffo.FlatFileHeader.ForkCount[1] == 3 {
+ err = binary.Write(rwc, binary.BigEndian, hlFile.rsrcForkHeader())
+ if err != nil {
+ return err
+ }
+
+ rFile, err := hlFile.rsrcForkFile()
+ if err != nil {
+ return err
}
- sentBytes, readErr := conn.Write(sendBuffer[:bytesRead])
- totalBytesSent += sentBytes
- if readErr != nil {
+ err = sendFile(rwc, rFile, int(dataOffset))
+ if err != nil {
return err
}
}
+
+ // Read the client's Next Action request. This is always 3, I think?
+ if _, err := io.ReadFull(rwc, nextAction); err != nil {
+ return err
+ }
+
return nil
})
if err != nil {
return err
}
+
s.Logger.Infow(
"Folder upload started",
"transactionRef", fileTransfer.ReferenceNumber,
- "RemoteAddr", conn.RemoteAddr().String(),
"dstPath", dstPath,
"TransferSize", fmt.Sprintf("%x", fileTransfer.TransferSize),
"FolderItemCount", fileTransfer.FolderItemCount,
)
// Check if the target folder exists. If not, create it.
- if _, err := FS.Stat(dstPath); os.IsNotExist(err) {
- s.Logger.Infow("Creating target path", "dstPath", dstPath)
- if err := FS.Mkdir(dstPath, 0777); err != nil {
- s.Logger.Error(err)
+ if _, err := s.FS.Stat(dstPath); os.IsNotExist(err) {
+ if err := s.FS.Mkdir(dstPath, 0777); err != nil {
+ return err
}
}
- readBuffer := make([]byte, 1024)
-
// Begin the folder upload flow by sending the "next file action" to client
- if _, err := conn.Write([]byte{0, dlFldrActionNextFile}); err != nil {
+ if _, err := rwc.Write([]byte{0, dlFldrActionNextFile}); err != nil {
return err
}
fileSize := make([]byte, 4)
- itemCount := binary.BigEndian.Uint16(fileTransfer.FolderItemCount)
- for i := uint16(0); i < itemCount; i++ {
- if _, err := conn.Read(readBuffer); err != nil {
+ for i := 0; i < fileTransfer.ItemCount(); i++ {
+ s.Stats.UploadCounter += 1
+
+ var fu folderUpload
+ if _, err := io.ReadFull(rwc, fu.DataSize[:]); err != nil {
+ return err
+ }
+ if _, err := io.ReadFull(rwc, fu.IsFolder[:]); err != nil {
+ return err
+ }
+ if _, err := io.ReadFull(rwc, fu.PathItemCount[:]); err != nil {
+ return err
+ }
+
+ fu.FileNamePath = make([]byte, binary.BigEndian.Uint16(fu.DataSize[:])-4) // -4 to subtract the path separator bytes
+
+ if _, err := io.ReadFull(rwc, fu.FileNamePath); err != nil {
return err
}
- fu := readFolderUpload(readBuffer)
s.Logger.Infow(
"Folder upload continued",
"transactionRef", fmt.Sprintf("%x", fileTransfer.ReferenceNumber),
- "RemoteAddr", conn.RemoteAddr().String(),
"FormattedPath", fu.FormattedPath(),
"IsFolder", fmt.Sprintf("%x", fu.IsFolder),
"PathItemCount", binary.BigEndian.Uint16(fu.PathItemCount[:]),
if fu.IsFolder == [2]byte{0, 1} {
if _, err := os.Stat(dstPath + "/" + fu.FormattedPath()); os.IsNotExist(err) {
- s.Logger.Infow("Target path does not exist; Creating...", "dstPath", dstPath)
if err := os.Mkdir(dstPath+"/"+fu.FormattedPath(), 0777); err != nil {
- s.Logger.Error(err)
+ return err
}
}
// Tell client to send next file
- if _, err := conn.Write([]byte{0, dlFldrActionNextFile}); err != nil {
- s.Logger.Error(err)
+ if _, err := rwc.Write([]byte{0, dlFldrActionNextFile}); err != nil {
return err
}
} else {
- // TODO: Check if we have the full file already. If so, send dlFldrAction_NextFile to client to skip.
- // TODO: Check if we have a partial file already. If so, send dlFldrAction_ResumeFile to client to resume upload.
- // Send dlFldrAction_SendFile to client to begin transfer
- if _, err := conn.Write([]byte{0, dlFldrActionSendFile}); err != nil {
+ nextAction := dlFldrActionSendFile
+
+ // Check if we have the full file already. If so, send dlFldrAction_NextFile to client to skip.
+ _, err = os.Stat(dstPath + "/" + fu.FormattedPath())
+ if err != nil && !errors.Is(err, fs.ErrNotExist) {
return err
}
-
- if _, err := conn.Read(fileSize); err != nil {
- fmt.Println("Error reading:", err.Error()) // TODO: handle
+ if err == nil {
+ nextAction = dlFldrActionNextFile
}
- s.Logger.Infow("Starting file transfer", "fileNum", i+1, "totalFiles", itemCount, "fileSize", fileSize)
-
- if err := transferFile(conn, dstPath+"/"+fu.FormattedPath()); err != nil {
- s.Logger.Error(err)
- }
-
- // Tell client to send next file
- if _, err := conn.Write([]byte{0, dlFldrActionNextFile}); err != nil {
- s.Logger.Error(err)
+ // Check if we have a partial file already. If so, send dlFldrAction_ResumeFile to client to resume upload.
+ incompleteFile, err := os.Stat(dstPath + "/" + fu.FormattedPath() + incompleteFileSuffix)
+ if err != nil && !errors.Is(err, fs.ErrNotExist) {
return err
}
+ if err == nil {
+ nextAction = dlFldrActionResumeFile
+ }
- // Client sends "MACR" after the file. Read and discard.
- // TODO: This doesn't seem to be documented. What is this? Maybe resource fork?
- if _, err := conn.Read(readBuffer); err != nil {
+ if _, err := rwc.Write([]byte{0, uint8(nextAction)}); err != nil {
return err
}
- }
- }
- s.Logger.Infof("Folder upload complete")
- }
- return nil
-}
+ switch nextAction {
+ case dlFldrActionNextFile:
+ continue
+ case dlFldrActionResumeFile:
+ offset := make([]byte, 4)
+ binary.BigEndian.PutUint32(offset, uint32(incompleteFile.Size()))
-func transferFile(conn net.Conn, dst string) error {
- const buffSize = 1024
- buf := make([]byte, buffSize)
+ file, err := os.OpenFile(dstPath+"/"+fu.FormattedPath()+incompleteFileSuffix, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
+ if err != nil {
+ return err
+ }
- // Read first chunk of bytes from conn; this will be the Flat File Object and initial chunk of file bytes
- if _, err := conn.Read(buf); err != nil {
- return err
- }
- ffo := ReadFlattenedFileObject(buf)
- payloadLen := len(ffo.BinaryMarshal())
- fileSize := int(binary.BigEndian.Uint32(ffo.FlatFileDataForkHeader.DataSize))
+ fileResumeData := NewFileResumeData([]ForkInfoList{*NewForkInfoList(offset)})
- newFile, err := os.Create(dst)
- if err != nil {
- return err
- }
- defer func() { _ = newFile.Close() }()
- if _, err := newFile.Write(buf[payloadLen:]); err != nil {
- return err
- }
- receivedBytes := buffSize - payloadLen
+ b, _ := fileResumeData.BinaryMarshal()
- for {
- if (fileSize - receivedBytes) < buffSize {
- _, err := io.CopyN(newFile, conn, int64(fileSize-receivedBytes))
- return err
- }
+ bs := make([]byte, 2)
+ binary.BigEndian.PutUint16(bs, uint16(len(b)))
- // Copy N bytes from conn to upload file
- n, err := io.CopyN(newFile, conn, buffSize)
- if err != nil {
- return err
+ if _, err := rwc.Write(append(bs, b...)); err != nil {
+ return err
+ }
+
+ if _, err := io.ReadFull(rwc, fileSize); err != nil {
+ return err
+ }
+
+ if err := receiveFile(rwc, file, ioutil.Discard, ioutil.Discard); err != nil {
+ s.Logger.Error(err)
+ }
+
+ err = os.Rename(dstPath+"/"+fu.FormattedPath()+".incomplete", dstPath+"/"+fu.FormattedPath())
+ if err != nil {
+ return err
+ }
+
+ case dlFldrActionSendFile:
+ if _, err := io.ReadFull(rwc, fileSize); err != nil {
+ return err
+ }
+
+ filePath := dstPath + "/" + fu.FormattedPath()
+
+ hlFile, err := newFileWrapper(s.FS, filePath, 0)
+ if err != nil {
+ return err
+ }
+
+ s.Logger.Infow("Starting file transfer", "path", filePath, "fileNum", i+1, "fileSize", binary.BigEndian.Uint32(fileSize))
+
+ incWriter, err := hlFile.incFileWriter()
+ if err != nil {
+ return err
+ }
+
+ rForkWriter := io.Discard
+ iForkWriter := io.Discard
+ if s.Config.PreserveResourceForks {
+ iForkWriter, err = hlFile.infoForkWriter()
+ if err != nil {
+ return err
+ }
+
+ rForkWriter, err = hlFile.rsrcForkWriter()
+ if err != nil {
+ return err
+ }
+ }
+ if err := receiveFile(rwc, incWriter, rForkWriter, iForkWriter); err != nil {
+ return err
+ }
+ // _ = newFile.Close()
+ if err := os.Rename(filePath+".incomplete", filePath); err != nil {
+ return err
+ }
+ }
+
+ // Tell client to send next fileWrapper
+ if _, err := rwc.Write([]byte{0, dlFldrActionNextFile}); err != nil {
+ return err
+ }
+ }
}
- receivedBytes += int(n)
+ s.Logger.Infof("Folder upload complete")
}
-}
-// sortedClients is a utility function that takes a map of *ClientConn and returns a sorted slice of the values.
-// The purpose of this is to ensure that the ordering of client connections is deterministic so that test assertions work.
-func sortedClients(unsortedClients map[uint16]*ClientConn) (clients []*ClientConn) {
- for _, c := range unsortedClients {
- clients = append(clients, c)
- }
- sort.Sort(byClientID(clients))
- return clients
+ return nil
}