all repos — flounder @ 68ea2ae1660587e2827ee67aac6e6759ff7bbb1e

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