Skip to content

Commit

Permalink
Merge branch 'development' into github/darwin-macos
Browse files Browse the repository at this point in the history
  • Loading branch information
ikr4-m committed Sep 13, 2024
2 parents 89e38b9 + 3ab8650 commit 7d3ac05
Show file tree
Hide file tree
Showing 17 changed files with 268 additions and 65 deletions.
8 changes: 4 additions & 4 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,8 @@ build-client: restore
build-tunnel: restore
go build -C ./cmd/mdrop-tunnel-tools -ldflags="-linkmode external -extldflags -static -w -s" -o "../../mdrop-tunnel"

build-client-darwin: restore
go build -C ./cmd/mdrop-client -ldflags="-extldflags -static -w -s" -o "../../mdrop-darwin"
build-client-general: restore
go build -C ./cmd/mdrop-client -ldflags="-extldflags -static -w -s" -o "../../mdrop"

build-tunnel-darwin: restore
go build -C ./cmd/mdrop-tunnel-tools -ldflags="-linkmode external -extldflags -static -w -s" -o "../../mdrop-tunnel-darwin"
build-tunnel-general: restore
go build -C ./cmd/mdrop-tunnel-tools -ldflags="-extldflags -static -w -s" -o "../../mdrop-tunnel"
78 changes: 74 additions & 4 deletions cmd/mdrop-client/auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,20 +6,26 @@ import (
"flag"
"fmt"
"os"
"os/signal"
"strconv"
"strings"
"syscall"

"github.com/mplus-oss/mdrop/internal"
"golang.org/x/term"
)

func AuthCommand(args []string) {
errChan := make(chan error, 0)

flag := flag.NewFlagSet("mdrop auth", flag.ExitOnError)
var (
defaultInstance = flag.String("set-default", "", "Set default tunnel instance.")
list = flag.Bool("list", false, "Get list of tunnel instance")
help = flag.Bool("help", false, "Print this message")
defaultInstance = flag.String("set-default", "", "Set default tunnel instance.")
list = flag.Bool("list", false, "Get list of tunnel instance")
help = flag.Bool("help", false, "Print this message")
deleteInstance = flag.String("delete", "", "Delete tunnel instance")
raw = flag.Bool("raw", false, "Print raw output of .mdrop file")
replace = flag.Bool("replace", false, "Replace .mdrop file with new config")
)
flag.Parse(args)

Expand All @@ -39,6 +45,11 @@ func AuthCommand(args []string) {
os.Exit(0)
}

if *deleteInstance != "" {
deleteTunnelInstance(*deleteInstance)
os.Exit(0)
}

// Set prompt
config, err := authPrompt()
if err != nil {
Expand Down Expand Up @@ -68,7 +79,16 @@ func AuthCommand(args []string) {
}

// Write config file
err = config.WriteConfig()
if *raw {
confString, err := config.WriteRawConfig(*replace)
if err != nil {
internal.PrintErrorWithExit("authWriteRawConfig", err, 1)
}
fmt.Println("\nCopy this secret below and paste it to ~/.mdrop")
fmt.Println(confString)
os.Exit(0)
}
err = config.WriteConfig(*replace)
if err != nil {
internal.PrintErrorWithExit("authWriteConfig", err, 1)
}
Expand Down Expand Up @@ -102,8 +122,50 @@ func getTunnelInstance() {
}
}

func deleteTunnelInstance(instanceName string) {
var authConfig internal.ConfigSourceAuth
err := authConfig.ParseConfig(&authConfig)
if err != nil {
internal.PrintErrorWithExit("authParseConfig", err, 1)
}

instanceIndex := -1
for i, instance := range authConfig.ListConfiguration {
if instance.Name == instanceName {
instanceIndex = i
break
}
}
if instanceIndex < 0 {
internal.PrintErrorWithExit("authInstanceNotFound", errors.New("Instance not found"), 1)
}
authConfig.ListConfiguration = append(
authConfig.ListConfiguration[:instanceIndex],
authConfig.ListConfiguration[instanceIndex+1:]...,
)
err = authConfig.WriteConfig()
if err != nil {
internal.PrintErrorWithExit("authParseConfig", err, 1)
}
}

func authPrompt() (config internal.ConfigFile, err error) {
reader := bufio.NewReader(os.Stdin)
stdin := int(syscall.Stdin)
oldState, err := term.GetState(stdin)
if err != nil {
return internal.ConfigFile{}, err
}
defer term.Restore(stdin, oldState)

sigch := make(chan os.Signal, 1)
signal.Notify(sigch, os.Interrupt)
go func() {
for _ = range sigch {
term.Restore(stdin, oldState)
os.Exit(1)
}
}()

fmt.Print("Instance Name: ")
instanceName, err := reader.ReadString('\n')
Expand Down Expand Up @@ -140,11 +202,19 @@ func authPrompt() (config internal.ConfigFile, err error) {
}
proxy = strings.Replace(proxy, "\n", "", -1)

fmt.Print("Private Key String [Set blank if none]: ")
privateKeyByte, err := term.ReadPassword(stdin)
if err != nil {
return internal.ConfigFile{}, err
}
privateKeyString := strings.Replace(string(privateKeyByte), "\n", "", -1)

config = internal.ConfigFile{
Name: instanceName,
Host: hostname,
Port: portInt,
Proxy: proxy,
Key: privateKeyString,
}
return config, nil
}
14 changes: 9 additions & 5 deletions cmd/mdrop-client/get_command.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,9 @@ func GetCommand(args []string) {

flag := flag.NewFlagSet("mdrop get", flag.ExitOnError)
var (
help = flag.Bool("help", false, "Print this message")
fileNameOpt = flag.String("output", "", "Set filename output")
localPort = flag.Int("local-port", 6000, "Specified sender port remoted on local")
help = flag.Bool("help", false, "Print this message")
fileNameOpt = flag.String("output", "", "Set file or directory output")
localPort = flag.Int("local-port", 6000, "Specified sender port remoted on local")
)
flag.Parse(args)

Expand All @@ -42,6 +42,9 @@ func GetCommand(args []string) {
if err != nil {
internal.PrintErrorWithExit("getParseConfigError", err, 1)
}
if len(authFile.ListConfiguration) == 0 {
internal.PrintErrorWithExit("getConfigFileEmpty", errors.New("Config file empty. Please log in using `mdrop auth` before executing this command."), 1)
}
config := authFile.ListConfiguration[authFile.Default]
if sender.Host != config.Host {
internal.PrintErrorWithExit("getHostNotMatch", errors.New("Host not match"), 1)
Expand All @@ -68,11 +71,12 @@ func GetCommand(args []string) {
GetTcpReadyConnect(*localPort)

// Downloading file
isSingleFile := len(sender.Files) < 2
for _, uuid := range sender.Files {
// No error checking needed.
fileName := GetPrompt(*localPort, uuid, *fileNameOpt)
fileName := GetPrompt(*localPort, uuid, *fileNameOpt, isSingleFile)
checksum := GetChecksum(*localPort, uuid)
filePath := GetDownload(*localPort, uuid, fileName)
filePath := GetDownload(*localPort, uuid, fileName, *fileNameOpt, isSingleFile)

// Check checksum
fmt.Println("Checking checksum...")
Expand Down
23 changes: 15 additions & 8 deletions cmd/mdrop-client/get_download.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ func GetChecksum(localPort int, uuid string) string {
return string(checksumBytes)
}

func GetPrompt(localPort int, uuid string, fileNameOpt string) (filePath string) {
func GetPrompt(localPort int, uuid string, fileNameOpt string, isSingleFile bool) (filePath string) {
reader := bufio.NewReader(os.Stdin)
client := http.Client{}

Expand Down Expand Up @@ -72,11 +72,14 @@ func GetPrompt(localPort int, uuid string, fileNameOpt string) (filePath string)
if err != nil {
internal.PrintErrorWithExit("sendFileWorkDir", err, 1)
}
if fileNameOpt != "" {
fmt.Println("Changing filename to", fileNameOpt)
fileName = fileNameOpt
// Check if it's single file
if isSingleFile {
if fileNameOpt != "" {
fmt.Println("Changing filename to", fileNameOpt)
fileName = fileNameOpt
}
}
if fileStatus, _ := os.Stat(filePath+"/"+fileName); fileStatus != nil {
if fileStatus, _ := os.Stat(filePath + "/" + fileName); fileStatus != nil {
fmt.Print("There's duplicate file. Action? [(R)eplace/R(e)name/(C)ancel] [Default: R] -> ")
prompt, err := reader.ReadString('\n')
if err != nil {
Expand All @@ -87,7 +90,7 @@ func GetPrompt(localPort int, uuid string, fileNameOpt string) (filePath string)
internal.PrintErrorWithExit("sendPromptCancel", errors.New("Canceled by action"), 0)
}
if strings.ToLower(prompt) == "e" {
fmt.Print("Change filename ["+fileName+"]: ")
fmt.Print("Change filename [" + fileName + "]: ")
prompt, err = reader.ReadString('\n')
if err != nil {
internal.PrintErrorWithExit("sendPromptError", err, 1)
Expand All @@ -103,7 +106,7 @@ func GetPrompt(localPort int, uuid string, fileNameOpt string) (filePath string)
return fileName
}

func GetDownload(localPort int, uuid string, fileName string) string {
func GetDownload(localPort int, uuid string, fileName string, fileNameOpt string, isSingleFile bool) string {
client := http.Client{}

resp, err := client.Post(
Expand All @@ -126,7 +129,11 @@ func GetDownload(localPort int, uuid string, fileName string) string {
if err != nil {
internal.PrintErrorWithExit("sendFileWorkDir", err, 1)
}
filePath += "/"+fileName
if !isSingleFile {
filePath = fileNameOpt
fmt.Println("Changing working directory to", filePath)
}
filePath += "/" + fileName

// Create file
file, err := os.Create(filePath)
Expand Down
10 changes: 9 additions & 1 deletion cmd/mdrop-client/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ import (
"os"
)

const version string = "v0.3.4-alya"

const subCmdHelpMeesage string = `
Subcommand:
auth
Expand All @@ -16,7 +18,10 @@ Subcommand:
Create instance for retriving file from sender
send [options] <file1> [file2] [file...]
subcommand
Send file to reciever instance`
Send file to reciever instance
version
subcommand
mdrop Version`

func main() {
help := flag.Bool("help", false, "Print this message")
Expand All @@ -39,6 +44,9 @@ func main() {
GetCommand(args)
case "send":
SendCommand(args)
case "version":
fmt.Println("Version:", version)
os.Exit(0)
default:
printUsage()
}
Expand Down
9 changes: 6 additions & 3 deletions cmd/mdrop-client/send_command.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,9 @@ func SendCommand(args []string) {
if err != nil {
internal.PrintErrorWithExit("sendParseConfigError", err, 1)
}
if len(authFile.ListConfiguration) == 0 {
internal.PrintErrorWithExit("getConfigFileEmpty", errors.New("Config file empty. Please log in using `mdrop auth` before executing this command."), 1)
}
config := authFile.ListConfiguration[authFile.Default]

// Get Port from Tunnel
Expand Down Expand Up @@ -88,16 +91,16 @@ func SendCommand(args []string) {

// Print token
token, err := TokenTransferJSON{
Host: config.Host,
Host: config.Host,
RemotePort: remotePort,
Files: fileUUID,
Files: fileUUID,
}.GenerateToken()
if err != nil {
errChan <- err
}

fmt.Print("\nPlease copy this token to the receiver.")
fmt.Print("\nToken: "+token+"\n\n")
fmt.Print("\nToken: " + token + "\n\n")

fmt.Println("Spawning webserver...")
err = SendWebserver(*localPort, file, fileUUID)
Expand Down
17 changes: 8 additions & 9 deletions cmd/mdrop-client/send_webserver.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ var senderErrorChan chan error = make(chan error)

func SendWebserver(localPort int, file []string, uuid []string) (err error) {
totalFile = len(file)
server.Addr = ":"+strconv.Itoa(localPort)
server.Addr = ":" + strconv.Itoa(localPort)

for i, _ := range file {
// Check mimetype
Expand All @@ -35,13 +35,13 @@ func SendWebserver(localPort int, file []string, uuid []string) (err error) {
senderErrorChan <- internal.CustomizeError("receiveMimeType", err)
}

http.Handle("/"+uuid[i], http.HandlerFunc(func (w http.ResponseWriter, request *http.Request) {
http.Handle("/"+uuid[i], http.HandlerFunc(func(w http.ResponseWriter, request *http.Request) {
receiveSendWebserver(w, request, file[i], mimeType.String())
}))
http.Handle("/checksum-"+uuid[i], http.HandlerFunc(func (w http.ResponseWriter, request *http.Request) {
http.Handle("/checksum-"+uuid[i], http.HandlerFunc(func(w http.ResponseWriter, request *http.Request) {
checksumSendWebserver(w, request, file[i])
}))
http.Handle("/verify-"+uuid[i], http.HandlerFunc(func (w http.ResponseWriter, request *http.Request) {
http.Handle("/verify-"+uuid[i], http.HandlerFunc(func(w http.ResponseWriter, request *http.Request) {
promptSendWebserver(w, request, file[i], mimeType.String())
}))
}
Expand All @@ -58,14 +58,14 @@ func SendWebserver(localPort int, file []string, uuid []string) (err error) {

err = <-senderErrorChan

shutdownCtx, shutdownRelease := context.WithTimeout(context.Background(), 10*time.Second)
defer shutdownRelease()
shutdownCtx, shutdownRelease := context.WithTimeout(context.Background(), 10*time.Second)
defer shutdownRelease()

fmt.Println("Gracefully shutdown server...")
err = server.Shutdown(shutdownCtx)
if err != nil {
if err != nil {
return err
}
}
return nil
}

Expand Down Expand Up @@ -131,7 +131,6 @@ func receiveSendWebserver(w http.ResponseWriter, request *http.Request, filePath
senderErrorChan <- internal.CustomizeError("receiveOpenFileStat", err)
}


w.Header().Set("Transfer-Encoding", "identity")
w.Header().Set(
"Content-Length",
Expand Down
Loading

0 comments on commit 7d3ac05

Please sign in to comment.