linsk/share/smb.go

93 lines
2.6 KiB
Go
Raw Normal View History

2023-09-02 20:03:44 +01:00
// Linsk - A utility to access Linux-native file systems on non-Linux operating systems.
// Copyright (c) 2023 The Linsk Authors.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
2023-08-31 16:19:03 +01:00
package share
import (
"context"
"fmt"
"net"
"strings"
2023-09-02 11:28:23 +01:00
"github.com/AlexSSD7/linsk/osspecifics"
2023-08-31 16:19:03 +01:00
"github.com/AlexSSD7/linsk/vm"
"github.com/pkg/errors"
)
const smbPort = 445
type SMBBackend struct {
listenIP net.IP
sharePort *uint16
}
func NewSMBBackend(uc *UserConfiguration) (Backend, *VMShareOptions, error) {
var ports []vm.PortForwardingRule
var sharePortPtr *uint16
if !uc.smbExtMode {
sharePort, err := getNetworkSharePort(0)
if err != nil {
return nil, nil, errors.Wrap(err, "get network share port")
}
sharePortPtr = &sharePort
ports = append(ports, vm.PortForwardingRule{
HostIP: uc.listenIP,
HostPort: sharePort,
VMPort: smbPort,
})
}
return &SMBBackend{
listenIP: uc.listenIP,
sharePort: sharePortPtr,
}, &VMShareOptions{
Ports: ports,
EnableTap: uc.smbExtMode,
}, nil
}
func (b *SMBBackend) Apply(ctx context.Context, sharePWD string, vc *VMShareContext) (string, error) {
if b.sharePort != nil && vc.NetTapCtx != nil {
return "", fmt.Errorf("conflict: configured to use a forwarded port but a net tap configuration was detected")
}
if b.sharePort == nil && vc.NetTapCtx == nil {
return "", fmt.Errorf("no net tap configuration found")
}
err := vc.FileManager.StartSMB(sharePWD)
if err != nil {
return "", errors.Wrap(err, "start smb server")
}
var shareURL string
2023-09-02 11:28:23 +01:00
switch {
case b.sharePort != nil:
2023-09-01 14:41:35 +01:00
shareURL = "smb://" + net.JoinHostPort(b.listenIP.String(), fmt.Sprint(*b.sharePort)) + "/linsk"
2023-09-02 11:28:23 +01:00
case vc.NetTapCtx != nil:
if osspecifics.IsWindows() {
2023-08-31 16:19:03 +01:00
shareURL = `\\` + strings.ReplaceAll(vc.NetTapCtx.Net.GuestIP.String(), ":", "-") + ".ipv6-literal.net" + `\linsk`
} else {
2023-09-01 14:41:35 +01:00
shareURL = "smb://" + net.JoinHostPort(vc.NetTapCtx.Net.GuestIP.String(), fmt.Sprint(smbPort)) + "/linsk"
2023-08-31 16:19:03 +01:00
}
2023-09-02 11:28:23 +01:00
default:
2023-08-31 16:19:03 +01:00
return "", fmt.Errorf("no port forwarding and net tap configured")
}
return shareURL, nil
}