Fix most compile errors
[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 for _, info := range fileinfos {
61 name := info.Name()
62 if info.IsDir() {
63 name += "/"
64 }
65 if !gConfig.IncludeDotfiles && name[0] == '.' {
66 continue
67 }
68 files = append(files, name)
69 }
70 return files, nil
71 }
72
73 func RemovePath(the_path string) error {
74 full_path := canonicalizePath(the_path)
75 if !checkInJail(full_path) {
76 return errors.New("Path outside of jail")
77 }
78 return os.RemoveAll(full_path)
79 }
80
81 func MovePath(source string, target string) error {
82 source = canonicalizePath(source)
83 target = canonicalizePath(target)
84 if !checkInJail(source) {
85 return errors.New("Source outside of jail")
86 }
87 if !checkInJail(target) {
88 return errors.New("Target outside of jail")
89 }
90 return os.Rename(source, target)
91 }
92
93 func MakeDir(target string) error {
94 target = canonicalizePath(target)
95 if !checkInJail(target) {
96 return errors.New("Path outside of jail")
97 }
98 return os.Mkdir(target, 0755)
99 }