http.go (view raw)
1package main
2
3import (
4 "bytes"
5 "database/sql"
6 "fmt"
7 gmi "git.sr.ht/~adnano/go-gemini"
8 "github.com/gorilla/handlers"
9 "github.com/gorilla/sessions"
10 _ "github.com/mattn/go-sqlite3"
11 "golang.org/x/crypto/bcrypt"
12 "html/template"
13 "io"
14 "io/ioutil"
15 "log"
16 "mime"
17 "net/http"
18 "os"
19 "path"
20 "path/filepath"
21 "strings"
22 "time"
23)
24
25var t *template.Template
26var DB *sql.DB
27var SessionStore *sessions.CookieStore
28
29const InternalServerErrorMsg = "500: Internal Server Error"
30
31func renderError(w http.ResponseWriter, errorMsg string, statusCode int) {
32 data := struct {
33 PageTitle string
34 ErrorMsg string
35 }{"Error!", errorMsg}
36 err := t.ExecuteTemplate(w, "error.html", data)
37 if err != nil { // shouldn't happen probably
38 http.Error(w, errorMsg, statusCode)
39 }
40}
41
42func rootHandler(w http.ResponseWriter, r *http.Request) {
43 // serve everything inside static directory
44 if r.URL.Path != "/" {
45 fileName := path.Join(c.TemplatesDirectory, "static", filepath.Clean(r.URL.Path))
46 http.ServeFile(w, r, fileName)
47 return
48 }
49 authd, _, isAdmin := getAuthUser(r)
50 indexFiles, err := getIndexFiles()
51 if err != nil {
52 log.Println(err)
53 renderError(w, InternalServerErrorMsg, 500)
54 return
55 }
56 allUsers, err := getActiveUserNames()
57 if err != nil {
58 log.Println(err)
59 renderError(w, InternalServerErrorMsg, 500)
60 return
61 }
62 data := struct {
63 Host string
64 PageTitle string
65 Files []*File
66 Users []string
67 LoggedIn bool
68 IsAdmin bool
69 }{c.Host, c.SiteTitle, indexFiles, allUsers, authd, isAdmin}
70 err = t.ExecuteTemplate(w, "index.html", data)
71 if err != nil {
72 log.Println(err)
73 renderError(w, InternalServerErrorMsg, 500)
74 return
75 }
76}
77
78func editFileHandler(w http.ResponseWriter, r *http.Request) {
79 session, _ := SessionStore.Get(r, "cookie-session")
80 authUser, ok := session.Values["auth_user"].(string)
81 if !ok {
82 renderError(w, "403: Forbidden", 403)
83 return
84 }
85 fileName := filepath.Clean(r.URL.Path[len("/edit/"):])
86 isText := strings.HasPrefix(mime.TypeByExtension(path.Ext(fileName)), "text")
87 if !isText {
88 renderError(w, "Not a text file", 400) // correct status code?
89 return
90 }
91 filePath := path.Join(c.FilesDirectory, authUser, fileName)
92 if r.Method == "GET" {
93 err := checkIfValidFile(filePath, nil)
94 if err != nil {
95 log.Println(err)
96 renderError(w, err.Error(), 400)
97 return
98 }
99 f, err := os.OpenFile(filePath, os.O_RDONLY|os.O_CREATE, 0644)
100 defer f.Close()
101 fileBytes, err := ioutil.ReadAll(f)
102 if err != nil {
103 log.Println(err)
104 renderError(w, InternalServerErrorMsg, 500)
105 return
106 }
107 data := struct {
108 FileName string
109 FileText string
110 PageTitle string
111 }{fileName, string(fileBytes), c.SiteTitle}
112 err = t.ExecuteTemplate(w, "edit_file.html", data)
113 if err != nil {
114 log.Println(err)
115 renderError(w, InternalServerErrorMsg, 500)
116 return
117 }
118 } else if r.Method == "POST" {
119 // get post body
120 r.ParseForm()
121 fileBytes := []byte(r.Form.Get("file_text"))
122 err := checkIfValidFile(filePath, fileBytes)
123 if err != nil {
124 log.Println(err)
125 renderError(w, err.Error(), 400)
126 return
127 }
128 err = ioutil.WriteFile(filePath, fileBytes, 0644)
129 if err != nil {
130 log.Println(err)
131 renderError(w, InternalServerErrorMsg, 500)
132 return
133 }
134 http.Redirect(w, r, "/my_site", 302)
135 }
136}
137
138func uploadFilesHandler(w http.ResponseWriter, r *http.Request) {
139 if r.Method == "POST" {
140 session, _ := SessionStore.Get(r, "cookie-session")
141 authUser, ok := session.Values["auth_user"].(string)
142 if !ok {
143 renderError(w, "403: Forbidden", 403)
144 return
145 }
146 r.ParseMultipartForm(10 << 6) // why does this not work
147 file, fileHeader, err := r.FormFile("file")
148 fileName := filepath.Clean(fileHeader.Filename)
149 defer file.Close()
150 if err != nil {
151 log.Println(err)
152 renderError(w, err.Error(), 400)
153 return
154 }
155 dest, _ := ioutil.ReadAll(file)
156 err = checkIfValidFile(fileName, dest)
157 if err != nil {
158 log.Println(err)
159 renderError(w, err.Error(), 400)
160 return
161 }
162 destPath := path.Join(c.FilesDirectory, authUser, fileName)
163
164 f, err := os.OpenFile(destPath, os.O_WRONLY|os.O_CREATE, 0644)
165 if err != nil {
166 log.Println(err)
167 renderError(w, InternalServerErrorMsg, 500)
168 return
169 }
170 defer f.Close()
171 io.Copy(f, bytes.NewReader(dest))
172 }
173 http.Redirect(w, r, "/my_site", 302)
174}
175
176// bool whether auth'd, string is auth user
177func getAuthUser(r *http.Request) (bool, string, bool) {
178 session, _ := SessionStore.Get(r, "cookie-session")
179 user, ok := session.Values["auth_user"].(string)
180 isAdmin, _ := session.Values["admin"].(bool)
181 return ok, user, isAdmin
182}
183func deleteFileHandler(w http.ResponseWriter, r *http.Request) {
184 authd, authUser, _ := getAuthUser(r)
185 if !authd {
186 renderError(w, "403: Forbidden", 403)
187 return
188 }
189 fileName := filepath.Clean(r.URL.Path[len("/delete/"):])
190 filePath := path.Join(c.FilesDirectory, authUser, fileName)
191 if r.Method == "POST" {
192 os.Remove(filePath) // suppress error
193 }
194 http.Redirect(w, r, "/my_site", 302)
195}
196
197func mySiteHandler(w http.ResponseWriter, r *http.Request) {
198 authd, authUser, isAdmin := getAuthUser(r)
199 if !authd {
200 renderError(w, "403: Forbidden", 403)
201 return
202 }
203 // check auth
204 files, _ := getUserFiles(authUser)
205 data := struct {
206 Host string
207 PageTitle string
208 AuthUser string
209 Files []*File
210 LoggedIn bool
211 IsAdmin bool
212 }{c.Host, c.SiteTitle, authUser, files, authd, isAdmin}
213 _ = t.ExecuteTemplate(w, "my_site.html", data)
214}
215
216func loginHandler(w http.ResponseWriter, r *http.Request) {
217 if r.Method == "GET" {
218 // show page
219 data := struct {
220 Error string
221 PageTitle string
222 }{"", "Login"}
223 err := t.ExecuteTemplate(w, "login.html", data)
224 if err != nil {
225 log.Println(err)
226 renderError(w, InternalServerErrorMsg, 500)
227 return
228 }
229 } else if r.Method == "POST" {
230 r.ParseForm()
231 name := r.Form.Get("username")
232 password := r.Form.Get("password")
233 row := DB.QueryRow("SELECT password_hash, active, admin FROM user where username = $1", name)
234 var db_password []byte
235 var active bool
236 var isAdmin bool
237 _ = row.Scan(&db_password, &active, &isAdmin)
238 if db_password != nil && !active {
239 data := struct {
240 Error string
241 PageTitle string
242 }{"Your account is not active yet. Pending admin approval", c.SiteTitle}
243 t.ExecuteTemplate(w, "login.html", data)
244 return
245 }
246 if bcrypt.CompareHashAndPassword(db_password, []byte(password)) == nil {
247 log.Println("logged in")
248 session, _ := SessionStore.Get(r, "cookie-session")
249 session.Values["auth_user"] = name
250 session.Values["admin"] = isAdmin
251 session.Save(r, w)
252 http.Redirect(w, r, "/my_site", 302)
253 } else {
254 data := struct {
255 Error string
256 PageTitle string
257 }{"Invalid login or password", c.SiteTitle}
258 err := t.ExecuteTemplate(w, "login.html", data)
259 if err != nil {
260 log.Println(err)
261 renderError(w, InternalServerErrorMsg, 500)
262 return
263 }
264 }
265 }
266}
267
268func logoutHandler(w http.ResponseWriter, r *http.Request) {
269 session, _ := SessionStore.Get(r, "cookie-session")
270 session.Options.MaxAge = -1
271 session.Save(r, w)
272 http.Redirect(w, r, "/", 302)
273}
274
275const ok = "-0123456789abcdefghijklmnopqrstuvwxyz"
276
277func isOkUsername(s string) bool {
278 if len(s) < 1 {
279 return false
280 }
281 if len(s) > 31 {
282 return false
283 }
284 for _, char := range s {
285 if !strings.Contains(ok, strings.ToLower(string(char))) {
286 return false
287 }
288 }
289 return true
290}
291func registerHandler(w http.ResponseWriter, r *http.Request) {
292 if r.Method == "GET" {
293 data := struct {
294 Host string
295 Errors []string
296 PageTitle string
297 }{c.Host, nil, "Register"}
298 err := t.ExecuteTemplate(w, "register.html", data)
299 if err != nil {
300 log.Println(err)
301 renderError(w, InternalServerErrorMsg, 500)
302 return
303 }
304 } else if r.Method == "POST" {
305 r.ParseForm()
306 email := r.Form.Get("email")
307 password := r.Form.Get("password")
308 errors := []string{}
309 if !strings.Contains(email, "@") {
310 errors = append(errors, "Invalid Email")
311 }
312 if r.Form.Get("password") != r.Form.Get("password2") {
313 errors = append(errors, "Passwords don't match")
314 }
315 if len(password) < 6 {
316 errors = append(errors, "Password is too short")
317 }
318 username := strings.ToLower(r.Form.Get("username"))
319 if !isOkUsername(username) {
320 errors = append(errors, "Username is invalid: can only contain letters, numbers and hypens. Maximum 32 characters.")
321 }
322 hashedPassword, err := bcrypt.GenerateFromPassword([]byte(password), 8) // TODO handle error
323 if len(errors) == 0 {
324 _, err = DB.Exec("insert into user (username, email, password_hash) values ($1, $2, $3)", username, email, string(hashedPassword))
325 if err != nil {
326 log.Println(err)
327 errors = append(errors, "Username or email is already used")
328 }
329 }
330 if len(errors) > 0 {
331 data := struct {
332 Host string
333 Errors []string
334 PageTitle string
335 }{c.Host, errors, "Register"}
336 t.ExecuteTemplate(w, "register.html", data)
337 } else {
338 data := struct {
339 Host string
340 Message string
341 PageTitle string
342 }{c.Host, "Registration complete! The server admin will approve your request before you can log in.", "Registration Complete"}
343 t.ExecuteTemplate(w, "message.html", data)
344 }
345 }
346}
347
348func adminHandler(w http.ResponseWriter, r *http.Request) {
349 _, _, isAdmin := getAuthUser(r)
350 if !isAdmin {
351 renderError(w, "403: Forbidden", 403)
352 return
353 }
354 allUsers, err := getUsers()
355 if err != nil {
356 log.Println(err)
357 renderError(w, InternalServerErrorMsg, 500)
358 return
359 }
360 data := struct {
361 Users []User
362 LoggedIn bool
363 IsAdmin bool
364 PageTitle string
365 Host string
366 }{allUsers, true, true, "Admin", c.Host}
367 err = t.ExecuteTemplate(w, "admin.html", data)
368 if err != nil {
369 log.Println(err)
370 renderError(w, InternalServerErrorMsg, 500)
371 return
372 }
373}
374
375// Server a user's file
376func userFile(w http.ResponseWriter, r *http.Request) {
377 userName := strings.Split(r.Host, ".")[0]
378 p := filepath.Clean(r.URL.Path)
379 if p == "/" {
380 p = "index.gmi"
381 }
382 fileName := path.Join(c.FilesDirectory, userName, p)
383 extension := path.Ext(fileName)
384 if r.URL.Path == "/style.css" {
385 http.ServeFile(w, r, path.Join(c.TemplatesDirectory, "static/style.css"))
386 }
387 query := r.URL.Query()
388 _, raw := query["raw"]
389 if !raw && (extension == ".gmi" || extension == ".gemini") {
390 _, err := os.Stat(fileName)
391 if err != nil {
392 renderError(w, "404: file not found", 404)
393 return
394 }
395 file, _ := os.Open(fileName)
396
397 htmlString := textToHTML(gmi.Parse(file))
398 data := struct {
399 SiteBody template.HTML
400 PageTitle string
401 }{template.HTML(htmlString), userName}
402 t.ExecuteTemplate(w, "user_page.html", data)
403 } else {
404 http.ServeFile(w, r, fileName)
405 }
406}
407
408func adminUserHandler(w http.ResponseWriter, r *http.Request) {
409 _, _, isAdmin := getAuthUser(r)
410 if r.Method == "POST" {
411 if !isAdmin {
412 renderError(w, "403: Forbidden", 403)
413 return
414 }
415 components := strings.Split(r.URL.Path, "/")
416 if len(components) < 5 {
417 renderError(w, "Invalid action", 400)
418 return
419 }
420 userName := components[3]
421 action := components[4]
422 var err error
423 if action == "activate" {
424 err = activateUser(userName)
425 } else if action == "delete" {
426 err = deleteUser(userName)
427 }
428 if err != nil {
429 log.Println(err)
430 renderError(w, InternalServerErrorMsg, 500)
431 return
432 }
433 http.Redirect(w, r, "/admin", 302)
434 }
435}
436
437func runHTTPServer() {
438 log.Printf("Running http server with hostname %s on port %d. TLS enabled: %t", c.Host, c.HttpPort, c.HttpsEnabled)
439 var err error
440 t, err = template.ParseGlob(path.Join(c.TemplatesDirectory, "*.html"))
441 if err != nil {
442 log.Fatal(err)
443 }
444 serveMux := http.NewServeMux()
445
446 s := strings.SplitN(c.Host, ":", 2)
447 hostname := s[0]
448 port := c.HttpPort
449
450 serveMux.HandleFunc(hostname+"/", rootHandler)
451 serveMux.HandleFunc(hostname+"/my_site", mySiteHandler)
452 serveMux.HandleFunc(hostname+"/admin", adminHandler)
453 serveMux.HandleFunc(hostname+"/edit/", editFileHandler)
454 serveMux.HandleFunc(hostname+"/upload", uploadFilesHandler)
455 serveMux.HandleFunc(hostname+"/login", loginHandler)
456 serveMux.HandleFunc(hostname+"/logout", logoutHandler)
457 serveMux.HandleFunc(hostname+"/register", registerHandler)
458 serveMux.HandleFunc(hostname+"/delete/", deleteFileHandler)
459
460 // admin commands
461 serveMux.HandleFunc(hostname+"/admin/user/", adminUserHandler)
462
463 // TODO rate limit login https://github.com/ulule/limiter
464
465 wrapped := handlers.LoggingHandler(log.Writer(), serveMux)
466
467 // handle user files based on subdomain
468 serveMux.HandleFunc("/", userFile)
469 // login+register functions
470 srv := &http.Server{
471 ReadTimeout: 5 * time.Second,
472 WriteTimeout: 10 * time.Second,
473 IdleTimeout: 120 * time.Second,
474 Addr: fmt.Sprintf(":%d", port),
475 // TLSConfig: tlsConfig,
476 Handler: wrapped,
477 }
478 if c.HttpsEnabled {
479 log.Fatal(srv.ListenAndServeTLS(c.TLSCertFile, c.TLSKeyFile))
480 } else {
481 log.Fatal(srv.ListenAndServe())
482 }
483}