Add an IncludeDotfiles configuration directive.
[armadillo.git] / src / paths.go
1 //
2 // Armadillo File Manager
3 // Copyright (c) 2010, 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 paths
11
12 import (
13 "container/vector"
14 "os"
15 "path"
16 "strings"
17 "./config"
18 )
19
20 var gJailRoot string
21 var gConfig *config.Configuration
22
23 func SetConfig(aConfig *config.Configuration) {
24 gConfig = aConfig
25 gJailRoot = aConfig.JailRoot
26 }
27
28 func canonicalizePath(raw_path string) string {
29 raw_path = path.Join(gJailRoot, raw_path)
30 return path.Clean(raw_path)
31 }
32
33 func checkInJail(the_path string) bool {
34 if len(the_path) < len(gJailRoot) {
35 return false
36 }
37 if the_path[0:len(gJailRoot)] != gJailRoot {
38 return false
39 }
40 if strings.Index(the_path, "../") != -1 {
41 return false
42 }
43 return true
44 }
45
46 func List(the_path string) (files vector.StringVector, err os.Error) {
47 full_path := canonicalizePath(the_path)
48 if !checkInJail(full_path) {
49 return nil, os.NewError("Path outside of jail")
50 }
51
52 fd, file_error := os.Open(full_path, os.O_RDONLY, 0)
53 if file_error != nil {
54 return nil, file_error
55 }
56
57 fileinfos, read_err := fd.Readdir(-1)
58 if read_err != nil {
59 return nil, read_err
60 }
61
62 for _, info := range fileinfos {
63 name := info.Name
64 if info.IsDirectory() {
65 name += "/"
66 }
67 if !gConfig.IncludeDotfiles && name[0] == '.' {
68 continue
69 }
70 files.Push(name)
71 }
72 return files, nil
73 }
74
75 func Remove(the_path string) os.Error {
76 full_path := canonicalizePath(the_path)
77 if !checkInJail(full_path) {
78 return os.NewError("Path outside of jail")
79 }
80 return os.RemoveAll(full_path)
81 }
82
83 func Move(source string, target string) os.Error {
84 source = canonicalizePath(source)
85 target = canonicalizePath(target)
86 if !checkInJail(source) {
87 return os.NewError("Source outside of jail")
88 }
89 if !checkInJail(target) {
90 return os.NewError("Target outside of jail")
91 }
92 return os.Rename(source, target)
93 }