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