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