repos / pico

pico services mono repo
git clone https://github.com/picosh/pico.git

pico / pkg / send / pipe
Eric Bower  ·  2026-03-02

pipe.go

 1package pipe
 2
 3import (
 4	"fmt"
 5	"io/fs"
 6	"strconv"
 7	"strings"
 8	"time"
 9
10	"github.com/picosh/pico/pkg/pssh"
11	"github.com/picosh/pico/pkg/send/utils"
12)
13
14func Middleware(writeHandler utils.CopyFromClientHandler, ext string) pssh.SSHServerMiddleware {
15	return func(sshHandler pssh.SSHServerHandler) pssh.SSHServerHandler {
16		return func(session *pssh.SSHServerConnSession) error {
17			_, _, activePty := session.Pty()
18			if activePty {
19				_ = session.Exit(0)
20				err := session.Close()
21				return err
22			}
23
24			cmd := session.Command()
25
26			name := ""
27			if len(cmd) > 0 {
28				name = strings.TrimSpace(cmd[0])
29				if strings.Contains(name, "=") {
30					name = ""
31				}
32			}
33
34			postTime := time.Now()
35
36			if name == "" {
37				name = fmt.Sprintf("%s%s", strconv.Itoa(int(postTime.UnixNano())), ext)
38			}
39			// add a `/` prefix mainly for pgs support
40			if !strings.HasPrefix(name, "/") {
41				name = "/" + name
42			}
43
44			result, err := writeHandler.Write(session, &utils.FileEntry{
45				Filepath: name,
46				Mode:     fs.FileMode(0777),
47				Size:     0,
48				Mtime:    postTime.Unix(),
49				Atime:    postTime.Unix(),
50				Reader:   session,
51			})
52			if err != nil {
53				utils.ErrorHandler(session, err)
54				return err
55			}
56
57			if result != "" {
58				_, err := fmt.Fprintf(session, "%s\r\n", result)
59				if err != nil {
60					utils.ErrorHandler(session, err)
61				}
62				return err
63			}
64
65			return sshHandler(session)
66		}
67	}
68}