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