2
2
mirror of https://github.com/octoleo/restic.git synced 2024-12-04 19:03:46 +00:00
restic/vendor/github.com/pkg/sftp/request-server.go

231 lines
5.8 KiB
Go
Raw Normal View History

2017-07-23 12:24:45 +00:00
package sftp
import (
"encoding"
"io"
"path"
2017-07-23 12:24:45 +00:00
"path/filepath"
"strconv"
"sync"
"syscall"
"github.com/pkg/errors"
)
var maxTxPacket uint32 = 1 << 15
type handleHandler func(string) string
// Handlers contains the 4 SFTP server request handlers.
type Handlers struct {
FileGet FileReader
FilePut FileWriter
FileCmd FileCmder
2017-09-13 12:09:48 +00:00
FileList FileLister
2017-07-23 12:24:45 +00:00
}
// RequestServer abstracts the sftp protocol with an http request-like protocol
type RequestServer struct {
*serverConn
Handlers Handlers
2017-09-13 12:09:48 +00:00
pktMgr *packetManager
openRequests map[string]*Request
2017-07-23 12:24:45 +00:00
openRequestLock sync.RWMutex
handleCount int
}
// NewRequestServer creates/allocates/returns new RequestServer.
// Normally there there will be one server per user-session.
func NewRequestServer(rwc io.ReadWriteCloser, h Handlers) *RequestServer {
svrConn := &serverConn{
conn: conn{
Reader: rwc,
WriteCloser: rwc,
},
}
return &RequestServer{
serverConn: svrConn,
Handlers: h,
pktMgr: newPktMgr(svrConn),
openRequests: make(map[string]*Request),
2017-07-23 12:24:45 +00:00
}
}
// New Open packet/Request
2017-09-13 12:09:48 +00:00
func (rs *RequestServer) nextRequest(r *Request) string {
2017-07-23 12:24:45 +00:00
rs.openRequestLock.Lock()
defer rs.openRequestLock.Unlock()
rs.handleCount++
handle := strconv.Itoa(rs.handleCount)
rs.openRequests[handle] = r
2017-07-23 12:24:45 +00:00
return handle
}
// Returns Request from openRequests, bool is false if it is missing
// If the method is different, save/return a new Request w/ that Method.
//
// The Requests in openRequests work essentially as open file descriptors that
// you can do different things with. What you are doing with it are denoted by
// the first packet of that type (read/write/etc). We create a new Request when
// it changes to set the request.Method attribute in a thread safe way.
func (rs *RequestServer) getRequest(handle, method string) (*Request, bool) {
2017-07-23 12:24:45 +00:00
rs.openRequestLock.RLock()
r, ok := rs.openRequests[handle]
rs.openRequestLock.RUnlock()
if !ok || r.Method == method {
return r, ok
}
// if we make it here we need to replace the request
rs.openRequestLock.Lock()
defer rs.openRequestLock.Unlock()
r, ok = rs.openRequests[handle]
if !ok || r.Method == method { // re-check needed b/c lock race
return r, ok
}
r = &Request{Method: method, Filepath: r.Filepath, state: r.state}
rs.openRequests[handle] = r
return r, ok
2017-07-23 12:24:45 +00:00
}
func (rs *RequestServer) closeRequest(handle string) error {
2017-07-23 12:24:45 +00:00
rs.openRequestLock.Lock()
defer rs.openRequestLock.Unlock()
if r, ok := rs.openRequests[handle]; ok {
delete(rs.openRequests, handle)
return r.close()
2017-07-23 12:24:45 +00:00
}
return syscall.EBADF
2017-07-23 12:24:45 +00:00
}
// Close the read/write/closer to trigger exiting the main server loop
func (rs *RequestServer) Close() error { return rs.conn.Close() }
// Serve requests for user session
func (rs *RequestServer) Serve() error {
var wg sync.WaitGroup
runWorker := func(ch requestChan) {
wg.Add(1)
go func() {
defer wg.Done()
if err := rs.packetWorker(ch); err != nil {
rs.conn.Close() // shuts down recvPacket
}
}()
}
pktChan := rs.pktMgr.workerChan(runWorker)
var err error
var pkt requestPacket
var pktType uint8
var pktBytes []byte
for {
pktType, pktBytes, err = rs.recvPacket()
if err != nil {
break
}
pkt, err = makePacket(rxPacket{fxp(pktType), pktBytes})
if err != nil {
debug("makePacket err: %v", err)
rs.conn.Close() // shuts down recvPacket
break
}
pktChan <- pkt
}
close(pktChan) // shuts down sftpServerWorkers
wg.Wait() // wait for all workers to exit
return err
}
func (rs *RequestServer) packetWorker(pktChan chan requestPacket) error {
for pkt := range pktChan {
var rpkt responsePacket
switch pkt := pkt.(type) {
case *sshFxInitPacket:
rpkt = sshFxVersionPacket{sftpProtocolVersion, nil}
case *sshFxpClosePacket:
handle := pkt.getHandle()
rpkt = statusFromError(pkt, rs.closeRequest(handle))
2017-07-23 12:24:45 +00:00
case *sshFxpRealpathPacket:
2017-09-13 12:09:48 +00:00
rpkt = cleanPacketPath(pkt)
case *sshFxpOpendirPacket:
request := requestFromPacket(pkt)
handle := rs.nextRequest(request)
2017-07-23 12:24:45 +00:00
rpkt = sshFxpHandlePacket{pkt.id(), handle}
case *sshFxpOpenPacket:
request := requestFromPacket(pkt)
handle := rs.nextRequest(request)
rpkt = sshFxpHandlePacket{pkt.id(), handle}
if pkt.hasPflags(ssh_FXF_CREAT) {
if p := request.call(rs.Handlers, pkt); !isOk(p) {
rpkt = p // if error in write, return it
}
2017-07-23 12:24:45 +00:00
}
case hasHandle:
handle := pkt.getHandle()
request, ok := rs.getRequest(handle, requestMethod(pkt))
if !ok {
2017-07-23 12:24:45 +00:00
rpkt = statusFromError(pkt, syscall.EBADF)
} else {
2017-09-13 12:09:48 +00:00
rpkt = request.call(rs.Handlers, pkt)
2017-07-23 12:24:45 +00:00
}
case hasPath:
request := requestFromPacket(pkt)
2017-09-13 12:09:48 +00:00
rpkt = request.call(rs.Handlers, pkt)
2017-07-23 12:24:45 +00:00
default:
return errors.Errorf("unexpected packet type %T", pkt)
}
err := rs.sendPacket(rpkt)
if err != nil {
return err
}
}
return nil
}
// True is responsePacket is an OK status packet
func isOk(rpkt responsePacket) bool {
p, ok := rpkt.(sshFxpStatusPacket)
return ok && p.StatusError.Code == ssh_FX_OK
}
// clean and return name packet for file
2017-09-13 12:09:48 +00:00
func cleanPacketPath(pkt *sshFxpRealpathPacket) responsePacket {
path := cleanPath(pkt.getPath())
2017-07-23 12:24:45 +00:00
return &sshFxpNamePacket{
ID: pkt.id(),
NameAttrs: []sshFxpNameAttr{{
2017-09-13 12:09:48 +00:00
Name: path,
LongName: path,
2017-07-23 12:24:45 +00:00
Attrs: emptyFileStat,
}},
}
}
// Makes sure we have a clean POSIX (/) absolute path to work with
func cleanPath(p string) string {
p = filepath.ToSlash(p)
if !filepath.IsAbs(p) {
p = "/" + p
2017-07-23 12:24:45 +00:00
}
return path.Clean(p)
2017-07-23 12:24:45 +00:00
}
// Wrap underlying connection methods to use packetManager
func (rs *RequestServer) sendPacket(m encoding.BinaryMarshaler) error {
if pkt, ok := m.(responsePacket); ok {
rs.pktMgr.readyPacket(pkt)
} else {
return errors.Errorf("unexpected packet type %T", m)
}
return nil
}
func (rs *RequestServer) sendError(p ider, err error) error {
return rs.sendPacket(statusFromError(p, err))
}