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

     1  package main
     2  
     3  import (
     4  	"bufio"
     5  	"flag"
     6  	"fmt"
     7  	"io"
     8  	"log"
     9  	"net"
    10  	"os"
    11  	"runtime"
    12  	"strings"
    13  )
    14  
    15  var host = flag.String("h", "localhost", "FTP Server")
    16  var port = flag.Int("p", 2020, "Port number")
    17  
    18  var commands = map[string]func(string, string){
    19  	"lcd":  localCD,
    20  	"lls":  localList,
    21  	"lpwd": localPwd,
    22  	"cd":   remoteCD,
    23  	"ls":   remoteList,
    24  	"pwd":  remotePwd,
    25  	"get":  getFile,
    26  	"put":  putFile,
    27  }
    28  
    29  var conn net.Conn
    30  var netReader *bufio.Reader
    31  
    32  var serverErrorMsg = "Communication error with server. Server may be down.\nExiting..."
    33  
    34  func main() {
    35  	flag.Parse()
    36  	connString := fmt.Sprintf("%s:%d", *host, *port)
    37  	var err error
    38  	conn, err = net.Dial("tcp", connString)
    39  	if err != nil {
    40  		log.Fatalf("Unable to establish connection to %s:%d\n%s\nExiting...", *host, *port, err)
    41  	}
    42  	defer conn.Close()
    43  	netReader = bufio.NewReader(conn)
    44  
    45  	reader := bufio.NewReader(os.Stdin)
    46  	fmt.Println("GoFTP connection established")
    47  	fmt.Println("----------------------------")
    48  	for {
    49  		fmt.Printf("GoFTP(%s)> ", *host)
    50  		text, _ := reader.ReadString('\n')
    51  		if runtime.GOOS == "windows" {
    52  			text = strings.Replace(text, "\r\n", "", -1)
    53  		} else {
    54  			text = strings.Replace(text, "\n", "", -1)
    55  		}
    56  		text = strings.TrimSpace(text)
    57  		if text == "exit" {
    58  			break
    59  		}
    60  		input := strings.Split(text, " ")
    61  		command := input[0]
    62  		args := strings.Join(input[1:], " ")
    63  
    64  		function, ok := commands[command]
    65  		if !ok {
    66  			fmt.Printf("Unrecognized command: '%s'\n", command)
    67  			continue
    68  		}
    69  		function(command, args)
    70  	}
    71  }
    72  
    73  // localCD changes the working directory on the client
    74  func localCD(cmd string, dir string) {
    75  	if len(dir) > 0 {
    76  		err := os.Chdir(dir)
    77  		if err != nil {
    78  			fmt.Printf("%s does not exist\n", dir)
    79  		}
    80  	}
    81  }
    82  
    83  // localList lists the client working directory contents
    84  // Optionally may list contents of a supplied directory
    85  func localList(cmd string, dir string) {
    86  	listDir, err := os.Getwd()
    87  	if err != nil {
    88  		fmt.Println("Unable to list directory contents")
    89  		return
    90  	}
    91  	if len(dir) > 0 {
    92  		listDir = dir // How does GO handle spaces in the dir argument?
    93  	}
    94  	dirContents, err := os.ReadDir(listDir)
    95  	if err != nil {
    96  		fmt.Println("Unable to list directory contents")
    97  		return
    98  	}
    99  	for _, entry := range dirContents {
   100  		fmt.Println(entry)
   101  	}
   102  }
   103  
   104  // localPwd displays the client working directory
   105  func localPwd(cmd string, _ string) {
   106  	cwd, err := os.Getwd()
   107  	if err != nil {
   108  		fmt.Println("Unable to determine working directory")
   109  		return
   110  	}
   111  	fmt.Println(cwd)
   112  }
   113  
   114  // remoteCD changes the working directory on the server
   115  func remoteCD(cmd string, dir string) {
   116  	err := sendServerCommand(conn, cmd, dir)
   117  	if err != nil {
   118  		log.Fatalln(serverErrorMsg)
   119  	}
   120  	invalidPath, err := receiveServerResponse(netReader)
   121  	if *invalidPath != "" || err != nil {
   122  		fmt.Println("Unable to change remote directory")
   123  	}
   124  }
   125  
   126  // remoteList lists the server working directory contents
   127  // Optionally may list contents of a supplied directory
   128  func remoteList(cmd string, dir string) {
   129  	err := sendServerCommand(conn, cmd, dir)
   130  	if err != nil {
   131  		log.Fatalln(serverErrorMsg)
   132  	}
   133  	dirContents, err := receiveServerResponse(netReader)
   134  	if err != nil {
   135  		log.Fatalln("Unable to display remote working directory")
   136  	}
   137  	for _, entry := range strings.Split(*dirContents, " ; ") {
   138  		fmt.Println(entry)
   139  	}
   140  }
   141  
   142  // remotePwd displays the server working directory
   143  func remotePwd(cmd string, args string) {
   144  	err := sendServerCommand(conn, cmd, args)
   145  	if err != nil {
   146  		log.Fatalln(serverErrorMsg)
   147  	}
   148  	cwd, err := receiveServerResponse(netReader)
   149  	if err != nil {
   150  		log.Fatalln("Unable to display remote working directory")
   151  	}
   152  	fmt.Println(*cwd)
   153  }
   154  
   155  // getFile copies a file from the server to the client
   156  func getFile(cmd string, filename string) {
   157  	err := sendServerCommand(conn, cmd, filename)
   158  	if err != nil {
   159  		log.Fatalln(serverErrorMsg)
   160  	}
   161  	file, err := os.Create(filename)
   162  	if err != nil {
   163  		log.Fatal(err)
   164  	}
   165  	// defer file.Close()
   166  	var currentByte int64 = 0
   167  	totalBytesReceived := 0
   168  	bufferSize := 64
   169  	buffer := make([]byte, bufferSize)
   170  	for {
   171  		n, err := conn.Read(buffer)
   172  		_, err = file.WriteAt(buffer[:n], currentByte)
   173  		totalBytesReceived += n
   174  		if err == io.EOF || n < bufferSize {
   175  			break
   176  		}
   177  		currentByte += int64(n)
   178  	}
   179  	file.Close()
   180  	fmt.Println(totalBytesReceived, "bytes received")
   181  }
   182  
   183  // putFile sends a file to the server from the client
   184  func putFile(cmd string, filename string) {
   185  	err := sendServerCommand(conn, cmd, filename)
   186  	if err != nil {
   187  		log.Fatalln(serverErrorMsg)
   188  	}
   189  	file, err := os.Open(filename)
   190  	if err != nil {
   191  		log.Fatal(err)
   192  	}
   193  	defer file.Close()
   194  	n, err := io.Copy(conn, file)
   195  	if err != nil {
   196  		log.Fatal(err)
   197  	}
   198  	fmt.Println(n, "bytes sent")
   199  
   200  	resp, err := receiveServerResponse(netReader)
   201  	if err != nil {
   202  		log.Fatalln("Unable to read server response on PUT")
   203  	}
   204  	fmt.Println(*resp)
   205  }
   206  
   207  // sendServerCommand sends the command and arguments across the connection to the server
   208  func sendServerCommand(conn net.Conn, command string, args string) error {
   209  	_, err := io.WriteString(conn, command+"\n")
   210  	if err != nil {
   211  		return err
   212  	}
   213  	// if len(args) > 0 {
   214  	_, err = io.WriteString(conn, args+"\n")
   215  	if err != nil {
   216  		return err
   217  	}
   218  	// }
   219  	return nil
   220  }
   221  
   222  // receiveServerResponse reads the response from the server and strips the newline
   223  func receiveServerResponse(reader *bufio.Reader) (*string, error) {
   224  	response, err := reader.ReadString('\n')
   225  	if err != nil {
   226  		return nil, err
   227  	}
   228  	response = strings.Replace(response, "\n", "", -1)
   229  	return &response, nil
   230  }