github.com/dallinallred/goftp@v0.0.0-20240626003405-61936bc079f1/server/ftpServer.go (about)

     1  package main
     2  
     3  import (
     4  	"bufio"
     5  	"flag"
     6  	"fmt"
     7  	"io"
     8  	"log"
     9  	"net"
    10  	"os"
    11  	"path/filepath"
    12  	"regexp"
    13  	"strings"
    14  )
    15  
    16  var port = flag.Int("p", 2020, "Port number")
    17  
    18  var fsRoots = `^(?i)\/|[A-Z]:`
    19  
    20  func main() {
    21  	flag.Parse()
    22  	fmt.Printf("Server running on port %d\n", *port)
    23  	connString := fmt.Sprintf("localhost:%d", *port)
    24  	listener, err := net.Listen("tcp", connString)
    25  	if err != nil {
    26  		log.Fatal(err)
    27  	}
    28  	for {
    29  		conn, err := listener.Accept()
    30  		fmt.Printf("Connection established with %s\n", conn.RemoteAddr())
    31  		if err != nil {
    32  			log.Print(err)
    33  			continue
    34  		}
    35  		sessionDir, err := os.Getwd()
    36  		if err != nil {
    37  			log.Fatal(err)
    38  		}
    39  		go handleConn(conn, sessionDir)
    40  	}
    41  }
    42  
    43  func handleConn(c net.Conn, sessionDir string) {
    44  	defer c.Close()
    45  	reader := bufio.NewReader(c)
    46  	for {
    47  		command, err := reader.ReadString('\n')
    48  		if err != nil {
    49  			_, err = io.WriteString(c, err.Error()+"\n")
    50  		}
    51  		command = strings.Replace(command, "\n", "", -1)
    52  
    53  		args, err := reader.ReadString('\n')
    54  		if err != nil {
    55  			_, err = io.WriteString(c, err.Error()+"\n")
    56  		}
    57  		args = strings.Replace(args, "\n", "", -1)
    58  
    59  		if command == "" {
    60  			break
    61  		}
    62  		fmt.Printf("%s -- Command: %s %s\n", c.RemoteAddr(), command, args)
    63  		switch command {
    64  		case "pwd":
    65  			_, err = io.WriteString(c, sessionDir+"\n")
    66  
    67  		case "cd":
    68  			if len(args) > 0 {
    69  				proposedPath := args
    70  				root, err := regexp.Match(fsRoots, []byte(args))
    71  				if err != nil {
    72  					_, err = io.WriteString(c, sessionDir+"\n")
    73  					return
    74  				}
    75  				if !root {
    76  					pathSegments := []string{sessionDir, proposedPath}
    77  					proposedPath = filepath.Join(pathSegments...)
    78  					proposedPath, _ = filepath.Abs(proposedPath)
    79  				}
    80  				_, err = os.Stat(proposedPath)
    81  				if err != nil {
    82  					_, err = io.WriteString(c, err.Error()+"\n")
    83  				} else {
    84  					sessionDir = proposedPath
    85  					_, err = io.WriteString(c, "\n")
    86  				}
    87  				fmt.Println(sessionDir)
    88  			}
    89  
    90  		case "ls":
    91  			dir := sessionDir
    92  			if err != nil {
    93  				_, err = io.WriteString(c, err.Error()+"\n")
    94  			}
    95  			if len(args) > 0 {
    96  				dir = args
    97  			}
    98  			dirContents, err := os.ReadDir(dir)
    99  			if err != nil {
   100  				_, err = io.WriteString(c, err.Error()+"\n")
   101  			}
   102  			strContents := []string{}
   103  			for _, entry := range dirContents {
   104  				strContents = append(strContents, fmt.Sprint(entry))
   105  			}
   106  			response := strings.Join(strContents, " ; ")
   107  			_, err = io.WriteString(c, response+"\n")
   108  
   109  		case "get":
   110  			if len(args) == 0 {
   111  				continue
   112  			}
   113  			file, err := os.Open(args)
   114  			if err != nil {
   115  				_, err = io.WriteString(c, err.Error()+"\n")
   116  			}
   117  			n, err := io.Copy(c, file)
   118  			file.Close()
   119  			fmt.Println(n, "bytes sent")
   120  			if err != nil {
   121  				_, err = io.WriteString(c, err.Error()+"\n")
   122  			}
   123  		case "put":
   124  			if len(args) == 0 {
   125  				continue
   126  			}
   127  			file, err := os.Create(args)
   128  			if err != nil {
   129  				_, err = io.WriteString(c, err.Error()+"\n")
   130  			}
   131  			var currentByte int64 = 0
   132  			totalBytesReceived := 0
   133  			bufferSize := 64
   134  			buffer := make([]byte, bufferSize)
   135  			for {
   136  				n, err := c.Read(buffer)
   137  				_, err = file.WriteAt(buffer[:n], currentByte)
   138  				totalBytesReceived += n
   139  				if err == io.EOF || n < bufferSize {
   140  					break
   141  				}
   142  				currentByte += int64(n)
   143  			}
   144  			file.Close()
   145  			fmt.Printf("%d bytes received by server\n", totalBytesReceived)
   146  			_, err = io.WriteString(c, fmt.Sprintf("%d bytes received by server\n", totalBytesReceived))
   147  		}
   148  	}
   149  	fmt.Printf("Connection with %s terminated\n", c.RemoteAddr())
   150  }