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