File: sftp.go

package info (click to toggle)
incus 6.0.4-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, trixie
  • size: 23,864 kB
  • sloc: sh: 16,015; ansic: 3,121; python: 456; makefile: 321; ruby: 51; sql: 50; lisp: 6
file content (74 lines) | stat: -rw-r--r-- 1,386 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
package main

import (
	"fmt"
	"net/http"

	"github.com/pkg/sftp"

	"github.com/lxc/incus/v6/internal/server/response"
)

var sftpCmd = APIEndpoint{
	Name: "sftp",
	Path: "sftp",

	Get: APIEndpointAction{Handler: sftpHandler},
}

func sftpHandler(d *Daemon, r *http.Request) response.Response {
	return &sftpServe{d, r}
}

type sftpServe struct {
	d *Daemon
	r *http.Request
}

func (r *sftpServe) String() string {
	return "sftp handler"
}

// Code returns the HTTP code.
func (r *sftpServe) Code() int {
	return http.StatusOK
}

func (r *sftpServe) Render(w http.ResponseWriter) error {
	// Upgrade to sftp.
	if r.r.Header.Get("Upgrade") != "sftp" {
		http.Error(w, "Missing or invalid upgrade header", http.StatusBadRequest)
		return nil
	}

	hijacker, ok := w.(http.Hijacker)
	if !ok {
		http.Error(w, "Webserver doesn't support hijacking", http.StatusInternalServerError)

		return nil
	}

	conn, _, err := hijacker.Hijack()
	if err != nil {
		http.Error(w, fmt.Errorf("Failed to hijack connection: %w", err).Error(), http.StatusInternalServerError)

		return nil
	}

	defer func() { _ = conn.Close() }()

	err = response.Upgrade(conn, "sftp")
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)

		return nil
	}

	// Start sftp server.
	server, err := sftp.NewServer(conn, sftp.WithAllocator())
	if err != nil {
		return nil
	}

	return server.Serve()
}