all repos — flounder @ c6b4711306bbd9c0d58ebda18a76d6e0515fd68f

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