all repos — flounder @ 858ec21770c0e2d0b25fc302688fbde9bb24d9f1

A small site builder for the Gemini protocol

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				log.Printf("Changed domain for %s from %s to %s", authUser, me.Domain, newDomain)
310			}
311		}
312		if newEmail != me.Email {
313			_, err = DB.Exec("update user set email = ? where username = ?", newEmail, me.Username)
314			if err != nil {
315				// TODO better error not sql
316				errors = append(errors, err.Error())
317			} else {
318				log.Printf("Changed email for %s from %s to %s", authUser, me.Email, newEmail)
319			}
320		}
321		if newUsername != authUser {
322			// Rename User
323			err = renameUser(authUser, newUsername)
324			if err != nil {
325				log.Println(err)
326				errors = append(errors, "Could not rename user")
327			} else {
328				session, _ := SessionStore.Get(r, "cookie-session")
329				session.Values["auth_user"] = newUsername
330				session.Save(r, w)
331			}
332		}
333		// reset auth
334		user = newGetAuthUser(r)
335		data.Errors = errors
336		data.AuthUser = user
337		data.MyUser.Email = newEmail
338		data.MyUser.Domain = newDomain
339		_ = t.ExecuteTemplate(w, "me.html", data)
340	}
341}
342
343func archiveHandler(w http.ResponseWriter, r *http.Request) {
344	authUser := newGetAuthUser(r)
345	if !authUser.LoggedIn {
346		renderDefaultError(w, http.StatusForbidden)
347		return
348	}
349	if r.Method == "GET" {
350		userFolder := getUserDirectory(authUser.Username)
351		err := zipit(userFolder, w)
352		if err != nil {
353			panic(err)
354		}
355
356	}
357}
358func loginHandler(w http.ResponseWriter, r *http.Request) {
359	if r.Method == "GET" {
360		// show page
361		data := struct {
362			Error  string
363			Config Config
364		}{"", c}
365		err := t.ExecuteTemplate(w, "login.html", data)
366		if err != nil {
367			panic(err)
368		}
369	} else if r.Method == "POST" {
370		r.ParseForm()
371		name := r.Form.Get("username")
372		password := r.Form.Get("password")
373		row := DB.QueryRow("SELECT username, password_hash, active, admin FROM user where username = $1 OR email = $1", name)
374		var db_password []byte
375		var username string
376		var active bool
377		var isAdmin bool
378		err := row.Scan(&username, &db_password, &active, &isAdmin)
379		if err != nil {
380			panic(err)
381		}
382		if db_password != nil && !active {
383			data := struct {
384				Error  string
385				Config Config
386			}{"Your account is not active yet. Pending admin approval", c}
387			t.ExecuteTemplate(w, "login.html", data)
388			return
389		}
390		if bcrypt.CompareHashAndPassword(db_password, []byte(password)) == nil {
391			log.Println("logged in")
392			session, _ := SessionStore.Get(r, "cookie-session")
393			session.Values["auth_user"] = username
394			session.Values["admin"] = isAdmin
395			session.Save(r, w)
396			http.Redirect(w, r, "/my_site", http.StatusSeeOther)
397		} else {
398			data := struct {
399				Error  string
400				Config Config
401			}{"Invalid login or password", c}
402			err := t.ExecuteTemplate(w, "login.html", data)
403			if err != nil {
404				panic(err)
405			}
406		}
407	}
408}
409
410func logoutHandler(w http.ResponseWriter, r *http.Request) {
411	session, _ := SessionStore.Get(r, "cookie-session")
412	impers, ok := session.Values["impersonating_user"].(string)
413	if ok {
414		session.Values["auth_user"] = impers
415		session.Values["impersonating_user"] = nil // TODO expire this automatically
416		// session.Values["admin"] = nil // TODO fix admin
417	} else {
418		session.Options.MaxAge = -1
419	}
420	session.Save(r, w)
421	http.Redirect(w, r, "/", http.StatusSeeOther)
422}
423
424const ok = "-0123456789abcdefghijklmnopqrstuvwxyz"
425
426func isOkUsername(s string) error {
427	if len(s) < 1 {
428		return fmt.Errorf("Username is too short")
429	}
430	if len(s) > 32 {
431		return fmt.Errorf("Username is too long. 32 char max.")
432	}
433	for _, char := range s {
434		if !strings.Contains(ok, strings.ToLower(string(char))) {
435			return fmt.Errorf("Username contains invalid characters. Valid characters include lowercase letters, numbers, and hyphens.")
436		}
437	}
438	return nil
439}
440func registerHandler(w http.ResponseWriter, r *http.Request) {
441	if r.Method == "GET" {
442		data := struct {
443			Errors []string
444			Config Config
445		}{nil, c}
446		err := t.ExecuteTemplate(w, "register.html", data)
447		if err != nil {
448			panic(err)
449		}
450	} else if r.Method == "POST" {
451		r.ParseForm()
452		email := r.Form.Get("email")
453		password := r.Form.Get("password")
454		errors := []string{}
455		if r.Form.Get("password") != r.Form.Get("password2") {
456			errors = append(errors, "Passwords don't match")
457		}
458		if len(password) < 6 {
459			errors = append(errors, "Password is too short")
460		}
461		username := strings.ToLower(r.Form.Get("username"))
462		err := isOkUsername(username)
463		if err != nil {
464			errors = append(errors, err.Error())
465		}
466		hashedPassword, err := bcrypt.GenerateFromPassword([]byte(password), 8) // TODO handle error
467		if err != nil {
468			panic(err)
469		}
470		reference := r.Form.Get("reference")
471		if len(errors) == 0 {
472			_, err = DB.Exec("insert into user (username, email, password_hash, reference) values ($1, $2, $3, $4)", username, email, string(hashedPassword), reference)
473			if err != nil {
474				errors = append(errors, "Username or email is already used")
475			}
476		}
477		if len(errors) > 0 {
478			data := struct {
479				Config Config
480				Errors []string
481			}{c, errors}
482			t.ExecuteTemplate(w, "register.html", data)
483		} else {
484			data := struct {
485				Config  Config
486				Message string
487				Title   string
488			}{c, "Registration complete! The server admin will approve your request before you can log in.", "Registration Complete"}
489			t.ExecuteTemplate(w, "message.html", data)
490		}
491	}
492}
493
494func deleteFileHandler(w http.ResponseWriter, r *http.Request) {
495	user := newGetAuthUser(r)
496	if !user.LoggedIn {
497		renderDefaultError(w, http.StatusForbidden)
498		return
499	}
500	filePath := safeGetFilePath(user.Username, r.URL.Path[len("/delete/"):])
501	if r.Method == "POST" {
502		os.Remove(filePath) // TODO handle error
503	}
504	http.Redirect(w, r, "/my_site", http.StatusSeeOther)
505}
506
507func adminHandler(w http.ResponseWriter, r *http.Request) {
508	user := newGetAuthUser(r)
509	if !user.IsAdmin {
510		renderDefaultError(w, http.StatusForbidden)
511		return
512	}
513	allUsers, err := getUsers()
514	if err != nil {
515		log.Println(err)
516		renderDefaultError(w, http.StatusInternalServerError)
517		return
518	}
519	data := struct {
520		Users    []User
521		AuthUser AuthUser
522		Config   Config
523	}{allUsers, user, c}
524	err = t.ExecuteTemplate(w, "admin.html", data)
525	if err != nil {
526		panic(err)
527	}
528}
529
530func getFavicon(user string) string {
531	faviconPath := path.Join(c.FilesDirectory, filepath.Clean(user), "favicon.txt")
532	content, err := ioutil.ReadFile(faviconPath)
533	if err != nil {
534		return ""
535	}
536	strcontent := []rune(string(content))
537	if len(strcontent) > 0 {
538		return string(strcontent[0])
539	}
540	return ""
541}
542
543// Server a user's file
544// TODO replace with gemini proxy
545// Here be dragons
546func userFile(w http.ResponseWriter, r *http.Request) {
547	userName := filepath.Clean(strings.Split(r.Host, ".")[0]) // Clean probably unnecessary
548	p := filepath.Clean(r.URL.Path)
549	var isDir bool
550	fullPath := path.Join(c.FilesDirectory, userName, p) // TODO rename filepath
551	stat, err := os.Stat(fullPath)
552	if stat != nil {
553		isDir = stat.IsDir()
554	}
555	if strings.HasSuffix(p, "index.gmi") {
556		http.Redirect(w, r, path.Dir(p), http.StatusMovedPermanently)
557	}
558
559	if strings.HasPrefix(p, "/"+HiddenFolder) {
560		renderDefaultError(w, http.StatusForbidden)
561		return
562	}
563	if r.URL.Path == "/gemlog/atom.xml" && os.IsNotExist(err) {
564		w.Header().Set("Content-Type", "application/atom+xml")
565		// TODO set always somehow
566		feed := generateFeedFromUser(userName)
567		atomString := feed.toAtomFeed()
568		io.Copy(w, strings.NewReader(atomString))
569		return
570	}
571
572	var geminiContent string
573	_, err = os.Stat(path.Join(fullPath, "index.gmi"))
574	if p == "/" || isDir {
575		if os.IsNotExist(err) {
576			if p == "/gemlog" {
577				geminiContent = generateGemfeedPage(userName)
578			} else {
579				geminiContent = generateFolderPage(fullPath)
580			}
581		} else {
582			fullPath = path.Join(fullPath, "index.gmi")
583		}
584	}
585	if geminiContent == "" && os.IsNotExist(err) {
586		renderDefaultError(w, http.StatusNotFound)
587		return
588	}
589	// Dumb content negotiation
590	_, raw := r.URL.Query()["raw"]
591	acceptsGemini := strings.Contains(r.Header.Get("Accept"), "text/gemini")
592	if !raw && !acceptsGemini && (isGemini(fullPath) || geminiContent != "") {
593		var htmlString string
594		if geminiContent == "" {
595			file, _ := os.Open(fullPath)
596			htmlString = textToHTML(nil, gmi.ParseText(file))
597			defer file.Close()
598		} else {
599			htmlString = textToHTML(nil, gmi.ParseText(strings.NewReader(geminiContent)))
600		}
601		favicon := getFavicon(userName)
602		hostname := strings.Split(r.Host, ":")[0]
603		uri := url.URL{
604			Scheme: "gemini",
605			Host:   hostname,
606			Path:   p,
607		}
608		data := struct {
609			SiteBody  template.HTML
610			Favicon   string
611			PageTitle string
612			URI       *url.URL
613		}{template.HTML(htmlString), favicon, userName + p, &uri}
614		err = t.ExecuteTemplate(w, "user_page.html", data)
615		if err != nil {
616			panic(err)
617		}
618	} else {
619		http.ServeFile(w, r, fullPath)
620	}
621}
622
623func deleteAccountHandler(w http.ResponseWriter, r *http.Request) {
624	user := newGetAuthUser(r)
625	if r.Method == "POST" {
626		r.ParseForm()
627		validate := r.Form.Get("validate-delete")
628		if validate == user.Username {
629			err := deleteUser(user.Username)
630			if err != nil {
631				log.Println(err)
632				renderDefaultError(w, http.StatusInternalServerError)
633				return
634			}
635			logoutHandler(w, r)
636		} else {
637			http.Redirect(w, r, "/me", http.StatusSeeOther)
638		}
639	}
640}
641
642func resetPasswordHandler(w http.ResponseWriter, r *http.Request) {
643	user := newGetAuthUser(r)
644	data := struct {
645		Config   Config
646		AuthUser AuthUser
647		Error    string
648	}{c, user, ""}
649	if r.Method == "GET" {
650		err := t.ExecuteTemplate(w, "reset_pass.html", data)
651		if err != nil {
652			panic(err)
653		}
654	} else if r.Method == "POST" {
655		r.ParseForm()
656		enteredCurrPass := r.Form.Get("password")
657		password1 := r.Form.Get("new_password1")
658		password2 := r.Form.Get("new_password2")
659		if password1 != password2 {
660			data.Error = "New passwords do not match"
661		} else if len(password1) < 6 {
662			data.Error = "Password is too short"
663		} else {
664			err := checkAuth(user.Username, enteredCurrPass)
665			if err == nil {
666				hashedPassword, err := bcrypt.GenerateFromPassword([]byte(password1), 8)
667				if err != nil {
668					panic(err)
669				}
670				_, err = DB.Exec("update user set password_hash = ? where username = ?", hashedPassword, user.Username)
671				if err != nil {
672					panic(err)
673				}
674				log.Printf("User %s reset password", user.Username)
675				http.Redirect(w, r, "/me", http.StatusSeeOther)
676				return
677			} else {
678				data.Error = "That's not your current password"
679			}
680		}
681		err := t.ExecuteTemplate(w, "reset_pass.html", data)
682		if err != nil {
683			panic(err)
684		}
685	}
686}
687
688func adminUserHandler(w http.ResponseWriter, r *http.Request) {
689	user := newGetAuthUser(r)
690	if r.Method == "POST" {
691		if !user.IsAdmin {
692			renderDefaultError(w, http.StatusForbidden)
693			return
694		}
695		components := strings.Split(r.URL.Path, "/")
696		if len(components) < 5 {
697			renderError(w, "Invalid action", http.StatusBadRequest)
698			return
699		}
700		userName := components[3]
701		action := components[4]
702		var err error
703		if action == "activate" {
704			err = activateUser(userName)
705		} else if action == "impersonate" {
706			if user.ImpersonatingUser != "" {
707				// Don't allow nested impersonation
708				renderError(w, "Cannot nest impersonation, log out from impersonated user first.", 400)
709				return
710			}
711			session, _ := SessionStore.Get(r, "cookie-session")
712			session.Values["auth_user"] = userName
713			session.Values["impersonating_user"] = user.Username
714			session.Save(r, w)
715			log.Printf("User %s impersonated %s", user.Username, userName)
716			http.Redirect(w, r, "/", http.StatusSeeOther)
717			return
718		}
719		if err != nil {
720			log.Println(err)
721			renderDefaultError(w, http.StatusInternalServerError)
722			return
723		}
724		http.Redirect(w, r, "/admin", http.StatusSeeOther)
725	}
726}
727
728func runHTTPServer() {
729	log.Printf("Running http server with hostname %s on port %d.", c.Host, c.HttpPort)
730	var err error
731	t = template.New("main").Funcs(template.FuncMap{"parent": path.Dir})
732	t, err = t.ParseGlob(path.Join(c.TemplatesDirectory, "*.html"))
733	if err != nil {
734		log.Fatal(err)
735	}
736	serveMux := http.NewServeMux()
737
738	s := strings.SplitN(c.Host, ":", 2)
739	hostname := s[0]
740	port := c.HttpPort
741
742	serveMux.HandleFunc(hostname+"/", rootHandler)
743	serveMux.HandleFunc(hostname+"/feed", feedHandler)
744	serveMux.HandleFunc(hostname+"/my_site", mySiteHandler)
745	serveMux.HandleFunc(hostname+"/me", myAccountHandler)
746	serveMux.HandleFunc(hostname+"/my_site/flounder-archive.zip", archiveHandler)
747	serveMux.HandleFunc(hostname+"/admin", adminHandler)
748	serveMux.HandleFunc(hostname+"/edit/", editFileHandler)
749	serveMux.HandleFunc(hostname+"/upload", uploadFilesHandler)
750	serveMux.Handle(hostname+"/login", limit(http.HandlerFunc(loginHandler)))
751	serveMux.Handle(hostname+"/register", limit(http.HandlerFunc(registerHandler)))
752	serveMux.HandleFunc(hostname+"/logout", logoutHandler)
753	serveMux.HandleFunc(hostname+"/delete/", deleteFileHandler)
754	serveMux.HandleFunc(hostname+"/delete-account", deleteAccountHandler)
755	serveMux.HandleFunc(hostname+"/reset-password", resetPasswordHandler)
756
757	// admin commands
758	serveMux.HandleFunc(hostname+"/admin/user/", adminUserHandler)
759	// TODO authentication
760	serveMux.HandleFunc(hostname+"/webdav/", webdavHandler)
761
762	wrapped := handlers.CustomLoggingHandler(log.Writer(), handlers.RecoveryHandler()(serveMux), logFormatter)
763
764	// handle user files based on subdomain
765	// also routes to proxy
766	serveMux.HandleFunc("proxy."+hostname+"/", proxyGemini) // eg. proxy.flounder.online
767	serveMux.HandleFunc("/", userFile)
768	// login+register functions
769	srv := &http.Server{
770		ReadTimeout:  5 * time.Second,
771		WriteTimeout: 10 * time.Second,
772		IdleTimeout:  120 * time.Second,
773		Addr:         fmt.Sprintf(":%d", port),
774		// TLSConfig:    tlsConfig,
775		Handler: wrapped,
776	}
777	log.Fatal(srv.ListenAndServe())
778}