]> src.bluestatic.org Git - armadillo.git/blob - server/paths.go
Remove the error handling from JSON callbacks now that HTTP status codes are used.
[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 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(p string) (files []string, err error) {
43 p = canonicalizePath(p)
44 if !checkInJail(p) {
45 return nil, errors.New("Path outside of jail")
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(p string) error {
74 p = canonicalizePath(p)
75 if !checkInJail(p) {
76 return errors.New("Path outside of jail")
77 }
78 return os.RemoveAll(p)
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 }