all repos — flounder @ e53e5ea968f373f93d404acc0c1c90e1a6f52fd9

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