github.com/dnutiu/simplFT@v0.0.0-20181023061248-df4b14cdce57/server/path.go (about) 1 package server 2 3 // The Path module should work with the stack by providing functions that update the stack 4 // with information that helps keeping track of the directories that the clients use. 5 6 import ( 7 "bytes" 8 "os" 9 ) 10 11 // PATH is the constant which should contain the fixed path where the simpleFTP server will run 12 // This will act like a root cage. It must end with a forward slash! 13 var BasePath = "" 14 15 // MakePathFromStringStack gets a StringStack and makes a path. 16 func MakePathFromStringStack(stack *StringStack) string { 17 var buffer bytes.Buffer 18 19 buffer.WriteString(BasePath) 20 if BasePath[len(BasePath)-1] != '/' { 21 buffer.WriteString("/") 22 } 23 24 for i := 0; i < stack.Size(); i++ { 25 buffer.WriteString(stack.Items()[i] + "/") 26 } 27 28 return buffer.String() 29 } 30 31 // ChangeDirectory changes the current working directory with respect to BasePath 32 func ChangeDirectory(stack *StringStack, directory string) error { 33 stack.Push(directory) 34 35 path := MakePathFromStringStack(stack) 36 fileInfo, err := os.Stat(path) 37 if err != nil { 38 stack.Pop() 39 return PathError{err} 40 } 41 42 if fileInfo.IsDir() == false { 43 stack.Pop() 44 return ErrNotADirectory 45 } 46 47 // The last 9 bits represent the Unix perms format rwxrwxrwx 48 perms := fileInfo.Mode().Perm() 49 50 // The user has permission to view the directory 51 if (perms&1 != 0) && (perms&(1<<2) != 0) || (perms&(1<<6) != 0) && (perms&(1<<8) != 0) { 52 return nil 53 } 54 stack.Pop() 55 return PathError{err} 56 } 57 58 // ChangeDirectoryToPrevious changes the current working directory to the previous one, 59 // doesn't go past the BasePath 60 func ChangeDirectoryToPrevious(stack *StringStack) error { 61 if stack.IsEmpty() { 62 return ErrAlreadyAtBaseDirectory 63 } 64 stack.Pop() 65 return nil 66 }