all repos — flounder @ 18a042de0538b53ca8cf949b0b575d1d597bf92a

A small site builder for the Gemini protocol

http.go (view raw)

  1package main
  2
  3import (
  4	"bytes"
  5	"database/sql"
  6	"fmt"
  7	gmi "git.sr.ht/~adnano/go-gemini"
  8	"github.com/gorilla/handlers"
  9	"github.com/gorilla/sessions"
 10	_ "github.com/mattn/go-sqlite3"
 11	"golang.org/x/crypto/bcrypt"
 12	"html/template"
 13	"io"
 14	"io/ioutil"
 15	"log"
 16	"mime"
 17	"net/http"
 18	"os"
 19	"path"
 20	"path/filepath"
 21	"strings"
 22	"time"
 23)
 24
 25var t *template.Template
 26var DB *sql.DB
 27var SessionStore *sessions.CookieStore
 28
 29func renderDefaultError(w http.ResponseWriter, statusCode int) {
 30	errorMsg := http.StatusText(statusCode)
 31	renderError(w, errorMsg, statusCode)
 32}
 33
 34func renderError(w http.ResponseWriter, errorMsg string, statusCode int) {
 35	data := struct {
 36		PageTitle  string
 37		StatusCode int
 38		ErrorMsg   string
 39	}{"Error!", statusCode, errorMsg}
 40	err := t.ExecuteTemplate(w, "error.html", data)
 41	if err != nil { // Shouldn't happen probably
 42		http.Error(w, errorMsg, statusCode)
 43	}
 44}
 45
 46func rootHandler(w http.ResponseWriter, r *http.Request) {
 47	// serve everything inside static directory
 48	if r.URL.Path != "/" {
 49		fileName := path.Join(c.TemplatesDirectory, "static", filepath.Clean(r.URL.Path))
 50		_, err := os.Stat(fileName)
 51		if err != nil {
 52			renderDefaultError(w, http.StatusNotFound)
 53			return
 54		}
 55		http.ServeFile(w, r, fileName) // TODO better error handling
 56		return
 57	}
 58
 59	user := newGetAuthUser(r)
 60	indexFiles, err := getIndexFiles(user.IsAdmin)
 61	if err != nil {
 62		panic(err)
 63	}
 64	allUsers, err := getActiveUserNames()
 65	if err != nil {
 66		panic(err)
 67	}
 68	data := struct {
 69		Host      string
 70		PageTitle string
 71		Files     []*File
 72		Users     []string
 73		AuthUser  AuthUser
 74	}{c.Host, c.SiteTitle, indexFiles, allUsers, user}
 75	err = t.ExecuteTemplate(w, "index.html", data)
 76	if err != nil {
 77		panic(err)
 78	}
 79}
 80
 81func feedHandler(w http.ResponseWriter, r *http.Request) {
 82	user := newGetAuthUser(r)
 83	feedEntries, feeds, err := getAllGemfeedEntries()
 84	if err != nil {
 85		panic(err)
 86	}
 87	data := struct {
 88		Host        string
 89		PageTitle   string
 90		FeedEntries []*FeedEntry
 91		Feeds       []*Gemfeed
 92		AuthUser    AuthUser
 93	}{c.Host, c.SiteTitle, feedEntries, feeds, user}
 94	err = t.ExecuteTemplate(w, "feed.html", data)
 95	if err != nil {
 96		panic(err)
 97	}
 98}
 99
100func editFileHandler(w http.ResponseWriter, r *http.Request) {
101	user := newGetAuthUser(r)
102	if !user.LoggedIn {
103		renderDefaultError(w, http.StatusForbidden)
104		return
105	}
106	fileName := filepath.Clean(r.URL.Path[len("/edit/"):])
107	isText := strings.HasPrefix(mime.TypeByExtension(path.Ext(fileName)), "text")
108	filePath := path.Join(c.FilesDirectory, user.Username, fileName)
109
110	if r.Method == "GET" {
111		err := checkIfValidFile(filePath, nil)
112		if err != nil {
113			log.Println(err)
114			renderError(w, err.Error(), http.StatusBadRequest)
115			return
116		}
117		// Create directories if dne
118		f, err := os.OpenFile(filePath, os.O_RDONLY, 0644)
119		var fileBytes []byte
120		if os.IsNotExist(err) || !isText {
121			fileBytes = []byte{}
122			err = nil
123		} else {
124			defer f.Close()
125			fileBytes, err = ioutil.ReadAll(f)
126		}
127		if err != nil {
128			panic(err)
129		}
130		data := struct {
131			FileName  string
132			FileText  string
133			PageTitle string
134			AuthUser  AuthUser
135			Host      string
136			IsText    bool
137		}{fileName, string(fileBytes), c.SiteTitle, user, c.Host, isText}
138		err = t.ExecuteTemplate(w, "edit_file.html", data)
139		if err != nil {
140			panic(err)
141		}
142	} else if r.Method == "POST" {
143		// get post body
144		r.ParseForm()
145		fileText := r.Form.Get("file_text")
146		// Web form by default gives us CR LF newlines.
147		// Unix files use just LF
148		fileText = strings.ReplaceAll(fileText, "\r\n", "\n")
149		fileBytes := []byte(fileText)
150		err := checkIfValidFile(filePath, fileBytes)
151		if err != nil {
152			log.Println(err)
153			renderError(w, err.Error(), http.StatusBadRequest)
154			return
155		}
156		// create directories if dne
157		os.MkdirAll(path.Dir(filePath), os.ModePerm)
158		if userHasSpace(user.Username, len(fileBytes)) {
159			if isText { // Cant edit binary files here
160				err = ioutil.WriteFile(filePath, fileBytes, 0644)
161			}
162		} else {
163			renderError(w, fmt.Sprintf("Bad Request: Out of file space. Max space: %d.", c.MaxUserBytes), http.StatusBadRequest)
164			return
165		}
166		if err != nil {
167			panic(err)
168		}
169		newName := filepath.Clean(r.Form.Get("rename"))
170		err = checkIfValidFile(newName, fileBytes)
171		if err != nil {
172			log.Println(err)
173			renderError(w, err.Error(), http.StatusBadRequest)
174			return
175		}
176		if newName != fileName {
177			newPath := path.Join(c.FilesDirectory, user.Username, newName)
178			os.MkdirAll(path.Dir(newPath), os.ModePerm)
179			os.Rename(filePath, newPath)
180			fileName = newName
181		}
182		http.Redirect(w, r, path.Join("/edit", fileName), http.StatusSeeOther)
183	}
184}
185
186func uploadFilesHandler(w http.ResponseWriter, r *http.Request) {
187	if r.Method == "POST" {
188		user := newGetAuthUser(r)
189		if !user.LoggedIn {
190			renderDefaultError(w, http.StatusForbidden)
191			return
192		}
193		r.ParseMultipartForm(10 << 6) // why does this not work
194		file, fileHeader, err := r.FormFile("file")
195		fileName := filepath.Clean(fileHeader.Filename)
196		defer file.Close()
197		if err != nil {
198			log.Println(err)
199			renderError(w, err.Error(), http.StatusBadRequest)
200			return
201		}
202		dest, _ := ioutil.ReadAll(file)
203		err = checkIfValidFile(fileName, dest)
204		if err != nil {
205			log.Println(err)
206			renderError(w, err.Error(), http.StatusBadRequest)
207			return
208		}
209		destPath := path.Join(c.FilesDirectory, user.Username, fileName)
210
211		f, err := os.OpenFile(destPath, os.O_WRONLY|os.O_CREATE, 0644)
212		if err != nil {
213			panic(err)
214		}
215		defer f.Close()
216		if userHasSpace(user.Username, c.MaxFileBytes) { // Not quite right
217			io.Copy(f, bytes.NewReader(dest))
218		} else {
219			renderError(w, fmt.Sprintf("Bad Request: Out of file space. Max space: %d.", c.MaxUserBytes), http.StatusBadRequest)
220			return
221		}
222	}
223	http.Redirect(w, r, "/my_site", http.StatusSeeOther)
224}
225
226type AuthUser struct {
227	LoggedIn          bool
228	Username          string
229	IsAdmin           bool
230	ImpersonatingUser string // used if impersonating
231}
232
233func newGetAuthUser(r *http.Request) AuthUser {
234	session, _ := SessionStore.Get(r, "cookie-session")
235	user, ok := session.Values["auth_user"].(string)
236	impers, _ := session.Values["impersonating_user"].(string)
237	isAdmin, _ := session.Values["admin"].(bool)
238	return AuthUser{
239		LoggedIn:          ok,
240		Username:          user,
241		IsAdmin:           isAdmin,
242		ImpersonatingUser: impers,
243	}
244}
245
246func mySiteHandler(w http.ResponseWriter, r *http.Request) {
247	user := newGetAuthUser(r)
248	if !user.LoggedIn {
249		renderDefaultError(w, http.StatusForbidden)
250		return
251	}
252	// check auth
253	userFolder := getUserDirectory(user.Username)
254	files, _ := getMyFilesRecursive(userFolder, user.Username)
255	currentDate := time.Now().Format("2006-01-02")
256	data := struct {
257		Host        string
258		PageTitle   string
259		Files       []*File
260		AuthUser    AuthUser
261		CurrentDate string
262	}{c.Host, c.SiteTitle, files, user, currentDate}
263	_ = t.ExecuteTemplate(w, "my_site.html", data)
264}
265
266func myAccountHandler(w http.ResponseWriter, r *http.Request) {
267	user := newGetAuthUser(r)
268	authUser := user.Username
269	if !user.LoggedIn {
270		renderDefaultError(w, http.StatusForbidden)
271		return
272	}
273	me, _ := getUserByName(user.Username)
274	type pageData struct {
275		PageTitle string
276		AuthUser  AuthUser
277		Email     string
278		Errors    []string
279	}
280	data := pageData{"My Account", user, me.Email, nil}
281
282	if r.Method == "GET" {
283		err := t.ExecuteTemplate(w, "me.html", data)
284		if err != nil {
285			panic(err)
286		}
287	} else if r.Method == "POST" {
288		r.ParseForm()
289		newUsername := r.Form.Get("username")
290		errors := []string{}
291		newEmail := r.Form.Get("email")
292		newUsername = strings.ToLower(newUsername)
293		var err error
294		if newEmail != me.Email {
295			_, err = DB.Exec("update user set email = ? where username = ?", newEmail, me.Email)
296			if err != nil {
297				// TODO better error not sql
298				errors = append(errors, err.Error())
299			} else {
300				log.Printf("Changed email for %s from %s to %s", authUser, me.Email, newEmail)
301			}
302		}
303		if newUsername != authUser {
304			// Rename User
305			err = renameUser(authUser, newUsername)
306			if err != nil {
307				log.Println(err)
308				errors = append(errors, "Could not rename user")
309			} else {
310				session, _ := SessionStore.Get(r, "cookie-session")
311				session.Values["auth_user"] = newUsername
312				session.Save(r, w)
313			}
314		}
315		// reset auth
316		user = newGetAuthUser(r)
317		data.Errors = errors
318		data.AuthUser = user
319		data.Email = newEmail
320		_ = t.ExecuteTemplate(w, "me.html", data)
321	}
322}
323
324func archiveHandler(w http.ResponseWriter, r *http.Request) {
325	authUser := newGetAuthUser(r)
326	if !authUser.LoggedIn {
327		renderDefaultError(w, http.StatusForbidden)
328		return
329	}
330	if r.Method == "GET" {
331		userFolder := getUserDirectory(authUser.Username)
332		err := zipit(userFolder, w)
333		if err != nil {
334			panic(err)
335		}
336
337	}
338}
339func loginHandler(w http.ResponseWriter, r *http.Request) {
340	if r.Method == "GET" {
341		// show page
342		data := struct {
343			Error     string
344			PageTitle string
345		}{"", "Login"}
346		err := t.ExecuteTemplate(w, "login.html", data)
347		if err != nil {
348			panic(err)
349		}
350	} else if r.Method == "POST" {
351		r.ParseForm()
352		name := r.Form.Get("username")
353		password := r.Form.Get("password")
354		row := DB.QueryRow("SELECT username, password_hash, active, admin FROM user where username = $1 OR email = $1", name)
355		var db_password []byte
356		var username string
357		var active bool
358		var isAdmin bool
359		err := row.Scan(&username, &db_password, &active, &isAdmin)
360		if err != nil {
361			panic(err)
362		}
363		if db_password != nil && !active {
364			data := struct {
365				Error     string
366				PageTitle string
367			}{"Your account is not active yet. Pending admin approval", c.SiteTitle}
368			t.ExecuteTemplate(w, "login.html", data)
369			return
370		}
371		if bcrypt.CompareHashAndPassword(db_password, []byte(password)) == nil {
372			log.Println("logged in")
373			session, _ := SessionStore.Get(r, "cookie-session")
374			session.Values["auth_user"] = username
375			session.Values["admin"] = isAdmin
376			session.Save(r, w)
377			http.Redirect(w, r, "/my_site", http.StatusSeeOther)
378		} else {
379			data := struct {
380				Error     string
381				PageTitle string
382			}{"Invalid login or password", c.SiteTitle}
383			err := t.ExecuteTemplate(w, "login.html", data)
384			if err != nil {
385				panic(err)
386			}
387		}
388	}
389}
390
391func logoutHandler(w http.ResponseWriter, r *http.Request) {
392	session, _ := SessionStore.Get(r, "cookie-session")
393	impers, ok := session.Values["impersonating_user"].(string)
394	if ok {
395		session.Values["auth_user"] = impers
396		session.Values["impersonating_user"] = nil // TODO expire this automatically
397		// session.Values["admin"] = nil // TODO fix admin
398	} else {
399		session.Options.MaxAge = -1
400	}
401	session.Save(r, w)
402	http.Redirect(w, r, "/", http.StatusSeeOther)
403}
404
405const ok = "-0123456789abcdefghijklmnopqrstuvwxyz"
406
407func isOkUsername(s string) error {
408	if len(s) < 1 {
409		return fmt.Errorf("Username is too short")
410	}
411	if len(s) > 32 {
412		return fmt.Errorf("Username is too long. 32 char max.")
413	}
414	for _, char := range s {
415		if !strings.Contains(ok, strings.ToLower(string(char))) {
416			return fmt.Errorf("Username contains invalid characters. Valid characters include lowercase letters, numbers, and hyphens.")
417		}
418	}
419	return nil
420}
421func registerHandler(w http.ResponseWriter, r *http.Request) {
422	if r.Method == "GET" {
423		data := struct {
424			Host      string
425			Errors    []string
426			PageTitle string
427		}{c.Host, nil, "Register"}
428		err := t.ExecuteTemplate(w, "register.html", data)
429		if err != nil {
430			panic(err)
431		}
432	} else if r.Method == "POST" {
433		r.ParseForm()
434		email := r.Form.Get("email")
435		password := r.Form.Get("password")
436		errors := []string{}
437		if r.Form.Get("password") != r.Form.Get("password2") {
438			errors = append(errors, "Passwords don't match")
439		}
440		if len(password) < 6 {
441			errors = append(errors, "Password is too short")
442		}
443		username := strings.ToLower(r.Form.Get("username"))
444		err := isOkUsername(username)
445		if err != nil {
446			errors = append(errors, err.Error())
447		}
448		hashedPassword, err := bcrypt.GenerateFromPassword([]byte(password), 8) // TODO handle error
449		if err != nil {
450			panic(err)
451		}
452		reference := r.Form.Get("reference")
453		if len(errors) == 0 {
454			_, err = DB.Exec("insert into user (username, email, password_hash, reference) values ($1, $2, $3, $4)", username, email, string(hashedPassword), reference)
455			if err != nil {
456				errors = append(errors, "Username or email is already used")
457			}
458		}
459		if len(errors) > 0 {
460			data := struct {
461				Host      string
462				Errors    []string
463				PageTitle string
464			}{c.Host, errors, "Register"}
465			t.ExecuteTemplate(w, "register.html", data)
466		} else {
467			data := struct {
468				Host      string
469				Message   string
470				PageTitle string
471			}{c.Host, "Registration complete! The server admin will approve your request before you can log in.", "Registration Complete"}
472			t.ExecuteTemplate(w, "message.html", data)
473		}
474	}
475}
476
477func deleteFileHandler(w http.ResponseWriter, r *http.Request) {
478	user := newGetAuthUser(r)
479	if !user.LoggedIn {
480		renderDefaultError(w, http.StatusForbidden)
481		return
482	}
483	filePath := safeGetFilePath(user.Username, r.URL.Path[len("/delete/"):])
484	if r.Method == "POST" {
485		os.Remove(filePath) // TODO handle error
486	}
487	http.Redirect(w, r, "/my_site", http.StatusSeeOther)
488}
489
490func adminHandler(w http.ResponseWriter, r *http.Request) {
491	user := newGetAuthUser(r)
492	if !user.IsAdmin {
493		renderDefaultError(w, http.StatusForbidden)
494		return
495	}
496	allUsers, err := getUsers()
497	if err != nil {
498		log.Println(err)
499		renderDefaultError(w, http.StatusInternalServerError)
500		return
501	}
502	data := struct {
503		Users     []User
504		AuthUser  AuthUser
505		PageTitle string
506		Host      string
507	}{allUsers, user, "Admin", c.Host}
508	err = t.ExecuteTemplate(w, "admin.html", data)
509	if err != nil {
510		panic(err)
511	}
512}
513
514func getFavicon(user string) string {
515	faviconPath := path.Join(c.FilesDirectory, filepath.Clean(user), "favicon.txt")
516	content, err := ioutil.ReadFile(faviconPath)
517	if err != nil {
518		return ""
519	}
520	strcontent := []rune(string(content))
521	if len(strcontent) > 0 {
522		return string(strcontent[0])
523	}
524	return ""
525}
526
527// Server a user's file
528// Here be dragons
529func userFile(w http.ResponseWriter, r *http.Request) {
530	userName := filepath.Clean(strings.Split(r.Host, ".")[0]) // Clean probably unnecessary
531	p := filepath.Clean(r.URL.Path)
532	var isDir bool
533	fileName := path.Join(c.FilesDirectory, userName, p) // TODO rename filepath
534	stat, err := os.Stat(fileName)
535	if stat != nil {
536		isDir = stat.IsDir()
537	}
538	if p == "/" || isDir {
539		fileName = path.Join(fileName, "index.gmi")
540	}
541
542	if strings.HasPrefix(p, "/"+HIDDEN_FOLDER) {
543		renderDefaultError(w, http.StatusForbidden)
544		return
545	}
546	if r.URL.Path == "/style.css" {
547		http.ServeFile(w, r, path.Join(c.TemplatesDirectory, "static/style.css"))
548		return
549	}
550
551	_, err = os.Stat(fileName)
552	if os.IsNotExist(err) {
553		if p == "/" || isDir {
554			fileName := path.Join(c.FilesDirectory, userName, p)
555			favicon := getFavicon(userName)
556			files, _ := ioutil.ReadDir(fileName)
557			renderedFiles := []File{}
558			for _, file := range files {
559				n := file.Name()
560				newFile := File{
561					Name:        path.Join(p, n), // SHOULD be safe
562					UpdatedTime: file.ModTime(),
563					Host:        c.Host,
564					Creator:     getCreator(fileName),
565				}
566				renderedFiles = append(renderedFiles, newFile)
567			}
568			hostname := strings.Split(r.Host, ":")[0]
569			URI := hostname + r.URL.String()
570			data := struct {
571				Folder    string
572				Files     []File
573				Favicon   string
574				PageTitle string
575				URI       string
576			}{p, renderedFiles, favicon, userName + p, URI}
577			// TODO check if gemlog
578			t.ExecuteTemplate(w, "folder.html", data)
579			return
580		} else {
581			renderDefaultError(w, http.StatusNotFound)
582			return
583		}
584	}
585
586	// Dumb content negotiation
587	_, raw := r.URL.Query()["raw"]
588	acceptsGemini := strings.Contains(r.Header.Get("Accept"), "text/gemini")
589	if !raw && !acceptsGemini && isGemini(fileName) {
590		file, _ := os.Open(fileName)
591		htmlString := textToHTML(gmi.ParseText(file))
592		favicon := getFavicon(userName)
593		hostname := strings.Split(r.Host, ":")[0]
594		URI := hostname + r.URL.String()
595		data := struct {
596			SiteBody  template.HTML
597			Favicon   string
598			PageTitle string
599			URI       string
600		}{template.HTML(htmlString), favicon, userName + p, URI}
601		t.ExecuteTemplate(w, "user_page.html", data)
602		file.Close()
603	} else {
604		http.ServeFile(w, r, fileName)
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.LoggingHandler(log.Writer(), handlers.RecoveryHandler()(serveMux)))
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}