Add the LICENSE.txt file
[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 "fmt"
14 "os"
15 "path"
16 "strings"
17 )
18
19 func canonicalizePath(raw string) string {
20 return path.Clean(path.Join(gConfig.JailRoot, raw))
21 }
22
23 func checkInJail(p string) bool {
24 if len(p) < len(gConfig.JailRoot) {
25 return false
26 }
27 if p[0:len(gConfig.JailRoot)] != gConfig.JailRoot {
28 return false
29 }
30 if strings.Index(p, "../") != -1 {
31 return false
32 }
33 return true
34 }
35
36 func IsValidPath(p string) (bool, string) {
37 p = canonicalizePath(p)
38 _, err := os.Lstat(p)
39 return err == nil && checkInJail(p), p
40 }
41
42 func ListPath(op string) (files []string, err error) {
43 p := canonicalizePath(op)
44 if !checkInJail(p) {
45 return nil, fmt.Errorf("Path outside of jail: %q", op)
46 }
47
48 f, err := os.Open(p)
49 if err != nil {
50 return
51 }
52 defer f.Close()
53
54 fileinfos, err := f.Readdir(-1)
55 if err != nil {
56 return
57 }
58
59 files = make([]string, 0)
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(op string) error {
74 p := canonicalizePath(op)
75 if !checkInJail(p) {
76 return fmt.Errorf("Path outside of jail: %q", op)
77 }
78 return os.RemoveAll(p)
79 }
80
81 func MovePath(oSource string, oTarget string) error {
82 source := canonicalizePath(oSource)
83 target := canonicalizePath(oTarget)
84 if !checkInJail(source) {
85 return fmt.Errorf("Source outside of jail: %q", oSource)
86 }
87 if !checkInJail(target) {
88 return fmt.Errorf("Target outside of jail: %q", oTarget)
89 }
90 return os.Rename(source, target)
91 }
92
93 func MakeDir(oTarget string) error {
94 target := canonicalizePath(oTarget)
95 if !checkInJail(target) {
96 return fmt.Errorf("Path outside of jail: %q", oTarget)
97 }
98 return os.Mkdir(target, 0755)
99 }