Run gofix
[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 "../config"
14 "container/vector"
15 "errors"
16 "os"
17 "path"
18 "strings"
19 )
20
21 var gConfig *config.Configuration
22
23 func SetConfig(aConfig *config.Configuration) {
24 gConfig = aConfig
25 }
26
27 func canonicalizePath(raw_path string) string {
28 raw_path = path.Join(gConfig.JailRoot, raw_path)
29 return path.Clean(raw_path)
30 }
31
32 func checkInJail(the_path string) bool {
33 if len(the_path) < len(gConfig.JailRoot) {
34 return false
35 }
36 if the_path[0:len(gConfig.JailRoot)] != gConfig.JailRoot {
37 return false
38 }
39 if strings.Index(the_path, "../") != -1 {
40 return false
41 }
42 return true
43 }
44
45 func IsValid(path string) (bool, string) {
46 path = canonicalizePath(path)
47 _, err := os.Lstat(path)
48 return err == nil && checkInJail(path), path
49 }
50
51 func List(the_path string) (files vector.StringVector, err error) {
52 full_path := canonicalizePath(the_path)
53 if !checkInJail(full_path) {
54 return nil, errors.New("Path outside of jail")
55 }
56
57 fd, file_error := os.Open(full_path)
58 if file_error != nil {
59 return nil, file_error
60 }
61 defer fd.Close()
62
63 fileinfos, read_err := fd.Readdir(-1)
64 if read_err != nil {
65 return nil, read_err
66 }
67
68 for _, info := range fileinfos {
69 name := info.Name
70 if info.IsDirectory() {
71 name += "/"
72 }
73 if !gConfig.IncludeDotfiles && name[0] == '.' {
74 continue
75 }
76 files.Push(name)
77 }
78 return files, nil
79 }
80
81 func Remove(the_path string) error {
82 full_path := canonicalizePath(the_path)
83 if !checkInJail(full_path) {
84 return errors.New("Path outside of jail")
85 }
86 return os.RemoveAll(full_path)
87 }
88
89 func Move(source string, target string) error {
90 source = canonicalizePath(source)
91 target = canonicalizePath(target)
92 if !checkInJail(source) {
93 return errors.New("Source outside of jail")
94 }
95 if !checkInJail(target) {
96 return errors.New("Target outside of jail")
97 }
98 return os.Rename(source, target)
99 }
100
101 func MakeDir(target string) error {
102 target = canonicalizePath(target)
103 if !checkInJail(target) {
104 return errors.New("Path outside of jail")
105 }
106 return os.Mkdir(target, 0755)
107 }