r66

package module
v0.1.6 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 2, 2023 License: MIT Imports: 28 Imported by: 3

README

r66

The r66 package provides an implementation of the R66 protocol in golang to sends file to a R66 server. It also implements an R66 server for serving files from the filesystem.

import: code.waarp.fr/waarp-r66/r66

R66

R66 is an MFT (Managed File Transert) protocol designed to optimise file transfers, ensure the integrity of the data and provide ways to integrate transfers in larger business transactions.

features

  • r66 client
  • r66 server
  • multi-plexing
  • send/receive files
  • request infos filesystem/transfers
  • request bandwidth set/get
  • request shutdown/block

roadmap

  • cleanup api
  • more unit tests
  • imports/export of configuration
  • support 3rd party digest

getting started

getting and importing the library
go get code.waarp.fr/waarp-r66/r66
import code.waarp.fr/waarp-r66/r66
connect to an R66 server
client, err := r66.Dial("127.0.0.1:6666", nil)
if err != nil {
	return err
}
defer client.Close()
// DO STUFF
send a file
// Connect
client, err := r66.Dial("127.0.0.1:6666", nil)
if err != nil {
	return err
}
defer client.Close()
// Create a session
ses, err := client.NewSession()
if err != nil {
    return err
}
defer ses.Close()
auth, err := ses.Authent("login", []byte("password"), nil) 
if err != nil {
    return err
}
// Valid received auth
// Open file
f, err := os.Open(localFilename)
if err != nil {
    ses.SendError(&r66.Error{
        Code:   r66.FileNotFound,
        Detail: "Internal error",
    })
    return err
}
defer f.Close()
// Get file size
i, err := f.Stat()
if err != nil {
    return err
}
s := i.Size()
// Send request
req, err := ses.Request(&r66.Request{
    ID:       time.Now().Unix(), // To garantee ID unicity
    Filepath: remoteFilename,
    FileSize: s,
    Rule:     "send",
    Mode:     uint32(r66.MODE_SEND),
    Block:    32000,
    Rank:     0,
})
if err != nil {
    return err
}
// Valid received req
// Send the file
eot, err := ses.Send(f, func() ([]byte, error) {
    h := sha256.New()
    _, err := io.Copy(h, f)
    if err != nil {
        return nil, err
    }
    return h.Sum(nil), nil
})
if err != nil {
    return err
}
// Valid received end transfer
err = ses.EndRequest()
if err != nil {
	return err
}
return nil
launch a server
server := r66.Server{
    Login:    "serverLogin",
    Password: []byte("serverPassword"),
    Conf: r66.Configuration{
        FileSize:   true,
        FinalHash:  true,
        DigestAlgo: "SHA-256",
        Proxified:  true,
    },
    AuthentHandler: &r66.BasicAuthentHandler{Server: true},
}
err := server.ListenAndServe("127.0.0.1:6666")
if err != nil {
    fmt.Println(err.Error())
}

Documentation

Index

Constants

View Source
const (
	//InitOk stands for initialization ok (internal connection, authentication)
	InitOk = 'i'
	//PreProcessingOk stands for pre processing ok
	PreProcessingOk = 'B'
	//TransferOk stands for transfer OK
	TransferOk = 'X'
	//PostProcessingOk stands for post processing ok
	PostProcessingOk = 'P'
	//CompleteOk stands for All action are completed ok
	CompleteOk = 'O'
	//ConnectionImpossible stands for connection is impossible (remote or local reason)
	ConnectionImpossible = 'C'
	//ServerOverloaded stands for connection is impossible now due to limits(remote or local reason)
	ServerOverloaded = 'l'
	//BadAuthent stands for bad authentication (remote or local)
	BadAuthent = 'A'
	//ExternalOperation stands for External operation in error (pre, post or error processing
	ExternalOperation = 'E'
	//TransferError stands for Transfer is in error
	TransferError = 'T'
	//MD5Error stands for Transfer in error due to MD5
	MD5Error = 'M'
	//Disconnection stands for Network disconnection
	Disconnection = 'D'
	//RemoteShutdown stands for Remote Shutdown
	RemoteShutdown = 'r'
	//FinalOp stands for final action (like moving file) is in error
	FinalOp = 'F'
	//Unimplemented stands for unimplemented feature
	Unimplemented = 'U'
	//Shutdown stands for shutdown is in progress
	Shutdown = 'S'
	//RemoteError stands for a remote error is received
	RemoteError = 'R'
	//Internal stands for an internal error
	Internal = 'I'
	//StoppedTransfer stands for a request of stopping transfer
	StoppedTransfer = 'H'
	//CanceledTransfer stands for a request of canceling transfer
	CanceledTransfer = 'K'
	//Warning in execution
	Warning = 'W'
	//Unknown stands for unknown type of error
	Unknown = '-'
	//QueryAlreadyFinished stands for a request that is already remotely finished
	QueryAlreadyFinished = 'Q'
	//QueryStillRunning stands for request that is still running
	QueryStillRunning = 's'
	//NotKnownHost stands for not known host
	NotKnownHost = 'N'
	//LoopSelfRequestedHost stands for self requested host starting request is invalid
	LoopSelfRequestedHost = 'L'
	//QueryRemotelyUnknown stands for request should exist but is not found on remote host
	QueryRemotelyUnknown = 'u'
	//FileNotFound stands for File not found error
	FileNotFound = 'f'
	//CommandNotFound stands for Command not found error
	CommandNotFound = 'c'
	//PassThroughMode stands for a request in PassThroughMode and required action is incompatible with this mode
	PassThroughMode = 'p'
	//Running stands for running step
	Running = 'z'
	//IncorrectCommand stands for Incorrect command
	IncorrectCommand = 'n'
	//FileNotAllowed stands for File not allowed
	FileNotAllowed = 'a'
	//SizeNotAllowed stands for Size not allowed
	SizeNotAllowed = 'd'
)

FIXME 1.0.0 errorCode should be its own type (cf infoRequest or globalStep)

View Source
const (
	// DigestMD5 is used to identify the MD5 hash algorith
	DigestMD5 = "MD5"
	// DigestSHA1 is used to identify the SHA1 hash algorith
	DigestSHA1 = "SHA-1"
	// DigestSHA256 is used to identify the SHA256 hash algorith
	DigestSHA256 = "SHA-256"
	// DigestADLER32 is used to identify the ADLER32 hash algorith
	DigestADLER32 = "ADLER32"
	// DigestSHA384 is used to identify the SHA384 hash algorith
	DigestSHA384 = "SHA-384"
	// DigestSHA512 is used to identify the SHA512 hash algorith
	DigestSHA512 = "SHA-512"
)
View Source
const (
	// ModeUnknown is a placeholder and it should not be used.
	// Deprecated 1.0.0 will be unexported
	ModeUnknown mode = 0
	// ModeSend is used for a file exchange from the client to the server.
	// Deprecated 1.0.0 will be unexported
	ModeSend mode = 1
	// ModeRecv is used for a file exchange from the server to the client.
	// Deprecated 1.0.0 will be unexported
	ModeRecv mode = 2
	// ModeSendMD5 is used for a file exchange from the client to the server.
	// Each data block transmited will carry its hash validation.
	// Deprecated 1.0.0 will be unexported
	ModeSendMD5 mode = 3
	// ModeRecvMD5 is used for a file exchange from the server to the client.
	// Each data block transmited will carry its hash validation.
	// Deprecated 1.0.0 will be unexported
	ModeRecvMD5 mode = 4
	// ModeSendThrough is used for a file exchange from the client to the server.
	// The server should not store the file but send it to another server.
	// This mode is not enforced by the library.
	// Deprecated 1.0.0 will be unexported
	ModeSendThrough mode = 5
	// ModeRecvThrough is used for a file exchange from the server to the client.
	// The client should not store the file but send it to another server.
	// This mode is not enforced by the library.
	// Deprecated 1.0.0 will be unexported
	ModeRecvThrough mode = 6
	// ModeSendMD5Through is used for a file exchange from the client to the server.
	// The server should not store the file but send it to another server.
	// This mode is not enforced by the library.
	// Each data block transmited will carry its hash validation.
	// Deprecated 1.0.0 will be unexported
	ModeSendMD5Through mode = 7
	// ModeRecvMD5Through is used for a file exchange from the server to the client.
	// The client should not store the file but send it to another server.
	// This mode is not enforced by the library.
	// Each data block transmited will carry its hash validation.
	// Deprecated 1.0.0 will be unexported
	ModeRecvMD5Through mode = 8
)

FIXME 1.0.0 mode should be its own type (cf infoRequest or globalStep)

Variables

View Source
var (

	// InfoFile is used to request the existence or not of a single file.
	InfoFile infoRequest = infoRequest{0}
	// InfoFileDetails is used to request the full details of a single file.
	InfoFileDetails infoRequest = infoRequest{1}
	// InfoList is used to request the existence of a list of files matching
	// a pattern.
	InfoList infoRequest = infoRequest{2}
	// InfoListDetails is used to request the fule details of a list of files
	// matching a pattern.
	InfoListDetails infoRequest = infoRequest{3}

	// StepNoTask indicates the transfer has not yet started.
	StepNoTask globalStep = globalStep{0}
	// StepPreTask indicates the transfer is in a state before the transfer of data.
	StepPreTask globalStep = globalStep{1}
	// StrepTransfer indicates the transfer of the data is in process.
	StrepTransfer globalStep = globalStep{2}
	// StepPost indicates the transfer of the data is complete.
	StepPost globalStep = globalStep{3}
	// StepDone indicates the transfer of the file is complete.
	StepDone globalStep = globalStep{4}
	// StepError indicates the transfer is in error.
	StepError globalStep = globalStep{5}
)
View Source
var ErrBadProtocol = &Error{
	Code:   Internal,
	Detail: "Protocol error: unexpected packet",
}

ErrBadProtocol is returned when handlers receive unexpected packets

View Source
var ErrMisformedPacket = &Error{
	Code:   Internal,
	Detail: "Protocol error: misformed packet",
}

ErrMisformedPacket is returned when hadnlers receive misformed packets

View Source
var ErrUninplementedPacket = &Error{
	Code:   Internal,
	Detail: "Uninplemented packet",
}

ErrUninplementedPacket is returned when handlers receive packets they cannot process

View Source
var ErrUnsupportedFeature = &Error{
	Code:   Unimplemented,
	Detail: "Remote server doesn't support this feature",
}

ErrUnsupportedFeature is returned when the implementation doesn't support the requested feature

Functions

func CryptPass

func CryptPass(pwd []byte) []byte

CryptPass returns a hashed version of the password according to R66

func GetHasher

func GetHasher(algo string) (hash.Hash, error)

GetHasher return a new hasher of the specified algorithm

func HashBlock

func HashBlock(block []byte, hasher hash.Hash) ([]byte, error)

HashBlock returns the hash of the profided byte array according to the specified algorithm

func HashFile

func HashFile(file *os.File, hasher hash.Hash) ([]byte, error)

HashFile returns the hash of the profided file according to the specified algorithm

func IsBeforePostTask

func IsBeforePostTask(code rune) bool

IsBeforePostTask returns true if the code provided is an operation before the post tasks

func IsBeforePreTask

func IsBeforePreTask(code rune) bool

IsBeforePreTask returns true if the code provided is an operation before the pre tasks

func IsBeforeTransfer

func IsBeforeTransfer(code rune) bool

IsBeforeTransfer returns true if the code provided is an operation before the transfer

func IsError

func IsError(code rune) bool

IsError returns true if the code provided is an error code

func IsMD5

func IsMD5(mode uint32) bool

IsMD5 return true if the provided mode is a hashed mode Deprecated 1.0.0 will be unexported

func IsPassThrough

func IsPassThrough(mode uint32) bool

IsPassThrough return true if the provided mode is a passthrough mode Deprecated 1.0.0 will be unexported

func IsRecv

func IsRecv(mode uint32) bool

IsRecv return true if the provided mode is a receive mode Deprecated 1.0.0 will be unexported

Types

type AdminHandler

type AdminHandler interface {
	Shutdown(password []byte, restart bool) error
	BlockRequest(password []byte, block bool) error
}

AdminHandler is the interface that handle shutdown and block transfers request.

Shutdown verifies password and halt the server if restart if false or restart it if is true. Shutdown returns an error if the halt request is refused or fails.

BlockRequest verifies password and prevent the server from accepting new transfer request if block is true or allows it to accept new transfer request is block is false. BlockRequest returns an error if the block request is refused or fails.

Implementations of Shutdown and BlockRequest are encouraged to return a Error (rather than a builtin error).

type Authent

type Authent struct {
	Login     string
	Password  []byte
	Version   string // Refused < 3.0.0
	Address   string // usefull ?
	Filesize  bool
	FinalHash bool
	Digest    string // Must be SHA-256
	Proxified bool
	Separator rune // Must be ';'
	TLS       *tls.ConnectionState
}

Authent is a structure providing information to authentified an R66 session

type AuthentHandler

type AuthentHandler interface {
	ValidAuth(*Authent) (SessionHandler, error)
}

AuthentHandler is an interface responsible to authorize new R66 session If ValidAuth returns a nil error SessionHandler MUST NOT be nil. If a non nil error is returned the authententication is concidered in error.

type Bandwidth

type Bandwidth struct {
	// GlobalReadLimit is the upper limit (in o/s) at which the server reads
	// network packets.
	GlobalReadLimit int64
	// GlobalWriteLimit is the upper limit (in o/s) at which the server writes
	// network packets.
	GlobalWriteLimit int64
	// SessionReadLimit is the upper limit (in o/s) at which the server reads
	// packets for a given transfer.
	SessionReadLimit int64
	// SessionWriteLimit is the upper limit (in o/s) at which the server
	// writes packet for a given transfer.
	SessionWriteLimit int64
}

Bandwidth is a structure representing information about the server's bandwidth limitations.

type BandwidthHandler

type BandwidthHandler interface {
	GetBandwidth() (*Bandwidth, error)
	SetBandwidth(*Bandwidth) (*Bandwidth, error)
}

BandwidthHandler is the interface that handle get and set operations on the server bandwidth limitations.

GetBandwidth returns the current Bandwidth limitations of the server. GetBandwidth returns an error if the bandwidth request is refused or fails.

SetBandwidth updates the current Bandwidth limitations of the server and returns the new value of these limitations. SetBandwidth returns an error if the bandwidth update is refused or fails.

Implementations of GetBandwidth and SetBandwidth are encouraged to return an Error (rather than a builtin error).

type BasicAuthentHandler

type BasicAuthentHandler struct {
	Root          string
	Logger        *log.Logger
	AcceptAuth    bool
	AcceptRequest bool
}

BasicAuthentHandler is a simple AuthentHandler which accept all request.

func (*BasicAuthentHandler) ValidAuth

func (h *BasicAuthentHandler) ValidAuth(auth *Authent) (SessionHandler, error)

ValidAuth accepts all authent and return a basic implementation of SessionHandler.

type BasicSessionHandler

type BasicSessionHandler struct {
	// contains filtered or unexported fields
}

BasicSessionHandler is a simple SessionHandler which accept all request.

func (*BasicSessionHandler) GetFileInfo

func (h *BasicSessionHandler) GetFileInfo(rule string, filename string) ([]FileInfo, error)

GetFileInfo returns the information of the file requested

func (*BasicSessionHandler) ValidRequest

func (h *BasicSessionHandler) ValidRequest(req *Request) (t TransferHandler, err error)

ValidRequest accepts all request and return a basic implementation of TransferHandler.

type BasicTransferHandler

type BasicTransferHandler struct {
	File        string
	Size        int64
	UserContent string
	// contains filtered or unexported fields
}

BasicTransferHandler is a simple TransferHandler which run no Tasks.

func (*BasicTransferHandler) GetHash

func (h *BasicTransferHandler) GetHash() ([]byte, error)

GetHash returns the hash of the transfered file according to the hasher of the handler

func (*BasicTransferHandler) GetStream

func (h *BasicTransferHandler) GetStream() (utils.ReadWriterAt, error)

GetStream opens the file if first called and return it as an ReadWriter

func (*BasicTransferHandler) UpdateTransferInfo

func (h *BasicTransferHandler) UpdateTransferInfo(i *UpdateInfo) error

UpdateTransferInfo modifies the informations about the transfered file according to the providing informations

func (*BasicTransferHandler) ValidEndRequest

func (h *BasicTransferHandler) ValidEndRequest() error

ValidEndRequest closes the file

func (*BasicTransferHandler) ValidEndTransfer

func (h *BasicTransferHandler) ValidEndTransfer(e *EndTransfer) error

ValidEndTransfer does nothing

type Client

type Client struct {
	// contains filtered or unexported fields
}

Client represents a connection to a r66 server

func Dial

func Dial(addr string, logger *log.Logger) (*Client, error)

Dial connects to the address and returns an R66 Client. If provided the logger will give additional information.

func DialTLS

func DialTLS(addr string, tlsConf *tls.Config, logger *log.Logger) (*Client, error)

DialTLS connects to the address and returns an R66 Client using the provided tls configuration. If provided the logger will give additional information.

func NewClient

func NewClient(conn net.Conn, logger *log.Logger) (*Client, error)

NewClient returns an R66 Client using the provided connection. If provided the logger will give additional information.

func (*Client) Close

func (c *Client) Close()

Close closes the Client and the connection used.

func (*Client) NewSession

func (c *Client) NewSession() (*Session, error)

NewSession returns an R66 Session on the connected Client.

type ClientAuthentHandler

type ClientAuthentHandler interface {
	ValidAuth(*Authent) (RequestHandler, error)
}

ClientAuthentHandler is an interface responsible to authorize new R66 session Deprecated 1.0.0 will be removed

type Config

type Config struct {
	FileSize   bool
	FinalHash  bool
	DigestAlgo string
	Proxified  bool
}

Config is used to configure a R66 client or server. After one has been passed to an R66 function it must not be modified. A config should not be reused; the package r66 will modify it.

func (*Config) Clone

func (c *Config) Clone() *Config

Clone returns a copy of the provided configuration.

func (*Config) Valid

func (c *Config) Valid() error

Valid returns nil if the configuration is valid and an error if the configuration is invalid. FIXME: Is it really needed, Should be able to support any hasher

type EndTransfer

type EndTransfer struct {
	// Hash is the hash of the file transfered.
	Hash []byte
}

EndTransfer is a structure providing information to valid the correctness of the transfer.

type Error

type Error struct {
	Code   rune
	Detail string
}

Error is a representation of an R66 error with a code and a message associated

func GetError

func GetError(p *packet.ErrorPacket) *Error

GetError return the error contained in the provided ErrorPacket

func (*Error) Error

func (e *Error) Error() string

type ErrorTasker

type ErrorTasker interface {
	RunErrorTask(error) error
}

ErrorTasker is the interface that handle custom operations if the file transfer fails. A TransferHandler can be a ErrorTasker if such operations are wanted.

type FileInfo

type FileInfo struct {
	// Name is the filepath of the file
	Name string
	// Size is the size (in o) of the file
	Size int64
	// LastModify is the last date at which the file has been modified
	LastModify time.Time
	// The type of the file (file, directory, link, ...)
	Type string
	// The permission on the file
	Permission string
}

FileInfo is a structure representing information on a file of the server filesystem.

type InfoHandler

type InfoHandler interface {
	GetTransferInfo(ID int64, isClient bool) (*TransferInfo, error)
	GetFileInfo(rule string, patern string) ([]FileInfo, error)
}

InfoHandler is the interface that handle requests about the filesystem of the serveer and information about current or past transfers.

GetTransferInfo returns the transfer informations with the given ID. GetTransferInfo returns an error if the information request fails.

GetFileInfo returns information about files matching the requested patern in the context of the provided rules (if the files can be requested with the rule). GetFileInfo returns an error if the rule is unknown, if no files matches the requested pattern or if the filesystem request fails.

Implementations of GetFileInfo are discourages from returning an empty FileInfo array with a nil error.

Implementations of GetTransferInfo and GetFileInfo are encouraged to return an Error (rather than a builtin error).

type PostTasker

type PostTasker interface {
	RunPostTask() error
}

PostTasker is the interface that handle custom operations after the file is transfered. A TransferHandler can be a PostTasker if such operations are wanted.

type PreTasker

type PreTasker interface {
	RunPreTask() (*UpdateInfo, error)
}

PreTasker is the interface that handle custom operations before the file is transfered. A TransferHandler can be a PreTasker if such operations are wanted.

RunPreTask returns an UpdateInfo if the file trnasfered undergone modifications during the PreTasks (compression, renaming, ...). RunPreTask returns an error if the transfer cannot proceed. RunPreTask can return a nil UpdateInfo and a nil error if the file transfered has been left unchanged.

type Request

type Request struct {
	ID       int64
	Filepath string
	FileSize int64
	Rule     string
	IsRecv   bool // TODO: Rename to isPull
	IsMD5    bool
	Block    uint32
	Rank     uint32
	Code     rune   // Should be ignored
	Limit    uint32 // FIXME: Should be moved to requestInfo
	Infos    string // FIXME: 1.0.0 rename to UserContent
}

Request is a structure reprensenting informations about a transfer request.

type RequestHandler

type RequestHandler interface {
	ValidRequest(*Request) (TransferHandler, error)
}

A RequestHandler is the interface that handle the validation of received transfer request.

ValidRequest returns a TransferHandler which will be called during the actual file transfer. ValidRequest returns an error if the transfer request cannot be proceded or is refused. ValidRequest should not returns a nil TransferHandler with a nil error.

type RequestInfo

type RequestInfo struct {
	OriginalSize int64 `json:"ORIGINALSIZE"`
	FollowID     int64 `json:"follow"`
}

RequestInfo is a struct reprensenting updated informations about a transfer. DEPRECATED

type Server

type Server struct {
	// Login is the hostid sent by the server to the client for authentication
	Login string
	// Password is the secret sent by the server to the client for authentication
	Password []byte
	// Config is the R66 configuration used by the server
	Conf *Config
	// Handler defines how the server will handle the client requests
	Handler AuthentHandler
	// Logger allows to monitor the server processes
	Logger *log.Logger
	// contains filtered or unexported fields
}

Server defines parameters for running an R66 server. The zero value for Server is NOT a valid configuration. You should at least fill Login and Password.

func (*Server) IsClosed

func (s *Server) IsClosed() bool

IsClosed returns true once the server has been closed.

func (*Server) IsListening

func (s *Server) IsListening() bool

IsListening returns true while the server is listening.

func (*Server) IsStarting

func (s *Server) IsStarting() bool

IsStarting returns true if the server is starting and not listening yet.

func (*Server) ListenAndServe

func (s *Server) ListenAndServe(ip string) error

ListenAndServe listens on the TCP network address ip and then calls Serve to handle requests on incoming connections. ListenAndServe always returns a non-nil error. After Shutdown or Close, the returned error is ErrServerClosed. TODO ErrServerClosed ???

func (*Server) ListenAndServeTLS

func (s *Server) ListenAndServeTLS(ip string, conf *tls.Config) error

ListenAndServeTLS listens on the TCP network address ip using the provided TLS connection and then calls Serve to handle requests on incoming connections. ListenAndServeTLS always returns a non-nil error. After Shutdown or Close, the returned error is ErrServerClosed. TODO ErrServerClosed ???

func (*Server) Serve

func (s *Server) Serve(l net.Listener) error

Serve accepts incoming connections on the Listener l, creating a new service goroutine for each. The service goroutines read requests and then call srv.Handler to reply to them. Serve always returns a non-nil error and closes l. After Shutdown or Close, the returned error is ErrServerClosed. TODO ErrServerClosed ???

func (*Server) Shutdown

func (s *Server) Shutdown(ctx context.Context) error

Shutdown gracefully shuts down the server without interrupting any active connections. Shutdown works by first closing all open listeners, then closing all idle connections, and then waiting indefinitely for connections to return to idle and then shut down. If the provided context expires before the shutdown is complete, Shutdown returns the context's error, otherwise it returns any error returned from closing the Server's underlying Listener(s).

type Session

type Session struct {
	// contains filtered or unexported fields
}

Session is an R66 Session.

It is advised to manualy close the session before closing the connection.

Sessions should be used by the same goroutine

func (*Session) Authent

func (ses *Session) Authent(login string, password []byte, conf *Config) (auth *Authent, err error)

Authent sends the given authentication to the remote server and return an authentified session if the authent process complete successfuly

func (*Session) BlockRequest

func (ses *Session) BlockRequest(adminPassword []byte, block bool) (err error)

BlockRequest request the blocking of new transfer requests on the server.

func (*Session) Cancel

func (ses *Session) Cancel() error

Cancel sends the server a message to cancel the transfer (stop with no resume).

Cancel returns an error if the session has no transfer is currently running or if the operation fails.

func (*Session) Close

func (ses *Session) Close()

Close terminates the session and removes it from the connection's sessions list

func (*Session) EndRequest

func (ses *Session) EndRequest() (err error)

EndRequest finishes the transfer.

Recv returns an error if the session cannot end the transfer or if the operation fails.

func (*Session) GetBandwidth

func (ses *Session) GetBandwidth() (res *Bandwidth, err error)

GetBandwidth request the current bandwitdh limitations of the server.

func (*Session) GetFileInfo

func (ses *Session) GetFileInfo(pattern, rule string, request byte) (info []FileInfo, err error)

GetFileInfo requests the server for informations about the provided file pattern and rule.

GetFileInfo returns a list of FileInfo. If InfoFile or InfoFileDetails are provided as request info will contain 1 entry. If InfoFile or InfoList are provided only the the Name field of FileInfo will be fulfield.

GetFileInfo returns an error if the server retruns an error, or if a connection error occurs. Deprecated 1.0.0 remove use GetFileInfoV2 instead

func (*Session) GetFileInfoV2

func (ses *Session) GetFileInfoV2(pattern, rule string, request infoRequest) (info []FileInfo, err error)

GetFileInfoV2 requests the server for informations about the provided file pattern and rule.

GetFileInfoV2 returns a list of FileInfo. If InfoFile or InfoFileDetails are provided as request info will contain 1 entry. If InfoFile or InfoList are provided only the the Name field of FileInfo will be fulfield.

GetFileInfoV2 returns an error if the server retruns an error, or if a connection error occurs.

func (*Session) GetTransferInfo

func (ses *Session) GetTransferInfo(id int64) (info *TransferInfo, err error)

GetTransferInfo requests the server for informations about the provided transfer.

GetTransferInfo returns a TransferInfo. GetFileInfo returns an error if the server retruns an error, or if a connection error occurs.

func (*Session) Recv

func (ses *Session) Recv(stream io.WriterAt) (eot *EndTransfer, err error)

Recv writes the content sent by the server in the provided WriterAt.

Recv returns the EndTransfer information provided by the server. Recv returns an error if the session cannot write the file or if the operation fails.

func (*Session) RecvUpdateRequest

func (ses *Session) RecvUpdateRequest() (res *UpdateInfo, err error)

RecvUpdateRequest waits for an modification of the transmited file from the server.

Updates return the new information (name, size, ...) of the file transfered. Update returns an error if the session cannot sends the update or if the operation fails.

This method must only be called for a pull transfer (Recv, RecvMD5, ...). You should always call this function after Request and before Recv.

func (*Session) Request

func (ses *Session) Request(req *Request) (res *Request, err error)

Request sends the request provided to the server then wait and valid the server response.

Request returns a Request containing the information of the request. Request returns an error if the session cannot sends the request or if the operation failed.

func (*Session) Send

func (ses *Session) Send(stream io.ReaderAt, getHash func() ([]byte, error)) (eot *EndTransfer, err error)

Send transmits the content of the provided ReaderAt to the server. Send finish the file transfer by sending the hash returned by the getHash function.

Send returns the EndTransfer information sent by the server. Send returns an error if the session cannot sends the file or if the operation fails.

getHash must returns the hash of the complete file even in the case of a resumed transfered where the file is partialy transmited.

func (*Session) SendError

func (ses *Session) SendError(err error) error

SendError creates an ErrorPacket from the provided error and sends it to the connection returns nothing network error are checked at reading

func (*Session) SendUpdateRequest

func (ses *Session) SendUpdateRequest(infos *UpdateInfo) (err error)

SendUpdateRequest sends the modification of the transmited file to the server.

Update returns an error if the session cannot sends the update or if the operation fails.

This method must only be called for a push transfer (Send, SendMD5, ...). If the transfered file was not changed between the request and the transfer this function is optional.

func (*Session) SetBandwidth

func (ses *Session) SetBandwidth(src *Bandwidth) (err error)

SetBandwidth request a modification of the current bandwitdh limitations of the server.

func (*Session) Shutdown

func (ses *Session) Shutdown(adminPassword []byte, restart bool) (err error)

Shutdown request the extinction of the server.

func (*Session) Stop

func (ses *Session) Stop() error

Stop sends the server a message to stop the transfer.

Stop returns an error if the session has no transfer is currently running or if the operation fails.

func (*Session) Test

func (ses *Session) Test(message string, bounce int) (err error)

Test sends a ping message to the server. The message is send back and forth bounce time.

type SessionHandler

type SessionHandler interface {
	RequestHandler
}

SessionHandler is an interface responsible to handle r66 request (transfer, information, admin, ...)

type SystemData

type SystemData struct {
	// FollowID is an ID that can be transmited with the file along a chain of
	// transfers.
	FollowID int `json:"follow,omitempty"`
}

SystemData is a structure representing informations to caracterise transfer.

type TransferData

type TransferData struct {
	// UserContent is additional information provided on a transfer basis.
	UserContent string
	// SystemData are additional information to caracterized the transfer.
	SystemData SystemData
}

TransferData is a structure representing additional information about a transfer (not directly related to the file transfered).

type TransferHandler

type TransferHandler interface {
	UpdateTransferInfo(*UpdateInfo) error
	GetStream() (utils.ReadWriterAt, error)
	GetHash() ([]byte, error)
	ValidEndTransfer(*EndTransfer) error
	ValidEndRequest() error
}

TransferHandler is the interface that handle the operations required during a file transfer.

UpdateTransferInfo is called to update transfer informations after the request has been validated but before the any data has been transmited. UpdateTransferInfo returns an error if the information update is refused.

GetStream returns a ReadWriterAt to read or write the file transfered. GetStream returns an error if a filesystem error occurs. GetStreal should not returns a nil ReadWriterAt with a nil error.

ValidEndTransfer is called when the file has been completly transfered. ValidEndTransfer returns an error if the file transfered is invalid (hash, size, fylesystem, ...)

ValidEndRequest is called when at the end of the Transfer one all operations are done.

type TransferInfo

type TransferInfo struct {
	// ID is the unique identifier of the transfer.
	ID int64
	// Client is the login used by the client of the transfer.
	Client string // FIXME: Change name for ClientLogin
	// Server is the login used by the server of the transfer.
	Server string // FIXME: Change name for ServerLogin
	// File is the path of the file which is transfered.
	File string // FIXME: Change name for Filepath
	// Rule is the name of the rule used for the transfer.
	Rule string
	// IsRecv is true if the file is transfered from the server to the client.
	// IsRecv is false if the file is pushed from the cliend to the server.
	IsRecv bool
	// IsMd5 is true if each block of the transfered file is transfered with its control hash.
	IsMd5 bool
	// IsThrough is true if the transfered file is supposed to be directly retransfered.
	// This mode is not enforced by this library.
	IsThrough bool
	// RuleMode is the transfer mode used for the transfer.
	// Deprecated 1.0.0 will be removed
	RuleMode uint32
	// Info is the additional information provided by the user for the
	// transfer.
	// Deprecated 1.0.0 use UserContent instead
	Info string
	// UserContent is the additional information provided by the user for the
	// transfer.
	UserContent string
	// BlockSize is the size of the block (in o) used for the transfer.
	BlockSize uint32
	// Rank is the number of block successfully transferd
	Rank uint32
	// Step is the
	Step   globalStep // GlobalStep
	Status rune       // Step or LastGlobalStep
	// Start is the date/time at which the transfer started.
	Start time.Time
	// Stoped is the date/time at which the transfer stopped.
	Stop time.Time
}

TransferInfo is a structure representing information on a transfer performed by the server.

type UpdateInfo

type UpdateInfo struct {
	// Filename is the new path of the transfered file.
	Filename string // FIXME: rename for filepath
	// FileSize is the new size of the transferd file.
	FileSize int64
	// FileInfo are additional information about the transfer.
	FileInfo *TransferData
}

UpdateInfo is a struct reprensenting updated informations about a transfer.

type Version

type Version struct {
	Major uint
	Minor uint
	Patch uint
}

Version is a representation of a protocol version

func CurrentVersion

func CurrentVersion() Version

CurrentVersion returns the implemented version of the protocol

func ParseVersion

func ParseVersion(s string) (Version, error)

ParseVersion the provided string in a Version struct

func SupportedVersion

func SupportedVersion() Version

SupportedVersion returns the minimum version of the protocol compatible with this library

func (Version) IsGreater

func (v Version) IsGreater(other Version) bool

IsGreater returns true if the provided Version is srictly inferior to the comparee

func (Version) ToString

func (v Version) ToString() string

ToString returns a string representation of the version

Directories

Path Synopsis
cmd

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL