all repos — flounder @ f0ec25f3b1de5cba69cf8ed647c9391c9b7ea81d

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		http.ServeFile(w, r, fileName)
 51		return
 52	}
 53	authd, _, isAdmin := getAuthUser(r)
 54	indexFiles, err := getIndexFiles()
 55	if err != nil {
 56		log.Println(err)
 57		renderDefaultError(w, http.StatusInternalServerError)
 58		return
 59	}
 60	allUsers, err := getActiveUserNames()
 61	if err != nil {
 62		log.Println(err)
 63		renderDefaultError(w, http.StatusInternalServerError)
 64		return
 65	}
 66	data := struct {
 67		Host      string
 68		PageTitle string
 69		Files     []*File
 70		Users     []string
 71		LoggedIn  bool
 72		IsAdmin   bool
 73	}{c.Host, c.SiteTitle, indexFiles, allUsers, authd, isAdmin}
 74	err = t.ExecuteTemplate(w, "index.html", data)
 75	if err != nil {
 76		log.Println(err)
 77		renderDefaultError(w, http.StatusInternalServerError)
 78		return
 79	}
 80}
 81
 82func editFileHandler(w http.ResponseWriter, r *http.Request) {
 83	session, _ := SessionStore.Get(r, "cookie-session")
 84	authUser, ok := session.Values["auth_user"].(string)
 85	if !ok {
 86		renderDefaultError(w, http.StatusForbidden)
 87		return
 88	}
 89	fileName := filepath.Clean(r.URL.Path[len("/edit/"):])
 90	isText := strings.HasPrefix(mime.TypeByExtension(path.Ext(fileName)), "text")
 91	if !isText {
 92		renderError(w, "Bad Request: Not a text file, cannot be edited here", http.StatusBadRequest) // correct status code?
 93		return
 94	}
 95	filePath := path.Join(c.FilesDirectory, authUser, fileName)
 96
 97	if r.Method == "GET" {
 98		err := checkIfValidFile(filePath, nil)
 99		if err != nil {
100			log.Println(err)
101			renderError(w, err.Error(), http.StatusBadRequest)
102			return
103		}
104		// create directories if dne
105		f, err := os.OpenFile(filePath, os.O_RDONLY, 0644)
106		var fileBytes []byte
107		if os.IsNotExist(err) {
108			fileBytes = []byte{}
109			err = nil
110		} else {
111			defer f.Close()
112			fileBytes, err = ioutil.ReadAll(f)
113		}
114		if err != nil {
115			log.Println(err)
116			renderDefaultError(w, http.StatusInternalServerError)
117			return
118		}
119		data := struct {
120			FileName  string
121			FileText  string
122			PageTitle string
123			AuthUser  string
124			Host      string
125		}{fileName, string(fileBytes), c.SiteTitle, authUser, c.Host}
126		err = t.ExecuteTemplate(w, "edit_file.html", data)
127		if err != nil {
128			log.Println(err)
129			renderDefaultError(w, http.StatusInternalServerError)
130			return
131		}
132	} else if r.Method == "POST" {
133		// get post body
134		r.ParseForm()
135		fileBytes := []byte(r.Form.Get("file_text"))
136		err := checkIfValidFile(filePath, fileBytes)
137		if err != nil {
138			log.Println(err)
139			renderError(w, err.Error(), http.StatusBadRequest)
140			return
141		}
142		// create directories if dne
143		os.MkdirAll(path.Dir(filePath), os.ModePerm)
144		err = ioutil.WriteFile(filePath, fileBytes, 0644)
145		if err != nil {
146			log.Println(err)
147			renderDefaultError(w, http.StatusInternalServerError)
148			return
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, authUser, newName)
159			os.MkdirAll(path.Dir(newPath), os.ModePerm)
160			os.Rename(filePath, newPath)
161		}
162		http.Redirect(w, r, path.Join("/edit", fileName), http.StatusSeeOther)
163	}
164}
165
166func uploadFilesHandler(w http.ResponseWriter, r *http.Request) {
167	if r.Method == "POST" {
168		session, _ := SessionStore.Get(r, "cookie-session")
169		authUser, ok := session.Values["auth_user"].(string)
170		if !ok {
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, authUser, fileName)
191
192		f, err := os.OpenFile(destPath, os.O_WRONLY|os.O_CREATE, 0644)
193		if err != nil {
194			log.Println(err)
195			renderDefaultError(w, http.StatusInternalServerError)
196			return
197		}
198		defer f.Close()
199		io.Copy(f, bytes.NewReader(dest))
200	}
201	http.Redirect(w, r, "/my_site", http.StatusSeeOther)
202}
203
204// bool whether auth'd, string is auth user
205func getAuthUser(r *http.Request) (bool, string, bool) {
206	session, _ := SessionStore.Get(r, "cookie-session")
207	user, ok := session.Values["auth_user"].(string)
208	isAdmin, _ := session.Values["admin"].(bool)
209	return ok, user, isAdmin
210}
211func deleteFileHandler(w http.ResponseWriter, r *http.Request) {
212	authd, authUser, _ := getAuthUser(r)
213	if !authd {
214		renderDefaultError(w, http.StatusForbidden)
215		return
216	}
217	fileName := filepath.Clean(r.URL.Path[len("/delete/"):])
218	filePath := path.Join(c.FilesDirectory, authUser, fileName)
219	if r.Method == "POST" {
220		os.Remove(filePath) // suppress error
221	}
222	http.Redirect(w, r, "/my_site", http.StatusSeeOther)
223}
224
225func mySiteHandler(w http.ResponseWriter, r *http.Request) {
226	authd, authUser, isAdmin := getAuthUser(r)
227	if !authd {
228		renderDefaultError(w, http.StatusForbidden)
229		return
230	}
231	// check auth
232	userFolder := path.Join(c.FilesDirectory, authUser)
233	files, _ := getMyFilesRecursive(userFolder, authUser)
234	data := struct {
235		Host      string
236		PageTitle string
237		AuthUser  string
238		Files     []*File
239		LoggedIn  bool
240		IsAdmin   bool
241	}{c.Host, c.SiteTitle, authUser, files, authd, isAdmin}
242	_ = t.ExecuteTemplate(w, "my_site.html", data)
243}
244
245func archiveHandler(w http.ResponseWriter, r *http.Request) {
246	authd, authUser, _ := getAuthUser(r)
247	if !authd {
248		renderDefaultError(w, http.StatusForbidden)
249		return
250	}
251	if r.Method == "GET" {
252		userFolder := filepath.Join(c.FilesDirectory, filepath.Clean(authUser))
253		err := zipit(userFolder, w)
254		if err != nil {
255			log.Println(err)
256			renderDefaultError(w, http.StatusInternalServerError)
257			return
258		}
259
260	}
261}
262func loginHandler(w http.ResponseWriter, r *http.Request) {
263	if r.Method == "GET" {
264		// show page
265		data := struct {
266			Error     string
267			PageTitle string
268		}{"", "Login"}
269		err := t.ExecuteTemplate(w, "login.html", data)
270		if err != nil {
271			log.Println(err)
272			renderDefaultError(w, http.StatusInternalServerError)
273			return
274		}
275	} else if r.Method == "POST" {
276		r.ParseForm()
277		name := r.Form.Get("username")
278		password := r.Form.Get("password")
279		row := DB.QueryRow("SELECT username, password_hash, active, admin FROM user where username = $1 OR email = $1", name)
280		var db_password []byte
281		var username string
282		var active bool
283		var isAdmin bool
284		_ = row.Scan(&username, &db_password, &active, &isAdmin)
285		if db_password != nil && !active {
286			data := struct {
287				Error     string
288				PageTitle string
289			}{"Your account is not active yet. Pending admin approval", c.SiteTitle}
290			t.ExecuteTemplate(w, "login.html", data)
291			return
292		}
293		if bcrypt.CompareHashAndPassword(db_password, []byte(password)) == nil {
294			log.Println("logged in")
295			session, _ := SessionStore.Get(r, "cookie-session")
296			session.Values["auth_user"] = username
297			session.Values["admin"] = isAdmin
298			session.Save(r, w)
299			http.Redirect(w, r, "/my_site", http.StatusSeeOther)
300		} else {
301			data := struct {
302				Error     string
303				PageTitle string
304			}{"Invalid login or password", c.SiteTitle}
305			err := t.ExecuteTemplate(w, "login.html", data)
306			if err != nil {
307				log.Println(err)
308				renderDefaultError(w, http.StatusInternalServerError)
309				return
310			}
311		}
312	}
313}
314
315func logoutHandler(w http.ResponseWriter, r *http.Request) {
316	session, _ := SessionStore.Get(r, "cookie-session")
317	session.Options.MaxAge = -1
318	session.Save(r, w)
319	http.Redirect(w, r, "/", http.StatusSeeOther)
320}
321
322const ok = "-0123456789abcdefghijklmnopqrstuvwxyz"
323
324func isOkUsername(s string) bool {
325	if len(s) < 1 {
326		return false
327	}
328	if len(s) > 31 {
329		return false
330	}
331	for _, char := range s {
332		if !strings.Contains(ok, strings.ToLower(string(char))) {
333			return false
334		}
335	}
336	return true
337}
338func registerHandler(w http.ResponseWriter, r *http.Request) {
339	if r.Method == "GET" {
340		data := struct {
341			Host      string
342			Errors    []string
343			PageTitle string
344		}{c.Host, nil, "Register"}
345		err := t.ExecuteTemplate(w, "register.html", data)
346		if err != nil {
347			log.Println(err)
348			renderDefaultError(w, http.StatusInternalServerError)
349			return
350		}
351	} else if r.Method == "POST" {
352		r.ParseForm()
353		email := r.Form.Get("email")
354		password := r.Form.Get("password")
355		errors := []string{}
356		if !strings.Contains(email, "@") {
357			errors = append(errors, "Invalid Email")
358		}
359		if r.Form.Get("password") != r.Form.Get("password2") {
360			errors = append(errors, "Passwords don't match")
361		}
362		if len(password) < 6 {
363			errors = append(errors, "Password is too short")
364		}
365		username := strings.ToLower(r.Form.Get("username"))
366		if !isOkUsername(username) {
367			errors = append(errors, "Username is invalid: can only contain letters, numbers and hypens. Maximum 32 characters.")
368		}
369		hashedPassword, err := bcrypt.GenerateFromPassword([]byte(password), 8) // TODO handle error
370		reference := r.Form.Get("reference")
371		if len(errors) == 0 {
372			_, err = DB.Exec("insert into user (username, email, password_hash, reference) values ($1, $2, $3, $4)", username, email, string(hashedPassword), reference)
373			if err != nil {
374				log.Println(err)
375				errors = append(errors, "Username or email is already used")
376			}
377		}
378		if len(errors) > 0 {
379			data := struct {
380				Host      string
381				Errors    []string
382				PageTitle string
383			}{c.Host, errors, "Register"}
384			t.ExecuteTemplate(w, "register.html", data)
385		} else {
386			data := struct {
387				Host      string
388				Message   string
389				PageTitle string
390			}{c.Host, "Registration complete! The server admin will approve your request before you can log in.", "Registration Complete"}
391			t.ExecuteTemplate(w, "message.html", data)
392		}
393	}
394}
395
396func adminHandler(w http.ResponseWriter, r *http.Request) {
397	_, _, isAdmin := getAuthUser(r)
398	if !isAdmin {
399		renderDefaultError(w, http.StatusForbidden)
400		return
401	}
402	allUsers, err := getUsers()
403	if err != nil {
404		log.Println(err)
405		renderDefaultError(w, http.StatusInternalServerError)
406		return
407	}
408	data := struct {
409		Users     []User
410		LoggedIn  bool
411		IsAdmin   bool
412		PageTitle string
413		Host      string
414	}{allUsers, true, true, "Admin", c.Host}
415	err = t.ExecuteTemplate(w, "admin.html", data)
416	if err != nil {
417		log.Println(err)
418		renderDefaultError(w, http.StatusInternalServerError)
419		return
420	}
421}
422
423func getFavicon(user string) string {
424	faviconPath := path.Join(c.FilesDirectory, filepath.Clean(user), "favicon.txt")
425	content, err := ioutil.ReadFile(faviconPath)
426	if err != nil {
427		return ""
428	}
429	strcontent := []rune(string(content))
430	if len(strcontent) > 0 {
431		return string(strcontent[0])
432	}
433	return ""
434}
435
436// Server a user's file
437func userFile(w http.ResponseWriter, r *http.Request) {
438	userName := filepath.Clean(strings.Split(r.Host, ".")[0]) // Clean probably unnecessary
439	p := filepath.Clean(r.URL.Path)
440	var isDir bool
441	fileName := path.Join(c.FilesDirectory, userName, p)
442	stat, err := os.Stat(fileName)
443	if stat != nil {
444		isDir = stat.IsDir()
445	}
446	if p == "/" || isDir {
447		fileName = path.Join(fileName, "index.gmi")
448	}
449
450	if strings.HasPrefix(p, "/.hidden") {
451		renderDefaultError(w, http.StatusForbidden)
452		return
453	}
454	if r.URL.Path == "/style.css" {
455		http.ServeFile(w, r, path.Join(c.TemplatesDirectory, "static/style.css"))
456		return
457	}
458
459	_, err = os.Stat(fileName)
460	if os.IsNotExist(err) {
461		renderDefaultError(w, http.StatusNotFound)
462		return
463	}
464
465	// Dumb content negotiation
466	extension := path.Ext(fileName)
467	_, raw := r.URL.Query()["raw"]
468	acceptsGemini := strings.Contains(r.Header.Get("Accept"), "text/gemini")
469	if !raw && !acceptsGemini && (extension == ".gmi" || extension == ".gemini") {
470		file, _ := os.Open(fileName)
471		htmlString := textToHTML(gmi.ParseText(file))
472		favicon := getFavicon(userName)
473		data := struct {
474			SiteBody  template.HTML
475			Favicon   string
476			PageTitle string
477		}{template.HTML(htmlString), favicon, userName + p}
478		t.ExecuteTemplate(w, "user_page.html", data)
479	} else {
480		http.ServeFile(w, r, fileName) // TODO make errors pretty
481	}
482}
483
484func adminUserHandler(w http.ResponseWriter, r *http.Request) {
485	_, _, isAdmin := getAuthUser(r)
486	if r.Method == "POST" {
487		if !isAdmin {
488			renderDefaultError(w, http.StatusForbidden)
489			return
490		}
491		components := strings.Split(r.URL.Path, "/")
492		if len(components) < 5 {
493			renderError(w, "Invalid action", http.StatusBadRequest)
494			return
495		}
496		userName := components[3]
497		action := components[4]
498		var err error
499		if action == "activate" {
500			err = activateUser(userName)
501		} else if action == "delete" {
502			err = deleteUser(userName)
503		}
504		if err != nil {
505			log.Println(err)
506			renderDefaultError(w, http.StatusInternalServerError)
507			return
508		}
509		http.Redirect(w, r, "/admin", http.StatusSeeOther)
510	}
511}
512
513func runHTTPServer() {
514	log.Printf("Running http server with hostname %s on port %d. TLS enabled: %t", c.Host, c.HttpPort, c.HttpsEnabled)
515	var err error
516	t, err = template.ParseGlob(path.Join(c.TemplatesDirectory, "*.html"))
517	if err != nil {
518		log.Fatal(err)
519	}
520	serveMux := http.NewServeMux()
521
522	s := strings.SplitN(c.Host, ":", 2)
523	hostname := s[0]
524	port := c.HttpPort
525
526	serveMux.HandleFunc(hostname+"/", rootHandler)
527	serveMux.HandleFunc(hostname+"/my_site", mySiteHandler)
528	serveMux.HandleFunc(hostname+"/my_site/flounder-archive.zip", archiveHandler)
529	serveMux.HandleFunc(hostname+"/admin", adminHandler)
530	serveMux.HandleFunc(hostname+"/edit/", editFileHandler)
531	serveMux.HandleFunc(hostname+"/upload", uploadFilesHandler)
532	serveMux.HandleFunc(hostname+"/login", loginHandler)
533	serveMux.HandleFunc(hostname+"/logout", logoutHandler)
534	serveMux.HandleFunc(hostname+"/register", registerHandler)
535	serveMux.HandleFunc(hostname+"/delete/", deleteFileHandler)
536
537	// admin commands
538	serveMux.HandleFunc(hostname+"/admin/user/", adminUserHandler)
539
540	// TODO rate limit login https://github.com/ulule/limiter
541
542	wrapped := handlers.LoggingHandler(log.Writer(), serveMux)
543
544	// handle user files based on subdomain
545	serveMux.HandleFunc("/", userFile)
546	// login+register functions
547	srv := &http.Server{
548		ReadTimeout:  5 * time.Second,
549		WriteTimeout: 10 * time.Second,
550		IdleTimeout:  120 * time.Second,
551		Addr:         fmt.Sprintf(":%d", port),
552		// TLSConfig:    tlsConfig,
553		Handler: wrapped,
554	}
555	if c.HttpsEnabled {
556		log.Fatal(srv.ListenAndServeTLS(c.TLSCertFile, c.TLSKeyFile))
557	} else {
558		log.Fatal(srv.ListenAndServe())
559	}
560}