all repos — flounder @ ab26d8c93d3179ea216929903435124f5aa7ed7e

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 editFileHandler(w http.ResponseWriter, r *http.Request) {
 82	user := newGetAuthUser(r)
 83	if !user.LoggedIn {
 84		renderDefaultError(w, http.StatusForbidden)
 85		return
 86	}
 87	fileName := filepath.Clean(r.URL.Path[len("/edit/"):])
 88	isText := strings.HasPrefix(mime.TypeByExtension(path.Ext(fileName)), "text")
 89	filePath := path.Join(c.FilesDirectory, user.Username, fileName)
 90
 91	if r.Method == "GET" {
 92		err := checkIfValidFile(filePath, nil)
 93		if err != nil {
 94			log.Println(err)
 95			renderError(w, err.Error(), http.StatusBadRequest)
 96			return
 97		}
 98		// Create directories if dne
 99		f, err := os.OpenFile(filePath, os.O_RDONLY, 0644)
100		var fileBytes []byte
101		if os.IsNotExist(err) || !isText {
102			fileBytes = []byte{}
103			err = nil
104		} else {
105			defer f.Close()
106			fileBytes, err = ioutil.ReadAll(f)
107		}
108		if err != nil {
109			panic(err)
110		}
111		data := struct {
112			FileName  string
113			FileText  string
114			PageTitle string
115			AuthUser  AuthUser
116			Host      string
117			IsText    bool
118		}{fileName, string(fileBytes), c.SiteTitle, user, c.Host, isText}
119		err = t.ExecuteTemplate(w, "edit_file.html", data)
120		if err != nil {
121			panic(err)
122		}
123	} else if r.Method == "POST" {
124		// get post body
125		r.ParseForm()
126		fileText := r.Form.Get("file_text")
127		// Web form by default gives us CR LF newlines.
128		// Unix files use just LF
129		fileText = strings.ReplaceAll(fileText, "\r\n", "\n")
130		fileBytes := []byte(fileText)
131		err := checkIfValidFile(filePath, fileBytes)
132		if err != nil {
133			log.Println(err)
134			renderError(w, err.Error(), http.StatusBadRequest)
135			return
136		}
137		// create directories if dne
138		os.MkdirAll(path.Dir(filePath), os.ModePerm)
139		if userHasSpace(user.Username, len(fileBytes)) {
140			if isText { // Cant edit binary files here
141				err = ioutil.WriteFile(filePath, fileBytes, 0644)
142			}
143		} else {
144			renderError(w, fmt.Sprintf("Bad Request: Out of file space. Max space: %d.", c.MaxUserBytes), http.StatusBadRequest)
145			return
146		}
147		if err != nil {
148			panic(err)
149		}
150		newName := filepath.Clean(r.Form.Get("rename"))
151		err = checkIfValidFile(newName, fileBytes)
152		if err != nil {
153			log.Println(err)
154			renderError(w, err.Error(), http.StatusBadRequest)
155			return
156		}
157		if newName != fileName {
158			newPath := path.Join(c.FilesDirectory, user.Username, newName)
159			os.MkdirAll(path.Dir(newPath), os.ModePerm)
160			os.Rename(filePath, newPath)
161			fileName = newName
162		}
163		http.Redirect(w, r, path.Join("/edit", fileName), http.StatusSeeOther)
164	}
165}
166
167func uploadFilesHandler(w http.ResponseWriter, r *http.Request) {
168	if r.Method == "POST" {
169		user := newGetAuthUser(r)
170		if !user.LoggedIn {
171			renderDefaultError(w, http.StatusForbidden)
172			return
173		}
174		r.ParseMultipartForm(10 << 6) // why does this not work
175		file, fileHeader, err := r.FormFile("file")
176		fileName := filepath.Clean(fileHeader.Filename)
177		defer file.Close()
178		if err != nil {
179			log.Println(err)
180			renderError(w, err.Error(), http.StatusBadRequest)
181			return
182		}
183		dest, _ := ioutil.ReadAll(file)
184		err = checkIfValidFile(fileName, dest)
185		if err != nil {
186			log.Println(err)
187			renderError(w, err.Error(), http.StatusBadRequest)
188			return
189		}
190		destPath := path.Join(c.FilesDirectory, user.Username, fileName)
191
192		f, err := os.OpenFile(destPath, os.O_WRONLY|os.O_CREATE, 0644)
193		if err != nil {
194			panic(err)
195		}
196		defer f.Close()
197		if userHasSpace(user.Username, c.MaxFileBytes) { // Not quite right
198			io.Copy(f, bytes.NewReader(dest))
199		} else {
200			renderError(w, fmt.Sprintf("Bad Request: Out of file space. Max space: %d.", c.MaxUserBytes), http.StatusBadRequest)
201			return
202		}
203	}
204	http.Redirect(w, r, "/my_site", http.StatusSeeOther)
205}
206
207type AuthUser struct {
208	LoggedIn          bool
209	Username          string
210	IsAdmin           bool
211	ImpersonatingUser string // used if impersonating
212}
213
214func newGetAuthUser(r *http.Request) AuthUser {
215	session, _ := SessionStore.Get(r, "cookie-session")
216	user, ok := session.Values["auth_user"].(string)
217	impers, _ := session.Values["impersonating_user"].(string)
218	isAdmin, _ := session.Values["admin"].(bool)
219	return AuthUser{
220		LoggedIn:          ok,
221		Username:          user,
222		IsAdmin:           isAdmin,
223		ImpersonatingUser: impers,
224	}
225}
226
227func mySiteHandler(w http.ResponseWriter, r *http.Request) {
228	user := newGetAuthUser(r)
229	if !user.LoggedIn {
230		renderDefaultError(w, http.StatusForbidden)
231		return
232	}
233	// check auth
234	userFolder := getUserDirectory(user.Username)
235	files, _ := getMyFilesRecursive(userFolder, user.Username)
236	data := struct {
237		Host      string
238		PageTitle string
239		Files     []*File
240		AuthUser  AuthUser
241	}{c.Host, c.SiteTitle, files, user}
242	_ = t.ExecuteTemplate(w, "my_site.html", data)
243}
244
245func myAccountHandler(w http.ResponseWriter, r *http.Request) {
246	user := newGetAuthUser(r)
247	authUser := user.Username
248	if !user.LoggedIn {
249		renderDefaultError(w, http.StatusForbidden)
250		return
251	}
252	me, _ := getUserByName(user.Username)
253	type pageData struct {
254		PageTitle string
255		AuthUser  AuthUser
256		Email     string
257		Errors    []string
258	}
259	data := pageData{"My Account", user, me.Email, nil}
260
261	if r.Method == "GET" {
262		err := t.ExecuteTemplate(w, "me.html", data)
263		if err != nil {
264			panic(err)
265		}
266	} else if r.Method == "POST" {
267		r.ParseForm()
268		newUsername := r.Form.Get("username")
269		errors := []string{}
270		newEmail := r.Form.Get("email")
271		newUsername = strings.ToLower(newUsername)
272		var err error
273		if newEmail != me.Email {
274			_, err = DB.Exec("update user set email = ? where username = ?", newEmail, me.Email)
275			if err != nil {
276				// TODO better error not sql
277				errors = append(errors, err.Error())
278			} else {
279				log.Printf("Changed email for %s from %s to %s", authUser, me.Email, newEmail)
280			}
281		}
282		if newUsername != authUser {
283			// Rename User
284			err = renameUser(authUser, newUsername)
285			if err != nil {
286				errors = append(errors, err.Error())
287			} else {
288				session, _ := SessionStore.Get(r, "cookie-session")
289				session.Values["auth_user"] = newUsername
290				session.Save(r, w)
291			}
292		}
293		// reset auth
294		user = newGetAuthUser(r)
295		data.Errors = errors
296		data.AuthUser = user
297		data.Email = newEmail
298		_ = t.ExecuteTemplate(w, "me.html", data)
299	}
300}
301
302func archiveHandler(w http.ResponseWriter, r *http.Request) {
303	authUser := newGetAuthUser(r)
304	if !authUser.LoggedIn {
305		renderDefaultError(w, http.StatusForbidden)
306		return
307	}
308	if r.Method == "GET" {
309		userFolder := getUserDirectory(authUser.Username)
310		err := zipit(userFolder, w)
311		if err != nil {
312			panic(err)
313		}
314
315	}
316}
317func loginHandler(w http.ResponseWriter, r *http.Request) {
318	if r.Method == "GET" {
319		// show page
320		data := struct {
321			Error     string
322			PageTitle string
323		}{"", "Login"}
324		err := t.ExecuteTemplate(w, "login.html", data)
325		if err != nil {
326			panic(err)
327		}
328	} else if r.Method == "POST" {
329		r.ParseForm()
330		name := r.Form.Get("username")
331		password := r.Form.Get("password")
332		row := DB.QueryRow("SELECT username, password_hash, active, admin FROM user where username = $1 OR email = $1", name)
333		var db_password []byte
334		var username string
335		var active bool
336		var isAdmin bool
337		_ = row.Scan(&username, &db_password, &active, &isAdmin)
338		if db_password != nil && !active {
339			data := struct {
340				Error     string
341				PageTitle string
342			}{"Your account is not active yet. Pending admin approval", c.SiteTitle}
343			t.ExecuteTemplate(w, "login.html", data)
344			return
345		}
346		if bcrypt.CompareHashAndPassword(db_password, []byte(password)) == nil {
347			log.Println("logged in")
348			session, _ := SessionStore.Get(r, "cookie-session")
349			session.Values["auth_user"] = username
350			session.Values["admin"] = isAdmin
351			session.Save(r, w)
352			http.Redirect(w, r, "/my_site", http.StatusSeeOther)
353		} else {
354			data := struct {
355				Error     string
356				PageTitle string
357			}{"Invalid login or password", c.SiteTitle}
358			err := t.ExecuteTemplate(w, "login.html", data)
359			if err != nil {
360				panic(err)
361			}
362		}
363	}
364}
365
366func logoutHandler(w http.ResponseWriter, r *http.Request) {
367	session, _ := SessionStore.Get(r, "cookie-session")
368	impers, ok := session.Values["impersonating_user"].(string)
369	if ok {
370		session.Values["auth_user"] = impers
371		session.Values["impersonating_user"] = nil // TODO expire this automatically
372		// session.Values["admin"] = nil // TODO fix admin
373	} else {
374		session.Options.MaxAge = -1
375	}
376	session.Save(r, w)
377	http.Redirect(w, r, "/", http.StatusSeeOther)
378}
379
380const ok = "-0123456789abcdefghijklmnopqrstuvwxyz"
381
382func isOkUsername(s string) error {
383	if len(s) < 1 {
384		return fmt.Errorf("Username is too short")
385	}
386	if len(s) > 32 {
387		return fmt.Errorf("Username is too long. 32 char max.")
388	}
389	for _, char := range s {
390		if !strings.Contains(ok, strings.ToLower(string(char))) {
391			return fmt.Errorf("Username contains invalid characters. Valid characters include lowercase letters, numbers, and hyphens.")
392		}
393	}
394	return nil
395}
396func registerHandler(w http.ResponseWriter, r *http.Request) {
397	if r.Method == "GET" {
398		data := struct {
399			Host      string
400			Errors    []string
401			PageTitle string
402		}{c.Host, nil, "Register"}
403		err := t.ExecuteTemplate(w, "register.html", data)
404		if err != nil {
405			panic(err)
406		}
407	} else if r.Method == "POST" {
408		r.ParseForm()
409		email := r.Form.Get("email")
410		password := r.Form.Get("password")
411		errors := []string{}
412		if r.Form.Get("password") != r.Form.Get("password2") {
413			errors = append(errors, "Passwords don't match")
414		}
415		if len(password) < 6 {
416			errors = append(errors, "Password is too short")
417		}
418		username := strings.ToLower(r.Form.Get("username"))
419		err := isOkUsername(username)
420		if err != nil {
421			errors = append(errors, err.Error())
422		}
423		hashedPassword, err := bcrypt.GenerateFromPassword([]byte(password), 8) // TODO handle error
424		reference := r.Form.Get("reference")
425		if len(errors) == 0 {
426			_, err = DB.Exec("insert into user (username, email, password_hash, reference) values ($1, $2, $3, $4)", username, email, string(hashedPassword), reference)
427			if err != nil {
428				errors = append(errors, "Username or email is already used")
429			}
430		}
431		if len(errors) > 0 {
432			data := struct {
433				Host      string
434				Errors    []string
435				PageTitle string
436			}{c.Host, errors, "Register"}
437			t.ExecuteTemplate(w, "register.html", data)
438		} else {
439			data := struct {
440				Host      string
441				Message   string
442				PageTitle string
443			}{c.Host, "Registration complete! The server admin will approve your request before you can log in.", "Registration Complete"}
444			t.ExecuteTemplate(w, "message.html", data)
445		}
446	}
447}
448
449func deleteFileHandler(w http.ResponseWriter, r *http.Request) {
450	user := newGetAuthUser(r)
451	if !user.LoggedIn {
452		renderDefaultError(w, http.StatusForbidden)
453		return
454	}
455	filePath := safeGetFilePath(user.Username, r.URL.Path[len("/delete/"):])
456	if r.Method == "POST" {
457		os.Remove(filePath) // TODO handle error
458	}
459	http.Redirect(w, r, "/my_site", http.StatusSeeOther)
460}
461
462func adminHandler(w http.ResponseWriter, r *http.Request) {
463	user := newGetAuthUser(r)
464	if !user.IsAdmin {
465		renderDefaultError(w, http.StatusForbidden)
466		return
467	}
468	allUsers, err := getUsers()
469	if err != nil {
470		log.Println(err)
471		renderDefaultError(w, http.StatusInternalServerError)
472		return
473	}
474	data := struct {
475		Users     []User
476		AuthUser  AuthUser
477		PageTitle string
478		Host      string
479	}{allUsers, user, "Admin", c.Host}
480	err = t.ExecuteTemplate(w, "admin.html", data)
481	if err != nil {
482		panic(err)
483	}
484}
485
486func getFavicon(user string) string {
487	faviconPath := path.Join(c.FilesDirectory, filepath.Clean(user), "favicon.txt")
488	content, err := ioutil.ReadFile(faviconPath)
489	if err != nil {
490		return ""
491	}
492	strcontent := []rune(string(content))
493	if len(strcontent) > 0 {
494		return string(strcontent[0])
495	}
496	return ""
497}
498
499// Server a user's file
500func userFile(w http.ResponseWriter, r *http.Request) {
501	userName := filepath.Clean(strings.Split(r.Host, ".")[0]) // Clean probably unnecessary
502	p := filepath.Clean(r.URL.Path)
503	var isDir bool
504	fileName := path.Join(c.FilesDirectory, userName, p)
505	stat, err := os.Stat(fileName)
506	if stat != nil {
507		isDir = stat.IsDir()
508	}
509	if p == "/" || isDir {
510		fileName = path.Join(fileName, "index.gmi")
511	}
512
513	if strings.HasPrefix(p, "/.hidden") {
514		renderDefaultError(w, http.StatusForbidden)
515		return
516	}
517	if r.URL.Path == "/style.css" {
518		http.ServeFile(w, r, path.Join(c.TemplatesDirectory, "static/style.css"))
519		return
520	}
521
522	_, err = os.Stat(fileName)
523	if os.IsNotExist(err) {
524		renderDefaultError(w, http.StatusNotFound)
525		return
526	}
527
528	// Dumb content negotiation
529	extension := path.Ext(fileName)
530	_, raw := r.URL.Query()["raw"]
531	acceptsGemini := strings.Contains(r.Header.Get("Accept"), "text/gemini")
532	if !raw && !acceptsGemini && (extension == ".gmi" || extension == ".gemini") {
533		file, _ := os.Open(fileName)
534		htmlString := textToHTML(gmi.ParseText(file))
535		favicon := getFavicon(userName)
536		data := struct {
537			SiteBody  template.HTML
538			Favicon   string
539			PageTitle string
540		}{template.HTML(htmlString), favicon, userName + p}
541		t.ExecuteTemplate(w, "user_page.html", data)
542	} else {
543		http.ServeFile(w, r, fileName)
544	}
545}
546
547func deleteAccountHandler(w http.ResponseWriter, r *http.Request) {
548	user := newGetAuthUser(r)
549	if r.Method == "POST" {
550		err := deleteUser(user.Username)
551		if err != nil {
552			log.Println(err)
553			renderDefaultError(w, http.StatusInternalServerError)
554			return
555		}
556		logoutHandler(w, r)
557	}
558}
559
560func resetPasswordHandler(w http.ResponseWriter, r *http.Request) {
561	user := newGetAuthUser(r)
562	data := struct {
563		PageTitle string
564		AuthUser  AuthUser
565		Error     error
566	}{"Reset Password", user, nil}
567	err := t.ExecuteTemplate(w, "reset_pass.html", data)
568	if err != nil {
569		panic(err)
570	}
571}
572
573func adminUserHandler(w http.ResponseWriter, r *http.Request) {
574	user := newGetAuthUser(r)
575	if r.Method == "POST" {
576		if !user.IsAdmin {
577			renderDefaultError(w, http.StatusForbidden)
578			return
579		}
580		components := strings.Split(r.URL.Path, "/")
581		if len(components) < 5 {
582			renderError(w, "Invalid action", http.StatusBadRequest)
583			return
584		}
585		userName := components[3]
586		action := components[4]
587		var err error
588		if action == "activate" {
589			err = activateUser(userName)
590		} else if action == "impersonate" {
591			session, _ := SessionStore.Get(r, "cookie-session")
592			session.Values["auth_user"] = userName
593			session.Values["impersonating_user"] = user.Username
594			session.Save(r, w)
595			log.Printf("User %s impersonated %s", user.Username, userName)
596			http.Redirect(w, r, "/", http.StatusSeeOther)
597			return
598		}
599		if err != nil {
600			log.Println(err)
601			renderDefaultError(w, http.StatusInternalServerError)
602			return
603		}
604		http.Redirect(w, r, "/admin", http.StatusSeeOther)
605	}
606}
607
608func runHTTPServer() {
609	log.Printf("Running http server with hostname %s on port %d. TLS enabled: %t", c.Host, c.HttpPort, c.HttpsEnabled)
610	var err error
611	t, err = template.ParseGlob(path.Join(c.TemplatesDirectory, "*.html"))
612	if err != nil {
613		log.Fatal(err)
614	}
615	serveMux := http.NewServeMux()
616
617	s := strings.SplitN(c.Host, ":", 2)
618	hostname := s[0]
619	port := c.HttpPort
620
621	serveMux.HandleFunc(hostname+"/", rootHandler)
622	serveMux.HandleFunc(hostname+"/my_site", mySiteHandler)
623	serveMux.HandleFunc(hostname+"/me", myAccountHandler)
624	serveMux.HandleFunc(hostname+"/my_site/flounder-archive.zip", archiveHandler)
625	serveMux.HandleFunc(hostname+"/admin", adminHandler)
626	serveMux.HandleFunc(hostname+"/edit/", editFileHandler)
627	serveMux.HandleFunc(hostname+"/upload", uploadFilesHandler)
628	serveMux.Handle(hostname+"/login", limit(http.HandlerFunc(loginHandler)))
629	serveMux.Handle(hostname+"/register", limit(http.HandlerFunc(registerHandler)))
630	serveMux.HandleFunc(hostname+"/logout", logoutHandler)
631	serveMux.HandleFunc(hostname+"/delete/", deleteFileHandler)
632	serveMux.HandleFunc(hostname+"/delete-account", deleteAccountHandler)
633	serveMux.HandleFunc(hostname+"/reset-password", resetPasswordHandler)
634
635	// admin commands
636	serveMux.HandleFunc(hostname+"/admin/user/", adminUserHandler)
637
638	// TODO rate limit login https://github.com/ulule/limiter
639
640	wrapped := (handlers.LoggingHandler(log.Writer(), handlers.RecoveryHandler()(serveMux)))
641
642	// handle user files based on subdomain
643	serveMux.HandleFunc("/", userFile)
644	// login+register functions
645	srv := &http.Server{
646		ReadTimeout:  5 * time.Second,
647		WriteTimeout: 10 * time.Second,
648		IdleTimeout:  120 * time.Second,
649		Addr:         fmt.Sprintf(":%d", port),
650		// TLSConfig:    tlsConfig,
651		Handler: wrapped,
652	}
653	if c.HttpsEnabled {
654		log.Fatal(srv.ListenAndServeTLS(c.TLSCertFile, c.TLSKeyFile))
655	} else {
656		log.Fatal(srv.ListenAndServe())
657	}
658}