Sanitze error messages so the jail path is not revealed.
[armadillo.git] / src / server.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 server
11
12 import (
13 "fmt"
14 "http"
15 "io"
16 "json"
17 "os"
18 "path"
19 "strings"
20 "./paths"
21 )
22
23 var dir, file = path.Split(path.Clean(os.Getenv("_")))
24 var kFrontEndFiles string = path.Join(dir, "fe")
25
26 func indexHandler(connection *http.Conn, request *http.Request) {
27 fd, err := os.Open(path.Join(kFrontEndFiles, "index.html"), os.O_RDONLY, 0)
28 if err != nil {
29 fmt.Print("Error opening file ", err.String(), "\n")
30 return
31 }
32 io.Copy(connection, fd)
33 }
34
35 func serviceHandler(connection *http.Conn, request *http.Request) {
36 if request.Method != "POST" {
37 io.WriteString(connection, "Error: Not a POST request")
38 return
39 }
40
41 switch request.FormValue("action") {
42 case "list":
43 files, err := paths.List(request.FormValue("path"))
44 if err != nil {
45 errorResponse(connection, err.String())
46 } else {
47 okResponse(connection, files)
48 }
49 default:
50 errorResponse(connection, "Unhandled action")
51 }
52 }
53
54 func errorResponse(connection *http.Conn, message string) {
55 message = strings.Replace(message, paths.JailRoot, "/", -1)
56 response := map[string] string {
57 "error": "-1",
58 "message": message,
59 }
60 json_data, err := json.Marshal(response)
61
62 connection.SetHeader("Content-Type", "text/json")
63 if err != nil {
64 io.WriteString(connection, "{\"error\":\"-9\",\"message\":\"Internal encoding error\"}")
65 } else {
66 connection.Write(json_data)
67 }
68 }
69
70 func okResponse(connection *http.Conn, data interface{}) {
71 connection.SetHeader("Content-Type", "text/json")
72 json_data, err := json.Marshal(data)
73 if err != nil {
74 errorResponse(connection, "Internal encoding error")
75 } else {
76 connection.Write(json_data)
77 }
78 }
79
80 func RunFrontEnd(port int) {
81 mux := http.NewServeMux()
82 mux.HandleFunc("/", indexHandler)
83 mux.Handle("/fe/", http.FileServer(kFrontEndFiles, "/fe/"))
84 mux.HandleFunc("/service", serviceHandler)
85
86 error := http.ListenAndServe(fmt.Sprintf(":%d", port), mux)
87 fmt.Printf("error %v", error)
88 }