all repos — flounder @ e286a19d517d41e50443c3885ce8695878da32c0

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