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 _, err := os.Stat(fileName)
51 if err != nil {
52 renderDefaultError(w, http.StatusNotFound)
53 return
54 }
55 http.ServeFile(w, r, fileName) // TODO better error handling
56 return
57 }
58
59 user := newGetAuthUser(r)
60 indexFiles, err := getIndexFiles(user.IsAdmin)
61 if err != nil {
62 panic(err)
63 }
64 allUsers, err := getActiveUserNames()
65 if err != nil {
66 panic(err)
67 }
68 data := struct {
69 Host string
70 PageTitle string
71 Files []*File
72 Users []string
73 AuthUser AuthUser
74 }{c.Host, c.SiteTitle, indexFiles, allUsers, user}
75 err = t.ExecuteTemplate(w, "index.html", data)
76 if err != nil {
77 panic(err)
78 }
79}
80
81func editFileHandler(w http.ResponseWriter, r *http.Request) {
82 user := newGetAuthUser(r)
83 if !user.LoggedIn {
84 renderDefaultError(w, http.StatusForbidden)
85 return
86 }
87 fileName := filepath.Clean(r.URL.Path[len("/edit/"):])
88 isText := strings.HasPrefix(mime.TypeByExtension(path.Ext(fileName)), "text")
89 filePath := path.Join(c.FilesDirectory, user.Username, fileName)
90
91 if r.Method == "GET" {
92 err := checkIfValidFile(filePath, nil)
93 if err != nil {
94 log.Println(err)
95 renderError(w, err.Error(), http.StatusBadRequest)
96 return
97 }
98 // Create directories if dne
99 f, err := os.OpenFile(filePath, os.O_RDONLY, 0644)
100 var fileBytes []byte
101 if os.IsNotExist(err) || !isText {
102 fileBytes = []byte{}
103 err = nil
104 } else {
105 defer f.Close()
106 fileBytes, err = ioutil.ReadAll(f)
107 }
108 if err != nil {
109 panic(err)
110 }
111 data := struct {
112 FileName string
113 FileText string
114 PageTitle string
115 AuthUser AuthUser
116 Host string
117 IsText bool
118 }{fileName, string(fileBytes), c.SiteTitle, user, c.Host, isText}
119 err = t.ExecuteTemplate(w, "edit_file.html", data)
120 if err != nil {
121 panic(err)
122 }
123 } else if r.Method == "POST" {
124 // get post body
125 r.ParseForm()
126 fileText := r.Form.Get("file_text")
127 // Web form by default gives us CR LF newlines.
128 // Unix files use just LF
129 fileText = strings.ReplaceAll(fileText, "\r\n", "\n")
130 fileBytes := []byte(fileText)
131 err := checkIfValidFile(filePath, fileBytes)
132 if err != nil {
133 log.Println(err)
134 renderError(w, err.Error(), http.StatusBadRequest)
135 return
136 }
137 // create directories if dne
138 os.MkdirAll(path.Dir(filePath), os.ModePerm)
139 if userHasSpace(user.Username, len(fileBytes)) {
140 if isText { // Cant edit binary files here
141 err = ioutil.WriteFile(filePath, fileBytes, 0644)
142 }
143 } else {
144 renderError(w, fmt.Sprintf("Bad Request: Out of file space. Max space: %d.", c.MaxUserBytes), http.StatusBadRequest)
145 return
146 }
147 if err != nil {
148 panic(err)
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, user.Username, newName)
159 os.MkdirAll(path.Dir(newPath), os.ModePerm)
160 os.Rename(filePath, newPath)
161 fileName = newName
162 }
163 http.Redirect(w, r, path.Join("/edit", fileName), http.StatusSeeOther)
164 }
165}
166
167func uploadFilesHandler(w http.ResponseWriter, r *http.Request) {
168 if r.Method == "POST" {
169 user := newGetAuthUser(r)
170 if !user.LoggedIn {
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, user.Username, fileName)
191
192 f, err := os.OpenFile(destPath, os.O_WRONLY|os.O_CREATE, 0644)
193 if err != nil {
194 panic(err)
195 }
196 defer f.Close()
197 if userHasSpace(user.Username, c.MaxFileBytes) { // Not quite right
198 io.Copy(f, bytes.NewReader(dest))
199 } else {
200 renderError(w, fmt.Sprintf("Bad Request: Out of file space. Max space: %d.", c.MaxUserBytes), http.StatusBadRequest)
201 return
202 }
203 }
204 http.Redirect(w, r, "/my_site", http.StatusSeeOther)
205}
206
207type AuthUser struct {
208 LoggedIn bool
209 Username string
210 IsAdmin bool
211 ImpersonatingUser string // used if impersonating
212}
213
214func newGetAuthUser(r *http.Request) AuthUser {
215 session, _ := SessionStore.Get(r, "cookie-session")
216 user, ok := session.Values["auth_user"].(string)
217 impers, _ := session.Values["impersonating_user"].(string)
218 isAdmin, _ := session.Values["admin"].(bool)
219 return AuthUser{
220 LoggedIn: ok,
221 Username: user,
222 IsAdmin: isAdmin,
223 ImpersonatingUser: impers,
224 }
225}
226
227func mySiteHandler(w http.ResponseWriter, r *http.Request) {
228 user := newGetAuthUser(r)
229 if !user.LoggedIn {
230 renderDefaultError(w, http.StatusForbidden)
231 return
232 }
233 // check auth
234 userFolder := getUserDirectory(user.Username)
235 files, _ := getMyFilesRecursive(userFolder, user.Username)
236 data := struct {
237 Host string
238 PageTitle string
239 Files []*File
240 AuthUser AuthUser
241 }{c.Host, c.SiteTitle, files, user}
242 _ = t.ExecuteTemplate(w, "my_site.html", data)
243}
244
245func myAccountHandler(w http.ResponseWriter, r *http.Request) {
246 user := newGetAuthUser(r)
247 authUser := user.Username
248 if !user.LoggedIn {
249 renderDefaultError(w, http.StatusForbidden)
250 return
251 }
252 me, _ := getUserByName(user.Username)
253 type pageData struct {
254 PageTitle string
255 AuthUser AuthUser
256 Email string
257 Errors []string
258 }
259 data := pageData{"My Account", user, me.Email, nil}
260
261 if r.Method == "GET" {
262 err := t.ExecuteTemplate(w, "me.html", data)
263 if err != nil {
264 panic(err)
265 }
266 } else if r.Method == "POST" {
267 r.ParseForm()
268 newUsername := r.Form.Get("username")
269 errors := []string{}
270 newEmail := r.Form.Get("email")
271 newUsername = strings.ToLower(newUsername)
272 var err error
273 if newEmail != me.Email {
274 _, err = DB.Exec("update user set email = ? where username = ?", newEmail, me.Email)
275 if err != nil {
276 // TODO better error not sql
277 errors = append(errors, err.Error())
278 } else {
279 log.Printf("Changed email for %s from %s to %s", authUser, me.Email, newEmail)
280 }
281 }
282 if newUsername != authUser {
283 // Rename User
284 err = renameUser(authUser, newUsername)
285 if err != nil {
286 errors = append(errors, err.Error())
287 } else {
288 session, _ := SessionStore.Get(r, "cookie-session")
289 session.Values["auth_user"] = newUsername
290 session.Save(r, w)
291 }
292 }
293 // reset auth
294 user = newGetAuthUser(r)
295 data.Errors = errors
296 data.AuthUser = user
297 data.Email = newEmail
298 _ = t.ExecuteTemplate(w, "me.html", data)
299 }
300}
301
302func archiveHandler(w http.ResponseWriter, r *http.Request) {
303 authUser := newGetAuthUser(r)
304 if !authUser.LoggedIn {
305 renderDefaultError(w, http.StatusForbidden)
306 return
307 }
308 if r.Method == "GET" {
309 userFolder := getUserDirectory(authUser.Username)
310 err := zipit(userFolder, w)
311 if err != nil {
312 panic(err)
313 }
314
315 }
316}
317func loginHandler(w http.ResponseWriter, r *http.Request) {
318 if r.Method == "GET" {
319 // show page
320 data := struct {
321 Error string
322 PageTitle string
323 }{"", "Login"}
324 err := t.ExecuteTemplate(w, "login.html", data)
325 if err != nil {
326 panic(err)
327 }
328 } else if r.Method == "POST" {
329 r.ParseForm()
330 name := r.Form.Get("username")
331 password := r.Form.Get("password")
332 row := DB.QueryRow("SELECT username, password_hash, active, admin FROM user where username = $1 OR email = $1", name)
333 var db_password []byte
334 var username string
335 var active bool
336 var isAdmin bool
337 err := row.Scan(&username, &db_password, &active, &isAdmin)
338 if err != nil {
339 panic(err)
340 }
341 if db_password != nil && !active {
342 data := struct {
343 Error string
344 PageTitle string
345 }{"Your account is not active yet. Pending admin approval", c.SiteTitle}
346 t.ExecuteTemplate(w, "login.html", data)
347 return
348 }
349 if bcrypt.CompareHashAndPassword(db_password, []byte(password)) == nil {
350 log.Println("logged in")
351 session, _ := SessionStore.Get(r, "cookie-session")
352 session.Values["auth_user"] = username
353 session.Values["admin"] = isAdmin
354 session.Save(r, w)
355 http.Redirect(w, r, "/my_site", http.StatusSeeOther)
356 } else {
357 data := struct {
358 Error string
359 PageTitle string
360 }{"Invalid login or password", c.SiteTitle}
361 err := t.ExecuteTemplate(w, "login.html", data)
362 if err != nil {
363 panic(err)
364 }
365 }
366 }
367}
368
369func logoutHandler(w http.ResponseWriter, r *http.Request) {
370 session, _ := SessionStore.Get(r, "cookie-session")
371 impers, ok := session.Values["impersonating_user"].(string)
372 if ok {
373 session.Values["auth_user"] = impers
374 session.Values["impersonating_user"] = nil // TODO expire this automatically
375 // session.Values["admin"] = nil // TODO fix admin
376 } else {
377 session.Options.MaxAge = -1
378 }
379 session.Save(r, w)
380 http.Redirect(w, r, "/", http.StatusSeeOther)
381}
382
383const ok = "-0123456789abcdefghijklmnopqrstuvwxyz"
384
385func isOkUsername(s string) error {
386 if len(s) < 1 {
387 return fmt.Errorf("Username is too short")
388 }
389 if len(s) > 32 {
390 return fmt.Errorf("Username is too long. 32 char max.")
391 }
392 for _, char := range s {
393 if !strings.Contains(ok, strings.ToLower(string(char))) {
394 return fmt.Errorf("Username contains invalid characters. Valid characters include lowercase letters, numbers, and hyphens.")
395 }
396 }
397 return nil
398}
399func registerHandler(w http.ResponseWriter, r *http.Request) {
400 if r.Method == "GET" {
401 data := struct {
402 Host string
403 Errors []string
404 PageTitle string
405 }{c.Host, nil, "Register"}
406 err := t.ExecuteTemplate(w, "register.html", data)
407 if err != nil {
408 panic(err)
409 }
410 } else if r.Method == "POST" {
411 r.ParseForm()
412 email := r.Form.Get("email")
413 password := r.Form.Get("password")
414 errors := []string{}
415 if r.Form.Get("password") != r.Form.Get("password2") {
416 errors = append(errors, "Passwords don't match")
417 }
418 if len(password) < 6 {
419 errors = append(errors, "Password is too short")
420 }
421 username := strings.ToLower(r.Form.Get("username"))
422 err := isOkUsername(username)
423 if err != nil {
424 errors = append(errors, err.Error())
425 }
426 hashedPassword, err := bcrypt.GenerateFromPassword([]byte(password), 8) // TODO handle error
427 if err != nil {
428 panic(err)
429 }
430 reference := r.Form.Get("reference")
431 if len(errors) == 0 {
432 _, err = DB.Exec("insert into user (username, email, password_hash, reference) values ($1, $2, $3, $4)", username, email, string(hashedPassword), reference)
433 if err != nil {
434 errors = append(errors, "Username or email is already used")
435 }
436 }
437 if len(errors) > 0 {
438 data := struct {
439 Host string
440 Errors []string
441 PageTitle string
442 }{c.Host, errors, "Register"}
443 t.ExecuteTemplate(w, "register.html", data)
444 } else {
445 data := struct {
446 Host string
447 Message string
448 PageTitle string
449 }{c.Host, "Registration complete! The server admin will approve your request before you can log in.", "Registration Complete"}
450 t.ExecuteTemplate(w, "message.html", data)
451 }
452 }
453}
454
455func deleteFileHandler(w http.ResponseWriter, r *http.Request) {
456 user := newGetAuthUser(r)
457 if !user.LoggedIn {
458 renderDefaultError(w, http.StatusForbidden)
459 return
460 }
461 filePath := safeGetFilePath(user.Username, r.URL.Path[len("/delete/"):])
462 if r.Method == "POST" {
463 os.Remove(filePath) // TODO handle error
464 }
465 http.Redirect(w, r, "/my_site", http.StatusSeeOther)
466}
467
468func adminHandler(w http.ResponseWriter, r *http.Request) {
469 user := newGetAuthUser(r)
470 if !user.IsAdmin {
471 renderDefaultError(w, http.StatusForbidden)
472 return
473 }
474 allUsers, err := getUsers()
475 if err != nil {
476 log.Println(err)
477 renderDefaultError(w, http.StatusInternalServerError)
478 return
479 }
480 data := struct {
481 Users []User
482 AuthUser AuthUser
483 PageTitle string
484 Host string
485 }{allUsers, user, "Admin", c.Host}
486 err = t.ExecuteTemplate(w, "admin.html", data)
487 if err != nil {
488 panic(err)
489 }
490}
491
492func getFavicon(user string) string {
493 faviconPath := path.Join(c.FilesDirectory, filepath.Clean(user), "favicon.txt")
494 content, err := ioutil.ReadFile(faviconPath)
495 if err != nil {
496 return ""
497 }
498 strcontent := []rune(string(content))
499 if len(strcontent) > 0 {
500 return string(strcontent[0])
501 }
502 return ""
503}
504
505// Server a user's file
506func userFile(w http.ResponseWriter, r *http.Request) {
507 userName := filepath.Clean(strings.Split(r.Host, ".")[0]) // Clean probably unnecessary
508 p := filepath.Clean(r.URL.Path)
509 var isDir bool
510 fileName := path.Join(c.FilesDirectory, userName, p)
511 stat, err := os.Stat(fileName)
512 if stat != nil {
513 isDir = stat.IsDir()
514 }
515 if p == "/" || isDir {
516 fileName = path.Join(fileName, "index.gmi")
517 }
518
519 if strings.HasPrefix(p, "/.hidden") {
520 renderDefaultError(w, http.StatusForbidden)
521 return
522 }
523 if r.URL.Path == "/style.css" {
524 http.ServeFile(w, r, path.Join(c.TemplatesDirectory, "static/style.css"))
525 return
526 }
527
528 _, err = os.Stat(fileName)
529 if os.IsNotExist(err) {
530 renderDefaultError(w, http.StatusNotFound)
531 return
532 }
533
534 // Dumb content negotiation
535 extension := path.Ext(fileName)
536 _, raw := r.URL.Query()["raw"]
537 acceptsGemini := strings.Contains(r.Header.Get("Accept"), "text/gemini")
538 if !raw && !acceptsGemini && (extension == ".gmi" || extension == ".gemini") {
539 file, _ := os.Open(fileName)
540 htmlString := textToHTML(gmi.ParseText(file))
541 favicon := getFavicon(userName)
542 data := struct {
543 SiteBody template.HTML
544 Favicon string
545 PageTitle string
546 }{template.HTML(htmlString), favicon, userName + p}
547 t.ExecuteTemplate(w, "user_page.html", data)
548 } else {
549 http.ServeFile(w, r, fileName)
550 }
551}
552
553func deleteAccountHandler(w http.ResponseWriter, r *http.Request) {
554 user := newGetAuthUser(r)
555 if r.Method == "POST" {
556 err := deleteUser(user.Username)
557 if err != nil {
558 log.Println(err)
559 renderDefaultError(w, http.StatusInternalServerError)
560 return
561 }
562 logoutHandler(w, r)
563 }
564}
565
566func resetPasswordHandler(w http.ResponseWriter, r *http.Request) {
567 user := newGetAuthUser(r)
568 data := struct {
569 PageTitle string
570 AuthUser AuthUser
571 Error string
572 }{"Reset Password", user, ""}
573 if r.Method == "GET" {
574 err := t.ExecuteTemplate(w, "reset_pass.html", data)
575 if err != nil {
576 panic(err)
577 }
578 } else if r.Method == "POST" {
579 r.ParseForm()
580 enteredCurrPass := r.Form.Get("password")
581 var currPass []byte
582 password1 := r.Form.Get("new_password1")
583 password2 := r.Form.Get("new_password2")
584 row := DB.QueryRow("SELECT password_hash FROM user where username = ?", user.Username)
585 err := row.Scan(&currPass)
586 if password1 != password2 {
587 data.Error = "New passwords do not match"
588 } else if len(password1) < 6 {
589 data.Error = "Password is too short"
590 } else {
591 err = bcrypt.CompareHashAndPassword(currPass, []byte(enteredCurrPass))
592 if err == nil {
593 hashedPassword, err := bcrypt.GenerateFromPassword([]byte(password1), 8) // TODO handle error
594 if err != nil {
595 panic(err)
596 }
597 _, err = DB.Exec("update user set password_hash = ? where username = ?", hashedPassword, user.Username)
598 if err != nil {
599 panic(err)
600 }
601 http.Redirect(w, r, "/me", http.StatusSeeOther)
602 return
603 } else {
604 data.Error = "That's not your current password"
605 }
606 }
607 err = t.ExecuteTemplate(w, "reset_pass.html", data)
608 if err != nil {
609 panic(err)
610 }
611 }
612}
613
614func adminUserHandler(w http.ResponseWriter, r *http.Request) {
615 user := newGetAuthUser(r)
616 if r.Method == "POST" {
617 if !user.IsAdmin {
618 renderDefaultError(w, http.StatusForbidden)
619 return
620 }
621 components := strings.Split(r.URL.Path, "/")
622 if len(components) < 5 {
623 renderError(w, "Invalid action", http.StatusBadRequest)
624 return
625 }
626 userName := components[3]
627 action := components[4]
628 var err error
629 if action == "activate" {
630 err = activateUser(userName)
631 } else if action == "impersonate" {
632 session, _ := SessionStore.Get(r, "cookie-session")
633 session.Values["auth_user"] = userName
634 session.Values["impersonating_user"] = user.Username
635 session.Save(r, w)
636 log.Printf("User %s impersonated %s", user.Username, userName)
637 http.Redirect(w, r, "/", http.StatusSeeOther)
638 return
639 }
640 if err != nil {
641 log.Println(err)
642 renderDefaultError(w, http.StatusInternalServerError)
643 return
644 }
645 http.Redirect(w, r, "/admin", http.StatusSeeOther)
646 }
647}
648
649func runHTTPServer() {
650 log.Printf("Running http server with hostname %s on port %d. TLS enabled: %t", c.Host, c.HttpPort, c.HttpsEnabled)
651 var err error
652 t, err = template.ParseGlob(path.Join(c.TemplatesDirectory, "*.html"))
653 if err != nil {
654 log.Fatal(err)
655 }
656 serveMux := http.NewServeMux()
657
658 s := strings.SplitN(c.Host, ":", 2)
659 hostname := s[0]
660 port := c.HttpPort
661
662 serveMux.HandleFunc(hostname+"/", rootHandler)
663 serveMux.HandleFunc(hostname+"/my_site", mySiteHandler)
664 serveMux.HandleFunc(hostname+"/me", myAccountHandler)
665 serveMux.HandleFunc(hostname+"/my_site/flounder-archive.zip", archiveHandler)
666 serveMux.HandleFunc(hostname+"/admin", adminHandler)
667 serveMux.HandleFunc(hostname+"/edit/", editFileHandler)
668 serveMux.HandleFunc(hostname+"/upload", uploadFilesHandler)
669 serveMux.Handle(hostname+"/login", limit(http.HandlerFunc(loginHandler)))
670 serveMux.Handle(hostname+"/register", limit(http.HandlerFunc(registerHandler)))
671 serveMux.HandleFunc(hostname+"/logout", logoutHandler)
672 serveMux.HandleFunc(hostname+"/delete/", deleteFileHandler)
673 serveMux.HandleFunc(hostname+"/delete-account", deleteAccountHandler)
674 serveMux.HandleFunc(hostname+"/reset-password", resetPasswordHandler)
675
676 // admin commands
677 serveMux.HandleFunc(hostname+"/admin/user/", adminUserHandler)
678
679 // TODO rate limit login https://github.com/ulule/limiter
680
681 wrapped := (handlers.LoggingHandler(log.Writer(), handlers.RecoveryHandler()(serveMux)))
682
683 // handle user files based on subdomain
684 serveMux.HandleFunc("/", userFile)
685 // login+register functions
686 srv := &http.Server{
687 ReadTimeout: 5 * time.Second,
688 WriteTimeout: 10 * time.Second,
689 IdleTimeout: 120 * time.Second,
690 Addr: fmt.Sprintf(":%d", port),
691 // TLSConfig: tlsConfig,
692 Handler: wrapped,
693 }
694 if c.HttpsEnabled {
695 log.Fatal(srv.ListenAndServeTLS(c.TLSCertFile, c.TLSKeyFile))
696 } else {
697 log.Fatal(srv.ListenAndServe())
698 }
699}