all repos — flounder @ 1a867bb9b9fbf406d431b32799bd280c17d4a20a

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