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