all repos — flounder @ 383d618d53b72f3ca8aec4643ca60e7a1695f685

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 loginHandler(w http.ResponseWriter, r *http.Request) {
217	if r.Method == "GET" {
218		// show page
219		data := struct {
220			Error     string
221			PageTitle string
222		}{"", "Login"}
223		err := t.ExecuteTemplate(w, "login.html", data)
224		if err != nil {
225			log.Println(err)
226			renderError(w, InternalServerErrorMsg, 500)
227			return
228		}
229	} else if r.Method == "POST" {
230		r.ParseForm()
231		name := r.Form.Get("username")
232		password := r.Form.Get("password")
233		row := DB.QueryRow("SELECT username, password_hash, active, admin FROM user where username = $1 OR email = $1", name)
234		var db_password []byte
235		var username string
236		var active bool
237		var isAdmin bool
238		_ = row.Scan(&username, &db_password, &active, &isAdmin)
239		if db_password != nil && !active {
240			data := struct {
241				Error     string
242				PageTitle string
243			}{"Your account is not active yet. Pending admin approval", c.SiteTitle}
244			t.ExecuteTemplate(w, "login.html", data)
245			return
246		}
247		if bcrypt.CompareHashAndPassword(db_password, []byte(password)) == nil {
248			log.Println("logged in")
249			session, _ := SessionStore.Get(r, "cookie-session")
250			session.Values["auth_user"] = username
251			session.Values["admin"] = isAdmin
252			session.Save(r, w)
253			http.Redirect(w, r, "/my_site", 303)
254		} else {
255			data := struct {
256				Error     string
257				PageTitle string
258			}{"Invalid login or password", c.SiteTitle}
259			err := t.ExecuteTemplate(w, "login.html", data)
260			if err != nil {
261				log.Println(err)
262				renderError(w, InternalServerErrorMsg, 500)
263				return
264			}
265		}
266	}
267}
268
269func logoutHandler(w http.ResponseWriter, r *http.Request) {
270	session, _ := SessionStore.Get(r, "cookie-session")
271	session.Options.MaxAge = -1
272	session.Save(r, w)
273	http.Redirect(w, r, "/", 303)
274}
275
276const ok = "-0123456789abcdefghijklmnopqrstuvwxyz"
277
278func isOkUsername(s string) bool {
279	if len(s) < 1 {
280		return false
281	}
282	if len(s) > 31 {
283		return false
284	}
285	for _, char := range s {
286		if !strings.Contains(ok, strings.ToLower(string(char))) {
287			return false
288		}
289	}
290	return true
291}
292func registerHandler(w http.ResponseWriter, r *http.Request) {
293	if r.Method == "GET" {
294		data := struct {
295			Host      string
296			Errors    []string
297			PageTitle string
298		}{c.Host, nil, "Register"}
299		err := t.ExecuteTemplate(w, "register.html", data)
300		if err != nil {
301			log.Println(err)
302			renderError(w, InternalServerErrorMsg, 500)
303			return
304		}
305	} else if r.Method == "POST" {
306		r.ParseForm()
307		email := r.Form.Get("email")
308		password := r.Form.Get("password")
309		errors := []string{}
310		if !strings.Contains(email, "@") {
311			errors = append(errors, "Invalid Email")
312		}
313		if r.Form.Get("password") != r.Form.Get("password2") {
314			errors = append(errors, "Passwords don't match")
315		}
316		if len(password) < 6 {
317			errors = append(errors, "Password is too short")
318		}
319		username := strings.ToLower(r.Form.Get("username"))
320		if !isOkUsername(username) {
321			errors = append(errors, "Username is invalid: can only contain letters, numbers and hypens. Maximum 32 characters.")
322		}
323		hashedPassword, err := bcrypt.GenerateFromPassword([]byte(password), 8) // TODO handle error
324		if len(errors) == 0 {
325			_, err = DB.Exec("insert into user (username, email, password_hash) values ($1, $2, $3)", username, email, string(hashedPassword))
326			if err != nil {
327				log.Println(err)
328				errors = append(errors, "Username or email is already used")
329			}
330		}
331		if len(errors) > 0 {
332			data := struct {
333				Host      string
334				Errors    []string
335				PageTitle string
336			}{c.Host, errors, "Register"}
337			t.ExecuteTemplate(w, "register.html", data)
338		} else {
339			data := struct {
340				Host      string
341				Message   string
342				PageTitle string
343			}{c.Host, "Registration complete! The server admin will approve your request before you can log in.", "Registration Complete"}
344			t.ExecuteTemplate(w, "message.html", data)
345		}
346	}
347}
348
349func adminHandler(w http.ResponseWriter, r *http.Request) {
350	_, _, isAdmin := getAuthUser(r)
351	if !isAdmin {
352		renderError(w, "403: Forbidden", 403)
353		return
354	}
355	allUsers, err := getUsers()
356	if err != nil {
357		log.Println(err)
358		renderError(w, InternalServerErrorMsg, 500)
359		return
360	}
361	data := struct {
362		Users     []User
363		LoggedIn  bool
364		IsAdmin   bool
365		PageTitle string
366		Host      string
367	}{allUsers, true, true, "Admin", c.Host}
368	err = t.ExecuteTemplate(w, "admin.html", data)
369	if err != nil {
370		log.Println(err)
371		renderError(w, InternalServerErrorMsg, 500)
372		return
373	}
374}
375
376// Server a user's file
377func userFile(w http.ResponseWriter, r *http.Request) {
378	userName := filepath.Clean(strings.Split(r.Host, ".")[0]) // clean probably unnecessary
379	p := filepath.Clean(r.URL.Path)
380	if p == "/" {
381		p = "index.gmi"
382	}
383	fileName := path.Join(c.FilesDirectory, userName, p)
384	extension := path.Ext(fileName)
385	if r.URL.Path == "/style.css" {
386		http.ServeFile(w, r, path.Join(c.TemplatesDirectory, "static/style.css"))
387	}
388	query := r.URL.Query()
389	_, raw := query["raw"]
390	if !raw && (extension == ".gmi" || extension == ".gemini") {
391		_, err := os.Stat(fileName)
392		if err != nil {
393			renderError(w, "404: file not found", 404)
394			return
395		}
396		file, _ := os.Open(fileName)
397
398		htmlString := textToHTML(gmi.Parse(file))
399		data := struct {
400			SiteBody  template.HTML
401			PageTitle string
402		}{template.HTML(htmlString), userName}
403		t.ExecuteTemplate(w, "user_page.html", data)
404	} else {
405		http.ServeFile(w, r, fileName)
406	}
407}
408
409func adminUserHandler(w http.ResponseWriter, r *http.Request) {
410	_, _, isAdmin := getAuthUser(r)
411	if r.Method == "POST" {
412		if !isAdmin {
413			renderError(w, "403: Forbidden", 403)
414			return
415		}
416		components := strings.Split(r.URL.Path, "/")
417		if len(components) < 5 {
418			renderError(w, "Invalid action", 400)
419			return
420		}
421		userName := components[3]
422		action := components[4]
423		var err error
424		if action == "activate" {
425			err = activateUser(userName)
426		} else if action == "delete" {
427			err = deleteUser(userName)
428		}
429		if err != nil {
430			log.Println(err)
431			renderError(w, InternalServerErrorMsg, 500)
432			return
433		}
434		http.Redirect(w, r, "/admin", 303)
435	}
436}
437
438func runHTTPServer() {
439	log.Printf("Running http server with hostname %s on port %d. TLS enabled: %t", c.Host, c.HttpPort, c.HttpsEnabled)
440	var err error
441	t, err = template.ParseGlob(path.Join(c.TemplatesDirectory, "*.html"))
442	if err != nil {
443		log.Fatal(err)
444	}
445	serveMux := http.NewServeMux()
446
447	s := strings.SplitN(c.Host, ":", 2)
448	hostname := s[0]
449	port := c.HttpPort
450
451	serveMux.HandleFunc(hostname+"/", rootHandler)
452	serveMux.HandleFunc(hostname+"/my_site", mySiteHandler)
453	serveMux.HandleFunc(hostname+"/admin", adminHandler)
454	serveMux.HandleFunc(hostname+"/edit/", editFileHandler)
455	serveMux.HandleFunc(hostname+"/upload", uploadFilesHandler)
456	serveMux.HandleFunc(hostname+"/login", loginHandler)
457	serveMux.HandleFunc(hostname+"/logout", logoutHandler)
458	serveMux.HandleFunc(hostname+"/register", registerHandler)
459	serveMux.HandleFunc(hostname+"/delete/", deleteFileHandler)
460
461	// admin commands
462	serveMux.HandleFunc(hostname+"/admin/user/", adminUserHandler)
463
464	// TODO rate limit login https://github.com/ulule/limiter
465
466	wrapped := handlers.LoggingHandler(log.Writer(), serveMux)
467
468	// handle user files based on subdomain
469	serveMux.HandleFunc("/", userFile)
470	// login+register functions
471	srv := &http.Server{
472		ReadTimeout:  5 * time.Second,
473		WriteTimeout: 10 * time.Second,
474		IdleTimeout:  120 * time.Second,
475		Addr:         fmt.Sprintf(":%d", port),
476		// TLSConfig:    tlsConfig,
477		Handler: wrapped,
478	}
479	if c.HttpsEnabled {
480		log.Fatal(srv.ListenAndServeTLS(c.TLSCertFile, c.TLSKeyFile))
481	} else {
482		log.Fatal(srv.ListenAndServe())
483	}
484}