all repos — flounder @ cd39b4e60d52866ec16cde24c9b17d75287336d9

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 == "/gemlog/atom.xml" && os.IsNotExist(err) {
556		w.Header().Set("Content-Type", "application/atom+xml")
557		// TODO set always somehow
558		feed := generateFeedFromUser(userName)
559		atomString := feed.toAtomFeed()
560		io.Copy(w, strings.NewReader(atomString))
561		return
562	}
563
564	var geminiContent string
565	_, err = os.Stat(path.Join(fullPath, "index.gmi"))
566	if p == "/" || isDir {
567		if os.IsNotExist(err) {
568			if p == "/gemlog" {
569				geminiContent = generateGemfeedPage(userName)
570			} else {
571				geminiContent = generateFolderPage(fullPath)
572			}
573		} else {
574			fullPath = path.Join(fullPath, "index.gmi")
575		}
576	}
577	if geminiContent == "" && os.IsNotExist(err) {
578		renderDefaultError(w, http.StatusNotFound)
579		return
580	}
581	// Dumb content negotiation
582	_, raw := r.URL.Query()["raw"]
583	acceptsGemini := strings.Contains(r.Header.Get("Accept"), "text/gemini")
584	if !raw && !acceptsGemini && (isGemini(fullPath) || geminiContent != "") {
585		var htmlString string
586		if geminiContent == "" {
587			file, _ := os.Open(fullPath)
588			htmlString = textToHTML(gmi.ParseText(file))
589			defer file.Close()
590		} else {
591			htmlString = textToHTML(gmi.ParseText(strings.NewReader(geminiContent)))
592		}
593		favicon := getFavicon(userName)
594		hostname := strings.Split(r.Host, ":")[0]
595		URI := hostname + r.URL.String()
596		data := struct {
597			SiteBody  template.HTML
598			Favicon   string
599			PageTitle string
600			URI       string
601		}{template.HTML(htmlString), favicon, userName + p, URI}
602		t.ExecuteTemplate(w, "user_page.html", data)
603	} else {
604		http.ServeFile(w, r, fullPath)
605	}
606}
607
608func deleteAccountHandler(w http.ResponseWriter, r *http.Request) {
609	user := newGetAuthUser(r)
610	if r.Method == "POST" {
611		r.ParseForm()
612		validate := r.Form.Get("validate-delete")
613		if validate == user.Username {
614			err := deleteUser(user.Username)
615			if err != nil {
616				log.Println(err)
617				renderDefaultError(w, http.StatusInternalServerError)
618				return
619			}
620			logoutHandler(w, r)
621		} else {
622			http.Redirect(w, r, "/me", http.StatusSeeOther)
623		}
624	}
625}
626
627func resetPasswordHandler(w http.ResponseWriter, r *http.Request) {
628	user := newGetAuthUser(r)
629	data := struct {
630		PageTitle string
631		AuthUser  AuthUser
632		Error     string
633	}{"Reset Password", user, ""}
634	if r.Method == "GET" {
635		err := t.ExecuteTemplate(w, "reset_pass.html", data)
636		if err != nil {
637			panic(err)
638		}
639	} else if r.Method == "POST" {
640		r.ParseForm()
641		enteredCurrPass := r.Form.Get("password")
642		password1 := r.Form.Get("new_password1")
643		password2 := r.Form.Get("new_password2")
644		if password1 != password2 {
645			data.Error = "New passwords do not match"
646		} else if len(password1) < 6 {
647			data.Error = "Password is too short"
648		} else {
649			err := checkAuth(user.Username, enteredCurrPass)
650			if err == nil {
651				hashedPassword, err := bcrypt.GenerateFromPassword([]byte(password1), 8)
652				if err != nil {
653					panic(err)
654				}
655				_, err = DB.Exec("update user set password_hash = ? where username = ?", hashedPassword, user.Username)
656				if err != nil {
657					panic(err)
658				}
659				log.Printf("User %s reset password", user.Username)
660				http.Redirect(w, r, "/me", http.StatusSeeOther)
661				return
662			} else {
663				data.Error = "That's not your current password"
664			}
665		}
666		err := t.ExecuteTemplate(w, "reset_pass.html", data)
667		if err != nil {
668			panic(err)
669		}
670	}
671}
672
673func adminUserHandler(w http.ResponseWriter, r *http.Request) {
674	user := newGetAuthUser(r)
675	if r.Method == "POST" {
676		if !user.IsAdmin {
677			renderDefaultError(w, http.StatusForbidden)
678			return
679		}
680		components := strings.Split(r.URL.Path, "/")
681		if len(components) < 5 {
682			renderError(w, "Invalid action", http.StatusBadRequest)
683			return
684		}
685		userName := components[3]
686		action := components[4]
687		var err error
688		if action == "activate" {
689			err = activateUser(userName)
690		} else if action == "impersonate" {
691			if user.ImpersonatingUser != "" {
692				// Don't allow nested impersonation
693				renderError(w, "Cannot nest impersonation, log out from impersonated user first.", 400)
694				return
695			}
696			session, _ := SessionStore.Get(r, "cookie-session")
697			session.Values["auth_user"] = userName
698			session.Values["impersonating_user"] = user.Username
699			session.Save(r, w)
700			log.Printf("User %s impersonated %s", user.Username, userName)
701			http.Redirect(w, r, "/", http.StatusSeeOther)
702			return
703		}
704		if err != nil {
705			log.Println(err)
706			renderDefaultError(w, http.StatusInternalServerError)
707			return
708		}
709		http.Redirect(w, r, "/admin", http.StatusSeeOther)
710	}
711}
712
713func runHTTPServer() {
714	log.Printf("Running http server with hostname %s on port %d. TLS enabled: %t", c.Host, c.HttpPort, c.HttpsEnabled)
715	var err error
716	t, err = template.ParseGlob(path.Join(c.TemplatesDirectory, "*.html"))
717	if err != nil {
718		log.Fatal(err)
719	}
720	serveMux := http.NewServeMux()
721
722	s := strings.SplitN(c.Host, ":", 2)
723	hostname := s[0]
724	port := c.HttpPort
725
726	serveMux.HandleFunc(hostname+"/", rootHandler)
727	serveMux.HandleFunc(hostname+"/feed", feedHandler)
728	serveMux.HandleFunc(hostname+"/my_site", mySiteHandler)
729	serveMux.HandleFunc(hostname+"/me", myAccountHandler)
730	serveMux.HandleFunc(hostname+"/my_site/flounder-archive.zip", archiveHandler)
731	serveMux.HandleFunc(hostname+"/admin", adminHandler)
732	serveMux.HandleFunc(hostname+"/edit/", editFileHandler)
733	serveMux.HandleFunc(hostname+"/upload", uploadFilesHandler)
734	serveMux.Handle(hostname+"/login", limit(http.HandlerFunc(loginHandler)))
735	serveMux.Handle(hostname+"/register", limit(http.HandlerFunc(registerHandler)))
736	serveMux.HandleFunc(hostname+"/logout", logoutHandler)
737	serveMux.HandleFunc(hostname+"/delete/", deleteFileHandler)
738	serveMux.HandleFunc(hostname+"/delete-account", deleteAccountHandler)
739	serveMux.HandleFunc(hostname+"/reset-password", resetPasswordHandler)
740
741	// admin commands
742	serveMux.HandleFunc(hostname+"/admin/user/", adminUserHandler)
743	// TODO authentication
744	serveMux.HandleFunc(hostname+"/webdav/", webdavHandler)
745
746	wrapped := handlers.CustomLoggingHandler(log.Writer(), handlers.RecoveryHandler()(serveMux), logFormatter)
747
748	// handle user files based on subdomain
749	serveMux.HandleFunc("/", userFile)
750	// login+register functions
751	srv := &http.Server{
752		ReadTimeout:  5 * time.Second,
753		WriteTimeout: 10 * time.Second,
754		IdleTimeout:  120 * time.Second,
755		Addr:         fmt.Sprintf(":%d", port),
756		// TLSConfig:    tlsConfig,
757		Handler: wrapped,
758	}
759	if c.HttpsEnabled {
760		log.Fatal(srv.ListenAndServeTLS(c.TLSCertFile, c.TLSKeyFile))
761	} else {
762		log.Fatal(srv.ListenAndServe())
763	}
764}