Don't return a null slice from server.ListPath, return an empty one
[armadillo.git] / server / paths.go
1 //
2 // Armadillo File Manager
3 // Copyright (c) 2010-2012, Robert Sesek <http://www.bluestatic.org>
4 //
5 // This program is free software: you can redistribute it and/or modify it under
6 // the terms of the GNU General Public License as published by the Free Software
7 // Foundation, either version 3 of the License, or any later version.
8 //
9
10 package server
11
12 import (
13 "errors"
14 "os"
15 "path"
16 "strings"
17 )
18
19 func canonicalizePath(raw_path string) string {
20 raw_path = path.Join(gConfig.JailRoot, raw_path)
21 return path.Clean(raw_path)
22 }
23
24 func checkInJail(the_path string) bool {
25 if len(the_path) < len(gConfig.JailRoot) {
26 return false
27 }
28 if the_path[0:len(gConfig.JailRoot)] != gConfig.JailRoot {
29 return false
30 }
31 if strings.Index(the_path, "../") != -1 {
32 return false
33 }
34 return true
35 }
36
37 func IsValidPath(path string) (bool, string) {
38 path = canonicalizePath(path)
39 _, err := os.Lstat(path)
40 return err == nil && checkInJail(path), path
41 }
42
43 func ListPath(the_path string) (files []string, err error) {
44 full_path := canonicalizePath(the_path)
45 if !checkInJail(full_path) {
46 return nil, errors.New("Path outside of jail")
47 }
48
49 fd, file_error := os.Open(full_path)
50 if file_error != nil {
51 return nil, file_error
52 }
53 defer fd.Close()
54
55 fileinfos, read_err := fd.Readdir(-1)
56 if read_err != nil {
57 return nil, read_err
58 }
59
60 files = make([]string, 0)
61 for _, info := range fileinfos {
62 name := info.Name()
63 if info.IsDir() {
64 name += "/"
65 }
66 if !gConfig.IncludeDotfiles && name[0] == '.' {
67 continue
68 }
69 files = append(files, name)
70 }
71 return files, nil
72 }
73
74 func RemovePath(the_path string) error {
75 full_path := canonicalizePath(the_path)
76 if !checkInJail(full_path) {
77 return errors.New("Path outside of jail")
78 }
79 return os.RemoveAll(full_path)
80 }
81
82 func MovePath(source string, target string) error {
83 source = canonicalizePath(source)
84 target = canonicalizePath(target)
85 if !checkInJail(source) {
86 return errors.New("Source outside of jail")
87 }
88 if !checkInJail(target) {
89 return errors.New("Target outside of jail")
90 }
91 return os.Rename(source, target)
92 }
93
94 func MakeDir(target string) error {
95 target = canonicalizePath(target)
96 if !checkInJail(target) {
97 return errors.New("Path outside of jail")
98 }
99 return os.Mkdir(target, 0755)
100 }