all repos — flounder @ 32fd85e62324db1a34b5e78e1ef7b61cee31edde

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